Compare commits

..

1 Commits

Author SHA1 Message Date
bancika 405608dd44 package renamed 2011-01-04 19:06:09 +00:00
449 changed files with 4964 additions and 16916 deletions
+3 -2
View File
@@ -2,6 +2,7 @@
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="test"/>
<classpathentry kind="src" path="src.library"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/log4j-1.2.15.jar"/>
<classpathentry kind="lib" path="lib/xstream-1.3.1.jar"/>
@@ -9,9 +10,9 @@
<classpathentry kind="lib" path="lib/iText-2.1.7.jar"/>
<classpathentry kind="lib" path="lib/cloning-1.5.jar"/>
<classpathentry kind="lib" path="lib/objenesis-1.1.jar"/>
<classpathentry kind="lib" path="lib/bancika-gui-framework.jar"/>
<classpathentry kind="lib" path="lib/HttpProxy.jar"/>
<classpathentry kind="lib" path="lib/jettison-1.0.1.jar"/>
<classpathentry kind="lib" path="lib/poi-3.5-FINAL-20090928.jar"/>
<classpathentry kind="lib" path="library/main.jar"/>
<classpathentry kind="lib" path="lib/app-framework.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>diylc-core</name>
<name>DIYLC</name>
<comment></comment>
<projects>
</projects>
+2 -8
View File
@@ -1,11 +1,11 @@
<project name="diylc-swing" basedir="." default="jar">
<project name="diylc" basedir="." default="jar">
<property name="src.dir" value="src" />
<property name="lib.dir" value="${basedir}/lib" />
<property name="build.dir" value="${basedir}/build" />
<property name="jar.dir" value="${build.dir}/jar" />
<property name="report.dir" value="${build.dir}/junitreport" />
<property name="main.class" value="org.diylc.DIYLCStarter" />
<property name="main.class" value="com.diyfever.diylc.DIYLCStarter" />
<property name="classes.dir" value="${build.dir}/temp/${ant.project.name}/classes" />
<property name="test.classes.dir" value="${build.dir}/temp/${ant.project.name}/test.classes" />
@@ -35,11 +35,6 @@
<exclude name="**/*dll" />
</fileset>
</copy>
<copy todir="${jar.dir}/library" overwrite="true">
<fileset dir="${basedir}/library">
<exclude name="**/*dll" />
</fileset>
</copy>
<copy todir="${jar.dir}" overwrite="true">
<fileset dir="${basedir}/lib/" includes="**/*.dll" />
</copy>
@@ -48,7 +43,6 @@
<path id="class.path">
<fileset dir="${basedir}">
<include name="lib/**/*.jar" />
<include name="library/**/*.jar" />
</fileset>
</path>
+31
View File
@@ -0,0 +1,31 @@
<map>
<entry>
<string>defaults</string>
<map>
<entry>
<string>com.diyfever.diylc.components.MockComponentInstance:C</string>
<com.diyfever.diylc.model.measures.Capacitance>
<value>22.0</value>
<unit class="com.diyfever.diylc.model.measures.CapacitanceUnit">uF</unit>
</com.diyfever.diylc.model.measures.Capacitance>
</entry>
<entry>
<string>com.diyfever.diylc.components.MockComponentInstance:Color</string>
<awt-color>
<red>255</red>
<green>0</green>
<blue>0</blue>
<alpha>255</alpha>
</awt-color>
</entry>
</map>
</entry>
<entry>
<string>metric</string>
<boolean>true</boolean>
</entry>
<entry>
<string>lastPath</string>
<string>C:\Documents and Settings\Branislav Stojkovic\Desktop</string>
</entry>
</map>
-82
View File
@@ -1,82 +0,0 @@
<project name="diylc-core" basedir="." default="jar">
<property name="src.dir" value="src" />
<property name="lib.dir" value="${basedir}/lib" />
<property name="build.dir" value="${basedir}/build" />
<property name="jar.dir" value="${build.dir}/jar" />
<property name="report.dir" value="${build.dir}/junitreport" />
<property name="classes.dir" value="${build.dir}/temp/${ant.project.name}/classes" />
<property name="test.classes.dir" value="${build.dir}/temp/${ant.project.name}/test.classes" />
<target name="clean">
<delete dir="${build.dir}" />
</target>
<!--change src dir-->
<target name="compile">
<mkdir dir="${classes.dir}" />
<echo>Compile with JDK ${java.runtime.version}</echo>
<javac encoding="8859_1" srcdir="${src.dir}" destdir="${classes.dir}" classpathref="class.path" />
</target>
<target name="resource.copy">
<copy todir="${classes.dir}">
<fileset dir="${src.dir}">
<exclude name="**/*.java" />
</fileset>
</copy>
</target>
<target name="lib.copy">
<copy todir="${jar.dir}/lib" overwrite="true">
<fileset dir="${basedir}/lib">
<exclude name="**/*dll" />
</fileset>
</copy>
<copy todir="${jar.dir}/library" overwrite="true">
<fileset dir="${basedir}/library">
<exclude name="**/*dll" />
</fileset>
</copy>
<copy todir="${jar.dir}" overwrite="true">
<fileset dir="${basedir}/lib/" includes="**/*.dll" />
</copy>
</target>
<path id="class.path">
<fileset dir="${basedir}">
<include name="lib/**/*.jar" />
<include name="library/**/*.jar" />
</fileset>
</path>
<manifestclasspath jarfile="${ant.project.name}.jar" property="manifest.class.path">
<classpath refid="class.path" />
</manifestclasspath>
<target name="jar" depends="clean, lib.copy, resource.copy, compile">
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
<manifest>
<attribute name="Built-By" value="${user.name}" />
<attribute name="Class-Path" value="${manifest.class.path}" />
</manifest>
</jar>
<copy todir="../diylc-swing/lib" overwrite="true">
<fileset dir="${jar.dir}" includes="${ant.project.name}.jar" />
</copy>
<copy todir="../diylc-library/lib" overwrite="true">
<fileset dir="${jar.dir}" includes="${ant.project.name}.jar" />
</copy>
</target>
<target name="javadoc">
<javadoc access="public" author="true" classpathref="class.path" destdir="doc" nodeprecated="false" nodeprecatedlist="false" noindex="false" nonavbar="false" notree="false" source="1.6" splitindex="true" use="true" version="true">
<fileset dir="${src.dir}">
<exclude name="**\.svn\**" />
<include name="**/*.java" />
</fileset>
</javadoc>
</target>
</project>
-2
View File
@@ -1,2 +0,0 @@
#org.diylc.utils.Constants.CANVAS_COLOR=#005D96
#org.diylc.utils.Constants.GRID_COLOR=#FFFFFF
Binary file not shown.
Binary file not shown.
@@ -1,88 +0,0 @@
package org.diylc.common;
import javax.swing.Icon;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
/**
* Entity class used to describe a component type.
*
* @author Branislav Stojkovic
*
* @see IDIYComponent
*/
public class ComponentType {
private String name;
private String description;
private CreationMethod creationMethod;
private String category;
private String namePrefix;
private String author;
private Icon icon;
private Class<? extends IDIYComponent<?>> instanceClass;
private double zOrder;
private boolean stretchable;
public ComponentType(String name, String description, CreationMethod creationMethod,
String category, String namePrefix, String author, Icon icon,
Class<? extends IDIYComponent<?>> instanceClass, double zOrder, boolean stretchable) {
super();
this.name = name;
this.description = description;
this.creationMethod = creationMethod;
this.category = category;
this.namePrefix = namePrefix;
this.author = author;
this.icon = icon;
this.instanceClass = instanceClass;
this.zOrder = zOrder;
this.stretchable = stretchable;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public CreationMethod getCreationMethod() {
return creationMethod;
}
public String getCategory() {
return category;
}
public String getNamePrefix() {
return namePrefix;
}
public String getAuthor() {
return author;
}
public Icon getIcon() {
return icon;
}
public Class<? extends IDIYComponent<?>> getInstanceClass() {
return instanceClass;
}
public double getZOrder() {
return zOrder;
}
public boolean isStretchable() {
return stretchable;
}
@Override
public String toString() {
return name;
}
}
@@ -1,11 +0,0 @@
package org.diylc.common;
public enum Display {
NAME, VALUE;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -1,6 +0,0 @@
package org.diylc.common;
public enum GridType {
LINES, CROSSHAIR, DOT, NONE;
}
@@ -1,5 +0,0 @@
package org.diylc.common;
public enum HorizontalAlignment {
LEFT, CENTER, RIGHT
}
@@ -1,8 +0,0 @@
package org.diylc.common;
import org.diylc.core.IDIYComponent;
public interface IComponentFiler {
boolean testComponent(IDIYComponent<?> component);
}
@@ -1,68 +0,0 @@
package org.diylc.common;
import java.awt.Point;
public interface IMouseProcessor {
/**
* Notifies the presenter that mouse is clicked.
*
* Note: point coordinates are display based, i.e. scaled for zoom factor.
*
* @param point
* @param ctrlDown
* @param shiftDown
* @param altDown
* @param clickCount
*/
void mouseClicked(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown,
int clickCount);
/**
* Notifies the presenter that mouse is moved.
*
* Note: point coordinates are display based, i.e. scaled for zoom factor.
*
* @param point
* @param ctrlDown
* @param shiftDown
* @param altDown
*/
void mouseMoved(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown);
/**
* Notification that drag has been started from the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @param dragAction
*/
void dragStarted(Point point, int dragAction);
/**
* Checks if it's possible to drop over the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @return
*/
boolean dragOver(Point point);
/**
* Changes the current drag action during the dragging.
*
* @param dragAction
*/
void dragActionChanged(int dragAction);
/**
* Notification that drag has been ended in the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
*/
void dragEnded(Point point);
}
@@ -1,298 +0,0 @@
package org.diylc.common;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.diylc.appframework.simplemq.IMessageListener;
import org.diylc.appframework.simplemq.MessageDispatcher;
import org.diylc.appframework.update.VersionNumber;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.Theme;
/**
* Interface for communication between plug-ins and the application. Plug-ins
* may acquire information or make changes through this interface. Application
* events are dispatched to plug-ins through {@link MessageDispatcher}
*
* @author Branislav Stojkovic
*
* @see IPlugIn
* @see MessageDispatcher
* @see IMessageListener
* @see EventType
*/
public interface IPlugInPort extends ISelectionProcessor, IMouseProcessor {
public static final String ANTI_ALIASING_KEY = "antiAliasing";
public static final String HI_QUALITY_RENDER_KEY = "hiQualityRender";
public static final String EXPORT_GRID_KEY = "exportGrid";
public static final String STICKY_POINTS_KEY = "stickyPoints";
public static final String METRIC_KEY = "metric";
public static final String SNAP_TO_GRID_KEY = "snapToGrid";
public static final String AUTO_PADS_KEY = "autoCreatePads";
public static final String CONTINUOUS_CREATION_KEY = "continuousCreation";
public static final String AUTO_EDIT_KEY = "autoEdit";
public static final String ABNORMAL_EXIT_KEY = "abnormalExit";
public static final String WHEEL_ZOOM_KEY = "wheelZoom";
public static final String OUTLINE_KEY = "outline";
public static final String THEME_KEY = "theme";
public static final String RECENT_COMPONENTS_KEY = "recentComponents";
public static final int DND_TOGGLE_STICKY = 0x1;
public static final int DND_TOGGLE_SNAP = 0x40000000;
/**
* Returns size of the canvas that takes project dimensions into account as
* well as zoom level. Each dimension is calculated as the product of the
* actual size and the number of pixels per unit. If <code>useZoom</code> is
* set to true, the result is scaled by zoom factor.
*
* @param useZoom
*
* @return canvas dimensions
*/
Dimension getCanvasDimensions(boolean useZoom);
/**
* Returns an instance of {@link Cursor} that should be used at the
* specified location.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @return cursor
*/
Cursor getCursorAt(Point point);
/**
* Returns an instance of currently loaded project.
*
* @return
*/
Project getCurrentProject();
/**
* Loads specified {@link Project}.
*
* @param project
* @param freshStart
*/
void loadProject(Project project, boolean freshStart);
/**
* Creates a new project.
*/
void createNewProject();
/**
* Loads a project from the specified file.
*
* @param fileName
*/
void loadProjectFromFile(String fileName);
/**
* Saves the current project into the specified file.
*
* @param fileName
* @param isBackup
*/
void saveProjectToFile(String fileName, boolean isBackup);
/**
* @return the current file name.
*/
String getCurrentFileName();
/**
* @return true if the current project is modified.
*/
boolean isProjectModified();
/**
* Shows a user dialog if there are changes to confirm that it's safe to
* proceed.
*
* @return true, if file actions (new, open, close) can be taken
*/
boolean allowFileAction();
/**
* Returns all available {@link ComponentType}s classified by category.
* Result is a {@link Map} between category name to a {@link List} of all
* {@link ComponentType}s that share that category name.
*
* @return
*/
Map<String, List<ComponentType>> getComponentTypes();
/**
* Draws project on the provided {@link Graphics2D}. If the provided filter
* is not null, it will be used to filter the components that are shown.
*
* @param g2d
* @param drawOptions
* specific drawing options
* @param filter
*/
void draw(Graphics2D g2d, Set<DrawOption> drawOptions, IComponentFiler filter);
Double[] getAvailableZoomLevels();
/**
* Returns current zoom level where <code>zoomLevel = 1.0d</code> means
* 100%.
*
* @return current zoom level
*/
double getZoomLevel();
/**
* Changes current zoom level where <code>zoomLevel = 1.0d</code> means 100%
*
* @param zoomLevel
* new zoom leve
*/
void setZoomLevel(double zoomLevel);
/**
* Returns current version number.
*
* @return
*/
VersionNumber getCurrentVersionNumber();
/**
* Adds a list of components to the project.
*
* @param components
*/
void pasteComponents(List<IDIYComponent<?>> components);
/**
* Deletes all the selected components from the project.
*/
void deleteSelectedComponents();
/**
* Sets default value for the specified property name for currently selected
* component types.
*
* @param propertyName
* display name for property
* @param value
* new default value, must not be null
*/
void setSelectionDefaultPropertyValue(String propertyName, Object value);
/**
* Sets default value for the specified property name for projects.
*
* @param propertyName
* display name for property
* @param value
* new default value, must not be null
*/
void setProjectDefaultPropertyValue(String propertyName, Object value);
/**
* @return a list of properties that are mutual for all the selected
* components. Resulting list may be empty if selected components do
* not have mutual properties or can be null if the selection is
* empty.
*/
List<PropertyWrapper> getMutualSelectionProperties();
void editSelection();
/**
* @return a list of editable properties of the current project.
*/
List<PropertyWrapper> getProjectProperties();
/**
* Applies specified properties to the current project.
*
* @param properties
*/
void applyPropertiesToProject(List<PropertyWrapper> properties);
/**
* Sets the new component slot. Specified component type will be used to
* instantiate new component.
*/
void setNewComponentTypeSlot(ComponentType componentType);
/**
* Changes default size notation, true for metric, false for imperial.
*
* @param isMetric
*/
void setMetric(boolean isMetric);
/**
* Groups all selected components.
*/
void groupSelectedComponents();
/**
* Ungroups all selected components.
*/
void ungroupSelectedComponents();
/**
* Locks or unlocks the specified layer. All components within +- 0.5 range
* will be affected by the change as well.
*
* @param layerZOrder
* @param locked
*/
void setLayerLocked(int layerZOrder, boolean locked);
/**
* @return selection size expressed in either inches or centimeters, based
* on the user preference.
*/
Point2D calculateSelectionDimension();
/**
* Sends each of the selected components one step back.
*/
void sendSelectionToBack();
/**
* Brings each of the selected components one step to front.
*/
void bringSelectionToFront();
/**
* Causes the display to refresh.
*/
void refresh();
/**
* @return currently selected theme.
*/
Theme getSelectedTheme();
/**
* Changes the current theme.
*
* @param theme
*/
void setSelectedTheme(Theme theme);
/**
* Renumbers all the selected components.
*
* @param xAxisFirst
*/
void renumberSelectedComponents(boolean xAxisFirst);
}
@@ -1,39 +0,0 @@
package org.diylc.common;
import java.awt.Point;
import java.util.List;
import org.diylc.core.IDIYComponent;
public interface ISelectionProcessor {
/**
* Returns the current {@link ComponentTransferable}.
*
* @return
*/
List<IDIYComponent<?>> getSelectedComponents();
/**
* Updates the selection with the specified list of component. Also, updates
* control point map with all components that are stuck to the newly
* selected components.
*
* @param newSelection
*/
void updateSelection(List<IDIYComponent<?>> newSelection);
/**
* Finds all components at the specified location, sorted by z-index from
* top to bottom.
*
* @param point
* @return
*/
List<IDIYComponent<?>> findComponentsAt(Point point);
/**
* Selects all components in the project.
*/
void selectAll();
}
@@ -1,34 +0,0 @@
package org.diylc.common;
/**
* Abstract layer between the app and platform worker thread implementation.
*
* @author Branislav Stojkovic
*
* @param <T>
*/
public interface ITask<T> {
/**
* Runs in background thread.
*
* @return
* @throws Exception
*/
T doInBackground() throws Exception;
/**
* Called if background thread fails.
*
* @param e
*/
void failed(Exception e);
/**
* Called if background thread is executed correctly, the result is passed
* as a parameter.
*
* @param result
*/
void complete(T result);
}
@@ -1,11 +0,0 @@
package org.diylc.common;
public enum LabelPosition {
ABOVE, BELOW;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -1,39 +0,0 @@
package org.diylc.common;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Stroke;
import java.util.HashMap;
import java.util.Map;
/**
* Repository for object that may be reused, such as {@link Stroke} or
* {@link AlphaComposite}.
*
* @author Branislav Stojkovic
*/
public class ObjectCache {
private static ObjectCache instance;
public static ObjectCache getInstance() {
if (instance == null) {
instance = new ObjectCache();
}
return instance;
}
private ObjectCache() {
}
private Map<Integer, Stroke> basicStrokeMap = new HashMap<Integer, Stroke>();
public Stroke fetchBasicStroke(int width) {
if (basicStrokeMap.containsKey(width)) {
return basicStrokeMap.get(width);
}
Stroke stroke = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
basicStrokeMap.put(width, stroke);
return stroke;
}
}
@@ -1,15 +0,0 @@
package org.diylc.common;
public enum Orientation {
DEFAULT, _90, _180, _270;
@Override
public String toString() {
if (this == DEFAULT) {
return "Default";
} else {
return name().replace("_", "") + " degrees clockwise";
}
}
}
@@ -1,11 +0,0 @@
package org.diylc.common;
public enum OrientationHV {
VERTICAL, HORIZONTAL;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -1,14 +0,0 @@
package org.diylc.common;
public enum ResistorColorCode {
NONE, _4_BAND, _5_BAND;
@Override
public String toString() {
if (name().startsWith("_")) {
return name().substring(1).replace("_", " ").toLowerCase();
}
return name().substring(0, 1).toUpperCase() + name().substring(1).toLowerCase();
}
}
@@ -1,5 +0,0 @@
package org.diylc.common;
public enum VerticalAlignment {
TOP, CENTER, BOTTOM
}
@@ -1,119 +0,0 @@
package org.diylc.components;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import org.diylc.common.HorizontalAlignment;
import org.diylc.common.VerticalAlignment;
import org.diylc.core.IDIYComponent;
import org.diylc.core.annotations.EditableProperty;
/**
* Abstract implementation of {@link IDIYComponent} that contains component name
* and toString.
*
* @author Branislav Stojkovic
*
* @param <T>
*/
public abstract class AbstractComponent<T> implements IDIYComponent<T> {
private static final long serialVersionUID = 1L;
protected String name = "";
public static Color SELECTION_COLOR = Color.red;
public static Color LABEL_COLOR = Color.black;
public static Color LABEL_COLOR_SELECTED = Color.red;
public static Font LABEL_FONT = new Font("Tahoma", Font.PLAIN, 14);
@EditableProperty(defaultable = false)
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
}
@Override
public String toString() {
return name;
}
/**
* Returns the closest odd number, i.e. x when x is odd, or x + 1 when x is
* even.
*
* @param x
* @return
*/
protected int getClosestOdd(double x) {
return ((int) x / 2) * 2 + 1;
}
/**
* @param clip
* @return true if none of the control points lie in the clip rectangle.
*/
protected boolean checkPointsClipped(Shape clip) {
for (int i = 0; i < getControlPointCount(); i++) {
if (clip.contains(getControlPoint(i))) {
return false;
}
}
return true;
}
protected void drawCenteredText(Graphics2D g2d, String text, int x, int y,
HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle stringBounds = fontMetrics.getStringBounds(text, g2d).getBounds();
Font font = g2d.getFont();
FontRenderContext renderContext = g2d.getFontRenderContext();
GlyphVector glyphVector = font.createGlyphVector(renderContext, text);
Rectangle visualBounds = glyphVector.getVisualBounds().getBounds();
int textX = 0;
switch (horizontalAlignment) {
case CENTER:
textX = x - stringBounds.width / 2;
break;
case LEFT:
textX = x;
break;
case RIGHT:
textX = x - stringBounds.width;
break;
}
int textY = 0;
switch (verticalAlignment) {
case TOP:
textY = y + stringBounds.height;
break;
case CENTER:
textY = y - visualBounds.height / 2 - visualBounds.y;
break;
case BOTTOM:
textY = y - visualBounds.y;
break;
}
g2d.drawString(text, textX, textY);
}
}
@@ -1,249 +0,0 @@
package org.diylc.components;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.CubicCurve2D;
import org.diylc.common.ObjectCache;
import org.diylc.core.ComponentState;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
public abstract class AbstractCurvedComponent<T> extends AbstractTransparentComponent<T> {
private static final long serialVersionUID = 1L;
public static Color GUIDELINE_COLOR = Color.blue;
public static Size DEFAULT_SIZE = new Size(1d, SizeUnit.in);
protected Point[] controlPoints = new Point[] {
new Point(0, 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), (int) (DEFAULT_SIZE
.convertToPixels())),
new Point((int) DEFAULT_SIZE.convertToPixels(), (int) DEFAULT_SIZE.convertToPixels()) };
protected Color color = getDefaultColor();
protected PointCount pointCount = PointCount.FOUR;
/**
* Draws the specified curve onto graphics.
*
* @param curve
* @param g2d
* @param componentState
* @param theme
*/
protected abstract void drawCurve(CubicCurve2D curve, Graphics2D g2d,
ComponentState componentState);
/**
* @return default color.
*/
protected abstract Color getDefaultColor();
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(getDefaultColor().darker());
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(3));
CubicCurve2D curve = new CubicCurve2D.Double(1, height - 1, width / 4, height / 3,
3 * width / 4, 2 * height / 3, width - 1, 1);
g2d.draw(curve);
g2d.setColor(getDefaultColor());
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
g2d.draw(curve);
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
if (checkPointsClipped(g2d.getClip())) {
return;
}
if (componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING) {
// Do not track guidelines.
drawingObserver.stopTracking();
g2d.setStroke(Constants.DASHED_STROKE);
g2d.setColor(GUIDELINE_COLOR);
g2d.drawLine(controlPoints[0].x, controlPoints[0].y, controlPoints[1].x,
controlPoints[1].y);
g2d.drawLine(controlPoints[1].x, controlPoints[1].y, controlPoints[2].x,
controlPoints[2].y);
g2d.drawLine(controlPoints[2].x, controlPoints[2].y, controlPoints[3].x,
controlPoints[3].y);
drawingObserver.startTracking();
}
CubicCurve2D curve = new CubicCurve2D.Double(controlPoints[0].x, controlPoints[0].y,
controlPoints[1].x, controlPoints[1].y, controlPoints[2].x, controlPoints[2].y,
controlPoints[3].x, controlPoints[3].y);
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
// g2d.setColor(color.darker());
// g2d.setStroke(new BasicStroke(thickness));
// g2d.draw(path);
// g2d.setColor(color);
// g2d.setStroke(new BasicStroke(thickness - 2));
// g2d.draw(path);
drawCurve(curve, g2d, componentState);
g2d.setComposite(oldComposite);
}
@EditableProperty(name = "Point Count")
public PointCount getPointCount() {
if (pointCount == null) {
pointCount = PointCount.FOUR;
}
return pointCount;
}
public void setPointCount(PointCount pointCount) {
this.pointCount = pointCount;
// Reset control points.
for (int i = 0; i < getControlPointCount(); i++) {
setControlPoint(getControlPoint(i), i);
}
}
@Override
public int getControlPointCount() {
switch (getPointCount()) {
case TWO:
return 2;
case THREE:
return 3;
case FOUR:
return 4;
}
return 0;
}
@Override
public boolean isControlPointSticky(int index) {
return index == 0 || index == getControlPointCount() - 1;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public boolean canControlPointOverlap(int index) {
// Only shape control points may overlap.
switch (getPointCount()) {
case TWO:
return false;
case THREE:
return index == 1;
case FOUR:
return index == 1 || index == 2;
}
return false;
}
@Override
public Point getControlPoint(int index) {
if (index == 0) {
return controlPoints[0];
}
switch (getPointCount()) {
case TWO:
switch (index) {
case 1:
return controlPoints[3];
}
case THREE:
switch (index) {
case 1:
return controlPoints[1];
case 2:
return controlPoints[3];
}
case FOUR:
switch (index) {
case 1:
return controlPoints[1];
case 2:
return controlPoints[2];
case 3:
return controlPoints[3];
}
}
return controlPoints[index];
}
@Override
public void setControlPoint(Point point, int index) {
if (index == 0) {
controlPoints[0].setLocation(point);
} else {
switch (getPointCount()) {
case TWO:
switch (index) {
case 1:
Point center = new Point((point.x + controlPoints[0].x) / 2,
(point.y + controlPoints[0].y) / 2);
controlPoints[1].setLocation(center);
controlPoints[2].setLocation(center);
controlPoints[3].setLocation(point);
break;
}
break;
case THREE:
switch (index) {
case 1:
controlPoints[1].setLocation(point);
controlPoints[2].setLocation(point);
break;
case 2:
controlPoints[3].setLocation(point);
break;
}
break;
case FOUR:
switch (index) {
case 1:
controlPoints[1].setLocation(point);
break;
case 2:
controlPoints[2].setLocation(point);
break;
case 3:
controlPoints[3].setLocation(point);
break;
}
break;
}
}
}
@EditableProperty
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
enum PointCount {
TWO, THREE, FOUR;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
}
@@ -1,350 +0,0 @@
package org.diylc.components;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import org.diylc.appframework.miscutils.ConfigurationManager;
import org.diylc.common.Display;
import org.diylc.common.IPlugInPort;
import org.diylc.common.ObjectCache;
import org.diylc.core.ComponentState;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
/**
* Base class for all leaded components such as resistors or capacitors. Has two
* control points and draws leads between them. Also, it positions and draws the
* shape of the component as specified by a child class.
*
* @author Branislav Stojkovic
*/
public abstract class AbstractLeadedComponent<T> extends AbstractTransparentComponent<T> {
private static final long serialVersionUID = 1L;
public static Color LEAD_COLOR = Color.decode("#236B8E");
public static Size LEAD_THICKNESS = new Size(0.6d, SizeUnit.mm);
public static Size DEFAULT_SIZE = new Size(1d, SizeUnit.in);
protected Size length;
protected Size width;
protected Point[] points = new Point[] {
new Point((int) (-DEFAULT_SIZE.convertToPixels() / 2), 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), 0) };
protected Color bodyColor = Color.white;
protected Color borderColor = Color.black;
protected Color labelColor = LABEL_COLOR;
protected Display display = Display.VALUE;
protected AbstractLeadedComponent() {
super();
try {
this.length = getDefaultLength().clone();
this.width = getDefaultWidth().clone();
} catch (CloneNotSupportedException e) {
// This should never happen because Size supports cloning.
} catch (NullPointerException e) {
// This will happen if components do not have any shape.
}
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
double distance = points[0].distance(points[1]);
Shape shape = getBodyShape();
// If there's no body, just draw the line connecting the ending points.
if (shape == null) {
drawLead(g2d, componentState);
} else if (supportsStandingMode()
&& length.convertToPixels() > points[0].distance(points[1])) {
// When ending points are too close draw the component in standing
// mode.
int width = getClosestOdd(this.width.convertToPixels());
Shape body = new Ellipse2D.Double(points[0].x - width / 2, points[0].y - width / 2,
width, width);
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
g2d.setColor(outlineMode ? Constants.TRANSPARENT_COLOR : bodyColor);
g2d.fill(body);
g2d.setComposite(oldComposite);
Color finalBorderColor;
if (outlineMode) {
Theme theme = (Theme) ConfigurationManager.getInstance().readObject(
IPlugInPort.THEME_KEY, Constants.DEFAULT_THEME);
finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : theme
.getOutlineColor();
} else {
finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: borderColor;
}
g2d.setColor(finalBorderColor);
g2d.draw(body);
if (!outlineMode) {
drawLead(g2d, componentState);
}
} else {
// Normal mode with component body in the center and two lead parts.
Rectangle shapeRect = shape.getBounds();
Double theta = Math.atan2(points[1].y - points[0].y, points[1].x - points[0].x);
// Transform graphics to draw the body in the right place and at the
// right angle.
AffineTransform oldTransform = g2d.getTransform();
g2d.translate((points[0].x + points[1].x - shapeRect.width) / 2, (points[0].y
+ points[1].y - shapeRect.height) / 2);
g2d.rotate(theta, shapeRect.width / 2, shapeRect.height / 2);
// Draw body.
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
if (bodyColor != null) {
if (bodyColor != null) {
g2d.setColor(outlineMode ? Constants.TRANSPARENT_COLOR : bodyColor);
g2d.fill(shape);
}
}
decorateComponentBody(g2d, outlineMode);
g2d.setComposite(oldComposite);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
Color finalBorderColor;
if (outlineMode) {
Theme theme = (Theme) ConfigurationManager.getInstance().readObject(
IPlugInPort.THEME_KEY, Constants.DEFAULT_THEME);
finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : theme
.getOutlineColor();
} else {
finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: borderColor;
}
g2d.setColor(finalBorderColor);
g2d.draw(shape);
// Go back to the original transformation to draw leads.
if (!outlineMode) {
AffineTransform textTransform = g2d.getTransform();
g2d.setTransform(oldTransform);
if (length.convertToPixels() > points[0].distance(points[1])) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
}
int leadThickness = getClosestOdd(getLeadThickness());
double leadLength = (distance - shapeRect.width) / 2 - leadThickness / 2;
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness));
Color leadColor = shouldShadeLeads() ? getLeadColor(componentState).darker()
: getLeadColor(componentState);
g2d.setColor(leadColor);
int endX = (int) (points[0].x + Math.cos(theta) * leadLength);
int endY = (int) Math.round(points[0].y + Math.sin(theta) * leadLength);
g2d.drawLine(points[0].x, points[0].y, endX, endY);
endX = (int) (points[1].x + Math.cos(theta - Math.PI) * leadLength);
endY = (int) Math.round(points[1].y + Math.sin(theta - Math.PI) * leadLength);
g2d.drawLine(points[1].x, points[1].y, endX, endY);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness - 2));
leadColor = getLeadColor(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, (int) (points[0].x + Math.cos(theta)
* leadLength), (int) (points[0].y + Math.sin(theta) * leadLength));
g2d.drawLine(points[1].x, points[1].y, (int) (points[1].x + Math.cos(theta
- Math.PI)
* leadLength), (int) (points[1].y + Math.sin(theta - Math.PI)
* leadLength));
}
g2d.setComposite(oldComposite);
g2d.setTransform(textTransform);
}
// Draw label.
g2d.setFont(LABEL_FONT);
Color finalLabelColor;
if (outlineMode) {
Theme theme = (Theme) ConfigurationManager.getInstance().readObject(
IPlugInPort.THEME_KEY, Constants.DEFAULT_THEME);
finalLabelColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? LABEL_COLOR_SELECTED : theme
.getOutlineColor();
} else {
finalLabelColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? LABEL_COLOR_SELECTED
: labelColor;
}
g2d.setColor(finalLabelColor);
FontMetrics fontMetrics = g2d.getFontMetrics();
String label = display == Display.NAME ? getName() : getValue().toString();
Rectangle2D textRect = fontMetrics.getStringBounds(label, g2d);
// Don't offset in outline mode.
int offset = outlineMode ? 0 : getLabelOffset((int) shapeRect.getWidth(), (int) textRect.getWidth());
// Adjust label angle if needed to make sure that it's readable.
if ((theta >= Math.PI / 2 && theta <= Math.PI)
|| (theta < -Math.PI / 2 && theta > -Math.PI)) {
g2d.rotate(Math.PI, shapeRect.width / 2, shapeRect.height / 2);
offset = -offset;
}
g2d.drawString(label, (int) (shapeRect.width - textRect.getWidth()) / 2 + offset,
calculateLabelYCoordinate(shapeRect, textRect, fontMetrics));
g2d.setTransform(oldTransform);
}
}
private void drawLead(Graphics2D g2d, ComponentState componentState) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(getLeadThickness()));
Color leadColor = shouldShadeLeads() ? getLeadColor(componentState).darker()
: getLeadColor(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(getLeadThickness() - 2));
leadColor = getLeadColor(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
}
}
protected void decorateComponentBody(Graphics2D g2d, boolean outlineMode) {
// Do nothing.
}
protected int calculateLabelYCoordinate(Rectangle2D shapeRect, Rectangle2D textRect,
FontMetrics fontMetrics) {
return (int) (shapeRect.getHeight() - textRect.getHeight()) / 2 + fontMetrics.getAscent();
}
protected boolean shouldShadeLeads() {
return true;
}
protected boolean supportsStandingMode() {
return false;
}
protected int getLabelOffset(int bodyWidth, int labelWidth) {
return 0;
}
/**
* @return default component length.
*/
protected abstract Size getDefaultLength();
/**
* Returns default component width.
*
* @return
*/
protected abstract Size getDefaultWidth();
/**
* @return shape that represents component body. Shape should not be
* transformed and should be referenced to (0, 0).
*/
protected abstract Shape getBodyShape();
/**
* @return default lead thickness. Override this method to change it.
*/
protected int getLeadThickness() {
return (int) LEAD_THICKNESS.convertToPixels();
}
/**
* @return default lead color. Override this method to change it.
*/
protected Color getLeadColor(ComponentState componentState) {
return componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : LEAD_COLOR;
}
@Override
public int getControlPointCount() {
return points.length;
}
@Override
public Point getControlPoint(int index) {
return (Point) points[index];
}
@Override
public boolean isControlPointSticky(int index) {
return true;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.ALWAYS;
}
@Override
public void setControlPoint(Point point, int index) {
points[index].setLocation(point);
}
@EditableProperty(name = "Color")
public Color getBodyColor() {
return bodyColor;
}
public void setBodyColor(Color bodyColor) {
this.bodyColor = bodyColor;
}
@EditableProperty(name = "Border")
public Color getBorderColor() {
return borderColor;
}
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
@EditableProperty(name = "Length", defaultable = true)
public Size getLength() {
return length;
}
public void setLength(Size length) {
this.length = length;
}
@EditableProperty(name = "Width", defaultable = true)
public Size getWidth() {
return width;
}
public void setWidth(Size width) {
this.width = width;
}
@EditableProperty
public Display getDisplay() {
return display;
}
public void setDisplay(Display display) {
this.display = display;
}
}
@@ -1,72 +0,0 @@
package org.diylc.components;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.geom.Rectangle2D;
import org.diylc.common.LabelPosition;
import org.diylc.core.ComponentState;
import org.diylc.core.annotations.EditableProperty;
public abstract class AbstractSchematicLeadedSymbol<T> extends AbstractLeadedComponent<T> {
private static final long serialVersionUID = 1L;
public static Color COLOR = Color.blue;
public static Color LEAD_COLOR = Color.black;
protected LabelPosition labelPosition = LabelPosition.ABOVE;
public AbstractSchematicLeadedSymbol() {
super();
// We don't want to fill the body, so use null.
this.bodyColor = null;
this.borderColor = COLOR;
}
@Override
public Color getBodyColor() {
return super.getBodyColor();
}
@Override
protected boolean shouldShadeLeads() {
return false;
}
@Override
protected int getLeadThickness() {
return 1;
}
@Override
protected int calculateLabelYCoordinate(Rectangle2D shapeRect, Rectangle2D textRect,
FontMetrics fontMetrics) {
if (labelPosition == LabelPosition.ABOVE) {
return -1;
} else {
return (int) (shapeRect.getHeight() + textRect.getHeight() - 1);
}
}
@EditableProperty(name = "Label position")
public LabelPosition getLabelPosition() {
return labelPosition;
}
@Override
@EditableProperty(name = "Color")
public Color getBorderColor() {
return super.getBorderColor();
}
public void setLabelPosition(LabelPosition labelPosition) {
this.labelPosition = labelPosition;
}
@Override
protected Color getLeadColor(ComponentState componentState) {
return componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : LEAD_COLOR;
}
}
@@ -1,21 +0,0 @@
package org.diylc.components;
import org.diylc.core.annotations.EditableProperty;
public abstract class AbstractTransparentComponent<T> extends AbstractComponent<T> {
private static final long serialVersionUID = 1L;
public static byte MAX_ALPHA = 127;
protected byte alpha = MAX_ALPHA;
@EditableProperty
public Byte getAlpha() {
return alpha;
}
public void setAlpha(Byte alpha) {
this.alpha = alpha;
}
}
@@ -1,13 +0,0 @@
package org.diylc.core;
/**
* Validator that allows all values.
*
* @author Branislav Stojkovic
*/
public class AllowAllValidator implements IPropertyValidator {
@Override
public void validate(Object value) throws ValidationException {
}
}
@@ -1,6 +0,0 @@
package org.diylc.core;
public enum CreationMethod {
SINGLE_CLICK, POINT_BY_POINT;
}
@@ -1,122 +0,0 @@
package org.diylc.core;
import java.awt.Graphics2D;
import java.awt.Point;
import java.io.Serializable;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
/**
* Interface for component instance. Implementation classes of this interface
* will be instantiated by the application when component is added to the
* canvas. <br>
* <br>
* <b>Implementing classes should meet the following: </b>
* <ul>
* <li>Must have an empty constructor.</li>
* <li>Class should be annotated with {@link ComponentDescriptor}.</li>
* <li>Getters for properties editable by users should be annotated with
* {@link EditableProperty}.</li>
* <li>Component configuration should be stored int <code>public static</code>
* fields so they can be set through config file.</li>
* </ul>
*
* @author Branislav Stojkovic
*
* @param <T>
* type of component values, e.g. Resistance for resistors or String
* for transistors.
*/
public interface IDIYComponent<T> extends Serializable {
public static final int CHASSIS = 1;
public static final int BOARD = 2;
public static final int TRACE = 3;
public static final int COMPONENT = 4;
public static final int TEXT = 5;
/**
* @return component instance name.
*/
String getName();
/**
* Updates component instance name.
*
* @param name
*/
void setName(String name);
/**
* @return component value.
*/
T getValue();
/**
* Updates component value.
*
* @param value
*/
void setValue(T value);
/**
* @return number of control points for this component instance. May vary
* between two instances of the same type, e.g. DIL IC with 8 and 16
* pins will have 8 or 16 pins although they are of the same type.
*/
int getControlPointCount();
/**
* @param index
* @return control point at the specified index.
*/
Point getControlPoint(int index);
/**
* Updates the control point at the specified index.
*
* @param point
* @param index
*/
void setControlPoint(Point point, int index);
/**
* @param index
* @return true, if the specified control point may stick to control points
* of other components.
*/
boolean isControlPointSticky(int index);
/**
* @param index
* @return true, if the specified control point may overlap with other
* control points <b>of the same component</b>. The other control
* point must be able to overlap too.
*/
boolean canControlPointOverlap(int index);
VisibilityPolicy getControlPointVisibilityPolicy(int index);
/**
* Draws the component onto the {@link Graphics2D}.
*
* @param g2d
* @param componentState
* @param outlineMode
* @param project
* @param drawingObserver
*/
void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode, Project project,
IDrawingObserver drawingObserver);
/**
* Draws icon representation of the component. This should not depend on
* component state, i.e. it should be treated as a static method.
*
* @param g2d
* @param width
* @param height
*/
void drawIcon(Graphics2D g2d, int width, int height);
}
@@ -1,15 +0,0 @@
package org.diylc.core;
/**
* Interface for tracking component drawing process. Components may use it to
* stop or restart tracking. Anything drawn while tracking is stopped will not
* be added to the mouse hot-spot area.
*
* @author Branislav Stojkovic
*/
public interface IDrawingObserver {
void stopTracking();
void startTracking();
}
@@ -1,16 +0,0 @@
package org.diylc.core;
/**
* Interface for validating property value changes.
*
* @author Branislav Stojkovic
*/
public interface IPropertyValidator {
/**
* @param value
* @throws ValidationException
* if validation fails. Message will contain the reason.
*/
void validate(Object value) throws ValidationException;
}
-38
View File
@@ -1,38 +0,0 @@
package org.diylc.core;
import java.util.List;
import java.util.Set;
import org.diylc.common.PropertyWrapper;
/**
* Base interface for the main GUI component.
*
* @author Branislav Stojkovic
*/
public interface IView {
public static final int ERROR_MESSAGE = 0;
public static final int INFORMATION_MESSAGE = 1;
public static final int WARNING_MESSAGE = 2;
public static final int QUESTION_MESSAGE = 3;
public static final int PLAIN_MESSAGE = -1;
public static final int DEFAULT_OPTION = -1;
public static final int YES_NO_OPTION = 0;
public static final int YES_NO_CANCEL_OPTION = 1;
public static final int OK_CANCEL_OPTION = 2;
public static final int YES_OPTION = 0;
public static final int NO_OPTION = 1;
public static final int CANCEL_OPTION = 2;
public static final int OK_OPTION = 0;
public static final String CHECK_BOX_MENU_ITEM = "org.diylc.checkBoxMenuItem";
public static final String RADIO_BUTTON_GROUP_KEY = "org.diylc.radioButtonGroup";
void showMessage(String message, String title, int messageType);
int showConfirmDialog(String message, String title, int optionType, int messageType);
boolean editProperties(List<PropertyWrapper> properties, Set<PropertyWrapper> defaultedProperties);
}
-86
View File
@@ -1,86 +0,0 @@
package org.diylc.core;
import java.awt.Color;
import java.io.Serializable;
public class Theme implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Color bgColor;
private Color gridColor;
private Color outlineColor;
public Theme(String name, Color bgColor, Color gridColor, Color outlineColor) {
super();
this.name = name;
this.bgColor = bgColor;
this.gridColor = gridColor;
this.outlineColor = outlineColor;
}
public String getName() {
return name;
}
public Color getBgColor() {
return bgColor;
}
public Color getGridColor() {
return gridColor;
}
public Color getOutlineColor() {
return outlineColor;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bgColor == null) ? 0 : bgColor.hashCode());
result = prime * result + ((gridColor == null) ? 0 : gridColor.hashCode());
result = prime * result + ((outlineColor == null) ? 0 : outlineColor.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Theme other = (Theme) obj;
if (bgColor == null) {
if (other.bgColor != null)
return false;
} else if (!bgColor.equals(other.bgColor))
return false;
if (gridColor == null) {
if (other.gridColor != null)
return false;
} else if (!gridColor.equals(other.gridColor))
return false;
if (outlineColor == null) {
if (other.outlineColor != null)
return false;
} else if (!outlineColor.equals(other.outlineColor))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return name;
}
}
@@ -1,11 +0,0 @@
package org.diylc.core;
public class ValidationException extends Exception {
private static final long serialVersionUID = 1L;
public ValidationException(String message) {
super(message);
}
}
@@ -1,62 +0,0 @@
package org.diylc.core.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
/**
* Annotation for {@link IDIYComponent} implementation. Describes component
* properties.
*
* @author Branislav Stojkovic
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ComponentDescriptor {
/**
* @return component type name.
*/
String name();
/**
* @return component type description.
*/
String description();
/**
* @return method that should be used to create a component. If
* <code>CreationMethod.POINT_BY_POINT</code> is used, user will
* have to select ending points before the component is created.
*/
CreationMethod creationMethod() default CreationMethod.SINGLE_CLICK;
/**
* @return component category, e.g. "Passive", "Semiconductors", etc.
*/
String category();
/**
* @return component author name.
*/
String author();
/**
* @return prefix that will be used to generate component instance names,
* e.g. "R" for resistors or "Q" for transistors.
*/
String instanceNamePrefix();
/**
* @return Z-order of the component.
*/
double zOrder();
/**
* @return when false, moving one control point will cause all the others to
* move together with it.
*/
boolean stretchable() default true;
}
@@ -1,20 +0,0 @@
package org.diylc.core.annotations;
import org.diylc.core.IPropertyValidator;
import org.diylc.core.ValidationException;
import org.diylc.core.measures.AbstractMeasure;
public class PositiveMeasureValidator implements IPropertyValidator {
@Override
public void validate(Object value) throws ValidationException {
if (value instanceof AbstractMeasure) {
AbstractMeasure measure = (AbstractMeasure) value;
if (measure.getValue() < 0) {
throw new ValidationException("must be greater than zero.");
}
} else {
throw new ValidationException("wrong data type, measure expected.");
}
}
}
@@ -1,31 +0,0 @@
package org.diylc.core.measures;
public class Capacitance extends AbstractMeasure<CapacitanceUnit> {
private static final long serialVersionUID = 1L;
public Capacitance() {
super();
// TODO Auto-generated constructor stub
}
public Capacitance(Double value, CapacitanceUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Capacitance clone() throws CloneNotSupportedException {
return new Capacitance(value, unit);
}
public static Capacitance parseCapacitance(String value) {
for (CapacitanceUnit unit : CapacitanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Capacitance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse capacitance: " + value);
}
}
@@ -1,31 +0,0 @@
package org.diylc.core.measures;
public class Inductance extends AbstractMeasure<InductanceUnit> {
private static final long serialVersionUID = 1L;
public Inductance() {
super();
// TODO Auto-generated constructor stub
}
public Inductance(Double value, InductanceUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Inductance clone() throws CloneNotSupportedException {
return new Inductance(value, unit);
}
public static Inductance parseCapacitance(String value) {
for (InductanceUnit unit : InductanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Inductance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse inductance: " + value);
}
}
@@ -1,31 +0,0 @@
package org.diylc.core.measures;
public class Power extends AbstractMeasure<PowerUnit> {
private static final long serialVersionUID = 1L;
public Power() {
super();
// TODO Auto-generated constructor stub
}
public Power(Double value, PowerUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Power clone() throws CloneNotSupportedException {
return new Power(value, unit);
}
public static Power parseCapacitance(String value) {
for (PowerUnit unit : PowerUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Power(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse power: " + value);
}
}
@@ -1,24 +0,0 @@
package org.diylc.core.measures;
public enum PowerUnit implements Unit {
MW(1e-1, "mW"), W(1, "W"), KW(1e3, "KW");
double factor;
String display;
private PowerUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
@Override
public double getFactor() {
return factor;
}
@Override
public String toString() {
return display;
}
}
@@ -1,78 +0,0 @@
package org.diylc.core.measures;
import java.awt.Color;
import org.diylc.common.ResistorColorCode;
public class Resistance extends AbstractMeasure<ResistanceUnit> {
private static final long serialVersionUID = 1L;
private static final Color[] COLOR_DIGITS = new Color[] { Color.black, Color.decode("#8B4513"),
Color.red, Color.orange, Color.yellow, Color.decode("#76EE00"), Color.blue,
Color.decode("#91219E"), Color.lightGray, Color.white };
private static final Color[] COLOR_MULTIPLIER = new Color[] { Color.lightGray.brighter(),
Color.decode("#FFB90F"), Color.black, Color.decode("#8B4513"), Color.red, Color.orange,
Color.yellow, Color.decode("#76EE00"), Color.blue };
public Resistance() {
super();
// TODO Auto-generated constructor stub
}
public Resistance(Double value, ResistanceUnit multiplier) {
super(value, multiplier);
// TODO Auto-generated constructor stub
}
@Override
public Resistance clone() throws CloneNotSupportedException {
return new Resistance(value, unit);
}
public Color[] getColorCode(ResistorColorCode resistorColorCode) {
Color[] bands;
double base = getValue() * getUnit().getFactor();
int multiplier = 0;
while (base > (resistorColorCode == ResistorColorCode._4_BAND ? 99 : 999)) {
multiplier += 1;
base /= 10;
}
while (base < (resistorColorCode == ResistorColorCode._4_BAND ? 10 : 100)) {
multiplier -= 1;
base *= 10;
}
if (multiplier > 6 || multiplier < -2) {
// Out of range.
return new Color[] {};
}
switch (resistorColorCode) {
case _4_BAND:
bands = new Color[3];
bands[0] = COLOR_DIGITS[(int) (base / 10)];
bands[1] = COLOR_DIGITS[(int) (base % 10)];
bands[2] = COLOR_MULTIPLIER[multiplier + 2];
break;
case _5_BAND:
bands = new Color[4];
bands[0] = COLOR_DIGITS[(int) (base / 100)];
bands[1] = COLOR_DIGITS[(int) (base / 10 % 10)];
bands[2] = COLOR_DIGITS[(int) (base % 10)];
bands[3] = COLOR_MULTIPLIER[multiplier + 2];
break;
default:
bands = new Color[] {};
}
return bands;
}
public static Resistance parseResistance(String value) {
for (ResistanceUnit unit : ResistanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length()).trim();
return new Resistance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse resistance: " + value);
}
}
@@ -1,47 +0,0 @@
package org.diylc.core.measures;
import org.diylc.utils.Constants;
public class Size extends AbstractMeasure<SizeUnit> implements Comparable<Size> {
private static final long serialVersionUID = 1L;
public Size() {
super();
// TODO Auto-generated constructor stub
}
public Size(Double value, SizeUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
public double convertToPixels() {
// double factor = getUnit().getFactor() / SizeUnit.in.getFactor();
// int grids = (int) (factor * getValue() * Constants.GRIDS_PER_INCH);
// double remainder = (factor * getValue() * Constants.GRIDS_PER_INCH) - grids;
// return (int) Math.round(Constants.PIXELS_PER_INCH / Constants.GRIDS_PER_INCH
// * (grids + remainder));
return getValue() * getUnit().getFactor() / SizeUnit.in.getFactor() * Constants.PIXELS_PER_INCH;
}
@Override
public Size clone() throws CloneNotSupportedException {
return new Size(value, unit);
}
public static Size parseSize(String value) {
for (SizeUnit unit : SizeUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Size(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse size: " + value);
}
@Override
public int compareTo(Size o) {
return new Double(value * unit.getFactor()).compareTo(o.getValue() * o.getUnit().getFactor());
}
}
@@ -1,31 +0,0 @@
package org.diylc.core.measures;
public class Voltage extends AbstractMeasure<VoltageUnit> {
private static final long serialVersionUID = 1L;
public Voltage() {
super();
// TODO Auto-generated constructor stub
}
public Voltage(Double value, VoltageUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Voltage clone() throws CloneNotSupportedException {
return new Voltage(value, unit);
}
public static Voltage parseCapacitance(String value) {
for (VoltageUnit unit : VoltageUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Voltage(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse voltage: " + value);
}
}
@@ -1,24 +0,0 @@
package org.diylc.core.measures;
public enum VoltageUnit implements Unit {
MV(1e-1, "mV"), V(1, "V"), KV(1e3, "KV");
double factor;
String display;
private VoltageUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
@Override
public double getFactor() {
return factor;
}
@Override
public String toString() {
return display;
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 537 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 850 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 901 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 765 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 845 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 697 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 771 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 990 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 535 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 771 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 898 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 833 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 922 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 838 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 550 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 826 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 388 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 883 B

@@ -1,25 +0,0 @@
package org.diylc.presenter;
import java.awt.Point;
import org.diylc.core.measures.Size;
public class CalcUtils {
/**
* Rounds the number to the closest grid line.
*
* @param x
* @return
*/
public static int roundToGrid(int x, Size gridSpacing) {
double grid = gridSpacing.convertToPixels();
return (int) (Math.round(1f * x / grid) * grid);
}
public static void snapPointToGrid(Point point, Size gridSpacing) {
int x = roundToGrid(point.x, gridSpacing);
int y = roundToGrid(point.y, gridSpacing);
point.setLocation(x, y);
}
}
@@ -1,88 +0,0 @@
package org.diylc.presenter;
import java.util.Comparator;
import org.diylc.common.ComponentType;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IDIYComponent;
public class ComparatorFactory {
private static ComparatorFactory instance;
private Comparator<IDIYComponent<?>> componentNameComparator;
private Comparator<ComponentType> componentTypeComparator;
private Comparator<PropertyWrapper> propertyNameComparator;
private Comparator<IDIYComponent<?>> componentZOrderComparator;
public static ComparatorFactory getInstance() {
if (instance == null) {
instance = new ComparatorFactory();
}
return instance;
}
public Comparator<IDIYComponent<?>> getComponentNameComparator() {
if (componentNameComparator == null) {
componentNameComparator = new Comparator<IDIYComponent<?>>() {
@Override
public int compare(IDIYComponent<?> o1, IDIYComponent<?> o2) {
String name1 = o1.getName();
String name2 = o2.getName();
if (name1 == null || name2 == null) {
return 0;
}
return name1.compareToIgnoreCase(name2);
}
};
}
return componentNameComparator;
}
public Comparator<ComponentType> getComponentTypeComparator() {
if (componentTypeComparator == null) {
componentTypeComparator = new Comparator<ComponentType>() {
@Override
public int compare(ComponentType o1, ComponentType o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
}
return componentTypeComparator;
}
public Comparator<PropertyWrapper> getPropertyNameComparator() {
if (propertyNameComparator == null) {
propertyNameComparator = new Comparator<PropertyWrapper>() {
@Override
public int compare(PropertyWrapper o1, PropertyWrapper o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
}
return propertyNameComparator;
}
public Comparator<IDIYComponent<?>> getComponentZOrderComparator() {
if (componentZOrderComparator == null) {
componentZOrderComparator = new Comparator<IDIYComponent<?>>() {
@Override
public int compare(IDIYComponent<?> o1, IDIYComponent<?> o2) {
ComponentType type1 = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) o1.getClass());
ComponentType type2 = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) o2.getClass());
return new Double(type1.getZOrder()).compareTo(type2.getZOrder());
}
};
}
return componentZOrderComparator;
}
}
@@ -1,225 +0,0 @@
package org.diylc.presenter;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.apache.log4j.Logger;
import org.diylc.common.ComponentType;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IPropertyValidator;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import com.rits.cloning.Cloner;
/**
* Utility class with component processing methods.
*
* @author Branislav Stojkovic
*/
public class ComponentProcessor {
private static final Logger LOG = Logger.getLogger(ComponentProcessor.class);
private static ComponentProcessor instance;
private Map<String, List<PropertyWrapper>> propertyCache;
private Map<String, IPropertyValidator> propertyValidatorCache;
private Map<String, ComponentType> componentTypeMap;
private Cloner cloner;
public static ComponentProcessor getInstance() {
if (instance == null) {
instance = new ComponentProcessor();
}
return instance;
}
private ComponentProcessor() {
super();
this.cloner = new Cloner();
this.propertyCache = new HashMap<String, List<PropertyWrapper>>();
this.componentTypeMap = new HashMap<String, ComponentType>();
this.propertyValidatorCache = new HashMap<String, IPropertyValidator>();
}
public ComponentType extractComponentTypeFrom(Class<? extends IDIYComponent<?>> clazz) {
if (componentTypeMap.containsKey(clazz.getName())) {
return componentTypeMap.get(clazz.getName());
}
String name;
String description;
CreationMethod creationMethod;
String category;
String namePrefix;
String author;
Icon icon;
double zOrder;
boolean stretchable;
if (clazz.isAnnotationPresent(ComponentDescriptor.class)) {
ComponentDescriptor annotation = clazz.getAnnotation(ComponentDescriptor.class);
name = annotation.name();
description = annotation.description();
creationMethod = annotation.creationMethod();
category = annotation.category();
namePrefix = annotation.instanceNamePrefix();
author = annotation.author();
zOrder = annotation.zOrder();
stretchable = annotation.stretchable();
} else {
name = clazz.getSimpleName();
description = "";
creationMethod = CreationMethod.SINGLE_CLICK;
category = "Uncategorized";
namePrefix = "Unknown";
author = "Unknown";
zOrder = IDIYComponent.COMPONENT;
stretchable = true;
}
icon = null;
// Draw component icon.
try {
IDIYComponent<?> componentInstance = (IDIYComponent<?>) clazz.newInstance();
Image image = new BufferedImage(Presenter.ICON_SIZE, Presenter.ICON_SIZE,
java.awt.image.BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) image.getGraphics();
g2d
.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
componentInstance.drawIcon(g2d, Presenter.ICON_SIZE, Presenter.ICON_SIZE);
icon = new ImageIcon(image);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ComponentType componentType = new ComponentType(name, description, creationMethod,
category, namePrefix, author, icon, clazz, zOrder, stretchable);
componentTypeMap.put(clazz.getName(), componentType);
return componentType;
}
/**
* Extracts all editable properties from the component class.
*
* @param clazz
* @return
*/
public List<PropertyWrapper> extractProperties(Class<?> clazz) {
if (propertyCache.containsKey(clazz.getName())) {
return cloner.deepClone(propertyCache.get(clazz.getName()));
}
List<PropertyWrapper> properties = new ArrayList<PropertyWrapper>();
for (Method method : clazz.getMethods()) {
if (method.getName().startsWith("get")) {
try {
if (method.isAnnotationPresent(EditableProperty.class)
&& !method.isAnnotationPresent(Deprecated.class)) {
EditableProperty annotation = method.getAnnotation(EditableProperty.class);
String name;
if (annotation.name().equals("")) {
name = method.getName().substring(3);
} else {
name = annotation.name();
}
IPropertyValidator validator = getPropertyValidator(annotation
.validatorClass());
Method setter = clazz.getMethod("set" + method.getName().substring(3),
method.getReturnType());
PropertyWrapper property = new PropertyWrapper(name,
method.getReturnType(), method.getName(), setter.getName(),
annotation.defaultable(), validator);
properties.add(property);
}
} catch (NoSuchMethodException e) {
LOG.debug("No matching setter found for \"" + method.getName()
+ "\". Skipping...");
}
}
}
propertyCache.put(clazz.getName(), properties);
return cloner.deepClone(properties);
}
/**
* Returns properties that have the same value for all the selected
* components.
*
* @param selectedComponents
* @return
*/
public List<PropertyWrapper> getMutualSelectionProperties(
List<IDIYComponent<?>> selectedComponents) throws Exception {
if (selectedComponents.isEmpty()) {
return null;
}
List<PropertyWrapper> properties = new ArrayList<PropertyWrapper>();
IDIYComponent<?> firstComponent = selectedComponents.get(0);
properties.addAll(extractProperties(firstComponent.getClass()));
// Initialize values
for (PropertyWrapper property : properties) {
property.readFrom(firstComponent);
}
for (int i = 1; i < selectedComponents.size(); i++) {
IDIYComponent<?> component = selectedComponents.get(i);
List<PropertyWrapper> newProperties = extractProperties(component.getClass());
for (PropertyWrapper property : newProperties) {
property.readFrom(component);
}
properties.retainAll(newProperties);
// Try to find matching properties in old and new lists and see if
// their values match.
for (PropertyWrapper oldProperty : properties) {
if (newProperties.contains(oldProperty)) {
PropertyWrapper newProperty = newProperties.get(newProperties
.indexOf(oldProperty));
if ((newProperty.getValue() != null && newProperty.getValue() == null)
|| !newProperty.getValue().equals(oldProperty.getValue())) {
// Values don't match, so the property is not unique valued.
oldProperty.setUnique(false);
}
}
}
// for (PropertyWrapper property : properties) {
// try {
// property.readUniqueFrom(component);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
Collections.sort(properties, ComparatorFactory.getInstance().getPropertyNameComparator());
return properties;
}
private IPropertyValidator getPropertyValidator(Class<? extends IPropertyValidator> clazz) {
if (propertyValidatorCache.containsKey(clazz.getName())) {
return propertyValidatorCache.get(clazz.getName());
}
IPropertyValidator validator;
try {
validator = clazz.newInstance();
} catch (Exception e) {
LOG.error("Could not instantiate validator for " + clazz.getName(), e);
return null;
}
propertyValidatorCache.put(clazz.getName(), validator);
return validator;
}
}
@@ -1,23 +0,0 @@
package org.diylc.presenter;
import org.diylc.common.ComponentType;
import org.diylc.common.IComponentFiler;
import org.diylc.core.IDIYComponent;
public class ComponentZOrderFiler implements IComponentFiler {
private int zOrder;
public ComponentZOrderFiler(int zOrder) {
super();
this.zOrder = zOrder;
}
@SuppressWarnings("unchecked")
@Override
public boolean testComponent(IDIYComponent<?> component) {
ComponentType componentType = ComponentProcessor.getInstance().extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass());
return Math.round(componentType.getZOrder()) == zOrder;
}
}
@@ -1,398 +0,0 @@
package org.diylc.presenter;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Area;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.diylc.appframework.miscutils.ConfigurationManager;
import org.diylc.appframework.simplemq.MessageDispatcher;
import org.diylc.common.DrawOption;
import org.diylc.common.EventType;
import org.diylc.common.GridType;
import org.diylc.common.IComponentFiler;
import org.diylc.common.IPlugInPort;
import org.diylc.common.ObjectCache;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.utils.Constants;
/**
* Utility that deals with painting {@link Project} on the {@link Graphics2D}
* and keeps areas taken by each drawn component.
*
* @author Branislav Stojkovic
*/
public class DrawingManager {
private static final Logger LOG = Logger.getLogger(DrawingManager.class);
public static int CONTROL_POINT_SIZE = 7;
public static final String ZOOM_KEY = "zoom";
public static String DEBUG_COMPONENT_AREAS = "org.diylc.debugComponentAreas";
public static Color CONTROL_POINT_COLOR = Color.blue;
public static Color SELECTED_CONTROL_POINT_COLOR = Color.green;
private Theme theme = (Theme) ConfigurationManager.getInstance().readObject(
IPlugInPort.THEME_KEY, Constants.DEFAULT_THEME);
// Keeps Area object of each drawn component.
private Map<IDIYComponent<?>, Area> componentAreaMap;
// Maps components to the last state they are drawn in. Also, used to
// determine which components are invalidated when they are not in the map.
private Map<IDIYComponent<?>, ComponentState> lastDrawnStateMap;
private Composite slotComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
private Composite lockedComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
private List<IDIYComponent<?>> failedComponents = new ArrayList<IDIYComponent<?>>();
private double zoomLevel = 1d;// ConfigurationManager.getInstance().readDouble(ZOOM_KEY,
// 1d);
private MessageDispatcher<EventType> messageDispatcher;
private boolean debugComponentAreas;
public DrawingManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.messageDispatcher = messageDispatcher;
componentAreaMap = new HashMap<IDIYComponent<?>, Area>();
lastDrawnStateMap = new HashMap<IDIYComponent<?>, ComponentState>();
String debugComponentAreasStr = System.getProperty(DEBUG_COMPONENT_AREAS);
debugComponentAreas = debugComponentAreasStr != null
&& debugComponentAreasStr.equalsIgnoreCase("true");
}
/**
* Paints the project onto the canvas and returns the list of components
* that failed to draw.
*
* @param g2d
* @param project
* @param drawOptions
* @param filter
* @param selectionRect
* @param selectedComponents
* @param lockedComponents
* @param groupedComponents
* @param controlPointSlot
* @param componentSlot
* @param dragInProgress
* @return
*/
public List<IDIYComponent<?>> drawProject(Graphics2D g2d, Project project,
Set<DrawOption> drawOptions, IComponentFiler filter, Rectangle selectionRect,
List<IDIYComponent<?>> selectedComponents, Set<IDIYComponent<?>> lockedComponents,
Set<IDIYComponent<?>> groupedComponents, List<Point> controlPointSlot,
IDIYComponent<?> componentSlot, boolean dragInProgress) {
failedComponents.clear();
if (project == null) {
return failedComponents;
}
G2DWrapper g2dWrapper = new G2DWrapper(g2d);
if (drawOptions.contains(DrawOption.ANTIALIASING)) {
g2d
.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} else {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
if (ConfigurationManager.getInstance()
.readBoolean(IPlugInPort.HI_QUALITY_RENDER_KEY, false)) {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
} else {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
double zoom = 1d;
if (drawOptions.contains(DrawOption.ZOOM)) {
zoom = zoomLevel;
} else {
zoom = 1 / Constants.PIXEL_SIZE;
}
// AffineTransform initialTx = g2d.getTransform();
Dimension d = getCanvasDimensions(project, zoom, true);
g2dWrapper.setColor(theme.getBgColor());
g2dWrapper.fillRect(0, 0, d.width, d.height);
g2d.clip(new Rectangle(new Point(0, 0), d));
GridType gridType = GridType.LINES;
if (drawOptions.contains(DrawOption.GRID) && gridType != GridType.NONE) {
double zoomStep = project.getGridSpacing().convertToPixels() * zoom;
if (gridType == GridType.CROSSHAIR) {
g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10f, new float[] { (float) zoomStep / 2, (float) zoomStep / 2 },
(float) zoomStep / 4));
} else if (gridType == GridType.DOT) {
g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10f, new float[] { 1f, (float) zoomStep - 1 }, 0f));
}
g2dWrapper.setColor(theme.getGridColor());
for (double i = zoomStep; i < d.width; i += zoomStep) {
g2dWrapper.drawLine((int) i, 0, (int) i, d.height - 1);
}
for (double j = zoomStep; j < d.height; j += zoomStep) {
g2dWrapper.drawLine(0, (int) j, d.width - 1, (int) j);
}
}
if (Math.abs(1.0 - zoom) > 1e-4) {
g2dWrapper.scale(zoom, zoom);
}
// Composite mainComposite = g2d.getComposite();
// Composite alphaComposite =
// AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
// g2dWrapper.resetTx();
// componentAreaMap.clear();
for (IDIYComponent<?> component : project.getComponents()) {
// Do not draw the component if it's filtered out.
if (filter != null && !filter.testComponent(component)) {
continue;
}
ComponentState state = ComponentState.NORMAL;
if (drawOptions.contains(DrawOption.SELECTION)
&& selectedComponents.contains(component)) {
if (dragInProgress) {
state = ComponentState.DRAGGING;
} else {
state = ComponentState.SELECTED;
}
}
// Do not track the area if component is not invalidated and was
// drawn in the same state.
boolean trackArea = lastDrawnStateMap.get(component) != state;
synchronized (g2d) {
g2dWrapper.startedDrawingComponent();
if (!trackArea) {
g2dWrapper.stopTracking();
}
// Draw locked components in a new composite.
if (lockedComponents.contains(component)) {
g2d.setComposite(lockedComposite);
}
// Draw the component through the g2dWrapper.
try {
component.draw(g2dWrapper, state,
drawOptions.contains(DrawOption.OUTLINE_MODE), project, g2dWrapper);
} catch (Exception e) {
LOG.error("Error drawing " + component.getName(), e);
failedComponents.add(component);
}
Area area = g2dWrapper.finishedDrawingComponent();
if (trackArea && area != null && !area.isEmpty()) {
componentAreaMap.put(component, area);
lastDrawnStateMap.put(component, state);
}
}
}
// Draw control points.
if (drawOptions.contains(DrawOption.CONTROL_POINTS)) {
// Draw unselected points first to make sure they are below.
if (dragInProgress || drawOptions.contains(DrawOption.OUTLINE_MODE)) {
for (IDIYComponent<?> component : project.getComponents()) {
for (int i = 0; i < component.getControlPointCount(); i++) {
VisibilityPolicy visibilityPolicy = component
.getControlPointVisibilityPolicy(i);
if ((groupedComponents.contains(component)
&& (visibilityPolicy == VisibilityPolicy.ALWAYS || (selectedComponents
.contains(component) && visibilityPolicy == VisibilityPolicy.WHEN_SELECTED)) || (!groupedComponents
.contains(component)
&& !selectedComponents.contains(component) && component
.getControlPointVisibilityPolicy(i) == VisibilityPolicy.ALWAYS))) {
g2dWrapper.setColor(CONTROL_POINT_COLOR);
Point controlPoint = component.getControlPoint(i);
int pointSize = CONTROL_POINT_SIZE - 2;
g2dWrapper.fillOval(controlPoint.x - pointSize / 2, controlPoint.y
- pointSize / 2, pointSize, pointSize);
}
}
}
}
// Then draw the selected ones.
for (IDIYComponent<?> component : selectedComponents) {
for (int i = 0; i < component.getControlPointCount(); i++) {
if (!groupedComponents.contains(component)
&& (component.getControlPointVisibilityPolicy(i) == VisibilityPolicy.WHEN_SELECTED || component
.getControlPointVisibilityPolicy(i) == VisibilityPolicy.ALWAYS)) {
Point controlPoint = component.getControlPoint(i);
int pointSize = CONTROL_POINT_SIZE;
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR.darker());
g2dWrapper.fillOval(controlPoint.x - pointSize / 2, controlPoint.y
- pointSize / 2, pointSize, pointSize);
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR);
g2dWrapper.fillOval(controlPoint.x - CONTROL_POINT_SIZE / 2 + 1,
controlPoint.y - CONTROL_POINT_SIZE / 2 + 1,
CONTROL_POINT_SIZE - 2, CONTROL_POINT_SIZE - 2);
}
}
}
}
// Draw component slot in a separate composite.
if (componentSlot != null) {
g2dWrapper.startedDrawingComponent();
g2dWrapper.setComposite(slotComposite);
try {
componentSlot.draw(g2dWrapper, ComponentState.NORMAL, drawOptions
.contains(DrawOption.OUTLINE_MODE), project, g2dWrapper);
} catch (Exception e) {
LOG.error("Error drawing " + componentSlot.getName(), e);
failedComponents.add(componentSlot);
}
g2dWrapper.finishedDrawingComponent();
}
// Draw control points of the component in the slot.
if (controlPointSlot != null) {
for (Point point : controlPointSlot) {
if (point != null) {
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR.darker());
g2dWrapper.fillOval(point.x - CONTROL_POINT_SIZE / 2, point.y
- CONTROL_POINT_SIZE / 2, CONTROL_POINT_SIZE, CONTROL_POINT_SIZE);
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR);
g2dWrapper.fillOval(point.x - CONTROL_POINT_SIZE / 2 + 1, point.y
- CONTROL_POINT_SIZE / 2 + 1, CONTROL_POINT_SIZE - 2,
CONTROL_POINT_SIZE - 2);
}
}
}
// Go back to the original transformation and zoom in to draw the
// selection rectangle and other similar elements.
// g2d.setTransform(initialTx);
// if ((drawOptions.contains(DrawOption.ZOOM)) && (Math.abs(1.0 -
// zoomLevel) > 1e-4)) {
// g2d.scale(zoomLevel, zoomLevel);
// }
// At the end draw selection rectangle if needed.
if (drawOptions.contains(DrawOption.SELECTION) && (selectionRect != null)) {
g2d.setColor(Color.white);
g2d.draw(selectionRect);
g2d.setColor(Color.black);
g2d.setStroke(Constants.DASHED_STROKE);
g2d.draw(selectionRect);
}
// Draw component area for test
if (debugComponentAreas) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
g2d.setColor(Color.red);
for (Area area : componentAreaMap.values()) {
g2d.draw(area);
}
}
return failedComponents;
}
public double getZoomLevel() {
return zoomLevel;
}
public void setZoomLevel(double zoomLevel) {
this.zoomLevel = zoomLevel;
fireZoomChanged();
// ConfigurationManager.getInstance().writeValue(ZOOM_KEY, zoomLevel);
}
public void invalidateComponent(IDIYComponent<?> component) {
componentAreaMap.remove(component);
lastDrawnStateMap.remove(component);
}
public Area getComponentArea(IDIYComponent<?> component) {
return componentAreaMap.get(component);
}
public void clearComponentAreaMap() {
componentAreaMap.clear();
}
public List<IDIYComponent<?>> findComponentsAt(Point point, Project project) {
List<IDIYComponent<?>> components = new ArrayList<IDIYComponent<?>>();
for (int i = 0; i < project.getComponents().size(); i++) {
Area area = componentAreaMap.get(project.getComponents().get(i));
if (area != null && area.contains(point)) {
components.add(0, project.getComponents().get(i));
}
}
return components;
}
public Dimension getCanvasDimensions(Project project, Double zoomLevel, boolean useZoom) {
double width = project.getWidth().convertToPixels();
double height = project.getHeight().convertToPixels();
if (useZoom) {
width *= zoomLevel;
height *= zoomLevel;
} else {
width /= Constants.PIXEL_SIZE;
height /= Constants.PIXEL_SIZE;
}
return new Dimension((int) width, (int) height);
}
public void fireZoomChanged() {
messageDispatcher.dispatchMessage(EventType.ZOOM_CHANGED, zoomLevel);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
public Theme getTheme() {
return theme;
}
public void setTheme(Theme theme) {
this.theme = theme;
ConfigurationManager.getInstance().writeValue(IPlugInPort.THEME_KEY, theme);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
}
@@ -1,219 +0,0 @@
package org.diylc.presenter;
import java.awt.Point;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.diylc.appframework.miscutils.ConfigurationManager;
import org.diylc.common.ComponentType;
import org.diylc.common.IPlugInPort;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.measures.Size;
import com.rits.cloning.Cloner;
/**
* Manages component instantiation.
*
* @author Branislav Stojkovic
*/
public class InstantiationManager {
private static final Logger LOG = Logger.getLogger(InstantiationManager.class);
private static final int MAX_RECENT_COMPONENTS = 16;
private Cloner cloner;
private ComponentType componentTypeSlot;
private IDIYComponent<?> componentSlot;
private Point firstControlPoint;
private Point potentialControlPoint;
public InstantiationManager() {
cloner = new Cloner();
}
public ComponentType getComponentTypeSlot() {
return componentTypeSlot;
}
public IDIYComponent<?> getComponentSlot() {
return componentSlot;
}
public Point getFirstControlPoint() {
return firstControlPoint;
}
public Point getPotentialControlPoint() {
return potentialControlPoint;
}
public void setComponentTypeSlot(ComponentType componentTypeSlot, Project currentProject)
throws Exception {
this.componentTypeSlot = componentTypeSlot;
if (componentTypeSlot == null) {
this.componentSlot = null;
} else {
switch (componentTypeSlot.getCreationMethod()) {
case POINT_BY_POINT:
this.componentSlot = null;
break;
case SINGLE_CLICK:
this.componentSlot = instantiateComponent(componentTypeSlot, new Point(0, 0),
currentProject);
break;
}
}
this.firstControlPoint = null;
this.potentialControlPoint = null;
}
public void instatiatePointByPoint(Point scaledPoint, Project currentProject) throws Exception {
firstControlPoint = scaledPoint;
componentSlot = instantiateComponent(componentTypeSlot, firstControlPoint, currentProject);
// Set the other control point to the same location, we'll
// move it later when mouse moves.
componentSlot.setControlPoint(firstControlPoint, 0);
componentSlot.setControlPoint(firstControlPoint, 1);
}
/**
* Updates component in the slot with the new second control point.
*
* @param scaledPoint
* @return true, if any change is made
*/
public boolean updatePointByPoint(Point scaledPoint) {
boolean changeMade = !scaledPoint.equals(potentialControlPoint);
potentialControlPoint = scaledPoint;
if (componentSlot != null) {
componentSlot.setControlPoint(scaledPoint, 1);
}
return changeMade;
}
public boolean updateSingleClick(Point scaledPoint, boolean snapToGrid, Size gridSpacing) {
if (potentialControlPoint == null) {
potentialControlPoint = new Point(0, 0);
}
int dx = scaledPoint.x - potentialControlPoint.x;
int dy = scaledPoint.y - potentialControlPoint.y;
if (snapToGrid) {
dx = CalcUtils.roundToGrid(dx, gridSpacing);
dy = CalcUtils.roundToGrid(dy, gridSpacing);
}
// Only repaint if there's an actual change.
if (dx == 0 && dy == 0) {
return false;
}
potentialControlPoint.translate(dx, dy);
if (componentSlot == null) {
LOG.error("Component slot should not be null!");
} else {
Point p = new Point();
for (int i = 0; i < componentSlot.getControlPointCount(); i++) {
p.setLocation(componentSlot.getControlPoint(i));
p.translate(dx, dy);
componentSlot.setControlPoint(p, i);
}
}
return true;
}
@SuppressWarnings("unchecked")
public IDIYComponent<?> instantiateComponent(ComponentType componentType, Point point,
Project currentProject) throws Exception {
LOG.info("Instatiating component of type: " + componentType.getInstanceClass().getName());
// Instantiate the component.
IDIYComponent<?> component = componentType.getInstanceClass().newInstance();
component.setName(createUniqueName(componentType, currentProject));
// Translate them to the desired location.
if (point != null) {
for (int j = 0; j < component.getControlPointCount(); j++) {
Point controlPoint = new Point(component.getControlPoint(j));
controlPoint.translate(point.x, point.y);
// snapPointToGrid(controlPoint);
component.setControlPoint(controlPoint, j);
}
}
fillWithDefaultProperties(component);
// Write to recent components
List<String> recentComponentTypes = (List<String>) ConfigurationManager.getInstance()
.readObject(IPlugInPort.RECENT_COMPONENTS_KEY, new ArrayList<ComponentType>());
String className = componentType.getInstanceClass().getName();
if (recentComponentTypes.size() == 0 || !recentComponentTypes.get(0).equals(className)) {
// Remove if it's already somewhere in the list.
recentComponentTypes.remove(className);
// Add to the end of the list.
recentComponentTypes.add(0, className);
// Trim the list if necessary.
if (recentComponentTypes.size() > MAX_RECENT_COMPONENTS) {
recentComponentTypes.remove(recentComponentTypes.size() - 1);
}
ConfigurationManager.getInstance().writeValue(IPlugInPort.RECENT_COMPONENTS_KEY,
recentComponentTypes);
}
return component;
}
public String createUniqueName(ComponentType componentType, Project currentProject) {
int i = 0;
boolean exists = true;
while (exists) {
i++;
String name = componentType.getNamePrefix() + i;
exists = false;
for (IDIYComponent<?> c : currentProject.getComponents()) {
if (c.getName().equals(name)) {
exists = true;
break;
}
}
}
return componentType.getNamePrefix() + i;
}
/**
* Finds any properties that have default values and injects default values.
* Typically it should be used for {@link IDIYComponent} and {@link Project}
* objects.
*
* @param object
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws SecurityException
*/
public void fillWithDefaultProperties(Object object) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, SecurityException,
NoSuchMethodException {
// Extract properties.
List<PropertyWrapper> properties = ComponentProcessor.getInstance().extractProperties(
object.getClass());
// Override with default values if available.
for (PropertyWrapper property : properties) {
Object defaultValue = ConfigurationManager.getInstance().readObject(
Presenter.DEFAULTS_KEY_PREFIX + object.getClass().getName() + ":"
+ property.getName(), null);
if (defaultValue != null) {
property.setValue(cloner.deepClone(defaultValue));
property.writeTo(object);
}
}
}
}
@@ -1,41 +0,0 @@
package org.diylc.presenter;
import java.awt.Point;
import org.diylc.utils.Constants;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* Serializes {@link Point} objects by converting coordinates from pixels to
* inches, thus avoiding the resolution to affect point placement.
*
* @author Branislav Stojkovic
*/
public class PointConverter implements Converter {
@Override
public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) {
Point point = (Point) object;
writer.addAttribute("x", Double.toString(1d * point.x / Constants.PIXELS_PER_INCH));
writer.addAttribute("y", Double.toString(1d * point.y / Constants.PIXELS_PER_INCH));
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
double x = Double.parseDouble(reader.getAttribute("x"));
double y = Double.parseDouble(reader.getAttribute("y"));
return new Point((int) Math.round(x * Constants.PIXELS_PER_INCH), (int) Math.round(y
* Constants.PIXELS_PER_INCH));
}
@SuppressWarnings("unchecked")
@Override
public boolean canConvert(Class clazz) {
return Point.class.isAssignableFrom(clazz);
}
}
File diff suppressed because it is too large Load Diff
@@ -1,549 +0,0 @@
package org.diylc.presenter;
import java.awt.Color;
import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.diylc.appframework.simplemq.MessageDispatcher;
import org.diylc.common.Display;
import org.diylc.common.EventType;
import org.diylc.common.Orientation;
import org.diylc.components.AbstractComponent;
import org.diylc.components.AbstractLeadedComponent;
import org.diylc.components.AbstractTransparentComponent;
import org.diylc.components.boards.AbstractBoard;
import org.diylc.components.boards.BlankBoard;
import org.diylc.components.boards.PerfBoard;
import org.diylc.components.boards.VeroBoard;
import org.diylc.components.connectivity.CopperTrace;
import org.diylc.components.connectivity.HookupWire;
import org.diylc.components.connectivity.Jumper;
import org.diylc.components.connectivity.SolderPad;
import org.diylc.components.misc.Label;
import org.diylc.components.passive.PotentiometerPanel;
import org.diylc.components.passive.RadialElectrolytic;
import org.diylc.components.passive.RadialFilmCapacitor;
import org.diylc.components.passive.Resistor;
import org.diylc.components.passive.Taper;
import org.diylc.components.semiconductors.DIL_IC;
import org.diylc.components.semiconductors.DiodePlastic;
import org.diylc.components.semiconductors.LED;
import org.diylc.components.semiconductors.TransistorTO92;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.measures.Capacitance;
import org.diylc.core.measures.Resistance;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class ProjectFileManager {
private static final Logger LOG = Logger.getLogger(ProjectFileManager.class);
// private static final int V1_PIXELS_PER_INCH = 200;
private static final Size V1_GRID_SPACING = new Size(0.1d, SizeUnit.in);
private static final Map<String, Color> V1_COLOR_MAP = new HashMap<String, Color>();
static {
V1_COLOR_MAP.put("red", Color.red);
V1_COLOR_MAP.put("blue", Color.blue);
V1_COLOR_MAP.put("white", Color.white);
V1_COLOR_MAP.put("green", Color.green.darker());
V1_COLOR_MAP.put("black", Color.black);
V1_COLOR_MAP.put("yellow", Color.yellow);
}
private XStream xStream;
// Legacy deserializer for 3.0.1 through 3.0.7, loads Points referenced in
// pixels.
private XStream xStreamOld;
private String currentFileName = null;
private boolean modified = false;
private MessageDispatcher<EventType> messageDispatcher;
public ProjectFileManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.xStream = new XStream(new DomDriver());
xStream.autodetectAnnotations(true);
xStream.registerConverter(new PointConverter());
this.xStreamOld = new XStream(new DomDriver());
xStreamOld.autodetectAnnotations(true);
this.messageDispatcher = messageDispatcher;
}
public void startNewFile() {
currentFileName = null;
modified = false;
fireFileStatusChanged();
}
public void serializeProjectToFile(Project project, String fileName, boolean isBackup)
throws IOException {
if (!isBackup) {
LOG.info(String.format("saveProjectToFile(%s)", fileName));
}
FileOutputStream fos;
fos = new FileOutputStream(fileName);
xStream.toXML(project, fos);
fos.close();
if (!isBackup) {
this.currentFileName = fileName;
this.modified = false;
fireFileStatusChanged();
}
}
public Project deserializeProjectFromFile(String fileName, List<String> warnings)
throws SAXException, IOException, ParserConfigurationException {
LOG.info(String.format("loadProjectFromFile(%s)", fileName));
Project project;
File file = new File(fileName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
if (doc.getDocumentElement().getNodeName().equalsIgnoreCase(Project.class.getName())) {
project = parseV3File(fileName);
} else {
if (!doc.getDocumentElement().getNodeName().equalsIgnoreCase("layout")) {
throw new IllegalArgumentException(
"Could not open DIY file. Root node is not named 'Layout'.");
}
String formatVersion = doc.getDocumentElement().getAttribute("formatVersion");
if (formatVersion == null || formatVersion.trim().isEmpty()) {
LOG.debug("Detected v1 file.");
project = parseV1File(doc.getDocumentElement(), warnings);
} else if (formatVersion.equals("2.0")) {
LOG.debug("Detected v2 file.");
project = parseV2File(doc.getDocumentElement());
} else {
throw new IllegalArgumentException("Unknown file format version: " + formatVersion);
}
}
Collections.sort(warnings);
this.currentFileName = fileName;
this.modified = false;
return project;
}
public void notifyFileChange() {
this.modified = true;
fireFileStatusChanged();
}
public String getCurrentFileName() {
return currentFileName;
}
public boolean isModified() {
return modified;
}
public void fireFileStatusChanged() {
messageDispatcher.dispatchMessage(EventType.FILE_STATUS_CHANGED, getCurrentFileName(),
isModified());
}
private Project parseV1File(Element root, List<String> warnings) {
Project project = new Project();
project.setTitle(root.getAttribute("Project"));
project.setAuthor(root.getAttribute("Credits"));
project.setGridSpacing(V1_GRID_SPACING);
String type = root.getAttribute("Type");
// Create the board.
int width = Integer.parseInt(root.getAttribute("Width")) + 1;
int height = Integer.parseInt(root.getAttribute("Height")) + 1;
int boardWidth = (int) (width * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue());
int boardHeight = (int) (height * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue());
int projectWidth = (int) project.getWidth().convertToPixels();
int projectHeight = (int) project.getHeight().convertToPixels();
int x = (projectWidth - boardWidth) / 2;
int y = (projectHeight - boardHeight) / 2;
AbstractBoard board;
if (type.equalsIgnoreCase("pcb")) {
board = new BlankBoard();
board.setBoardColor(Color.white);
board.setBorderColor(Color.black);
} else if (type.equalsIgnoreCase("perfboard")) {
board = new PerfBoard();
} else if (type.equalsIgnoreCase("stripboard")) {
board = new VeroBoard();
} else {
throw new IllegalArgumentException("Unrecognized board type: " + type);
}
board.setName("Main board");
Point referencePoint = new Point(CalcUtils.roundToGrid(x, V1_GRID_SPACING), CalcUtils
.roundToGrid(y, V1_GRID_SPACING));
board.setControlPoint(referencePoint, 0);
board.setControlPoint(new Point(CalcUtils.roundToGrid(x + boardWidth, V1_GRID_SPACING),
CalcUtils.roundToGrid(y + boardHeight, V1_GRID_SPACING)), 1);
project.getComponents().add(board);
NodeList childNodes = root.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String nodeName = node.getNodeName();
String nameAttr = node.getAttributes().getNamedItem("Name").getNodeValue();
Node valueNode = node.getAttributes().getNamedItem("Value");
String valueAttr = valueNode == null ? null : valueNode.getNodeValue();
int x1Attr = Integer.parseInt(node.getAttributes().getNamedItem("X1")
.getNodeValue());
int y1Attr = Integer.parseInt(node.getAttributes().getNamedItem("Y1")
.getNodeValue());
Point point1 = convertV1CoordinatesToV3Point(referencePoint, x1Attr, y1Attr);
Point point2 = null;
Integer x2Attr = null;
Integer y2Attr = null;
Color color = null;
if (node.getAttributes().getNamedItem("Color") != null) {
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
color = V1_COLOR_MAP.get(colorAttr.toLowerCase());
}
if (node.getAttributes().getNamedItem("X2") != null
&& node.getAttributes().getNamedItem("Y2") != null) {
x2Attr = Integer.parseInt(node.getAttributes().getNamedItem("X2")
.getNodeValue());
y2Attr = Integer.parseInt(node.getAttributes().getNamedItem("Y2")
.getNodeValue());
point2 = convertV1CoordinatesToV3Point(referencePoint, x2Attr, y2Attr);
}
IDIYComponent<?> component = null;
if (nodeName.equalsIgnoreCase("text")) {
LOG.debug("Recognized " + nodeName);
Label label = new Label();
label.setName(nameAttr);
if (color != null) {
label.setColor(color);
}
label.setText(valueAttr);
label.setCenter(false);
label.setControlPoint(convertV1CoordinatesToV3Point(referencePoint, x1Attr,
y1Attr + 1), 0);
component = label;
} else if (nodeName.equalsIgnoreCase("pad")) {
LOG.debug("Recognized " + nodeName);
SolderPad pad = new SolderPad();
pad.setName(nameAttr);
if (color != null) {
pad.setColor(color);
}
pad.setControlPoint(convertV1CoordinatesToV3Point(referencePoint, x1Attr,
y1Attr), 0);
component = pad;
} else if (nodeName.equalsIgnoreCase("trace")) {
LOG.debug("Recognized " + nodeName);
CopperTrace trace = new CopperTrace();
trace.setName(nameAttr);
if (color != null) {
trace.setLeadColor(color);
}
trace.setControlPoint(point1, 0);
trace.setControlPoint(point2, 1);
component = trace;
} else if (nodeName.equalsIgnoreCase("jumper")) {
LOG.debug("Recognized " + nodeName);
Jumper jumper = new Jumper();
jumper.setName(nameAttr);
jumper.setControlPoint(point1, 0);
jumper.setControlPoint(point2, 1);
component = jumper;
} else if (nodeName.equalsIgnoreCase("wire")) {
LOG.debug("Recognized " + nodeName);
HookupWire wire = new HookupWire();
Point midPoint = new Point((point1.x + point2.x) / 2, (point1.y + point2.y) / 2);
wire.setName(nameAttr);
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
wire.setColor(parseV1Color(colorAttr));
wire.setControlPoint(point1, 0);
wire.setControlPoint(midPoint, 1);
wire.setControlPoint(midPoint, 2);
wire.setControlPoint(point2, 3);
component = wire;
} else if (nodeName.equalsIgnoreCase("resistor")) {
LOG.debug("Recognized " + nodeName);
Resistor resistor = new Resistor();
resistor.setName(nameAttr);
try {
resistor.setValue(Resistance.parseResistance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
resistor.setLength(new Size(6.35d, SizeUnit.mm));
resistor.setWidth(new Size(2.2d, SizeUnit.mm));
resistor.setControlPoint(point1, 0);
resistor.setControlPoint(point2, 1);
component = resistor;
} else if (nodeName.equalsIgnoreCase("capacitor")) {
LOG.debug("Recognized " + nodeName);
RadialFilmCapacitor capacitor = new RadialFilmCapacitor();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
capacitor.setLength(new Size(6d, SizeUnit.mm));
capacitor.setWidth(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("electrolyte")) {
LOG.debug("Recognized " + nodeName);
RadialElectrolytic capacitor = new RadialElectrolytic();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
try {
String sizeAttr = node.getAttributes().getNamedItem("Size").getNodeValue();
if (sizeAttr.equalsIgnoreCase("small")) {
capacitor.setLength(new Size(3.5d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("medium")) {
capacitor.setLength(new Size(5d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("large")) {
capacitor.setLength(new Size(7d, SizeUnit.mm));
} else {
capacitor.setLength(new Size(4d, SizeUnit.mm));
}
} catch (Exception e) {
capacitor.setLength(new Size(5d, SizeUnit.mm));
LOG.debug("Could not set size of " + nameAttr);
}
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("diode")) {
LOG.debug("Recognized " + nodeName);
DiodePlastic capacitor = new DiodePlastic();
capacitor.setName(nameAttr);
try {
capacitor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
capacitor.setLength(new Size(6d, SizeUnit.mm));
capacitor.setWidth(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("led")) {
LOG.debug("Recognized " + nodeName);
LED led = new LED();
led.setName(nameAttr);
led.setValue(valueAttr);
led.setBodyColor(Color.red);
led.setBorderColor(Color.red.darker());
led.setLength(new Size(3d, SizeUnit.mm));
led.setControlPoint(point1, 0);
led.setControlPoint(point2, 1);
component = led;
} else if (nodeName.equalsIgnoreCase("transistor")) {
LOG.debug("Recognized " + nodeName);
TransistorTO92 transistor = new TransistorTO92();
transistor.setName(nameAttr);
try {
transistor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
transistor.setControlPoint(point1, 0);
if (point1.y > point2.y) {
transistor.setOrientation(Orientation._180);
} else if (point1.y < point2.y) {
transistor.setOrientation(Orientation.DEFAULT);
} else if (point1.x < point2.x) {
transistor.setOrientation(Orientation._270);
} else if (point1.x > point2.x) {
transistor.setOrientation(Orientation._90);
}
// capacitor.setControlPoint(point2, 1);
component = transistor;
} else if (nodeName.equalsIgnoreCase("ic")) {
LOG.debug("Recognized " + nodeName);
DIL_IC ic = new DIL_IC();
int pinCount = 8;
int rowSpace = 3;
if (x1Attr < x2Attr && y1Attr < y2Attr) {
pinCount = (y2Attr - y1Attr + 1) * 2;
rowSpace = x2Attr - x1Attr;
ic.setOrientation(Orientation.DEFAULT);
} else if (x1Attr > x2Attr && y1Attr < y2Attr) {
pinCount = (x1Attr - x2Attr + 1) * 2;
rowSpace = y2Attr - y1Attr;
ic.setOrientation(Orientation._90);
} else if (x1Attr > x2Attr && y1Attr > y2Attr) {
rowSpace = x1Attr - x2Attr;
pinCount = (y1Attr - y2Attr + 1) * 2;
ic.setOrientation(Orientation._180);
} else if (x1Attr < x2Attr && y1Attr > y2Attr) {
rowSpace = y1Attr - y2Attr;
pinCount = (x2Attr - x1Attr + 1) * 2;
ic.setOrientation(Orientation._270);
}
ic.setRowSpacing(new Size(0.1 * rowSpace, SizeUnit.in));
ic.setPinCount(DIL_IC.PinCount.valueOf("_" + pinCount));
ic.setName(nameAttr);
// Translate control points.
for (int j = 0; j < ic.getControlPointCount(); j++) {
Point p = new Point(ic.getControlPoint(j));
p.translate(point1.x, point1.y);
ic.setControlPoint(p, j);
}
ic.setValue(valueAttr);
component = ic;
} else if (nodeName.equalsIgnoreCase("pot")) {
LOG.debug("Recognized " + nodeName);
PotentiometerPanel pot = new PotentiometerPanel();
pot.setBodyDiameter(new Size(14d, SizeUnit.mm));
pot.setSpacing(new Size(0.2, SizeUnit.in));
pot.setName(nameAttr);
try {
pot.setResistance(Resistance.parseResistance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
String taperAttr = node.getAttributes().getNamedItem("Taper").getNodeValue();
if ("Linear".equals(taperAttr)) {
pot.setTaper(Taper.LIN);
} else if ("Audio".equals(taperAttr)) {
pot.setTaper(Taper.LOG);
} else if ("Reverse Audio".equals(taperAttr)) {
pot.setTaper(Taper.REV_LOG);
}
// Pin spacing, we'll need to move pot around a bit.
int delta = Constants.PIXELS_PER_INCH / 5;
if (x1Attr < x2Attr) {
pot.setOrientation(Orientation.DEFAULT);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x - delta, point1.y);
pot.setControlPoint(p, j);
}
} else if (x1Attr > x2Attr) {
pot.setOrientation(Orientation._180);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x + delta, point1.y);
pot.setControlPoint(p, j);
}
} else if (y1Attr < y2Attr) {
pot.setOrientation(Orientation._90);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x, point1.y - delta);
pot.setControlPoint(p, j);
}
} else if (y1Attr > y2Attr) {
pot.setOrientation(Orientation._270);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x, point1.y + delta);
pot.setControlPoint(p, j);
}
;
}
component = pot;
} else {
String message = "Could not recognize component type " + nodeName;
LOG.debug(message);
if (!warnings.contains(message)) {
warnings.add(message);
}
}
if (component != null) {
if (component instanceof AbstractLeadedComponent<?>) {
((AbstractLeadedComponent<?>) component).setDisplay(Display.NAME);
}
if (component instanceof AbstractTransparentComponent<?>) {
((AbstractTransparentComponent<?>) component).setAlpha((byte) 100);
}
project.getComponents().add(component);
}
}
}
Collections.sort(project.getComponents(), ComparatorFactory.getInstance()
.getComponentZOrderComparator());
return project;
}
private Point convertV1CoordinatesToV3Point(Point reference, int x, int y) {
Point point = new Point(reference);
point.translate((int) (x * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue()),
(int) (y * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue()));
return point;
}
private Color parseV1Color(String color) {
if ("brown".equals(color.toLowerCase()))
return new Color(139, 69, 19);
try {
Field field = Color.class.getDeclaredField(color.toLowerCase());
return (Color) field.get(null);
} catch (Exception e) {
LOG.error("Could not parse color \"" + color + "\"", e);
return Color.black;
}
}
private Project parseV2File(Element root) {
Project project = new Project();
String projectName = root.getAttribute("projectName");
String credits = root.getAttribute("credits");
String width = root.getAttribute("width");
String height = root.getAttribute("height");
NodeList childNodes = root.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getNodeName().equalsIgnoreCase("component")) {
LOG.debug(node.getAttributes().getNamedItem("name").getNodeValue());
} else {
LOG.debug("Unrecognized node name found: " + node.getNodeName());
}
}
}
return project;
}
private Project parseV3File(String fileName) throws IOException {
Project project;
FileInputStream fis = new FileInputStream(fileName);
try {
project = (Project) xStream.fromXML(fis);
} catch (Exception e) {
LOG.warn("Could not open with the new xStream, trying the old one");
fis.close();
fis = new FileInputStream(fileName);
project = (Project) xStreamOld.fromXML(fis);
}
fis.close();
return project;
}
}
@@ -1,55 +0,0 @@
package org.diylc.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.diylc.core.IDIYComponent;
public class BomMaker {
private static BomMaker instance;
public static BomMaker getInstance() {
if (instance == null) {
instance = new BomMaker();
}
return instance;
}
private BomMaker() {
}
public List<BomEntry> createBom(List<IDIYComponent<?>> components) {
Map<String, BomEntry> entryMap = new HashMap<String, BomEntry>();
for (IDIYComponent<?> component : components) {
String name = component.getName();
String value = component.getValue() == null ? null : component.getValue().toString();
if ((name != null) && (value != null)) {
String key = name + "|" + value;
if (entryMap.containsKey(key)) {
BomEntry entry = entryMap.get(key);
entry.setQuantity(entry.getQuantity() + 1);
} else {
entryMap.put(key, new BomEntry(name, value, 1));
}
}
}
List<BomEntry> bom = new ArrayList<BomEntry>(entryMap.values());
Collections.sort(bom, new Comparator<BomEntry>() {
@Override
public int compare(BomEntry o1, BomEntry o2) {
int compare = o1.getName().compareToIgnoreCase(o2.getName());
if (compare != 0) {
return compare;
}
return o1.getValue().compareToIgnoreCase(o2.getValue());
}
});
return bom;
}
}
@@ -1,27 +0,0 @@
package org.diylc.utils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Stroke;
import java.awt.Toolkit;
import org.diylc.core.Theme;
public class Constants {
public static final int PIXELS_PER_INCH = 200;
public static final double PIXEL_SIZE = 1d * PIXELS_PER_INCH
/ Toolkit.getDefaultToolkit().getScreenResolution();
public static Color CANVAS_COLOR = Color.white;
public static final Stroke DASHED_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10f, new float[] { 2.0f }, 0.0f);
public static final Theme DEFAULT_THEME = new Theme("Light", Constants.CANVAS_COLOR, new Color(
240, 240, 240), Color.black);
public static final Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0);
public static final Color MULTI_VALUE_COLOR = Color.yellow;
}
-65
View File
@@ -1,65 +0,0 @@
<org.diylc.core.Project>
<title>New Project</title>
<author>Branislav Stojkovic</author>
<width>
<value>29.0</value>
<unit class="org.diylc.core.measures.SizeUnit">cm</unit>
</width>
<height>
<value>21.0</value>
<unit class="org.diylc.core.measures.SizeUnit">cm</unit>
</height>
<gridSpacing>
<value>0.1</value>
<unit class="org.diylc.core.measures.SizeUnit">in</unit>
</gridSpacing>
<components>
<org.diylc.components.boards.EyeletBoard>
<name>Board1</name>
<alpha>127</alpha>
<value></value>
<controlPoints>
<java.awt.Point>
<x>555</x>
<y>450</y>
</java.awt.Point>
<java.awt.Point>
<x>1140</x>
<y>795</y>
</java.awt.Point>
</controlPoints>
<firstPoint>
<x>555</x>
<y>450</y>
</firstPoint>
<secondPoint>
<x>1140</x>
<y>795</y>
</secondPoint>
<boardColor>
<red>248</red>
<green>235</green>
<blue>179</blue>
<alpha>255</alpha>
</boardColor>
<borderColor>
<red>173</red>
<green>164</green>
<blue>125</blue>
<alpha>255</alpha>
</borderColor>
<spacing>
<value>0.3</value>
<unit class="org.diylc.core.measures.SizeUnit">in</unit>
</spacing>
<eyeletColor>
<red>195</red>
<green>228</green>
<blue>237</blue>
<alpha>255</alpha>
</eyeletColor>
</org.diylc.components.boards.EyeletBoard>
</components>
<groups/>
<lockedLayers/>
</org.diylc.core.Project>
-65
View File
@@ -1,65 +0,0 @@
<org.diylc.core.Project>
<title>New Project</title>
<author>Branislav Stojkovic</author>
<width>
<value>29.0</value>
<unit class="org.diylc.core.measures.SizeUnit">cm</unit>
</width>
<height>
<value>21.0</value>
<unit class="org.diylc.core.measures.SizeUnit">cm</unit>
</height>
<gridSpacing>
<value>0.1</value>
<unit class="org.diylc.core.measures.SizeUnit">in</unit>
</gridSpacing>
<components>
<org.diylc.components.boards.PerfBoard>
<name>Board1</name>
<alpha>127</alpha>
<value></value>
<controlPoints>
<java.awt.Point>
<x>585</x>
<y>450</y>
</java.awt.Point>
<java.awt.Point>
<x>1050</x>
<y>690</y>
</java.awt.Point>
</controlPoints>
<firstPoint>
<x>585</x>
<y>450</y>
</firstPoint>
<secondPoint>
<x>1050</x>
<y>690</y>
</secondPoint>
<boardColor>
<red>248</red>
<green>235</green>
<blue>179</blue>
<alpha>255</alpha>
</boardColor>
<borderColor>
<red>173</red>
<green>164</green>
<blue>125</blue>
<alpha>255</alpha>
</borderColor>
<spacing>
<value>0.1</value>
<unit class="org.diylc.core.measures.SizeUnit">in</unit>
</spacing>
<padColor>
<red>218</red>
<green>138</green>
<blue>103</blue>
<alpha>255</alpha>
</padColor>
</org.diylc.components.boards.PerfBoard>
</components>
<groups/>
<lockedLayers/>
</org.diylc.core.Project>
@@ -1,145 +0,0 @@
package org.diylc.components;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Capacitance;
import org.diylc.core.measures.CapacitanceUnit;
import org.diylc.core.measures.Resistance;
import org.diylc.core.measures.ResistanceUnit;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Mock", author = "bancika", category = "Sample", instanceNamePrefix = "M", description = "test", zOrder = IDIYComponent.COMPONENT)
public class MockDIYComponent implements IDIYComponent<Capacitance> {
private static final long serialVersionUID = 1L;
private String testField = "Hello World";
private Capacitance c = new Capacitance(100d, CapacitanceUnit.uF);
private Resistance r = new Resistance(123d, ResistanceUnit.K);
private Size s = new Size(1d, SizeUnit.cm);
private Color color = Color.green;
private Point leftTopCorner = new Point(0, 0);
private String name = "something";
public MockDIYComponent(String testField, Capacitance c, Resistance r, Size s, Color color,
Point leftTopCorner) {
super();
this.testField = testField;
this.c = c;
this.r = r;
this.s = s;
this.color = color;
this.leftTopCorner = leftTopCorner;
}
public MockDIYComponent() {
super();
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
}
@EditableProperty
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int getControlPointCount() {
return 1;
}
@Override
public boolean isControlPointSticky(int index) {
return false;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public Point getControlPoint(int index) {
return leftTopCorner;
}
@Override
public void setControlPoint(Point point, int index) {
leftTopCorner.setLocation(point);
}
@EditableProperty(name = "Test Field")
public String getTestField() {
return testField;
}
public void setTestField(String testField) {
this.testField = testField;
}
@EditableProperty(defaultable = true)
public Capacitance getValue() {
return c;
}
public void setValue(Capacitance c) {
this.c = c;
}
@EditableProperty(defaultable = true)
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
@EditableProperty
public Resistance getR() {
return r;
}
// Setter is commented out, ClassProcessor should ignore this property.
// public void setR(Resistance r) {
// this.r = r;
// }
// No annotation, so this property should be ignored.
public Size getS() {
return s;
}
public void setS(Size s) {
this.s = s;
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
g2d.setColor(componentState.equals(ComponentState.SELECTED) ? color : color.darker());
g2d.fillRect(leftTopCorner.x, leftTopCorner.y, 200, 50);
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.drawString("X", 10, 10);
}
}
@@ -1,37 +0,0 @@
package org.diylc.plugins.file;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import org.diylc.components.MockDIYComponent;
import org.diylc.core.IDIYComponent;
import org.diylc.core.measures.Capacitance;
import org.diylc.core.measures.CapacitanceUnit;
import org.diylc.utils.BomEntry;
import org.diylc.utils.BomMaker;
import org.junit.Test;
public class BomMakerTest {
@Test
public void testCreateBom() {
List<IDIYComponent<?>> components = new ArrayList<IDIYComponent<?>>();
MockDIYComponent c1 = new MockDIYComponent();
c1.setValue(new Capacitance(3d, CapacitanceUnit.pF));
components.add(c1);
components.add(new MockDIYComponent());
components.add(new MockDIYComponent());
List<BomEntry> bom = BomMaker.getInstance().createBom(components);
assertNotNull(bom);
assertEquals(2, bom.size());
BomEntry entry1 = bom.get(0);
assertEquals("something", entry1.getName());
assertEquals(2, (int) entry1.getQuantity());
BomEntry entry2 = bom.get(1);
assertEquals("something", entry2.getName());
assertEquals(1, (int) entry2.getQuantity());
}
}
@@ -1,22 +0,0 @@
package org.diylc.presenter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.diylc.common.PropertyWrapper;
import org.diylc.components.MockDIYComponent;
import org.junit.Test;
public class ClassProcessorTest {
@Test
public void testExtractProperties() {
List<PropertyWrapper> properties = ComponentProcessor.getInstance().extractProperties(
MockDIYComponent.class);
assertNotNull(properties);
assertEquals(4, properties.size());
};
}
-21
View File
@@ -1,21 +0,0 @@
<org.diylc.core.Theme>
<name>Blueprint</name>
<bgColor>
<red>3</red>
<green>122</green>
<blue>198</blue>
<alpha>255</alpha>
</bgColor>
<gridColor>
<red>29</red>
<green>140</green>
<blue>193</blue>
<alpha>255</alpha>
</gridColor>
<outlineColor>
<red>255</red>
<green>255</green>
<blue>255</blue>
<alpha>255</alpha>
</outlineColor>
</org.diylc.core.Theme>
-21
View File
@@ -1,21 +0,0 @@
<org.diylc.core.Theme>
<name>Dark</name>
<bgColor>
<red>0</red>
<green>0</green>
<blue>0</blue>
<alpha>255</alpha>
</bgColor>
<gridColor>
<red>40</red>
<green>40</green>
<blue>40</blue>
<alpha>255</alpha>
</gridColor>
<outlineColor>
<red>255</red>
<green>255</green>
<blue>255</blue>
<alpha>255</alpha>
</outlineColor>
</org.diylc.core.Theme>
-21
View File
@@ -1,21 +0,0 @@
<org.diylc.core.Theme>
<name>Light</name>
<bgColor>
<red>255</red>
<green>255</green>
<blue>255</blue>
<alpha>255</alpha>
</bgColor>
<gridColor>
<red>240</red>
<green>240</green>
<blue>240</blue>
<alpha>240</alpha>
</gridColor>
<outlineColor>
<red>0</red>
<green>0</green>
<blue>0</blue>
<alpha>255</alpha>
</outlineColor>
</org.diylc.core.Theme>
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/xstream-1.3.1.jar"/>
<classpathentry kind="lib" path="lib/log4j-1.2.15.jar"/>
<classpathentry kind="lib" path="lib/app-framework.jar"/>
<classpathentry combineaccessrules="false" kind="src" path="/diylc-core"/>
<classpathentry kind="output" path="bin"/>
</classpath>
-17
View File
@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>diylc-library</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
-63
View File
@@ -1,63 +0,0 @@
<project name="main" basedir="." default="jar">
<property name="src.dir" value="src" />
<property name="lib.dir" value="${basedir}/lib" />
<property name="build.dir" value="${basedir}/build" />
<property name="jar.dir" value="${build.dir}/jar" />
<property name="report.dir" value="${build.dir}/junitreport" />
<property name="classes.dir" value="${build.dir}/temp/${ant.project.name}/classes" />
<property name="test.classes.dir" value="${build.dir}/temp/${ant.project.name}/test.classes" />
<target name="clean">
<delete dir="${build.dir}" />
</target>
<target name="compile">
<mkdir dir="${classes.dir}" />
<echo>Compile with JDK ${java.runtime.version}</echo>
<javac encoding="8859_1" srcdir="${basedir}/${src.dir}" destdir="${classes.dir}" classpathref="class.path" debug="true" />
</target>
<target name="resource.copy">
<copy todir="${classes.dir}">
<fileset dir="${src.dir}">
<exclude name="**/*.java" />
</fileset>
</copy>
</target>
<target name="lib.copy">
<copy todir="${jar.dir}/lib" overwrite="true">
<fileset dir="${basedir}/lib">
<exclude name="**/*dll" />
</fileset>
</copy>
<copy todir="${jar.dir}" overwrite="true">
<fileset dir="${basedir}/lib/" includes="**/*.dll" />
</copy>
</target>
<path id="class.path">
<fileset dir="${basedir}">
<include name="lib/**/*.jar" />
</fileset>
</path>
<target name="jar" depends="clean, lib.copy, resource.copy, compile">
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}" />
<copy todir="../diylc-swing/library" overwrite="true">
<fileset dir="${jar.dir}" includes="${ant.project.name}.jar" />
</copy>
</target>
<target name="javadoc">
<javadoc access="public" author="true" classpathref="class.path" destdir="doc" nodeprecated="false" nodeprecatedlist="false" noindex="false" nonavbar="false" notree="false" source="1.6" splitindex="true" use="true" version="true">
<fileset dir="${src.dir}">
<exclude name="**\.svn\**" />
<include name="**/*.java" />
</fileset>
</javadoc>
</target>
</project>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,183 +0,0 @@
package org.diylc.components.boards;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Point;
import org.diylc.common.HorizontalAlignment;
import org.diylc.common.ObjectCache;
import org.diylc.common.VerticalAlignment;
import org.diylc.components.AbstractTransparentComponent;
import org.diylc.core.ComponentState;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
public abstract class AbstractBoard extends AbstractTransparentComponent<String> {
private static final long serialVersionUID = 1L;
public static Color BOARD_COLOR = Color.decode("#F8EBB3");
public static Color BORDER_COLOR = BOARD_COLOR.darker();
public static Color COORDINATE_COLOR = Color.gray.brighter();
public static float COORDINATE_FONT_SIZE = 9f;
public static Size DEFAULT_WIDTH = new Size(1.5d, SizeUnit.in);
public static Size DEFAULT_HEIGHT = new Size(1.2d, SizeUnit.in);
protected String value = "";
protected Point[] controlPoints = new Point[] {
new Point(0, 0),
new Point((int) DEFAULT_WIDTH.convertToPixels(), (int) DEFAULT_HEIGHT.convertToPixels()) };
protected Point firstPoint = new Point();
protected Point secondPoint = new Point();
protected Color boardColor = BOARD_COLOR;
protected Color borderColor = BORDER_COLOR;
protected Color coordinateColor = COORDINATE_COLOR;
protected Boolean drawCoordinates = true;
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
if (componentState != ComponentState.DRAGGING) {
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
g2d.setColor(boardColor);
g2d.fillRect(firstPoint.x, firstPoint.y, secondPoint.x - firstPoint.x, secondPoint.y
- firstPoint.y);
g2d.setComposite(oldComposite);
}
g2d.setColor(componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : borderColor);
g2d.drawRect(firstPoint.x, firstPoint.y, secondPoint.x - firstPoint.x, secondPoint.y
- firstPoint.y);
// Do not track any changes that follow because the whole board has been
// tracked so far.
drawingObserver.stopTracking();
}
protected void drawCoordinates(Graphics2D g2d, int spacing) {
if (!getDrawCoordinates())
return;
Point p = new Point(firstPoint);
g2d.setColor(coordinateColor);
g2d.setFont(LABEL_FONT.deriveFont(COORDINATE_FONT_SIZE));
int t = 1;
while (p.y < secondPoint.y - spacing) {
p.y += spacing;
super.drawCenteredText(g2d, getCoordinateLabel(t++), p.x + 2, p.y,
HorizontalAlignment.LEFT, VerticalAlignment.CENTER);
}
p = new Point(firstPoint);
t = 1;
while (p.x < secondPoint.x - spacing) {
p.x += spacing;
super.drawCenteredText(g2d, getCoordinateLabel(t++), p.x, p.y - 2,
HorizontalAlignment.CENTER, VerticalAlignment.TOP);
}
}
private String getCoordinateLabel(int coordinate) {
String result = "";
while (coordinate > 0) {
int digit = coordinate % 26;
coordinate /= 26;
if (digit == 0) {
result = 'Z' + result;
coordinate--;
} else {
result = (char) ((int) 'A' + digit - 1) + result;
}
}
return result;
}
@EditableProperty(name = "Color")
public Color getBoardColor() {
return boardColor;
}
public void setBoardColor(Color boardColor) {
this.boardColor = boardColor;
}
@EditableProperty(name = "Coordinate Color")
public Color getCoordinateColor() {
// Null protection for older files
return coordinateColor == null ? COORDINATE_COLOR : coordinateColor;
}
public void setCoordinateColor(Color coordinateColor) {
this.coordinateColor = coordinateColor;
}
@EditableProperty(name = "Border")
public Color getBorderColor() {
return borderColor;
}
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
@EditableProperty(name = "Draw Coordinates")
public boolean getDrawCoordinates() {
// Null protection for older files
return drawCoordinates == null || drawCoordinates;
}
public void setDrawCoordinates(boolean drawCoordinates) {
this.drawCoordinates = drawCoordinates;
}
@Override
public int getControlPointCount() {
return controlPoints.length;
}
@Override
public Point getControlPoint(int index) {
return controlPoints[index];
}
@Override
public boolean isControlPointSticky(int index) {
return false;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public void setControlPoint(Point point, int index) {
controlPoints[index].setLocation(point);
firstPoint.setLocation(Math.min(controlPoints[0].x, controlPoints[1].x), Math.min(
controlPoints[0].y, controlPoints[1].y));
secondPoint.setLocation(Math.max(controlPoints[0].x, controlPoints[1].x), Math.max(
controlPoints[0].y, controlPoints[1].y));
}
@EditableProperty
@Override
public String getValue() {
return value;
}
@Override
public void setValue(String value) {
this.value = value;
}
}
@@ -1,26 +0,0 @@
package org.diylc.components.boards;
import java.awt.Graphics2D;
import org.diylc.core.IDIYComponent;
import org.diylc.core.annotations.ComponentDescriptor;
@ComponentDescriptor(name = "Blank Board", category = "Boards", author = "Branislav Stojkovic", zOrder = IDIYComponent.BOARD, instanceNamePrefix = "Board", description = "Blank circuit board")
public class BlankBoard extends AbstractBoard {
private static final long serialVersionUID = 1L;
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BOARD_COLOR);
g2d.fillRect(2, 2, width - 4, height - 4);
g2d.setColor(BORDER_COLOR);
g2d.drawRect(2, 2, width - 4, height - 4);
}
@Override
public boolean getDrawCoordinates() {
// Override to prevent editing.
return super.getDrawCoordinates();
}
}
@@ -1,115 +0,0 @@
package org.diylc.components.boards;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
@ComponentDescriptor(name = "Eyelet Board", category = "Boards", author = "Branislav Stojkovic", zOrder = IDIYComponent.BOARD, instanceNamePrefix = "Board", description = "Perforated board with eyelets")
public class EyeletBoard extends AbstractBoard {
private static final long serialVersionUID = 1L;
public static Color BOARD_COLOR = Color.decode("#CCFFCC");
public static Color BORDER_COLOR = BOARD_COLOR.darker();
public static Color EYELET_COLOR = Color.decode("#C3E4ED");
public static Size SPACING = new Size(0.5d, SizeUnit.in);
public static Size EYELET_SIZE = new Size(0.2d, SizeUnit.in);
public static Size HOLE_SIZE = new Size(0.1d, SizeUnit.in);
// private Area copperArea;
protected Size spacing = SPACING;
protected Color eyeletColor = EYELET_COLOR;
public EyeletBoard() {
super();
this.boardColor = BOARD_COLOR;
this.borderColor = BORDER_COLOR;
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
Shape clip = g2d.getClip();
if (checkPointsClipped(clip) && !clip.contains(firstPoint.x, secondPoint.y)
&& !clip.contains(secondPoint.x, firstPoint.y)) {
return;
}
super.draw(g2d, componentState, outlineMode, project, drawingObserver);
if (componentState != ComponentState.DRAGGING) {
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
Point p = new Point(firstPoint);
int diameter = getClosestOdd((int) EYELET_SIZE.convertToPixels());
int holeDiameter = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int spacing = (int) this.spacing.convertToPixels();
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
while (p.x < secondPoint.x - spacing - diameter) {
p.x += spacing;
g2d.setColor(eyeletColor);
g2d.fillOval(p.x - diameter / 2, p.y - diameter / 2, diameter, diameter);
g2d.setColor(eyeletColor.darker());
g2d.drawOval(p.x - diameter / 2, p.y - diameter / 2, diameter, diameter);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeDiameter / 2, p.y - holeDiameter / 2, holeDiameter,
holeDiameter);
g2d.setColor(eyeletColor.darker());
g2d.drawOval(p.x - holeDiameter / 2, p.y - holeDiameter / 2, holeDiameter,
holeDiameter);
}
}
super.drawCoordinates(g2d, spacing);
}
}
@EditableProperty(name = "Eyelet color")
public Color getEyeletColor() {
return eyeletColor;
}
public void setEyeletColor(Color padColor) {
this.eyeletColor = padColor;
}
@EditableProperty
public Size getSpacing() {
return spacing;
}
public void setSpacing(Size spacing) {
this.spacing = spacing;
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BOARD_COLOR);
g2d.fillRect(2, 2, width - 4, height - 4);
g2d.setColor(BORDER_COLOR);
g2d.drawRect(2, 2, width - 4, height - 4);
g2d.setColor(EYELET_COLOR);
g2d.fillOval(width / 4, width / 4, width / 2, width / 2);
g2d.setColor(EYELET_COLOR.darker());
g2d.drawOval(width / 4, width / 4, width / 2, width / 2);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(width / 2 - 2, width / 2 - 2, 5, 5);
g2d.setColor(EYELET_COLOR.darker());
g2d.drawOval(width / 2 - 2, width / 2 - 2, 5, 5);
}
}
@@ -1,109 +0,0 @@
package org.diylc.components.boards;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
@ComponentDescriptor(name = "Marshall Style Perf Board", category = "Boards", author = "Branislav Stojkovic", zOrder = IDIYComponent.BOARD, instanceNamePrefix = "Board", description = "Perforated board as found on some Marshall and Trainwreck amps")
public class MarshallPerfBoard extends AbstractBoard {
private static final long serialVersionUID = 1L;
public static Color BOARD_COLOR = Color.decode("#CD8500");
public static Color BORDER_COLOR = BOARD_COLOR.darker();
public static Size SPACING = new Size(3 / 8d, SizeUnit.in);
public static Size HOLE_SIZE = new Size(1 / 8d, SizeUnit.in);
// private Area copperArea;
protected Size spacing = SPACING;
public MarshallPerfBoard() {
super();
this.boardColor = BOARD_COLOR;
this.borderColor = BORDER_COLOR;
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
Shape clip = g2d.getClip();
if (checkPointsClipped(clip) && !clip.contains(firstPoint.x, secondPoint.y)
&& !clip.contains(secondPoint.x, firstPoint.y)) {
return;
}
super.draw(g2d, componentState, outlineMode, project, drawingObserver);
if (componentState != ComponentState.DRAGGING) {
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
Point p = new Point(firstPoint);
int holeDiameter = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int spacing = (int) this.spacing.convertToPixels();
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
while (p.x < secondPoint.x - spacing - holeDiameter) {
p.x += spacing;
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeDiameter / 2, p.y - holeDiameter / 2, holeDiameter,
holeDiameter);
g2d.setColor(borderColor);
g2d.drawOval(p.x - holeDiameter / 2, p.y - holeDiameter / 2, holeDiameter,
holeDiameter);
}
}
super.drawCoordinates(g2d, spacing);
}
}
@EditableProperty
public Size getSpacing() {
return spacing;
}
public void setSpacing(Size spacing) {
this.spacing = spacing;
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BOARD_COLOR);
g2d.fillRect(2, 2, width - 4, height - 4);
g2d.setColor(BORDER_COLOR);
g2d.drawRect(2, 2, width - 4, height - 4);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(width / 3 - 2, width / 3 - 2, 5, 5);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(width / 3 - 2, width / 3 - 2, 5, 5);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(2 * width / 3 - 2, width / 3 - 2, 5, 5);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(2 * width / 3 - 2, width / 3 - 2, 5, 5);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(width / 3 - 2, 2 * width / 3 - 2, 5, 5);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(width / 3 - 2, 2 * width / 3 - 2, 5, 5);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(2 * width / 3 - 2, 2 * width / 3 - 2, 5, 5);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(2 * width / 3 - 2, 2 * width / 3 - 2, 5, 5);
}
}
@@ -1,107 +0,0 @@
package org.diylc.components.boards;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
@ComponentDescriptor(name = "Perf Board w/ Pads", category = "Boards", author = "Branislav Stojkovic", zOrder = IDIYComponent.BOARD, instanceNamePrefix = "Board", description = "Perforated board with solder pads")
public class PerfBoard extends AbstractBoard {
private static final long serialVersionUID = 1L;
public static Color COPPER_COLOR = Color.decode("#DA8A67");
public static Size SPACING = new Size(0.1d, SizeUnit.in);
public static Size PAD_SIZE = new Size(0.08d, SizeUnit.in);
public static Size HOLE_SIZE = new Size(0.7d, SizeUnit.mm);
// private Area copperArea;
protected Size spacing = SPACING;
protected Color padColor = COPPER_COLOR;
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
Shape clip = g2d.getClip();
if (checkPointsClipped(clip) && !clip.contains(firstPoint.x, secondPoint.y)
&& !clip.contains(secondPoint.x, firstPoint.y)) {
return;
}
super.draw(g2d, componentState, outlineMode, project, drawingObserver);
if (componentState != ComponentState.DRAGGING) {
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
Point p = new Point(firstPoint);
int diameter = getClosestOdd((int) PAD_SIZE.convertToPixels());
int holeDiameter = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int spacing = (int) this.spacing.convertToPixels();
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
while (p.x < secondPoint.x - spacing - diameter) {
p.x += spacing;
g2d.setColor(padColor);
g2d.fillOval(p.x - diameter / 2, p.y - diameter / 2, diameter, diameter);
g2d.setColor(padColor.darker());
g2d.drawOval(p.x - diameter / 2, p.y - diameter / 2, diameter, diameter);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeDiameter / 2, p.y - holeDiameter / 2, holeDiameter,
holeDiameter);
g2d.setColor(padColor.darker());
g2d.drawOval(p.x - holeDiameter / 2, p.y - holeDiameter / 2, holeDiameter,
holeDiameter);
}
}
super.drawCoordinates(g2d, spacing);
}
}
@EditableProperty(name = "Pad color")
public Color getPadColor() {
return padColor;
}
public void setPadColor(Color padColor) {
this.padColor = padColor;
}
@EditableProperty
public Size getSpacing() {
return spacing;
}
public void setSpacing(Size spacing) {
this.spacing = spacing;
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BOARD_COLOR);
g2d.fillRect(2, 2, width - 4, height - 4);
g2d.setColor(BORDER_COLOR);
g2d.drawRect(2, 2, width - 4, height - 4);
g2d.setColor(COPPER_COLOR);
g2d.fillOval(width / 4, width / 4, width / 2, width / 2);
g2d.setColor(COPPER_COLOR.darker());
g2d.drawOval(width / 4, width / 4, width / 2, width / 2);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(width / 2 - 2, width / 2 - 2, 5, 5);
g2d.setColor(COPPER_COLOR.darker());
g2d.drawOval(width / 2 - 2, width / 2 - 2, 5, 5);
}
}
@@ -1,143 +0,0 @@
package org.diylc.components.boards;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import org.diylc.common.OrientationHV;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
@ComponentDescriptor(name = "Vero Board", category = "Boards", author = "Branislav Stojkovic", zOrder = IDIYComponent.BOARD, instanceNamePrefix = "Board", description = "Perforated FR4 board with copper strips connecting all holes in a row")
public class VeroBoard extends AbstractBoard {
private static final long serialVersionUID = 1L;
public static Color STRIP_COLOR = Color.decode("#DA8A67");
public static Color BORDER_COLOR = BOARD_COLOR.darker();
public static Size SPACING = new Size(0.1d, SizeUnit.in);
public static Size STRIP_SIZE = new Size(0.07d, SizeUnit.in);
public static Size HOLE_SIZE = new Size(0.7d, SizeUnit.mm);
protected Size spacing = SPACING;
protected Color stripColor = STRIP_COLOR;
protected OrientationHV orientation = OrientationHV.HORIZONTAL;
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
Shape clip = g2d.getClip();
if (checkPointsClipped(clip) && !clip.contains(firstPoint.x, secondPoint.y)
&& !clip.contains(secondPoint.x, firstPoint.y)) {
return;
}
super.draw(g2d, componentState, outlineMode, project, drawingObserver);
if (componentState != ComponentState.DRAGGING) {
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
Point p = new Point(firstPoint);
int stripSize = getClosestOdd((int) STRIP_SIZE.convertToPixels());
int holeSize = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int spacing = (int) this.spacing.convertToPixels();
if (orientation == OrientationHV.HORIZONTAL) {
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
g2d.setColor(stripColor);
g2d.fillRect(p.x + spacing / 2, p.y - stripSize / 2, secondPoint.x - spacing
- p.x, stripSize);
g2d.setColor(stripColor.darker());
g2d.drawRect(p.x + spacing / 2, p.y - stripSize / 2, secondPoint.x - spacing
- p.x, stripSize);
while (p.x < secondPoint.x - spacing - holeSize) {
p.x += spacing;
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
g2d.setColor(stripColor.darker());
g2d.drawOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
}
}
} else {
while (p.x < secondPoint.x - spacing) {
p.x += spacing;
p.y = firstPoint.y;
g2d.setColor(stripColor);
g2d.fillRect(p.x - stripSize / 2, p.y + spacing / 2, stripSize, secondPoint.y
- spacing - p.y);
g2d.setColor(stripColor.darker());
g2d.drawRect(p.x - stripSize / 2, p.y + spacing / 2, stripSize, secondPoint.y
- spacing - p.y);
while (p.y < secondPoint.y - spacing - holeSize) {
p.y += spacing;
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
g2d.setColor(stripColor.darker());
g2d.drawOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
}
}
}
g2d.setComposite(oldComposite);
super.drawCoordinates(g2d, spacing);
}
}
@EditableProperty(name = "Strip color")
public Color getStripColor() {
return stripColor;
}
public void setStripColor(Color padColor) {
this.stripColor = padColor;
}
@EditableProperty
public Size getSpacing() {
return spacing;
}
public void setSpacing(Size spacing) {
this.spacing = spacing;
}
@EditableProperty
public OrientationHV getOrientation() {
return orientation;
}
public void setOrientation(OrientationHV orientation) {
this.orientation = orientation;
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BOARD_COLOR);
g2d.fillRect(2, 2, width - 4, height - 4);
g2d.setColor(BORDER_COLOR);
g2d.drawRect(2, 2, width - 4, height - 4);
g2d.setColor(STRIP_COLOR);
g2d.fillRect(4, width / 4, width - 8, width / 2);
g2d.setColor(STRIP_COLOR.darker());
g2d.drawRect(4, width / 4, width - 8, width / 2);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(width / 3 - 2, width / 2 - 2, 5, 5);
g2d.fillOval(2 * width / 3 - 2, width / 2 - 2, 5, 5);
g2d.setColor(STRIP_COLOR.darker());
g2d.drawOval(width / 3 - 2, width / 2 - 2, 5, 5);
g2d.drawOval(2 * width / 3 - 2, width / 2 - 2, 5, 5);
}
}
@@ -1,15 +0,0 @@
package org.diylc.components.connectivity;
public enum AWG {
_8, _10, _12, _14, _16, _18, _20, _22, _24, _26, _28, _30;
@Override
public String toString() {
return "#" + name().replace("_", "");
}
public int getValue() {
return Integer.parseInt(name().replace("_", ""));
}
}

Some files were not shown because too many files have changed in this diff Show More