Compare commits

..

1 Commits

Author SHA1 Message Date
bancika 405608dd44 package renamed 2011-01-04 19:06:09 +00:00
304 changed files with 3684 additions and 12161 deletions
+2 -1
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"/>
@@ -10,8 +11,8 @@
<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="output" path="bin"/>
</classpath>
View File
-15
View File
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.jdt.launching.localJavaApplication">
<stringAttribute key="bad_container_name" value="\DIYLC\r"/>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/DIYLC/src/org/diylc/DIYLCStarter.java"/>
</listAttribute>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="1"/>
</listAttribute>
<stringAttribute key="org.eclipse.debug.core.source_locator_id" value="org.eclipse.jdt.launching.sourceLocator.JavaSourceLookupDirector"/>
<stringAttribute key="org.eclipse.debug.core.source_locator_memento" value="&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt;&#13;&#10;&lt;sourceLookupDirector&gt;&#13;&#10;&lt;sourceContainers duplicates=&quot;false&quot;&gt;&#13;&#10;&lt;container memento=&quot;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; standalone=&amp;quot;no&amp;quot;?&amp;gt;&amp;#13;&amp;#10;&amp;lt;javaProject name=&amp;quot;Library&amp;quot;/&amp;gt;&amp;#13;&amp;#10;&quot; typeId=&quot;org.eclipse.jdt.launching.sourceContainer.javaProject&quot;/&gt;&#13;&#10;&lt;container memento=&quot;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; standalone=&amp;quot;no&amp;quot;?&amp;gt;&amp;#13;&amp;#10;&amp;lt;javaProject name=&amp;quot;DIYLC&amp;quot;/&amp;gt;&amp;#13;&amp;#10;&quot; typeId=&quot;org.eclipse.jdt.launching.sourceContainer.javaProject&quot;/&gt;&#13;&#10;&lt;container memento=&quot;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; standalone=&amp;quot;no&amp;quot;?&amp;gt;&amp;#13;&amp;#10;&amp;lt;default/&amp;gt;&amp;#13;&amp;#10;&quot; typeId=&quot;org.eclipse.debug.core.containerType.default&quot;/&gt;&#13;&#10;&lt;/sourceContainers&gt;&#13;&#10;&lt;/sourceLookupDirector&gt;&#13;&#10;"/>
<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.diylc.DIYLCStarter"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="DIYLC"/>
<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-Xms256m -Xmx512m"/>
</launchConfiguration>
-2
View File
@@ -1,2 +0,0 @@
#org.diylc.utils.Constants.CANVAS_COLOR=#005D96
#org.diylc.utils.Constants.GRID_COLOR=#FFFFFF
-22
View File
@@ -1,22 +0,0 @@
<map>
<entry>
<string>lastPath</string>
<string>C:\Documents and Settings\Branislav Stojkovic\Desktop\oldFiles</string>
</entry>
<entry>
<string>zoom</string>
<double>1.0</double>
</entry>
<entry>
<string>metric</string>
<boolean>true</boolean>
</entry>
<entry>
<string>showTemplatesAtStartup</string>
<boolean>false</boolean>
</entry>
<entry>
<string>default.org.diylc.components.semiconductors.TransistorTO92:Orientation</string>
<org.diylc.common.Orientation>DEFAULT</org.diylc.common.Orientation>
</entry>
</map>
Binary file not shown.
-74
View File
@@ -1,74 +0,0 @@
package org.diylc;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Properties;
import javax.swing.UIManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.diylc.presenter.Presenter;
import org.diylc.swing.gui.MainFrame;
import org.diylc.swing.gui.TemplateDialog;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.diyfever.gui.miscutils.PropertyInjector;
/**
* Main class that runs DIYLC.
*
* @author Branislav Stojkovic
*
* @see Presenter
* @see MainFrame
*/
public class DIYLCStarter {
private static final Logger LOG = Logger.getLogger(Presenter.class);
/**
* @param args
*/
public static void main(String[] args) {
URL url = DIYLCStarter.class.getResource("log4j.properties");
Properties properties = new Properties();
try {
properties.load(url.openStream());
PropertyConfigurator.configure(properties);
} catch (Exception e) {
LOG.error("Could not initialize log4j configuration", e);
}
LOG.info("Starting DIYLC with working directory " + System.getProperty("user.dir"));
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
LOG.error("Could not set Look&Feel", e);
}
MainFrame mainFrame = new MainFrame();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
boolean showTemplates = ConfigurationManager.getInstance().readBoolean(
TemplateDialog.SHOW_TEMPLATES_KEY, true);
if (showTemplates) {
TemplateDialog templateDialog = new TemplateDialog(mainFrame, mainFrame.getPresenter());
if (!templateDialog.getFiles().isEmpty()) {
templateDialog.setVisible(true);
}
}
url = DIYLCStarter.class.getResource("/config.properties");
properties = new Properties();
try {
LOG.info("Injecting default properties.");
properties.load(new FileInputStream("config.properties"));
PropertyInjector.injectProperties(properties);
} catch (Exception e) {
LOG.error("Could not read config.properties file", e);
}
}
}
@@ -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;
}
}
-11
View File
@@ -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();
}
}
-6
View File
@@ -1,6 +0,0 @@
package org.diylc.common;
public enum GridType {
LINES, CROSSHAIR, DOT, NONE;
}
@@ -1,8 +0,0 @@
package org.diylc.common;
import org.diylc.core.IDIYComponent;
public interface IComponentFiler {
boolean testComponent(IDIYComponent<?> component);
}
-34
View File
@@ -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,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";
}
}
}
-5
View File
@@ -1,5 +0,0 @@
package org.diylc.common;
public enum Power {
}
@@ -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,59 +0,0 @@
package org.diylc.components;
import java.awt.Color;
import java.awt.Font;
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, 12);
@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(int x) {
return (x / 2) * 2 + 1;
}
}
@@ -1,136 +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(DEFAULT_SIZE.convertToPixels() / 2, 0),
new Point(DEFAULT_SIZE.convertToPixels() / 2, DEFAULT_SIZE.convertToPixels()),
new Point(DEFAULT_SIZE.convertToPixels(), DEFAULT_SIZE.convertToPixels()) };
protected Color color = getDefaultColor();
/**
* Draws the specified curve onto graphics.
*
* @param curve
* @param g2d
* @param componentState
*/
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, Project project,
IDrawingObserver drawingObserver) {
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);
}
@Override
public int getControlPointCount() {
return controlPoints.length;
}
@Override
public boolean isControlPointSticky(int index) {
return index == 0 || index == 3;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public boolean canControlPointOverlap(int index) {
// Only shape control points may overlap.
return index == 1 || index == 2;
}
@Override
public Point getControlPoint(int index) {
return controlPoints[index];
}
@Override
public void setControlPoint(Point point, int index) {
controlPoints[index].setLocation(point);
}
@EditableProperty
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
@@ -1,249 +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.Rectangle2D;
import org.diylc.common.Display;
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;
/**
* 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(DEFAULT_SIZE.convertToPixels() / 2, 0) };
protected Color bodyColor = Color.white;
protected Color borderColor = Color.black;
protected Color labelColor = LABEL_COLOR;
protected Display display = Display.NAME;
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, Project project,
IDrawingObserver drawingObserver) {
double distance = points[0].distance(points[1]);
Shape shape = getBodyShape();
if (shape == null) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(
getLeadThickness().convertToPixels()));
g2d.setColor(shouldShadeLeads() ? getLeadColor(componentState).darker()
: getLeadColor(componentState));
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(
getLeadThickness().convertToPixels() - 2));
g2d.setColor(getLeadColor(componentState));
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
}
return;
}
Rectangle shapeRect = shape.getBounds();
double leadLenght = (distance - shapeRect.width) / 2;
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.
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));
}
g2d.setColor(bodyColor);
g2d.fill(shape);
decorateComponentBody(g2d);
g2d.setComposite(oldComposite);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
g2d.setColor(componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : borderColor);
g2d.draw(shape);
// Draw leads.
int leadThickness = getClosestOdd(getLeadThickness().convertToPixels());
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness));
g2d.setColor(shouldShadeLeads() ? getLeadColor(componentState).darker()
: getLeadColor(componentState));
g2d.drawLine((int) (shapeRect.width - distance) / 2, (int) shapeRect.height / 2,
(int) ((shapeRect.width - distance) / 2 + leadLenght) - leadThickness / 2,
(int) shapeRect.height / 2);
g2d.drawLine((int) (shapeRect.width + distance) / 2, (int) shapeRect.height / 2,
(int) ((shapeRect.width + distance) / 2 - leadLenght) + leadThickness / 2,
(int) shapeRect.height / 2);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness - 2));
g2d.setColor(getLeadColor(componentState));
g2d.drawLine((int) (shapeRect.width - distance) / 2, (int) shapeRect.height / 2,
(int) ((shapeRect.width - distance) / 2 + leadLenght) - leadThickness / 2,
(int) shapeRect.height / 2);
g2d.drawLine((int) (shapeRect.width + distance) / 2, (int) shapeRect.height / 2,
(int) ((shapeRect.width + distance) / 2 - leadLenght) + leadThickness / 2,
(int) shapeRect.height / 2);
}
// Do not track the label because that area was already covered.
drawingObserver.stopTracking();
// Draw label.
g2d.setFont(LABEL_FONT);
g2d.setColor(componentState == ComponentState.SELECTED ? LABEL_COLOR_SELECTED : labelColor);
FontMetrics fontMetrics = g2d.getFontMetrics();
String label = display == Display.NAME ? getName() : getValue().toString();
// 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);
}
Rectangle2D textRect = fontMetrics.getStringBounds(label, g2d);
g2d.drawString(label, (int) (shapeRect.width - textRect.getWidth()) / 2,
(int) (shapeRect.height - textRect.getHeight()) / 2 + fontMetrics.getAscent());
}
protected void decorateComponentBody(Graphics2D g2d) {
// Do nothing.
}
protected boolean shouldShadeLeads() {
return true;
}
/**
* @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 Size getLeadThickness() {
return LEAD_THICKNESS;
}
/**
* @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,36 +0,0 @@
package org.diylc.components;
import java.awt.Point;
public abstract class AbstractSinglePointComponent extends AbstractComponent<Void> {
private static final long serialVersionUID = 1L;
protected Point point = new Point(0, 0);
@Override
public int getControlPointCount() {
return 1;
}
@Override
public Point getControlPoint(int index) {
return point;
}
@Override
public void setControlPoint(Point point, int index) {
this.point.setLocation(point);
}
@Deprecated
@Override
public Void getValue() {
return null;
}
@Deprecated
@Override
public void setValue(Void value) {
}
}
@@ -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;
}
-121
View File
@@ -1,121 +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 project
* @param drawingObserver
*/
void draw(Graphics2D g2d, ComponentState componentState, 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;
}
-28
View File
@@ -1,28 +0,0 @@
package org.diylc.core;
/**
* 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;
void showMessage(String message, String title, int messageType);
int showConfirmDialog(String message, String title, int optionType, int messageType);
}
@@ -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,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) Math.round(base / 10)];
bands[1] = COLOR_DIGITS[(int) Math.round(base % 10)];
bands[2] = COLOR_MULTIPLIER[multiplier + 2];
break;
case _5_BAND:
bands = new Color[4];
bands[0] = COLOR_DIGITS[(int) Math.round(base / 100)];
bands[1] = COLOR_DIGITS[(int) Math.round(base / 10 % 10)];
bands[2] = COLOR_DIGITS[(int) Math.round(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() - 1).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 int 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 (int) (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());
}
}
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: 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: 838 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 550 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) {
int grid = gridSpacing.convertToPixels();
return (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,211 +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, setter, 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 mutual 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);
// 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,345 +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.common.DrawOption;
import org.diylc.common.EventType;
import org.diylc.common.GridType;
import org.diylc.common.IComponentFiler;
import org.diylc.common.ObjectCache;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.VisibilityPolicy;
import org.diylc.utils.Constants;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.diyfever.gui.simplemq.MessageDispatcher;
/**
* 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 ANTIALIASING_KEY = "anti-aliasing";
public static final String ZOOM_KEY = "zoom";
public static boolean DEBUG_COMPONENT_AREAS = false;
public static Color GRID_COLOR = new Color(240, 240, 240);
public static Color CONTROL_POINT_COLOR = Color.black;
public static Color SELECTED_CONTROL_POINT_COLOR = Color.green;
// 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;
public DrawingManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.messageDispatcher = messageDispatcher;
componentAreaMap = new HashMap<IDIYComponent<?>, Area>();
lastDrawnStateMap = new HashMap<IDIYComponent<?>, ComponentState>();
}
/**
* 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)
&& ConfigurationManager.getInstance().readBoolean(ANTIALIASING_KEY, true)) {
g2d
.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
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(Constants.CANVAS_COLOR);
g2dWrapper.fillRect(0, 0, d.width, d.height);
g2d.setClip(new Rectangle(new Point(0, 0), d));
GridType gridType = (GridType) ConfigurationManager.getInstance().readObject(
ANTIALIASING_KEY, 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(GRID_COLOR);
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;
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, project, g2dWrapper);
} catch (Exception e) {
LOG.error("Error drawing " + component.getName(), e);
failedComponents.add(component);
}
Area area = g2dWrapper.finishedDrawingComponent();
if (trackArea) {
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.
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, 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 (DEBUG_COMPONENT_AREAS) {
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 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(project.getComponents().get(i));
}
}
return components;
}
public Dimension getCanvasDimensions(Project project, Double zoomLevel, boolean useZoom) {
double width = project.getWidth().convertToPixels();
int 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);
}
}
@@ -1,191 +0,0 @@
package org.diylc.presenter;
import java.awt.Point;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.apache.log4j.Logger;
import org.diylc.common.ComponentType;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.measures.Size;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.rits.cloning.Cloner;
/**
* Manages component instantiation.
*
* @author Branislav Stojkovic
*/
public class InstantiationManager {
private static final Logger LOG = Logger.getLogger(InstantiationManager.class);
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;
}
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();
// Find the next available componentName for the component.
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;
}
}
}
component.setName(componentType.getNamePrefix() + i);
// 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);
return component;
}
/**
* 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
*/
public void fillWithDefaultProperties(Object object) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
// 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);
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,431 +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.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.common.EventType;
import org.diylc.common.Orientation;
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.ElectrolyticRadial;
import org.diylc.components.passive.RadialFilmCapacitor;
import org.diylc.components.passive.Resistor;
import org.diylc.components.semiconductors.DIL_IC;
import org.diylc.components.semiconductors.DiodePlastic;
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.diyfever.gui.simplemq.MessageDispatcher;
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;
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);
this.messageDispatcher = messageDispatcher;
}
public void startNewFile() {
currentFileName = null;
modified = false;
fireFileStatusChanged();
}
public void serializeProjectToFile(Project project, String fileName) throws IOException {
LOG.info(String.format("saveProjectToFile(%s)", fileName));
FileOutputStream fos;
fos = new FileOutputStream(fileName);
xStream.toXML(project, fos);
fos.close();
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 = project.getWidth().convertToPixels();
int projectHeight = 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(roundToGrid(x, V1_GRID_SPACING), roundToGrid(y,
V1_GRID_SPACING));
board.setControlPoint(referencePoint, 0);
board.setControlPoint(new Point(roundToGrid(x + boardWidth, V1_GRID_SPACING), 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), 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);
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(6d, SizeUnit.mm));
resistor.setWidth(new Size(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);
ElectrolyticRadial capacitor = new ElectrolyticRadial();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
String sizeAttr = node.getAttributes().getNamedItem("Size").getNodeValue();
if (sizeAttr.equalsIgnoreCase("small")) {
capacitor.setLength(new Size(3d, 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));
}
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("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();
if (x1Attr + 3 == x2Attr) {
if (y1Attr < y2Attr) {
ic
.setPinCount(DIL_IC.PinCount.valueOf("_" + 2
* (y2Attr - y1Attr + 1)));
} else {
ic.setOrientation(Orientation._180);
ic
.setPinCount(DIL_IC.PinCount.valueOf("_" + 2
* (y1Attr - y2Attr + 1)));
}
}
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 {
String message = "Could not recognize component type " + nodeName;
LOG.debug(message);
if (!warnings.contains(message)) {
warnings.add(message);
}
}
if (component != null) {
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 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);
project = (Project) xStream.fromXML(fis);
fis.close();
return project;
}
public int roundToGrid(int x, Size gridSpacing) {
int grid = gridSpacing.convertToPixels();
return (Math.round(1f * x / grid) * grid);
}
}
@@ -1,792 +0,0 @@
package org.diylc.swing;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.print.PrinterException;
import java.io.File;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.KeyStroke;
import org.apache.log4j.Logger;
import org.diylc.common.IPlugInPort;
import org.diylc.common.ITask;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IDIYComponent;
import org.diylc.images.IconLoader;
import org.diylc.swing.gui.DialogFactory;
import org.diylc.swing.gui.editor.PropertyEditorDialog;
import org.diylc.swing.plugins.edit.ComponentTransferable;
import org.diylc.swing.plugins.file.BomDialog;
import org.diylc.swing.plugins.file.BomEntry;
import org.diylc.swing.plugins.file.BomMaker;
import org.diylc.swing.plugins.file.FileFilterEnum;
import com.diyfever.gui.ButtonDialog;
import com.diyfever.gui.IDrawingProvider;
import com.diyfever.gui.export.DrawingExporter;
import com.rits.cloning.Cloner;
public class ActionFactory {
private static final Logger LOG = Logger.getLogger(ActionFactory.class);
private static ActionFactory instance;
private static Cloner cloner = new Cloner();
public static ActionFactory getInstance() {
if (instance == null) {
instance = new ActionFactory();
}
return instance;
}
private ActionFactory() {
}
// File menu actions.
public NewAction createNewAction(IPlugInPort plugInPort) {
return new NewAction(plugInPort);
}
public OpenAction createOpenAction(IPlugInPort plugInPort, ISwingUI swingUI) {
return new OpenAction(plugInPort, swingUI);
}
public SaveAction createSaveAction(IPlugInPort plugInPort, ISwingUI swingUI) {
return new SaveAction(plugInPort, swingUI);
}
public SaveAsAction createSaveAsAction(IPlugInPort plugInPort, ISwingUI swingUI) {
return new SaveAsAction(plugInPort, swingUI);
}
public CreateBomAction createBomAction(IPlugInPort plugInPort) {
return new CreateBomAction(plugInPort);
}
public ExportPDFAction createExportPDFAction(IDrawingProvider drawingProvider, ISwingUI swingUI) {
return new ExportPDFAction(drawingProvider, swingUI);
}
public ExportPNGAction createExportPNGAction(IDrawingProvider drawingProvider, ISwingUI swingUI) {
return new ExportPNGAction(drawingProvider, swingUI);
}
public PrintAction createPrintAction(IDrawingProvider drawingProvider) {
return new PrintAction(drawingProvider);
}
public ExitAction createExitAction(IPlugInPort plugInPort) {
return new ExitAction(plugInPort);
}
// Edit menu actions.
public CutAction createCutAction(IPlugInPort plugInPort, Clipboard clipboard,
ClipboardOwner clipboardOwner) {
return new CutAction(plugInPort, clipboard, clipboardOwner);
}
public CopyAction createCopyAction(IPlugInPort plugInPort, Clipboard clipboard,
ClipboardOwner clipboardOwner) {
return new CopyAction(plugInPort, clipboard, clipboardOwner);
}
public PasteAction createPasteAction(IPlugInPort plugInPort, Clipboard clipboard) {
return new PasteAction(plugInPort, clipboard);
}
public SelectAllAction createSelectAllAction(IPlugInPort plugInPort) {
return new SelectAllAction(plugInPort);
}
public GroupAction createGroupAction(IPlugInPort plugInPort) {
return new GroupAction(plugInPort);
}
public UngroupAction createUngroupAction(IPlugInPort plugInPort) {
return new UngroupAction(plugInPort);
}
public EditProjectAction createEditProjectAction(IPlugInPort plugInPort) {
return new EditProjectAction(plugInPort);
}
public EditSelectionAction createEditSelectionAction(IPlugInPort plugInPort) {
return new EditSelectionAction(plugInPort);
}
public DeleteSelectionAction createDeleteSelectionAction(IPlugInPort plugInPort) {
return new DeleteSelectionAction(plugInPort);
}
public SendToBackAction createSendToBackAction(IPlugInPort plugInPort) {
return new SendToBackAction(plugInPort);
}
public BringToFrontAction createBringToFrontAction(IPlugInPort plugInPort) {
return new BringToFrontAction(plugInPort);
}
// File menu actions.
public static class NewAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public NewAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "New");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.DocumentPlainYellow.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("NewAction triggered");
if (!plugInPort.allowFileAction()) {
return;
}
plugInPort.createNewProject();
List<PropertyWrapper> properties = plugInPort.getProjectProperties();
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Project");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToProject(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setProjectDefaultPropertyValue(property.getName(), property
.getValue());
}
}
}
}
public static class OpenAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private ISwingUI swingUI;
public OpenAction(IPlugInPort plugInPort, ISwingUI swingUI) {
super();
this.plugInPort = plugInPort;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Open");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.FolderOut.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("OpenAction triggered");
if (!plugInPort.allowFileAction()) {
return;
}
final File file = DialogFactory.getInstance().showOpenDialog(
FileFilterEnum.DIY.getFilter(), null, FileFilterEnum.DIY.getExtensions()[0],
null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Opening from " + file.getAbsolutePath());
plugInPort.loadProjectFromFile(file.getAbsolutePath());
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not open file. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class SaveAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private ISwingUI swingUI;
public SaveAction(IPlugInPort plugInPort, ISwingUI swingUI) {
super();
this.plugInPort = plugInPort;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Save");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.DiskBlue.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("SaveAction triggered");
if (plugInPort.getCurrentFileName() == null) {
final File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.DIY.getFilter(), null,
FileFilterEnum.DIY.getExtensions()[0], null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + file.getAbsolutePath());
plugInPort.saveProjectToFile(file.getAbsolutePath());
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not save to file. " + e.getMessage(),
"Error", ISwingUI.ERROR_MESSAGE);
}
});
}
} else {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + plugInPort.getCurrentFileName());
plugInPort.saveProjectToFile(plugInPort.getCurrentFileName());
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not save to file. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class SaveAsAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private ISwingUI swingUI;
public SaveAsAction(IPlugInPort plugInPort, ISwingUI swingUI) {
super();
this.plugInPort = plugInPort;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Save As");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S,
ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.DiskBlue.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("SaveAsAction triggered");
final File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.DIY.getFilter(), null, FileFilterEnum.DIY.getExtensions()[0],
null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + file.getAbsolutePath());
plugInPort.saveProjectToFile(file.getAbsolutePath());
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not save to file. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class CreateBomAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public CreateBomAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Create B.O.M.");
putValue(AbstractAction.SMALL_ICON, IconLoader.BOM.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("CreateBomAction triggered");
List<BomEntry> bom = BomMaker.getInstance().createBom(
plugInPort.getCurrentProject().getComponents());
BomDialog dialog = DialogFactory.getInstance().createBomDialog(bom);
dialog.setVisible(true);
}
}
public static class ExportPDFAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
private ISwingUI swingUI;
public ExportPDFAction(IDrawingProvider drawingProvider, ISwingUI swingUI) {
super();
this.drawingProvider = drawingProvider;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Export to PDF");
putValue(AbstractAction.SMALL_ICON, IconLoader.PDF.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("ExportPDFAction triggered");
final File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.PDF.getFilter(), null, FileFilterEnum.PDF.getExtensions()[0],
null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Exporting to " + file.getAbsolutePath());
DrawingExporter.getInstance().exportPDF(
ExportPDFAction.this.drawingProvider, file);
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not export to PDF. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class ExportPNGAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
private ISwingUI swingUI;
public ExportPNGAction(IDrawingProvider drawingProvider, ISwingUI swingUI) {
super();
this.drawingProvider = drawingProvider;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Export to PNG");
putValue(AbstractAction.SMALL_ICON, IconLoader.Image.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("ExportPNGAction triggered");
final File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.PNG.getFilter(), null, FileFilterEnum.PNG.getExtensions()[0],
null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Exporting to " + file.getAbsolutePath());
DrawingExporter.getInstance().exportPNG(
ExportPNGAction.this.drawingProvider, file);
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not export to PNG. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class PrintAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
public PrintAction(IDrawingProvider drawingProvider) {
super();
this.drawingProvider = drawingProvider;
putValue(AbstractAction.NAME, "Print...");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Print.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("ExportPNGAction triggered");
try {
DrawingExporter.getInstance().print(this.drawingProvider);
} catch (PrinterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public static class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public ExitAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Exit");
putValue(AbstractAction.SMALL_ICON, IconLoader.Exit.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
if (plugInPort.allowFileAction()) {
System.exit(0);
}
}
}
// Edit menu actions.
public static class CutAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private Clipboard clipboard;
private ClipboardOwner clipboardOwner;
public CutAction(IPlugInPort plugInPort, Clipboard clipboard, ClipboardOwner clipboardOwner) {
super();
this.plugInPort = plugInPort;
this.clipboard = clipboard;
this.clipboardOwner = clipboardOwner;
putValue(AbstractAction.NAME, "Cut");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Cut.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Cut triggered");
clipboard.setContents(new ComponentTransferable(cloner.deepClone(plugInPort
.getSelectedComponents())), clipboardOwner);
plugInPort.deleteSelectedComponents();
}
}
public static class CopyAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private Clipboard clipboard;
private ClipboardOwner clipboardOwner;
public CopyAction(IPlugInPort plugInPort, Clipboard clipboard, ClipboardOwner clipboardOwner) {
super();
this.plugInPort = plugInPort;
this.clipboard = clipboard;
this.clipboardOwner = clipboardOwner;
putValue(AbstractAction.NAME, "Copy");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Copy.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Copy triggered");
clipboard.setContents(new ComponentTransferable(cloner.deepClone(plugInPort
.getSelectedComponents())), clipboardOwner);
}
}
public static class PasteAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private Clipboard clipboard;
public PasteAction(IPlugInPort plugInPort, Clipboard clipboard) {
super();
this.plugInPort = plugInPort;
this.clipboard = clipboard;
putValue(AbstractAction.NAME, "Paste");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Paste.getIcon());
}
@SuppressWarnings("unchecked")
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Paste triggered");
try {
List<IDIYComponent<?>> components = (List<IDIYComponent<?>>) clipboard
.getData(ComponentTransferable.listFlavor);
plugInPort.pasteComponents(cloner.deepClone(components));
} catch (Exception ex) {
LOG.error("Coule not paste.", ex);
}
}
}
public static class SelectAllAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public SelectAllAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Select All");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Selection.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Select All triggered");
plugInPort.selectAll();
}
}
public static class GroupAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public GroupAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Group Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_G,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Group.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Group Selection triggered");
plugInPort.groupSelectedComponents();
}
}
public static class UngroupAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public UngroupAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Ungroup Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_U,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Ungroup.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Ungroup Selection triggered");
plugInPort.ungroupSelectedComponents();
}
}
public static class EditProjectAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public EditProjectAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Edit Project");
putValue(AbstractAction.SMALL_ICON, IconLoader.DocumentEdit.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Edit Project triggered");
List<PropertyWrapper> properties = plugInPort.getProjectProperties();
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Project");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToProject(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setProjectDefaultPropertyValue(property.getName(), property
.getValue());
}
}
}
}
public static class EditSelectionAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public EditSelectionAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Edit Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.EditComponent.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Edit Selection triggered");
List<PropertyWrapper> properties = plugInPort.getMutualSelectionProperties();
if (properties == null || properties.isEmpty()) {
LOG.info("Nothing to edit");
return;
}
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Selection");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToSelection(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setSelectionDefaultPropertyValue(property.getName(), property
.getValue());
}
}
}
}
public static class DeleteSelectionAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public DeleteSelectionAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Delete Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
putValue(AbstractAction.SMALL_ICON, IconLoader.Delete.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Delete Selection triggered");
plugInPort.deleteSelectedComponents();
}
}
public static class SendToBackAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public SendToBackAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Send to Back");
putValue(AbstractAction.SMALL_ICON, IconLoader.Back.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Send to Back triggered");
plugInPort.sendSelectionToBack();
}
}
public static class BringToFrontAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public BringToFrontAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Bring to Front");
putValue(AbstractAction.SMALL_ICON, IconLoader.Front.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Bring to Front triggered");
plugInPort.bringSelectionToFront();
}
}
}
-64
View File
@@ -1,64 +0,0 @@
package org.diylc.swing;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.SwingConstants;
import javax.swing.JPopupMenu.Separator;
import org.diylc.common.BadPositionException;
import org.diylc.common.ITask;
import org.diylc.core.IView;
/**
* Interface for plugin access to the swing front end.
*
* @author Branislav Stojkovic
*/
public interface ISwingUI extends IView {
/**
* Injects a custom GUI panels provided by the plug-in and desired position
* in the window. Application will layout plug-in panels accordingly. <br>
* Valid positions are:
* <ul>
* <li> {@link SwingConstants#TOP}</li>
* <li> {@link SwingConstants#BOTTOM}</li>
* <li> {@link SwingConstants#LEFT}</li>
* <li> {@link SwingConstants#RIGHT}</li>
* </ul>
*
* Center position is reserved for the main canvas panel and cannot be used.
*
* @param component
* @param position
* @throws BadPositionException
* in case invalid position is specified
*/
void injectGUIComponent(JComponent component, int position) throws BadPositionException;
/**
* Injects a custom menu action into application's main menu. If
* <code>action</code> is set to null {@link Separator} will be added. If
* the specified menu does not exist it will be automatically created.
*
* @param action
* {@link Action} to inser
* @param menuName
* name of the menu to insert into
*/
void injectMenuAction(Action action, String menuName);
/**
* Injects a custom submenu into application's main menu. If
* <code>action</code> is set to null {@link Separator} will be added. If
* the specified menu does not exist it will be automatically created.
*
* @param name
* @param icon
* @param parentMenuName
*/
void injectSubmenu(String name, Icon icon, String parentMenuName);
<T extends Object> void executeBackgroundTask(ITask<T> task);
}
@@ -1,310 +0,0 @@
package org.diylc.swing.gui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.common.ITask;
import org.diylc.images.IconLoader;
import org.diylc.presenter.Presenter;
import org.diylc.swing.ISwingUI;
import org.diylc.swing.plugins.canvas.CanvasPlugin;
import org.diylc.swing.plugins.edit.EditMenuPlugin;
import org.diylc.swing.plugins.file.FileMenuPlugin;
import org.diylc.swing.plugins.help.HelpMenuPlugin;
import org.diylc.swing.plugins.layers.LayersMenuPlugin;
import org.diylc.swing.plugins.statusbar.StatusBar;
import org.diylc.swing.plugins.toolbox.ToolBox;
public class MainFrame extends JFrame implements ISwingUI {
private static final Logger LOG = Logger.getLogger(MainFrame.class);
private static final long serialVersionUID = 1L;
private JPanel centerPanel;
private JPanel leftPanel;
private JPanel rightPanel;
private JPanel topPanel;
private JPanel bottomPanel;
private Presenter presenter;
private JMenuBar mainMenuBar;
private Map<String, JMenu> menuMap;
private CanvasPlugin canvasPlugin;
public MainFrame() {
super("DIYLC 3");
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setPreferredSize(new Dimension(800, 600));
createBasePanels();
menuMap = new HashMap<String, JMenu>();
setIconImages(Arrays.asList(IconLoader.IconSmall.getImage(), IconLoader.IconMedium
.getImage(), IconLoader.IconLarge.getImage()));
DialogFactory.getInstance().initialize(this);
this.presenter = new Presenter(this);
presenter.installPlugin(new ToolBox(this));
presenter.installPlugin(new FileMenuPlugin(this));
presenter.installPlugin(new EditMenuPlugin(this));
presenter.installPlugin(new LayersMenuPlugin(this));
// presenter.installPlugin(new OnlineManager());
presenter.installPlugin(new HelpMenuPlugin(this));
presenter.installPlugin(new StatusBar(this));
canvasPlugin = new CanvasPlugin(this);
presenter.installPlugin(canvasPlugin);
presenter.installPlugin(new FramePlugin());
presenter.createNewProject();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
if (presenter.allowFileAction()) {
dispose();
presenter.dispose();
System.exit(0);
}
}
@Override
public void windowClosing(WindowEvent e) {
if (presenter.allowFileAction()) {
dispose();
presenter.dispose();
System.exit(0);
}
}
});
// setGlassPane(new CustomGlassPane());
// getGlassPane().setVisible(true);
}
public Presenter getPresenter() {
return presenter;
}
@Override
public void setVisible(boolean b) {
super.setVisible(b);
// TODO: hack to prevent painting issues in the scroll bar rulers. Find
// a better fix if possible.
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
canvasPlugin.refresh();
}
});
timer.setRepeats(false);
timer.start();
// if (b) {
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
//
// }
// });
// }
}
private void createBasePanels() {
Container c = new Container();
c.setLayout(new BorderLayout());
centerPanel = new JPanel(new BorderLayout());
c.add(centerPanel, BorderLayout.CENTER);
topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.Y_AXIS));
c.add(topPanel, BorderLayout.NORTH);
leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.X_AXIS));
c.add(leftPanel, BorderLayout.WEST);
bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS));
c.add(bottomPanel, BorderLayout.SOUTH);
rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.X_AXIS));
c.add(rightPanel, BorderLayout.EAST);
setContentPane(c);
}
private JMenuBar getMainMenuBar() {
if (mainMenuBar == null) {
mainMenuBar = new JMenuBar();
setJMenuBar(mainMenuBar);
}
return mainMenuBar;
}
// IView
@Override
public void showMessage(String message, String title, int messageType) {
JOptionPane.showMessageDialog(this, message, title, messageType);
}
@Override
public int showConfirmDialog(String message, String title, int optionType, int messageType) {
return JOptionPane.showConfirmDialog(this, message, title, optionType, messageType);
}
private JMenu findOrCreateMenu(String menuName) {
JMenu menu;
if (menuMap.containsKey(menuName)) {
menu = menuMap.get(menuName);
} else {
menu = new JMenu(menuName);
menuMap.put(menuName, menu);
getMainMenuBar().add(menu);
}
return menu;
}
@Override
public void injectGUIComponent(JComponent component, int position) throws BadPositionException {
LOG.info(String.format("injectGUIComponent(%s, %s)", component.getClass().getName(),
position));
switch (position) {
case SwingConstants.TOP:
topPanel.add(component);
break;
case SwingConstants.LEFT:
leftPanel.add(component);
break;
case SwingConstants.BOTTOM:
bottomPanel.add(component);
break;
case SwingConstants.RIGHT:
rightPanel.add(component);
break;
case SwingConstants.CENTER:
centerPanel.add(component, BorderLayout.CENTER);
break;
default:
throw new BadPositionException();
}
pack();
}
@Override
public void injectMenuAction(Action action, String menuName) {
LOG.info(String.format("injectMenuAction(%s, %s)", action == null ? "Separator" : action
.getValue(Action.NAME), menuName));
JMenu menu = findOrCreateMenu(menuName);
if (action == null) {
menu.addSeparator();
} else {
Boolean isCheckBox = (Boolean) action.getValue(IPlugInPort.CHECK_BOX_MENU_ITEM);
if (isCheckBox != null && isCheckBox) {
menu.add(new JCheckBoxMenuItem(action));
} else {
menu.add(action);
}
}
}
@Override
public void injectSubmenu(String name, Icon icon, String parentMenuName) {
LOG.info(String.format("injectSubmenu(%s, icon, %s)", name, parentMenuName));
JMenu menu = findOrCreateMenu(parentMenuName);
JMenu submenu = new JMenu(name);
submenu.setIcon(icon);
menu.add(submenu);
menuMap.put(name, submenu);
}
@Override
public <T extends Object> void executeBackgroundTask(final ITask<T> task) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
SwingWorker<T, Void> worker = new SwingWorker<T, Void>() {
@Override
protected T doInBackground() throws Exception {
return task.doInBackground();
}
@Override
protected void done() {
try {
T result = get();
task.complete(result);
} catch (Exception e) {
LOG.error("Task failed", e);
task.failed(e);
}
setCursor(Cursor.getDefaultCursor());
}
};
worker.execute();
}
class FramePlugin implements IPlugIn {
private IPlugInPort plugInPort;
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.FILE_STATUS_CHANGED);
}
@Override
public void processMessage(EventType eventType, Object... params) {
if (eventType == EventType.FILE_STATUS_CHANGED) {
String fileName = (String) params[0];
if (fileName == null) {
fileName = "Untitled";
}
String modified = (Boolean) params[1] ? " (modified)" : "";
setTitle(String.format("DIYLC %s beta - %s %s", plugInPort
.getCurrentVersionNumber(), fileName, modified));
}
}
}
}
@@ -1,278 +0,0 @@
package org.diylc.swing.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.log4j.Logger;
import org.diylc.common.DrawOption;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IView;
import org.diylc.presenter.Presenter;
import com.diyfever.gui.miscutils.ConfigurationManager;
public class TemplateDialog extends JDialog {
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(TemplateDialog.class);
private static final Dimension panelSize = new Dimension(400, 300);
public static final String SHOW_TEMPLATES_KEY = "showTemplatesAtStartup";
private IPlugInPort plugInPort;
private JList fileList;
private JPanel canvasPanel;
private Presenter presenter;
private List<File> files;
private JCheckBox showTemplatesBox;
private JPanel mainPanel;
private JButton loadButton;
private JPanel infoPanel;
public TemplateDialog(JFrame owner, IPlugInPort plugInPort) {
super(owner, "Templates");
setModal(true);
setResizable(false);
this.plugInPort = plugInPort;
this.presenter = new Presenter(new IView() {
@Override
public int showConfirmDialog(String message, String title, int optionType,
int messageType) {
return JOptionPane.showConfirmDialog(TemplateDialog.this, message, title,
optionType, messageType);
}
@Override
public void showMessage(String message, String title, int messageType) {
JOptionPane.showMessageDialog(TemplateDialog.this, message, title, messageType);
}
});
// this.presenter.installPlugin(new IPlugIn() {
//
// @Override
// public void connect(IPlugInPort plugInPort) {
// }
//
// @Override
// public EnumSet<EventType> getSubscribedEventTypes() {
// return EnumSet.of(EventType.REPAINT);
// }
//
// @Override
// public void processMessage(EventType eventType, Object... params) {
// if (eventType == EventType.REPAINT) {
// getCanvasPanel().repaint();
// }
// }
// });
setContentPane(getMainPanel());
pack();
setLocationRelativeTo(owner);
}
public JPanel getMainPanel() {
if (mainPanel == null) {
mainPanel = new JPanel(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.weighty = 1;
c.weightx = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(0, 0, 4, 0);
mainPanel.add(getInfoPanel(), c);
c.gridy = 1;
c.weightx = 0;
c.gridwidth = 1;
c.insets = new Insets(0, 0, 0, 0);
JScrollPane scrollPane = new JScrollPane(getFileList());
mainPanel.add(scrollPane, c);
c.gridx = 1;
c.weightx = 1;
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(scrollPane.getBorder());
panel.add(getCanvasPanel(), BorderLayout.CENTER);
mainPanel.add(panel, c);
c.gridx = 0;
c.gridy = 2;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.LAST_LINE_START;
c.fill = GridBagConstraints.NONE;
mainPanel.add(getShowTemplatesBox(), c);
c.gridx = 1;
c.anchor = GridBagConstraints.LAST_LINE_END;
c.insets = new Insets(4, 0, 0, 0);
mainPanel.add(getLoadButton(), c);
}
return mainPanel;
}
public JButton getLoadButton() {
if (loadButton == null) {
loadButton = new JButton("Load Template");
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
plugInPort.loadProject(presenter.getCurrentProject(), true);
dispose();
}
});
}
return loadButton;
}
public JPanel getInfoPanel() {
if (infoPanel == null) {
infoPanel = new JPanel();
infoPanel.setBackground(Color.decode("#FFFFCC"));
infoPanel.setBorder(new JTextField().getBorder());
JLabel infoLabel = new JLabel(
"<html>Templates are semi-product layouts that are used as a starting point for your projects.<br>"
+ "Pick a templete in the left list and click \"Load Template\" to load it or close this dialog to continue.<br>"
+ "You can create your own templates by placing a DIY file into <b>diylc/templates</b> directory.</html>");
infoLabel.setOpaque(false);
infoPanel.add(infoLabel);
}
return infoPanel;
}
public JList getFileList() {
if (fileList == null) {
fileList = new JList(getFiles().toArray());
fileList.setPreferredSize(new Dimension(128, -1));
fileList.setCellRenderer(new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value instanceof File) {
label.setText(((File) value).getName());
}
return label;
}
});
fileList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
File file = (File) fileList.getSelectedValue();
if (file != null) {
presenter.loadProjectFromFile(file.getAbsolutePath());
Dimension dim = presenter.getCanvasDimensions(true);
double xFactor = panelSize.getWidth() / dim.getWidth();
double yFactor = panelSize.getHeight() / dim.getHeight();
presenter.setZoomLevel(Math.min(xFactor, yFactor));
getCanvasPanel().repaint();
}
}
});
fileList.setSelectedIndex(0);
}
return fileList;
}
public JCheckBox getShowTemplatesBox() {
if (showTemplatesBox == null) {
showTemplatesBox = new JCheckBox("Show this dialog at startup");
showTemplatesBox.setSelected(true);
showTemplatesBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ConfigurationManager.getInstance().writeValue(SHOW_TEMPLATES_KEY,
showTemplatesBox.isSelected());
}
});
}
return showTemplatesBox;
}
public List<File> getFiles() {
if (files == null) {
files = new ArrayList<File>();
File dir = new File("templates");
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().toLowerCase().endsWith(".diy")) {
files.add(f);
}
}
}
LOG.debug("Found " + files.size() + " templates");
}
return files;
}
public JPanel getCanvasPanel() {
if (canvasPanel == null) {
canvasPanel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
public void paint(Graphics g) {
super.paint(g);
// Graphics2D g2d = (Graphics2D) g;
// AffineTransform transform = g2d.getTransform();
presenter.draw((Graphics2D) g, EnumSet.of(DrawOption.ZOOM,
DrawOption.ANTIALIASING), null);
// g2d.setTransform(transform);
// Rectangle rect = canvasPanel.getBounds();
// BorderFactory.createEtchedBorder().paintBorder(canvasPanel,
// g, 0, 0,
// (int) rect.getWidth(), (int) rect.getHeight());
}
};
canvasPanel.setBackground(Color.white);
canvasPanel.setPreferredSize(panelSize);
}
return canvasPanel;
}
}
@@ -1,26 +0,0 @@
package org.diylc.swing.gui.editor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import org.diylc.common.PropertyWrapper;
public class BooleanEditor extends JCheckBox {
private static final long serialVersionUID = 1L;
public BooleanEditor(final PropertyWrapper property) {
super();
setSelected((Boolean) property.getValue());
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
property.setValue(isSelected());
}
});
}
}
@@ -1,26 +0,0 @@
package org.diylc.swing.gui.editor;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.diylc.common.PropertyWrapper;
public class ByteEditor extends JSlider {
private static final long serialVersionUID = 1L;
public ByteEditor(final PropertyWrapper property) {
super();
setMinimum(0);
setMaximum(127);
setValue((Byte) property.getValue());
addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
property.setValue(new Integer(getValue()).byteValue());
}
});
}
}
@@ -1,32 +0,0 @@
package org.diylc.swing.gui.editor;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import org.diylc.common.PropertyWrapper;
public class EnumEditor extends JComboBox {
private static final long serialVersionUID = 1L;
private final PropertyWrapper property;
public EnumEditor(PropertyWrapper property) {
this.property = property;
Object[] values = property.getType().getEnumConstants();
setModel(new DefaultComboBoxModel(values));
setSelectedItem(property.getValue());
addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
EnumEditor.this.property.setValue(e.getItem());
}
}
});
}
}
@@ -1,51 +0,0 @@
package org.diylc.swing.gui.editor;
import java.awt.Color;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import org.apache.log4j.Logger;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.measures.AbstractMeasure;
public class FieldEditorFactory {
private static final Logger LOG = Logger.getLogger(FieldEditorFactory.class);
public static Component createFieldEditor(PropertyWrapper property) {
if (property.getType().equals(String.class)) {
StringEditor editor = new StringEditor(property);
return editor;
}
if (property.getType().equals(Color.class)) {
ColorEditor editor = new ColorEditor(property);
return editor;
}
if (AbstractMeasure.class.isAssignableFrom(property.getType())) {
MeasureEditor editor = new MeasureEditor(property);
return editor;
}
if (ImageIcon.class.isAssignableFrom(property.getType())) {
ImageEditor editor = new ImageEditor(property);
return editor;
}
if (property.getType().isEnum()) {
EnumEditor editor = new EnumEditor(property);
return editor;
}
if (Byte.class.isAssignableFrom(property.getType())
|| byte.class.isAssignableFrom(property.getType())) {
ByteEditor editor = new ByteEditor(property);
return editor;
}
if (Boolean.class.isAssignableFrom(property.getType())
|| boolean.class.isAssignableFrom(property.getType())) {
BooleanEditor editor = new BooleanEditor(property);
return editor;
}
LOG.error("Unrecognized parameter type: " + property.getType().getName());
return new JLabel("Unrecognized");
}
}
@@ -1,51 +0,0 @@
package org.diylc.swing.gui.editor;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import org.diylc.common.PropertyWrapper;
public class FontEditor extends JLabel {
private static final long serialVersionUID = 1L;
public FontEditor(final PropertyWrapper property) {
super("Click to edit");
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
setBorder(BorderFactory.createEtchedBorder());
setBackground((Color) property.getValue());
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// JFo
Color newColor = JColorChooser.showDialog(FontEditor.this, "Choose Color",
getBackground());
if (newColor != null) {
property.setValue(newColor);
setBackground(newColor);
}
}
});
}
@Override
public void setBackground(Color bg) {
if (bg.getRed() < 127 || bg.getBlue() < 127 || bg.getGreen() < 127) {
setForeground(Color.white);
} else {
setForeground(Color.black);
}
super.setBackground(bg);
}
}
@@ -1,44 +0,0 @@
package org.diylc.swing.gui.editor;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import org.diylc.common.PropertyWrapper;
import org.diylc.swing.gui.DialogFactory;
import org.diylc.swing.plugins.file.FileFilterEnum;
public class ImageEditor extends JButton {
private static final long serialVersionUID = 1L;
public ImageEditor(final PropertyWrapper property) {
super("Click to load file");
addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
File file = DialogFactory.getInstance().showOpenDialog(
FileFilterEnum.IMAGES.getFilter(), null,
FileFilterEnum.IMAGES.getExtensions()[0], null);
if (file != null) {
ImageIcon image = new ImageIcon(file.getAbsolutePath());
property.setValue(image);
}
}
});
}
@Override
public void setBackground(Color bg) {
if (bg.getRed() < 127 || bg.getBlue() < 127 || bg.getGreen() < 127) {
setForeground(Color.white);
} else {
setForeground(Color.black);
}
super.setBackground(bg);
}
}
@@ -1,309 +0,0 @@
package org.diylc.swing.plugins.canvas;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.EnumSet;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.presenter.Presenter;
import org.diylc.swing.ActionFactory;
import org.diylc.swing.ISwingUI;
import org.diylc.swing.plugins.edit.ComponentTransferable;
import org.diylc.swing.plugins.file.ProjectDrawingProvider;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.diyfever.gui.ruler.IRulerListener;
import com.diyfever.gui.ruler.RulerScrollPane;
public class CanvasPlugin implements IPlugIn, ClipboardOwner {
private static final Logger LOG = Logger.getLogger(CanvasPlugin.class);
private static final String WHEEL_ZOOM = "wheelZoom";
private RulerScrollPane scrollPane;
private CanvasPanel canvasPanel;
private JPopupMenu popupMenu;
private ActionFactory.CutAction cutAction;
private ActionFactory.CopyAction copyAction;
private ActionFactory.PasteAction pasteAction;
private ActionFactory.EditSelectionAction editSelectionAction;
private ActionFactory.DeleteSelectionAction deleteSelectionAction;
private ActionFactory.GroupAction groupAction;
private ActionFactory.UngroupAction ungroupAction;
private ActionFactory.SendToBackAction sendToBackAction;
private ActionFactory.BringToFrontAction bringToFrontAction;
private IPlugInPort plugInPort;
private ISwingUI swingUI;
private Clipboard clipboard;
private double zoomLevel = 1;
public CanvasPlugin(ISwingUI swingUI) {
this.swingUI = swingUI;
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
try {
swingUI.injectGUIComponent(getScrollPane(), SwingConstants.CENTER);
} catch (BadPositionException e) {
LOG.error("Could not install canvas plugin", e);
}
}
public CanvasPanel getCanvasPanel() {
if (canvasPanel == null) {
canvasPanel = new CanvasPanel(plugInPort);
canvasPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
// Enable actions.
boolean enabled = !plugInPort.getSelectedComponents().isEmpty();
getCutAction().setEnabled(enabled);
getCopyAction().setEnabled(enabled);
try {
getPasteAction()
.setEnabled(
clipboard
.isDataFlavorAvailable(ComponentTransferable.listFlavor));
} catch (Exception ex) {
getPasteAction().setEnabled(false);
}
getEditSelectionAction().setEnabled(enabled);
getDeleteSelectionAction().setEnabled(enabled);
getGroupAction().setEnabled(enabled);
getUngroupAction().setEnabled(enabled);
getSendToBackAction().setEnabled(enabled);
getBringToFrontAction().setEnabled(enabled);
getPopupMenu().show(canvasPanel, e.getX(), e.getY());
}
}
});
}
return canvasPanel;
}
private RulerScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new RulerScrollPane(getCanvasPanel(), new ProjectDrawingProvider(
plugInPort, true), new Size(1d, SizeUnit.cm).convertToPixels(), new Size(1d,
SizeUnit.in).convertToPixels());
boolean metric = ConfigurationManager.getInstance().readBoolean(Presenter.METRIC_KEY,
true);
boolean wheelZoom = ConfigurationManager.getInstance().readBoolean(WHEEL_ZOOM, false);
scrollPane.setMetric(metric);
scrollPane.setWheelScrollingEnabled(!wheelZoom);
scrollPane.addUnitListener(new IRulerListener() {
@Override
public void unitsChanged(boolean isMetric) {
plugInPort.setMetric(isMetric);
}
});
if (wheelZoom) {
scrollPane.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
double d = plugInPort.getZoomLevel();
Double[] availableZoomLevels = plugInPort.getAvailableZoomLevels();
if (e.getWheelRotation() > 0) {
int i = availableZoomLevels.length - 1;
while (i > 0 && availableZoomLevels[i] >= d) {
i--;
}
plugInPort.setZoomLevel(availableZoomLevels[i]);
} else {
int i = 0;
while (i < availableZoomLevels.length - 1
&& availableZoomLevels[i] <= d) {
i++;
}
plugInPort.setZoomLevel(availableZoomLevels[i]);
}
}
});
}
}
return scrollPane;
}
public JPopupMenu getPopupMenu() {
if (popupMenu == null) {
popupMenu = new JPopupMenu();
popupMenu.add(getCutAction());
popupMenu.add(getCopyAction());
popupMenu.add(getPasteAction());
popupMenu.addSeparator();
popupMenu.add(getEditSelectionAction());
popupMenu.add(getDeleteSelectionAction());
popupMenu.add(getGroupAction());
popupMenu.add(getUngroupAction());
popupMenu.add(getSendToBackAction());
popupMenu.add(getBringToFrontAction());
popupMenu.addSeparator();
popupMenu.add(ActionFactory.getInstance().createEditProjectAction(plugInPort));
}
return popupMenu;
}
public ActionFactory.CutAction getCutAction() {
if (cutAction == null) {
cutAction = ActionFactory.getInstance().createCutAction(plugInPort, clipboard, this);
}
return cutAction;
}
public ActionFactory.CopyAction getCopyAction() {
if (copyAction == null) {
copyAction = ActionFactory.getInstance().createCopyAction(plugInPort, clipboard, this);
}
return copyAction;
}
public ActionFactory.PasteAction getPasteAction() {
if (pasteAction == null) {
pasteAction = ActionFactory.getInstance().createPasteAction(plugInPort, clipboard);
}
return pasteAction;
}
public ActionFactory.EditSelectionAction getEditSelectionAction() {
if (editSelectionAction == null) {
editSelectionAction = ActionFactory.getInstance().createEditSelectionAction(plugInPort);
}
return editSelectionAction;
}
public ActionFactory.DeleteSelectionAction getDeleteSelectionAction() {
if (deleteSelectionAction == null) {
deleteSelectionAction = ActionFactory.getInstance().createDeleteSelectionAction(
plugInPort);
}
return deleteSelectionAction;
}
public ActionFactory.GroupAction getGroupAction() {
if (groupAction == null) {
groupAction = ActionFactory.getInstance().createGroupAction(plugInPort);
}
return groupAction;
}
public ActionFactory.UngroupAction getUngroupAction() {
if (ungroupAction == null) {
ungroupAction = ActionFactory.getInstance().createUngroupAction(plugInPort);
}
return ungroupAction;
}
public ActionFactory.SendToBackAction getSendToBackAction() {
if (sendToBackAction == null) {
sendToBackAction = ActionFactory.getInstance().createSendToBackAction(plugInPort);
}
return sendToBackAction;
}
public ActionFactory.BringToFrontAction getBringToFrontAction() {
if (bringToFrontAction == null) {
bringToFrontAction = ActionFactory.getInstance().createBringToFrontAction(plugInPort);
}
return bringToFrontAction;
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.PROJECT_LOADED, EventType.ZOOM_CHANGED, EventType.REPAINT);
}
@Override
public void processMessage(final EventType eventType, Object... params) {
// SwingUtilities.invokeLater(new Runnable() {
//
// @Override
// public void run() {
// LOG.debug("event: " + eventType);
switch (eventType) {
case PROJECT_LOADED:
refreshSize();
if ((Boolean) params[1]) {
// Scroll to the center.
Rectangle visibleRect = canvasPanel.getVisibleRect();
visibleRect.setLocation((canvasPanel.getWidth() - visibleRect.width) / 2,
(canvasPanel.getHeight() - visibleRect.height) / 2);
canvasPanel.scrollRectToVisible(visibleRect);
canvasPanel.revalidate();
}
break;
case ZOOM_CHANGED:
Rectangle visibleRect = canvasPanel.getVisibleRect();
refreshSize();
// Try to set the visible area to be centered with the previous
// one.
double zoomFactor = (Double) params[0] / zoomLevel;
visibleRect.setBounds((int) (visibleRect.x * zoomFactor),
(int) (visibleRect.y * zoomFactor), visibleRect.width, visibleRect.height);
canvasPanel.scrollRectToVisible(visibleRect);
canvasPanel.revalidate();
zoomLevel = (Double) params[0];
break;
case REPAINT:
canvasPanel.repaint();
break;
}
// }
// });
}
private void refreshSize() {
Dimension d = plugInPort.getCanvasDimensions(true);
canvasPanel.setSize(d);
canvasPanel.setPreferredSize(d);
getScrollPane().setZoomLevel(plugInPort.getZoomLevel());
}
/**
* Causes ruler scroll pane to refresh by sending a fake mouse moved message
* to the canvasPanel.
*/
public void refresh() {
MouseEvent event = new MouseEvent(canvasPanel, MouseEvent.MOUSE_MOVED, System
.currentTimeMillis(), 0, 1, 1,// canvasPanel.getWidth() / 2,
// canvasPanel.getHeight() / 2,
0, false);
canvasPanel.dispatchEvent(event);
}
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
// TODO Auto-generated method stub
}
}
@@ -1,200 +0,0 @@
package org.diylc.swing.plugins.edit;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.Transferable;
import java.util.EnumSet;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.Project;
import org.diylc.swing.ActionFactory;
import org.diylc.swing.ISwingUI;
import com.diyfever.gui.undo.IUndoListener;
import com.diyfever.gui.undo.UndoHandler;
public class EditMenuPlugin implements IPlugIn, ClipboardOwner {
private static final String EDIT_TITLE = "Edit";
private IPlugInPort plugInPort;
private ISwingUI swingUI;
private Clipboard clipboard;
private ActionFactory.CutAction cutAction;
private ActionFactory.CopyAction copyAction;
private ActionFactory.PasteAction pasteAction;
private ActionFactory.EditSelectionAction editSelectionAction;
private ActionFactory.DeleteSelectionAction deleteSelectionAction;
private ActionFactory.GroupAction groupAction;
private ActionFactory.UngroupAction ungroupAction;
private ActionFactory.SendToBackAction sendToBackAction;
private ActionFactory.BringToFrontAction bringToFrontAction;
private UndoHandler<Project> undoHandler;
public EditMenuPlugin(ISwingUI swingUI) {
this.swingUI = swingUI;
// SecurityManager securityManager = System.getSecurityManager();
// if (securityManager != null) {
// try {
// securityManager.checkSystemClipboardAccess();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
undoHandler = new UndoHandler<Project>(new IUndoListener<Project>() {
@Override
public void actionPerformed(Project currentState) {
plugInPort.loadProject(currentState, false);
}
});
clipboard.addFlavorListener(new FlavorListener() {
@Override
public void flavorsChanged(FlavorEvent e) {
refreshActions();
}
});
}
public ActionFactory.CutAction getCutAction() {
if (cutAction == null) {
cutAction = ActionFactory.getInstance().createCutAction(plugInPort, clipboard, this);
}
return cutAction;
}
public ActionFactory.CopyAction getCopyAction() {
if (copyAction == null) {
copyAction = ActionFactory.getInstance().createCopyAction(plugInPort, clipboard, this);
}
return copyAction;
}
public ActionFactory.PasteAction getPasteAction() {
if (pasteAction == null) {
pasteAction = ActionFactory.getInstance().createPasteAction(plugInPort, clipboard);
}
return pasteAction;
}
public ActionFactory.EditSelectionAction getEditSelectionAction() {
if (editSelectionAction == null) {
editSelectionAction = ActionFactory.getInstance().createEditSelectionAction(plugInPort);
}
return editSelectionAction;
}
public ActionFactory.DeleteSelectionAction getDeleteSelectionAction() {
if (deleteSelectionAction == null) {
deleteSelectionAction = ActionFactory.getInstance().createDeleteSelectionAction(
plugInPort);
}
return deleteSelectionAction;
}
public ActionFactory.GroupAction getGroupAction() {
if (groupAction == null) {
groupAction = ActionFactory.getInstance().createGroupAction(plugInPort);
}
return groupAction;
}
public ActionFactory.UngroupAction getUngroupAction() {
if (ungroupAction == null) {
ungroupAction = ActionFactory.getInstance().createUngroupAction(plugInPort);
}
return ungroupAction;
}
public ActionFactory.SendToBackAction getSendToBackAction() {
if (sendToBackAction == null) {
sendToBackAction = ActionFactory.getInstance().createSendToBackAction(plugInPort);
}
return sendToBackAction;
}
public ActionFactory.BringToFrontAction getBringToFrontAction() {
if (bringToFrontAction == null) {
bringToFrontAction = ActionFactory.getInstance().createBringToFrontAction(plugInPort);
}
return bringToFrontAction;
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
ActionFactory actionFactory = ActionFactory.getInstance();
swingUI.injectMenuAction(undoHandler.getUndoAction(), EDIT_TITLE);
swingUI.injectMenuAction(undoHandler.getRedoAction(), EDIT_TITLE);
swingUI.injectMenuAction(null, EDIT_TITLE);
swingUI.injectMenuAction(getCutAction(), EDIT_TITLE);
swingUI.injectMenuAction(getCopyAction(), EDIT_TITLE);
swingUI.injectMenuAction(getPasteAction(), EDIT_TITLE);
swingUI.injectMenuAction(null, EDIT_TITLE);
swingUI.injectMenuAction(actionFactory.createSelectAllAction(plugInPort), EDIT_TITLE);
swingUI.injectMenuAction(getEditSelectionAction(), EDIT_TITLE);
swingUI.injectMenuAction(getDeleteSelectionAction(), EDIT_TITLE);
swingUI.injectMenuAction(getGroupAction(), EDIT_TITLE);
swingUI.injectMenuAction(getUngroupAction(), EDIT_TITLE);
swingUI.injectMenuAction(getSendToBackAction(), EDIT_TITLE);
swingUI.injectMenuAction(getBringToFrontAction(), EDIT_TITLE);
swingUI.injectMenuAction(null, EDIT_TITLE);
swingUI.injectMenuAction(actionFactory.createEditProjectAction(plugInPort), EDIT_TITLE);
refreshActions();
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.SELECTION_CHANGED, EventType.PROJECT_MODIFIED);
}
@Override
public void processMessage(EventType eventType, Object... params) {
switch (eventType) {
case SELECTION_CHANGED:
refreshActions();
break;
case PROJECT_MODIFIED:
undoHandler.stateChanged((Project) params[0], (Project) params[1], (String) params[2]);
break;
}
}
private void refreshActions() {
boolean enabled = !plugInPort.getSelectedComponents().isEmpty();
getCutAction().setEnabled(enabled);
getCopyAction().setEnabled(enabled);
try {
getPasteAction().setEnabled(
clipboard.isDataFlavorAvailable(ComponentTransferable.listFlavor));
} catch (Exception e) {
getPasteAction().setEnabled(false);
}
getEditSelectionAction().setEnabled(enabled);
getDeleteSelectionAction().setEnabled(enabled);
getGroupAction().setEnabled(enabled);
getUngroupAction().setEnabled(enabled);
getSendToBackAction().setEnabled(enabled);
getBringToFrontAction().setEnabled(enabled);
}
// ClipboardOwner
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
refreshActions();
}
}
@@ -1,69 +0,0 @@
package org.diylc.swing.plugins.file;
import java.util.EnumSet;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.images.IconLoader;
import org.diylc.swing.ActionFactory;
import org.diylc.swing.ISwingUI;
/**
* Entry point class for File management utilities.
*
* @author Branislav Stojkovic
*/
public class FileMenuPlugin implements IPlugIn {
private static final String FILE_TITLE = "File";
private static final String TRACE_MASK_TITLE = "Trace Mask";
private ProjectDrawingProvider drawingProvider;
private TraceMaskDrawingProvider traceMaskDrawingProvider;
private ISwingUI swingUI;
public FileMenuPlugin(ISwingUI swingUI) {
super();
this.swingUI = swingUI;
}
@Override
public void connect(IPlugInPort plugInPort) {
this.drawingProvider = new ProjectDrawingProvider(plugInPort, false);
this.traceMaskDrawingProvider = new TraceMaskDrawingProvider(plugInPort);
ActionFactory actionFactory = ActionFactory.getInstance();
swingUI.injectMenuAction(actionFactory.createNewAction(plugInPort), FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createOpenAction(plugInPort, swingUI), FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createSaveAction(plugInPort, swingUI), FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createSaveAsAction(plugInPort, swingUI), FILE_TITLE);
swingUI.injectMenuAction(null, FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createExportPDFAction(drawingProvider, swingUI),
FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createExportPNGAction(drawingProvider, swingUI),
FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createPrintAction(drawingProvider), FILE_TITLE);
swingUI.injectSubmenu(TRACE_MASK_TITLE, IconLoader.TraceMask.getIcon(), FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createExportPDFAction(traceMaskDrawingProvider,
swingUI), TRACE_MASK_TITLE);
swingUI.injectMenuAction(actionFactory.createExportPNGAction(traceMaskDrawingProvider,
swingUI), TRACE_MASK_TITLE);
swingUI.injectMenuAction(actionFactory.createPrintAction(traceMaskDrawingProvider),
TRACE_MASK_TITLE);
swingUI.injectMenuAction(actionFactory.createBomAction(plugInPort), FILE_TITLE);
swingUI.injectMenuAction(null, FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createExitAction(plugInPort), FILE_TITLE);
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return null;
}
@Override
public void processMessage(EventType eventType, Object... params) {
// Do nothing.
}
}
@@ -1,43 +0,0 @@
package org.diylc.swing.plugins.file;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.EnumSet;
import org.diylc.common.DrawOption;
import org.diylc.common.IComponentFiler;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IDIYComponent;
import org.diylc.presenter.ComponentZOrderFiler;
import com.diyfever.gui.IDrawingProvider;
/**
* {@link IDrawingProvider} implementation that uses {@link IPlugInPort} to draw
* a project onto the canvas.
*
* @author Branislav Stojkovic
*/
public class TraceMaskDrawingProvider implements IDrawingProvider {
private IPlugInPort plugInPort;
private IComponentFiler filter;
public TraceMaskDrawingProvider(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
this.filter = new ComponentZOrderFiler(IDIYComponent.TRACE);
}
@Override
public void draw(Graphics g) {
plugInPort.draw((Graphics2D) g, EnumSet.of(DrawOption.ANTIALIASING),
this.filter);
}
@Override
public Dimension getSize() {
return plugInPort.getCanvasDimensions(false);
}
}
@@ -1,113 +0,0 @@
package org.diylc.swing.plugins.help;
import java.awt.event.ActionEvent;
import java.util.EnumSet;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.images.IconLoader;
import org.diylc.swing.ISwingUI;
import org.diylc.swing.gui.DialogFactory;
import com.diyfever.gui.AboutDialog;
import com.diyfever.gui.miscutils.Utils;
/**
* Entry point class for help-related utilities.
*
* @author Branislav Stojkovic
*/
public class HelpMenuPlugin implements IPlugIn {
private static final String HELP_TITLE = "Help";
public static String MANUAL_URL = "http://code.google.com/p/diy-layout-creator/wiki/Manual";
public static String FAQ_URL = "http://code.google.com/p/diy-layout-creator/wiki/FAQ";
public static String COMPONENT_URL = "http://code.google.com/p/diy-layout-creator/wiki/ComponentAPI";
public static String PLUGIN_URL = "http://code.google.com/p/diy-layout-creator/wiki/PluginAPI";
public static String BUG_URL = "http://code.google.com/p/diy-layout-creator/issues/entry";
public static String DONATE_URL = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=25161";
private IPlugInPort plugInPort;
private AboutDialog aboutDialog;
public HelpMenuPlugin(ISwingUI swingUI) {
swingUI.injectMenuAction(new NavigateURLAction("User Manual", IconLoader.Manual.getIcon(),
MANUAL_URL), HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("FAQ", IconLoader.Faq.getIcon(), FAQ_URL),
HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("Component API", IconLoader.Component
.getIcon(), COMPONENT_URL), HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("Plugin API", IconLoader.Plugin.getIcon(),
PLUGIN_URL), HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("Submit a Bug", IconLoader.Bug.getIcon(),
BUG_URL), HELP_TITLE);
swingUI.injectMenuAction(null, HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("Donate", IconLoader.Donate.getIcon(),
DONATE_URL), HELP_TITLE);
swingUI.injectMenuAction(new AboutAction(), HELP_TITLE);
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return null;
}
@Override
public void processMessage(EventType eventType, Object... params) {
}
private AboutDialog getAboutDialog() {
if (aboutDialog == null) {
aboutDialog = DialogFactory.getInstance().createAboutDialog("DIY Layout Creator",
IconLoader.IconLarge.getIcon(),
plugInPort.getCurrentVersionNumber().toString(), "Branislav Stojkovic",
"diylc.org", "bancika@gmail.com", "");
}
return aboutDialog;
}
class AboutAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public AboutAction() {
super();
putValue(AbstractAction.NAME, "About");
putValue(AbstractAction.SMALL_ICON, IconLoader.About.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
getAboutDialog().setVisible(true);
}
}
class NavigateURLAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private String url;
public NavigateURLAction(String name, Icon icon, String url) {
super();
this.url = url;
putValue(AbstractAction.NAME, name);
putValue(AbstractAction.SMALL_ICON, icon);
}
@Override
public void actionPerformed(ActionEvent e) {
Utils.openURL(url);
}
}
}
@@ -1,88 +0,0 @@
package org.diylc.swing.plugins.layers;
import java.awt.event.ActionEvent;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IDIYComponent;
import org.diylc.swing.ISwingUI;
public class LayersMenuPlugin implements IPlugIn {
private static final String LOCK_LAYERS_TITLE = "Lock Layers";
private IPlugInPort plugInPort;
private Map<Layer, Action> lockActionMap;
public LayersMenuPlugin(ISwingUI swingUI) {
lockActionMap = new HashMap<Layer, Action>();
for (Layer layer : Layer.values()) {
final int zOrder = layer.getZOrder();
AbstractAction action = new AbstractAction(layer.getTitle()) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
LayersMenuPlugin.this.plugInPort.setLayerLocked(zOrder,
(Boolean) getValue(Action.SELECTED_KEY));
}
};
action.putValue(IPlugInPort.CHECK_BOX_MENU_ITEM, true);
lockActionMap.put(layer, action);
swingUI.injectMenuAction(action, LOCK_LAYERS_TITLE);
}
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.LAYER_STATE_CHANGED);
}
@SuppressWarnings("unchecked")
@Override
public void processMessage(EventType eventType, Object... params) {
if (eventType == EventType.LAYER_STATE_CHANGED) {
Set<Integer> lockedLayers = (Set<Integer>) params[0];
for (Layer layer : Layer.values()) {
lockActionMap.get(layer).putValue(Action.SELECTED_KEY,
lockedLayers.contains(layer.getZOrder()));
}
}
}
static enum Layer {
CHASSIS("Chassis", IDIYComponent.CHASSIS), BOARD("Board", IDIYComponent.BOARD), TRACE(
"Trace", IDIYComponent.TRACE), COMPONENT("Component", IDIYComponent.COMPONENT), TEXT(
"Text", IDIYComponent.TEXT);
String title;
int zOrder;
private Layer(String title, int order) {
this.title = title;
zOrder = order;
}
public String getTitle() {
return title;
}
public int getZOrder() {
return zOrder;
}
}
}
@@ -1,301 +0,0 @@
package org.diylc.swing.plugins.statusbar;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.ComponentType;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IDIYComponent;
import org.diylc.images.IconLoader;
import org.diylc.presenter.Presenter;
import org.diylc.swing.ISwingUI;
import com.diyfever.gui.MemoryBar;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.diyfever.gui.miscutils.PercentageListCellRenderer;
import com.diyfever.gui.miscutils.Utils;
import com.diyfever.gui.update.UpdateLabel;
public class StatusBar extends JPanel implements IPlugIn {
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(StatusBar.class);
public static String UPDATE_URL = "http://www.diy-fever.com/update.xml";
private static final Format sizeFormat = new DecimalFormat("0.##");
private JComboBox zoomBox;
private UpdateLabel updateLabel;
private MemoryBar memoryPanel;
private JLabel statusLabel;
private JLabel sizeLabel;
private IPlugInPort plugInPort;
// State variables
private ComponentType componentSlot;
private Point controlPointSlot;
private List<String> componentNamesUnderCursor;
private List<String> selectedComponentNames;
private List<String> stuckComponentNames;
private String statusMessage;
public StatusBar(ISwingUI swingUI) {
super();
setLayout(new GridBagLayout());
try {
swingUI.injectGUIComponent(this, SwingUtilities.BOTTOM);
} catch (BadPositionException e) {
LOG.error("Could not install status bar", e);
}
}
private JComboBox getZoomBox() {
if (zoomBox == null) {
zoomBox = new JComboBox(plugInPort.getAvailableZoomLevels());
zoomBox.setSelectedItem(plugInPort.getZoomLevel());
zoomBox.setFocusable(false);
zoomBox.setRenderer(new PercentageListCellRenderer());
zoomBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
plugInPort.setZoomLevel((Double) zoomBox.getSelectedItem());
}
});
}
return zoomBox;
}
private UpdateLabel getUpdateLabel() {
if (updateLabel == null) {
updateLabel = new UpdateLabel(plugInPort.getCurrentVersionNumber(), UPDATE_URL);
// updateLabel.setBorder(BorderFactory.createCompoundBorder(
// BorderFactory.createEtchedBorder(), BorderFactory
// .createEmptyBorder(2, 4, 2, 4)));
updateLabel.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
}
return updateLabel;
}
private MemoryBar getMemoryPanel() {
if (memoryPanel == null) {
memoryPanel = new MemoryBar(false);
}
return memoryPanel;
}
private JLabel getStatusLabel() {
if (statusLabel == null) {
statusLabel = new JLabel();
statusLabel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
}
return statusLabel;
}
public JLabel getSizeLabel() {
if (sizeLabel == null) {
sizeLabel = new JLabel(IconLoader.Size.getIcon());
sizeLabel.setFocusable(true);
sizeLabel.setToolTipText("Click to calculate selection size");
sizeLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Point2D size = plugInPort.calculateSelectionDimension();
boolean metric = ConfigurationManager.getInstance().readBoolean(
Presenter.METRIC_KEY, true);
String text;
if (size == null) {
text = "Selection is empty.";
} else {
text = "Selection size: " + sizeFormat.format(size.getX()) + " x "
+ sizeFormat.format(size.getY()) + (metric ? " cm" : " in");
}
JOptionPane.showMessageDialog(SwingUtilities.getRootPane(StatusBar.this), text,
"Information", JOptionPane.INFORMATION_MESSAGE);
}
});
}
return sizeLabel;
}
private void layoutComponents() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(getStatusLabel(), gbc);
JPanel zoomPanel = new JPanel(new BorderLayout());
zoomPanel.add(new JLabel("Zoom: "), BorderLayout.WEST);
zoomPanel.add(getZoomBox(), BorderLayout.CENTER);
// zoomPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory
// .createEtchedBorder(), BorderFactory.createEmptyBorder(2, 4, 2,
// 4)));
zoomPanel.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
gbc.gridx = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0;
add(zoomPanel, gbc);
gbc.gridx = 2;
add(getSizeLabel(), gbc);
gbc.gridx = 3;
add(getUpdateLabel(), gbc);
gbc.gridx = 4;
gbc.fill = GridBagConstraints.NONE;
add(getMemoryPanel(), gbc);
gbc.gridx = 5;
add(new JPanel(), gbc);
}
// IPlugIn
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
layoutComponents();
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.ZOOM_CHANGED, EventType.SLOT_CHANGED,
EventType.AVAILABLE_CTRL_POINTS_CHANGED, EventType.SELECTION_CHANGED,
EventType.STATUS_MESSAGE_CHANGED);
}
@SuppressWarnings("unchecked")
@Override
public void processMessage(EventType eventType, Object... params) {
switch (eventType) {
case ZOOM_CHANGED:
if (!params[0].equals(getZoomBox().getSelectedItem())) {
final Double zoom = (Double) params[0];
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
getZoomBox().setSelectedItem(zoom);
}
});
}
break;
case SELECTION_CHANGED:
List<IDIYComponent<?>> selection = (List<IDIYComponent<?>>) params[0];
Collection<IDIYComponent<?>> stuckComponents = (Collection<IDIYComponent<?>>) params[1];
Collection<String> componentNames = new HashSet<String>();
for (IDIYComponent<?> component : selection) {
componentNames.add("<font color='blue'>" + component.getName() + "</font>");
}
this.selectedComponentNames = new ArrayList<String>(componentNames);
Collections.sort(this.selectedComponentNames);
this.stuckComponentNames = new ArrayList<String>();
for (IDIYComponent<?> component : stuckComponents) {
this.stuckComponentNames.add("<font color='blue'>" + component.getName()
+ "</font>");
}
this.stuckComponentNames.removeAll(this.selectedComponentNames);
Collections.sort(this.stuckComponentNames);
refreshStatusText();
break;
case SLOT_CHANGED:
componentSlot = (ComponentType) params[0];
controlPointSlot = (Point) params[1];
refreshStatusText();
break;
case AVAILABLE_CTRL_POINTS_CHANGED:
componentNamesUnderCursor = new ArrayList<String>();
for (IDIYComponent<?> component : ((Map<IDIYComponent<?>, Integer>) params[0]).keySet()) {
componentNamesUnderCursor.add("<font color='blue'>" + component.getName()
+ "</font>");
}
Collections.sort(componentNamesUnderCursor);
refreshStatusText();
break;
case STATUS_MESSAGE_CHANGED:
statusMessage = (String) params[0];
}
}
private void refreshStatusText() {
String statusText = this.statusMessage;
if (componentSlot == null) {
if (componentNamesUnderCursor != null && !componentNamesUnderCursor.isEmpty()) {
String formattedNames = Utils.toCommaString(componentNamesUnderCursor);
statusText = "<html>Drag control point(s) of " + formattedNames + "</html>";
} else if (selectedComponentNames != null && !selectedComponentNames.isEmpty()) {
StringBuilder builder = new StringBuilder();
builder.append(Utils.toCommaString(selectedComponentNames));
if (!stuckComponentNames.isEmpty()) {
builder.append(" (hold <b>Ctrl</b> and drag to unstuck from ");
builder.append(Utils.toCommaString(stuckComponentNames));
builder.append(")");
}
statusText = "<html>Selection: " + builder.toString() + "</html>";
}
} else {
switch (componentSlot.getCreationMethod()) {
case POINT_BY_POINT:
String count;
if (controlPointSlot == null) {
count = "first";
} else {
count = "second";
}
statusText = "<html>Click on the canvas to set the " + count
+ " control point of a new <font color='blue'>" + componentSlot.getName()
+ "</font> or press <b>Esc</b> to cancel</html>";
break;
case SINGLE_CLICK:
statusText = "<html>Click on the canvas to create a new <font color='blue'>"
+ componentSlot.getName() + "</font> or press <b>Esc</b> to cancel</html>";
break;
}
}
final String finalStatus = statusText;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
getStatusLabel().setText(finalStatus);
}
});
}
}
@@ -1,116 +0,0 @@
package org.diylc.swing.plugins.toolbox;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.diylc.common.ComponentType;
import org.diylc.common.IPlugInPort;
import org.diylc.presenter.ComparatorFactory;
import org.diylc.presenter.Presenter;
/**
* Tabbed pane that shows all available components categorized into tabs.
*
* @author Branislav Stojkovic
*/
class ComponentTabbedPane extends JTabbedPane {
public static int SCROLL_STEP = Presenter.ICON_SIZE + ComponentButton.MARGIN * 2 + 2;
private static final long serialVersionUID = 1L;
private final IPlugInPort plugInPort;
public ComponentTabbedPane(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
Map<String, List<ComponentType>> componentTypes = plugInPort.getComponentTypes();
List<String> categories = new ArrayList<String>(componentTypes.keySet());
Collections.sort(categories);
for (String category : categories) {
JPanel panel = createTab((componentTypes.get(category)));
addTab(category, panel);
}
addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
ComponentTabbedPane.this.plugInPort.setNewComponentTypeSlot(null);
}
});
}
private JPanel createTab(List<ComponentType> componentTypes) {
JPanel panel = new JPanel(new BorderLayout());
// final JScrollPane scrollPane =
// createComponentScrollBar(componentTypes);
panel.setOpaque(false);
panel.add(createComponentPanel(componentTypes), BorderLayout.CENTER);
// JButton leftButton = new JButton("<");
// leftButton.addActionListener(new ActionListener() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// Rectangle rect = scrollPane.getVisibleRect();
// if (rect.x > SCROLL_STEP) {
// rect.translate(-SCROLL_STEP, 0);
// } else {
// rect.translate(-rect.x, 0);
// }
// }
// });
// leftButton.setMargin(new Insets(0, 2, 0, 2));
// JButton rightButton = new JButton(">");
// rightButton.addActionListener(new ActionListener() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// Rectangle rect = scrollPane.getVisibleRect();
// if (rect.x + rect.width < scrollPane.getViewport().getSize().width -
// SCROLL_STEP) {
// rect.translate(SCROLL_STEP, 0);
// } else {
// rect.translate(scrollPane.getViewport().getSize().width - rect.x -
// rect.width,
// 0);
// }
// }
// });
// rightButton.setMargin(new Insets(0, 2, 0, 2));
// panel.add(leftButton, BorderLayout.WEST);
// panel.add(scrollPane);
// panel.add(rightButton, BorderLayout.EAST);
return panel;
}
// private JScrollPane createComponentScrollBar(List<ComponentType> componentTypes) {
// JScrollPane scrollPane = new JScrollPane(createComponentPanel(componentTypes));
// scrollPane.setOpaque(false);
// scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
// return scrollPane;
// }
private Component createComponentPanel(List<ComponentType> componentTypes) {
Container toolbar = new Container();
Collections.sort(componentTypes, ComparatorFactory.getInstance()
.getComponentTypeComparator());
toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.X_AXIS));
for (ComponentType componentType : componentTypes) {
JButton button = new ComponentButton(plugInPort, componentType);
toolbar.add(button);
}
return toolbar;
}
}
@@ -1,57 +0,0 @@
package org.diylc.swing.plugins.toolbox;
import java.util.EnumSet;
import javax.swing.SwingConstants;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.swing.ISwingUI;
import org.diylc.swing.plugins.statusbar.StatusBar;
public class ToolBox implements IPlugIn {
private static final Logger LOG = Logger.getLogger(StatusBar.class);
private ISwingUI swingUI;
private IPlugInPort plugInPort;
private ComponentTabbedPane componentTabbedPane;
public ToolBox(ISwingUI swingUI) {
this.swingUI = swingUI;
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
try {
swingUI.injectGUIComponent(getComponentTabbedPane(), SwingConstants.TOP);
} catch (BadPositionException e) {
LOG.error("Could not install the toolbox", e);
}
}
public ComponentTabbedPane getComponentTabbedPane() {
if (componentTabbedPane == null) {
componentTabbedPane = new ComponentTabbedPane(plugInPort);
}
return componentTabbedPane;
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
// TODO Auto-generated method stub
return null;
}
@Override
public void processMessage(EventType eventType, Object... params) {
// TODO Auto-generated method stub
}
}
-18
View File
@@ -1,18 +0,0 @@
package org.diylc.utils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Stroke;
import java.awt.Toolkit;
public class Constants {
public static final int PIXELS_PER_INCH = 150;
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);
}
-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, 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.swing.plugins.file.BomEntry;
import org.diylc.swing.plugins.file.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());
};
}
-142
View File
@@ -1,142 +0,0 @@
<java.util.Arrays_-ArrayList>
<a class="com.diyfever.gui.update.Version-array">
<com.diyfever.gui.update.Version>
<versionNumber>
<major>3</major>
<minor>0</minor>
<build>4</build>
</versionNumber>
<releaseDate>2011-01-27 21:00:00.000 CET</releaseDate>
<name></name>
<changes>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Copy/paste between two instances of the application</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Parsing numerical values in countries that use comma as decimal separator</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Dragging sticky points affects selectability of objects</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Click is sometimes not registered while adding a new component</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Fixed NPE when using default values</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Allow shape control points of curves to overlap</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Added DIL IC first pin indentation</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Added transparency to the potentiometer</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Reduced number of layers</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Import from v1 files can now read label and electrolytic capacitor components and trace/pad colors</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Added worker thread for longer file operation, so GUI doesn't freeze</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added right click menu on the canvas</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added "send to back" and "bring to front" options</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added label component</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added image component</description>
</com.diyfever.gui.update.Change>
</changes>
<url>http://code.google.com/p/diy-layout-creator/downloads/list
</url>
</com.diyfever.gui.update.Version>
<com.diyfever.gui.update.Version>
<versionNumber>
<major>3</major>
<minor>0</minor>
<build>5</build>
</versionNumber>
<releaseDate>2011-01-30 20:00:00.000 CET</releaseDate>
<name></name>
<changes>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Curved trace does not show control points</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Potentiometer draws wrong at 180 degrees</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Reset component selection when tab is changed</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Resistor can show color bands</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Electrolytic capacitor has a new icon and new looks</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Solder pad can be square</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Added keyboard shortcuts to some menu options</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>V1 file importer can recognize hookup wire and transistors</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added support for creating and loading templates</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added TO-92 transistor</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added TO-220 transistor</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added LED</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added axial electrolytic capacitor</description>
</com.diyfever.gui.update.Change>
</changes>
<url>http://code.google.com/p/diy-layout-creator/downloads/list
</url>
</com.diyfever.gui.update.Version>
</a>
</java.util.Arrays_-ArrayList>
-9
View File
@@ -1,9 +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 combineaccessrules="false" kind="src" path="/DIYLC"/>
<classpathentry kind="lib" path="lib/xstream-1.3.1.jar"/>
<classpathentry kind="lib" path="lib/log4j-1.2.15.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
-17
View File
@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>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>
-60
View File
@@ -1,60 +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" />
</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}" />
</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.
@@ -1,118 +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.ObjectCache;
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 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(DEFAULT_WIDTH.convertToPixels(), DEFAULT_HEIGHT.convertToPixels()) };
protected Point firstPoint = new Point();
protected Point secondPoint = new Point();
protected Color boardColor = BOARD_COLOR;
protected Color borderColor = BORDER_COLOR;
@Override
public void draw(Graphics2D g2d, ComponentState componentState, 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();
}
@EditableProperty(name = "Color")
public Color getBoardColor() {
return boardColor;
}
public void setBoardColor(Color boardColor) {
this.boardColor = boardColor;
}
@EditableProperty(name = "Border")
public Color getBorderColor() {
return borderColor;
}
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
@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,20 +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);
}
}
@@ -1,100 +0,0 @@
package org.diylc.components.boards;
import java.awt.AlphaComposite;
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.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 EYELET_COLOR = Color.decode("#C3E4ED");
public static Size SPACING = new Size(0.3d, SizeUnit.in);
public static Size EYELET_SIZE = new Size(1/8d, SizeUnit.in);
public static Size HOLE_SIZE = new Size(2d, SizeUnit.mm);
// private Area copperArea;
protected Size spacing = SPACING;
protected Color eyeletColor = EYELET_COLOR;
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
super.draw(g2d, componentState, 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(EYELET_SIZE.convertToPixels());
int holeDiameter = getClosestOdd(HOLE_SIZE.convertToPixels());
int spacing = this.spacing.convertToPixels();
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
while (p.x < secondPoint.x - spacing) {
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);
}
}
}
}
@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,100 +0,0 @@
package org.diylc.components.boards;
import java.awt.AlphaComposite;
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.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, Project project,
IDrawingObserver drawingObserver) {
super.draw(g2d, componentState, 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(PAD_SIZE.convertToPixels());
int holeDiameter = getClosestOdd(HOLE_SIZE.convertToPixels());
int spacing = this.spacing.convertToPixels();
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
while (p.x < secondPoint.x - spacing) {
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);
}
}
}
}
@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,106 +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.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;
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
super.draw(g2d, componentState, 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(STRIP_SIZE.convertToPixels());
int holeSize = getClosestOdd(HOLE_SIZE.convertToPixels());
int spacing = this.spacing.convertToPixels();
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
g2d.setColor(stripColor);
g2d.fillRect(p.x + SPACING.convertToPixels() / 2, p.y - stripSize / 2,
secondPoint.x - spacing - p.x, stripSize);
g2d.setColor(stripColor.darker());
g2d.drawRect(p.x + SPACING.convertToPixels() / 2, p.y - stripSize / 2,
secondPoint.x - spacing - p.x, stripSize);
while (p.x < secondPoint.x - spacing) {
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);
}
}
g2d.setComposite(oldComposite);
}
}
@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;
}
@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("_", ""));
}
}
@@ -1,126 +0,0 @@
package org.diylc.components.connectivity;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import org.diylc.common.ObjectCache;
import org.diylc.components.AbstractLeadedComponent;
import org.diylc.core.ComponentState;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Copper Trace", author = "Branislav Stojkovic", category = "Connectivity", creationMethod = CreationMethod.POINT_BY_POINT, instanceNamePrefix = "Trace", description = "Straight copper trace", zOrder = IDIYComponent.TRACE)
public class CopperTrace extends AbstractLeadedComponent<Void> {
private static final long serialVersionUID = 1L;
public static Size THICKNESS = new Size(1d, SizeUnit.mm);
public static Color COLOR = Color.black;
private Color leadColor = COLOR;
private Size leadThickness = THICKNESS;
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(3));
g2d.setColor(COLOR);
g2d.drawLine(1, height - 2, width - 2, 1);
}
@Override
protected Color getLeadColor(ComponentState componentState) {
return componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : leadColor;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@EditableProperty(name = "Color")
public Color getLeadColor() {
return leadColor;
}
public void setLeadColor(Color leadColor) {
this.leadColor = leadColor;
}
@Override
@EditableProperty(name = "Thickness")
public Size getLeadThickness() {
return leadThickness;
}
public void setLeadThickness(Size leadThickness) {
this.leadThickness = leadThickness;
}
@Override
protected boolean shouldShadeLeads() {
return false;
}
@Deprecated
public Color getBodyColor() {
return super.getBodyColor();
}
@Deprecated
@Override
public Color getBorderColor() {
// TODO Auto-generated method stub
return super.getBorderColor();
}
@Deprecated
@Override
public Byte getAlpha() {
return super.getAlpha();
}
@Deprecated
@Override
public Size getLength() {
return super.getLength();
}
@Deprecated
@Override
public Size getWidth() {
return super.getWidth();
}
@Deprecated
@Override
public Void getValue() {
return null;
}
@Deprecated
@Override
public void setValue(Void value) {
}
@Override
protected Shape getBodyShape() {
return null;
}
@Override
protected Size getDefaultWidth() {
return null;
}
@Override
protected Size getDefaultLength() {
return null;
}
}
@@ -1,69 +0,0 @@
package org.diylc.components.connectivity;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.CubicCurve2D;
import org.diylc.common.ObjectCache;
import org.diylc.components.AbstractCurvedComponent;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Curved Trace", author = "Branislav Stojkovic", category = "Connectivity", instanceNamePrefix = "Trace", description = "Curved copper trace with two control points", zOrder = IDIYComponent.TRACE)
public class CurvedTrace extends AbstractCurvedComponent<Void> {
private static final long serialVersionUID = 1L;
public static Color COLOR = Color.black;
public static Size SIZE = new Size(1d, SizeUnit.mm);
protected Size size = SIZE;
@Override
protected Color getDefaultColor() {
return COLOR;
}
@Override
protected void drawCurve(CubicCurve2D curve, Graphics2D g2d, ComponentState componentState) {
int thickness = size.convertToPixels();
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(thickness));
g2d.setColor(componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color);
g2d.draw(curve);
}
@EditableProperty(name = "Width")
public Size getSize() {
return size;
}
public void setSize(Size size) {
this.size = size;
}
@Deprecated
@Override
public Void getValue() {
return null;
}
@Override
public void setValue(Void value) {
}
@Deprecated
@Override
public Byte getAlpha() {
return super.getAlpha();
}
@Override
public void setAlpha(Byte alpha) {
super.setAlpha(alpha);
}
}

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