Compare commits

..

1 Commits

Author SHA1 Message Date
bancika a37de776fa 2011-01-27 20:18:24 +00:00
108 changed files with 1944 additions and 5110 deletions
+1 -1
View File
@@ -9,9 +9,9 @@
<classpathentry kind="lib" path="lib/iText-2.1.7.jar"/>
<classpathentry kind="lib" path="lib/cloning-1.5.jar"/>
<classpathentry kind="lib" path="lib/objenesis-1.1.jar"/>
<classpathentry kind="lib" path="lib/bancika-gui-framework.jar"/>
<classpathentry kind="lib" path="lib/jettison-1.0.1.jar"/>
<classpathentry kind="lib" path="lib/poi-3.5-FINAL-20090928.jar"/>
<classpathentry kind="lib" path="library/main.jar"/>
<classpathentry kind="lib" path="lib/bancika-gui-framework.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
+13 -66
View File
@@ -1,76 +1,23 @@
<map>
<entry>
<string>default.org.diylc.components.passive.TrimmerPotentiometer:Type</string>
<org.diylc.components.passive.TrimmerPotentiometer_-TrimmerType>FLAT_LARGE</org.diylc.components.passive.TrimmerPotentiometer_-TrimmerType>
<string>metric</string>
<boolean>true</boolean>
</entry>
<entry>
<string>zoom</string>
<double>1.0</double>
</entry>
<entry>
<string>lastPath</string>
<string>C:\Documents and Settings\Branislav Stojkovic\Desktop</string>
</entry>
<entry>
<string>abnormalExit</string>
<boolean>false</boolean>
</entry>
<entry>
<string>stickyPoints</string>
<boolean>true</boolean>
</entry>
<entry>
<string>theme</string>
<org.diylc.core.Theme>
<name>Light</name>
<bgColor>
<red>255</red>
<green>255</green>
<blue>255</blue>
<alpha>255</alpha>
</bgColor>
<gridColor>
<red>240</red>
<green>240</green>
<blue>240</blue>
<alpha>240</alpha>
</gridColor>
</org.diylc.core.Theme>
</entry>
<entry>
<string>antiAliasing</string>
<boolean>true</boolean>
</entry>
<entry>
<string>snapToGrid</string>
<boolean>true</boolean>
</entry>
<entry>
<string>hiQualityRender</string>
<boolean>false</boolean>
</entry>
<entry>
<string>exportGrid</string>
<boolean>true</boolean>
</entry>
<entry>
<string>autoEdit</string>
<boolean>false</boolean>
</entry>
<entry>
<string>wheelZoom</string>
<boolean>false</boolean>
</entry>
<entry>
<string>default.org.diylc.components.misc.Label:Font Bold</string>
<boolean>false</boolean>
</entry>
<entry>
<string>autoCreatePads</string>
<boolean>false</boolean>
</entry>
<entry>
<string>continuousCreation</string>
<boolean>false</boolean>
</entry>
<entry>
<string>showTemplatesAtStartup</string>
<boolean>false</boolean>
<string>default.org.diylc.components.misc.Label:Color</string>
<awt-color>
<red>255</red>
<green>0</green>
<blue>0</blue>
<alpha>255</alpha>
</awt-color>
</entry>
</map>
Binary file not shown.
Binary file not shown.
+2 -14
View File
@@ -10,9 +10,7 @@ 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;
/**
@@ -40,8 +38,6 @@ public class DIYLCStarter {
LOG.error("Could not initialize log4j configuration", e);
}
LOG.debug("Java version: " + System.getProperty("java.runtime.version") + " by " + System.getProperty("java.vm.vendor"));
LOG.info("Starting DIYLC with working directory " + System.getProperty("user.dir"));
try {
@@ -53,16 +49,7 @@ public class DIYLCStarter {
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 {
@@ -72,5 +59,6 @@ public class DIYLCStarter {
} catch (Exception e) {
LOG.error("Could not read config.properties file", e);
}
}
}
+2 -8
View File
@@ -72,12 +72,6 @@ public enum EventType {
* current cursor location (not taking zoom into account).
*/
MOUSE_MOVED,
/**
* Called when a layer status is changed. The first parameter is a set of indices of locked layers. All layers not included are considered unlocked.
*/
LAYER_STATE_CHANGED,
/**
* Called to update the status message. New status message is passed as a first parameter.
*/
STATUS_MESSAGE_CHANGED;
LAYER_STATE_CHANGED;
;
}
+12 -37
View File
@@ -11,8 +11,6 @@ import java.util.Set;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.swing.plugins.edit.ComponentTransferable;
import com.diyfever.gui.simplemq.IMessageListener;
import com.diyfever.gui.simplemq.MessageDispatcher;
@@ -32,17 +30,7 @@ import com.diyfever.gui.update.VersionNumber;
*/
public interface IPlugInPort {
public static final String ANTI_ALIASING_KEY = "antiAliasing";
public static final String HI_QUALITY_RENDER_KEY = "hiQualityRender";
public static final String EXPORT_GRID_KEY = "exportGrid";
public static final String STICKY_POINTS_KEY = "stickyPoints";
public static final String METRIC_KEY = "metric";
public static final String SNAP_TO_GRID_KEY = "snapToGrid";
public static final String AUTO_PADS_KEY = "autoCreatePads";
public static final String CONTINUOUS_CREATION_KEY = "continuousCreation";
public static final String AUTO_EDIT_KEY = "autoEdit";
public static final String ABNORMAL_EXIT_KEY = "abnormalExit";
public static final String WHEEL_ZOOM_KEY = "wheelZoom";
public static final String CHECK_BOX_MENU_ITEM = "org.diylc.checkBoxMenuItem";
/**
* Returns size of the canvas that takes project dimensions into account as
@@ -98,9 +86,8 @@ public interface IPlugInPort {
* Saves the current project into the specified file.
*
* @param fileName
* @param isBackup
*/
void saveProjectToFile(String fileName, boolean isBackup);
void saveProjectToFile(String fileName);
/**
* @return the current file name.
@@ -167,9 +154,8 @@ public interface IPlugInPort {
* @param ctrlDown
* @param shiftDown
* @param altDown
* @param clickCount
*/
void mouseClicked(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown, int clickCount);
void mouseClicked(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown);
/**
* Notifies the presenter that mouse is moved.
@@ -274,9 +260,15 @@ public interface IPlugInPort {
*/
List<PropertyWrapper> getMutualSelectionProperties();
void editSelection();
/**
* Applies specified properties to all the selected components. If some of
* the properties are not applicable to some of the selected components an
* exception will be thrown.
*
* @param properties
*/
void applyPropertiesToSelection(List<PropertyWrapper> properties);
/**
* @return a list of editable properties of the current project.
*/
@@ -336,21 +328,4 @@ public interface IPlugInPort {
* Brings each of the selected components one step to front.
*/
void bringSelectionToFront();
/**
* Causes the display to refresh.
*/
void refresh();
/**
* @return currently selected theme.
*/
Theme getSelectedTheme();
/**
* Changes the current theme.
*
* @param theme
*/
void setSelectedTheme(Theme theme);
}
@@ -1,11 +0,0 @@
package org.diylc.common;
public enum LabelPosition {
ABOVE, BELOW;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -1,11 +0,0 @@
package org.diylc.common;
public enum OrientationHV {
VERTICAL, HORIZONTAL;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -3,8 +3,6 @@ package org.diylc.common;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.diylc.core.IPropertyValidator;
/**
* Entity class for editable properties extracted from component objects.
* Represents a single editable property together with it's current value.
@@ -19,21 +17,19 @@ public class PropertyWrapper implements Cloneable {
private Method setter;
private Method getter;
private boolean defaultable;
private IPropertyValidator validator;
public PropertyWrapper(String name, Class<?> type, Method getter, Method setter,
boolean defaultable, IPropertyValidator validator) {
boolean defaultable) {
super();
this.name = name;
this.type = type;
this.getter = getter;
this.setter = setter;
this.defaultable = defaultable;
this.validator = validator;
}
public void readFrom(Object object) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
public void readFrom(Object object) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
this.value = getter.invoke(object);
}
@@ -46,8 +42,8 @@ public class PropertyWrapper implements Cloneable {
// }
// }
public void writeTo(Object object) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
public void writeTo(Object object) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
setter.invoke(object, value);
}
@@ -71,8 +67,8 @@ public class PropertyWrapper implements Cloneable {
return defaultable;
}
public IPropertyValidator getValidator() {
return validator;
public void setDefaultable(boolean defaultable) {
this.defaultable = defaultable;
}
// @Override
@@ -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();
}
}
@@ -2,7 +2,6 @@ package org.diylc.components;
import java.awt.Color;
import java.awt.Font;
import java.awt.Shape;
import org.diylc.core.IDIYComponent;
import org.diylc.core.annotations.EditableProperty;
@@ -20,11 +19,11 @@ public abstract class AbstractComponent<T> implements IDIYComponent<T> {
private static final long serialVersionUID = 1L;
protected String name = "";
public static Color SELECTION_COLOR = Color.red;
public static Color LABEL_COLOR = Color.black;
public static Color LABEL_COLOR_SELECTED = Color.red;
public static Font LABEL_FONT = new Font("Tahoma", Font.PLAIN, 14);
public static Font LABEL_FONT = new Font("Tahoma", Font.PLAIN, 12);
@EditableProperty(defaultable = false)
@Override
@@ -36,7 +35,7 @@ public abstract class AbstractComponent<T> implements IDIYComponent<T> {
public void setName(String name) {
this.name = name;
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
@@ -54,20 +53,7 @@ public abstract class AbstractComponent<T> implements IDIYComponent<T> {
* @param x
* @return
*/
protected int getClosestOdd(double x) {
return ((int) x / 2) * 2 + 1;
}
/**
* @param clip
* @return true if none of the control points lie in the clip rectangle.
*/
protected boolean checkPointsClipped(Shape clip) {
for (int i = 0; i < getControlPointCount(); i++) {
if (clip.contains(getControlPoint(i))) {
return false;
}
}
return true;
protected int getClosestOdd(int x) {
return (x / 2) * 2 + 1;
}
}
@@ -24,15 +24,12 @@ public abstract class AbstractCurvedComponent<T> extends AbstractTransparentComp
public static Color GUIDELINE_COLOR = Color.blue;
public static Size DEFAULT_SIZE = new Size(1d, SizeUnit.in);
protected Point[] controlPoints = new Point[] {
new Point(0, 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), (int) (DEFAULT_SIZE
.convertToPixels())),
new Point((int) DEFAULT_SIZE.convertToPixels(), (int) DEFAULT_SIZE.convertToPixels()) };
protected 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();
protected PointCount pointCount = PointCount.FOUR;
/**
* Draws the specified curve onto graphics.
@@ -40,7 +37,6 @@ public abstract class AbstractCurvedComponent<T> extends AbstractTransparentComp
* @param curve
* @param g2d
* @param componentState
* @param theme
*/
protected abstract void drawCurve(CubicCurve2D curve, Graphics2D g2d,
ComponentState componentState);
@@ -65,9 +61,6 @@ public abstract class AbstractCurvedComponent<T> extends AbstractTransparentComp
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
if (checkPointsClipped(g2d.getClip())) {
return;
}
if (componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING) {
// Do not track guidelines.
drawingObserver.stopTracking();
@@ -100,133 +93,35 @@ public abstract class AbstractCurvedComponent<T> extends AbstractTransparentComp
g2d.setComposite(oldComposite);
}
@EditableProperty(name = "Point Count")
public PointCount getPointCount() {
if (pointCount == null) {
pointCount = PointCount.FOUR;
}
return pointCount;
}
public void setPointCount(PointCount pointCount) {
this.pointCount = pointCount;
// Reset control points.
for (int i = 0; i < getControlPointCount(); i++) {
setControlPoint(getControlPoint(i), i);
}
}
@Override
public int getControlPointCount() {
switch (getPointCount()) {
case TWO:
return 2;
case THREE:
return 3;
case FOUR:
return 4;
}
return 0;
return controlPoints.length;
}
@Override
public boolean isControlPointSticky(int index) {
return index == 0 || index == getControlPointCount() - 1;
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.
switch (getPointCount()) {
case TWO:
return false;
case THREE:
return index == 1;
case FOUR:
return index == 1 || index == 2;
}
return false;
return index == 1 || index == 2;
}
@Override
public Point getControlPoint(int index) {
if (index == 0) {
return controlPoints[0];
}
switch (getPointCount()) {
case TWO:
switch (index) {
case 1:
return controlPoints[3];
}
case THREE:
switch (index) {
case 1:
return controlPoints[1];
case 2:
return controlPoints[3];
}
case FOUR:
switch (index) {
case 1:
return controlPoints[1];
case 2:
return controlPoints[2];
case 3:
return controlPoints[3];
}
}
return controlPoints[index];
}
@Override
public void setControlPoint(Point point, int index) {
if (index == 0) {
controlPoints[0].setLocation(point);
} else {
switch (getPointCount()) {
case TWO:
switch (index) {
case 1:
Point center = new Point((point.x + controlPoints[0].x) / 2,
(point.y + controlPoints[0].y) / 2);
controlPoints[1].setLocation(center);
controlPoints[2].setLocation(center);
controlPoints[3].setLocation(point);
break;
}
break;
case THREE:
switch (index) {
case 1:
controlPoints[1].setLocation(point);
controlPoints[2].setLocation(point);
break;
case 2:
controlPoints[3].setLocation(point);
break;
}
break;
case FOUR:
switch (index) {
case 1:
controlPoints[1].setLocation(point);
break;
case 2:
controlPoints[2].setLocation(point);
break;
case 3:
controlPoints[3].setLocation(point);
break;
}
break;
}
}
controlPoints[index].setLocation(point);
}
@EditableProperty
@@ -238,12 +133,4 @@ public abstract class AbstractCurvedComponent<T> extends AbstractTransparentComp
this.color = color;
}
enum PointCount {
TWO, THREE, FOUR;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
}
@@ -8,8 +8,6 @@ import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import org.diylc.common.Display;
@@ -37,21 +35,21 @@ public abstract class AbstractLeadedComponent<T> extends AbstractTransparentComp
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 Size height;
protected Point[] points = new Point[] {
new Point((int) (-DEFAULT_SIZE.convertToPixels() / 2), 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), 0) };
protected Color bodyColor = Color.white;
protected Color borderColor = Color.black;
new Point(DEFAULT_SIZE.convertToPixels() / 2, 0) };
protected Color bodyColor = getDefaultBodyColor();
protected Color borderColor = getDefaultBorderColor();
protected Color labelColor = LABEL_COLOR;
protected Display display = Display.NAME;
protected AbstractLeadedComponent() {
super();
try {
this.length = getDefaultLength().clone();
this.width = getDefaultWidth().clone();
this.height = getDefaultHeight().clone();
} catch (CloneNotSupportedException e) {
// This should never happen because Size supports cloning.
} catch (NullPointerException e) {
@@ -64,140 +62,99 @@ public abstract class AbstractLeadedComponent<T> extends AbstractTransparentComp
IDrawingObserver drawingObserver) {
double distance = points[0].distance(points[1]);
Shape shape = getBodyShape();
// If there's no body, just draw the line connecting the ending points.
if (shape == null) {
drawLead(g2d, componentState);
} else if (supportsStandingMode()
&& length.convertToPixels() > points[0].distance(points[1])) {
// When ending points are too close draw the component in standing
// mode.
int width = getClosestOdd(this.width.convertToPixels());
Shape body = new Ellipse2D.Double(points[0].x - width / 2, points[0].y - width / 2,
width, width);
g2d.setColor(bodyColor);
g2d.fill(body);
Color finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : borderColor;
g2d.setColor(finalBorderColor);
g2d.draw(body);
drawLead(g2d, componentState);
} else {
// Normal mode with component body in the center and two lead parts.
Rectangle shapeRect = shape.getBounds();
Double theta = Math.atan2(points[1].y - points[0].y, points[1].x - points[0].x);
// Transform graphics to draw the body in the right place and at the
// right angle.
AffineTransform oldTransform = g2d.getTransform();
g2d.translate((points[0].x + points[1].x - shapeRect.width) / 2, (points[0].y
+ points[1].y - shapeRect.height) / 2);
g2d.rotate(theta, shapeRect.width / 2, shapeRect.height / 2);
// Draw body.
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
if (bodyColor != null) {
if (bodyColor != null) {
g2d.setColor(bodyColor);
g2d.fill(shape);
}
}
decorateComponentBody(g2d);
g2d.setComposite(oldComposite);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
Color finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : borderColor;
g2d.setColor(finalBorderColor);
g2d.draw(shape);
// Draw label.
g2d.setFont(LABEL_FONT);
Color finalLabelFont = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? LABEL_COLOR_SELECTED
: labelColor;
g2d.setColor(finalLabelFont);
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,
calculateLabelYCoordinate(shapeRect, textRect, fontMetrics));
// Go back to the original transformation to draw leads.
g2d.setTransform(oldTransform);
int leadThickness = getClosestOdd(getLeadThickness());
double leadLength = (distance - shapeRect.width) / 2 - leadThickness / 2;
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness));
Color leadColor = shouldShadeLeads() ? getLeadColor(componentState).darker()
: getLeadColor(componentState);
g2d.setColor(leadColor);
int endX = (int) (points[0].x + Math.cos(theta) * leadLength);
int endY = (int) Math.round(points[0].y + Math.sin(theta) * leadLength);
g2d.drawLine(points[0].x, points[0].y, endX, endY);
endX = (int) (points[1].x + Math.cos(theta - Math.PI) * leadLength);
endY = (int) Math.round(points[1].y + Math.sin(theta - Math.PI) * leadLength);
g2d.drawLine(points[1].x, points[1].y, endX, endY);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness - 2));
leadColor = getLeadColor(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, (int) (points[0].x + Math.cos(theta)
* leadLength), (int) (points[0].y + Math.sin(theta) * leadLength));
g2d
.drawLine(points[1].x, points[1].y, (int) (points[1].x + Math.cos(theta
- Math.PI)
* leadLength), (int) (points[1].y + Math.sin(theta - Math.PI)
* leadLength));
}
}
}
private void drawLead(Graphics2D g2d, ComponentState componentState) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(getLeadThickness()));
Color leadColor = shouldShadeLeads() ? getLeadColor(componentState).darker()
: getLeadColor(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(getLeadThickness() - 2));
leadColor = getLeadColor(componentState);
g2d.setColor(leadColor);
g2d.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 int calculateLabelYCoordinate(Rectangle2D shapeRect, Rectangle2D textRect,
FontMetrics fontMetrics) {
return (int) (shapeRect.getHeight() - textRect.getHeight()) / 2 + fontMetrics.getAscent();
}
protected boolean shouldShadeLeads() {
return true;
}
protected boolean supportsStandingMode() {
return false;
}
/**
* @return default component length.
* @return default component width.
*/
protected abstract Size getDefaultLength();
protected abstract Size getDefaultWidth();
/**
* Returns default component width.
* Returns default component height.
*
* @return
*/
protected abstract Size getDefaultWidth();
protected abstract Size getDefaultHeight();
/**
* @return shape that represents component body. Shape should not be
@@ -205,11 +162,21 @@ public abstract class AbstractLeadedComponent<T> extends AbstractTransparentComp
*/
protected abstract Shape getBodyShape();
/**
* @return default component body color.
*/
protected abstract Color getDefaultBodyColor();
/**
* @return default component border color.
*/
protected abstract Color getDefaultBorderColor();
/**
* @return default lead thickness. Override this method to change it.
*/
protected int getLeadThickness() {
return (int) LEAD_THICKNESS.convertToPixels();
protected Size getLeadThickness() {
return LEAD_THICKNESS;
}
/**
@@ -263,16 +230,7 @@ public abstract class AbstractLeadedComponent<T> extends AbstractTransparentComp
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)
@EditableProperty(defaultable = true)
public Size getWidth() {
return width;
}
@@ -281,6 +239,15 @@ public abstract class AbstractLeadedComponent<T> extends AbstractTransparentComp
this.width = width;
}
@EditableProperty(defaultable = true)
public Size getHeight() {
return height;
}
public void setHeight(Size height) {
this.height = height;
}
@EditableProperty
public Display getDisplay() {
return display;
@@ -1,72 +0,0 @@
package org.diylc.components;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.geom.Rectangle2D;
import org.diylc.common.LabelPosition;
import org.diylc.core.ComponentState;
import org.diylc.core.annotations.EditableProperty;
public abstract class AbstractSchematicLeadedSymbol<T> extends AbstractLeadedComponent<T> {
private static final long serialVersionUID = 1L;
public static Color COLOR = Color.blue;
public static Color LEAD_COLOR = Color.black;
protected LabelPosition labelPosition = LabelPosition.ABOVE;
public AbstractSchematicLeadedSymbol() {
super();
// We don't want to fill the body, so use null.
this.bodyColor = null;
this.borderColor = COLOR;
}
@Override
public Color getBodyColor() {
return super.getBodyColor();
}
@Override
protected boolean shouldShadeLeads() {
return false;
}
@Override
protected int getLeadThickness() {
return 1;
}
@Override
protected int calculateLabelYCoordinate(Rectangle2D shapeRect, Rectangle2D textRect,
FontMetrics fontMetrics) {
if (labelPosition == LabelPosition.ABOVE) {
return -1;
} else {
return (int) (shapeRect.getHeight() + textRect.getHeight() - 1);
}
}
@EditableProperty(name = "Label position")
public LabelPosition getLabelPosition() {
return labelPosition;
}
@Override
@EditableProperty(name = "Color")
public Color getBorderColor() {
return super.getBorderColor();
}
public void setLabelPosition(LabelPosition labelPosition) {
this.labelPosition = labelPosition;
}
@Override
protected Color getLeadColor(ComponentState componentState) {
return componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : LEAD_COLOR;
}
}
@@ -0,0 +1,36 @@
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,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,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;
}
-10
View File
@@ -1,10 +1,5 @@
package org.diylc.core;
import java.util.List;
import java.util.Set;
import org.diylc.common.PropertyWrapper;
/**
* Base interface for the main GUI component.
@@ -26,13 +21,8 @@ public interface IView {
public static final int NO_OPTION = 1;
public static final int CANCEL_OPTION = 2;
public static final int OK_OPTION = 0;
public static final String CHECK_BOX_MENU_ITEM = "org.diylc.checkBoxMenuItem";
public static final String RADIO_BUTTON_GROUP_KEY = "org.diylc.radioButtonGroup";
void showMessage(String message, String title, int messageType);
int showConfirmDialog(String message, String title, int optionType, int messageType);
boolean editProperties(List<PropertyWrapper> properties, Set<PropertyWrapper> defaultedProperties);
}
+3 -31
View File
@@ -7,12 +7,9 @@ import java.util.List;
import java.util.Set;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.annotations.PositiveMeasureValidator;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import com.diyfever.gui.update.VersionNumber;
/**
* Entity class that defines a project. Contains project properties and a
* collection of components.This class is serialized to file. Some filed getters
@@ -29,8 +26,6 @@ public class Project implements Serializable {
public static Size DEFAULT_HEIGHT = new Size(21d, SizeUnit.cm);
public static Size DEFAULT_GRID_SPACING = new Size(0.1d, SizeUnit.in);
private VersionNumber fileVersion;
private String title;
private String author;
private String description;
@@ -97,7 +92,7 @@ public class Project implements Serializable {
this.height = height;
}
@EditableProperty(name = "Grid spacing", validatorClass = SpacingValidator.class)
@EditableProperty(name = "Grid spacing")
public Size getGridSpacing() {
return gridSpacing;
}
@@ -123,18 +118,10 @@ public class Project implements Serializable {
public Set<Set<IDIYComponent<?>>> getGroups() {
return groups;
}
public Set<Integer> getLockedLayers() {
return lockedLayers;
}
public VersionNumber getFileVersion() {
return fileVersion;
}
public void setFileVersion(VersionNumber fileVersion) {
this.fileVersion = fileVersion;
}
@Override
public int hashCode() {
@@ -190,27 +177,12 @@ public class Project implements Serializable {
return false;
return true;
}
@Override
public String toString() {
return title;
}
public static class SpacingValidator extends PositiveMeasureValidator {
@Override
public void validate(Object value) throws ValidationException {
super.validate(value);
Size size = (Size) value;
if (size.compareTo(new Size(1d, SizeUnit.mm)) < 0) {
throw new ValidationException("must be greater than 1mm");
}
if (size.compareTo(new Size(1d, SizeUnit.in)) > 0) {
throw new ValidationException("must be less than 1in");
}
}
}
// @Override
// public Project clone() throws CloneNotSupportedException {
// List<IDIYComponent> clonedComponents = new
-74
View File
@@ -1,74 +0,0 @@
package org.diylc.core;
import java.awt.Color;
import java.io.Serializable;
public class Theme implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Color bgColor;
private Color gridColor;
public Theme(String name, Color bgColor, Color gridColor) {
super();
this.name = name;
this.bgColor = bgColor;
this.gridColor = gridColor;
}
public String getName() {
return name;
}
public Color getBgColor() {
return bgColor;
}
public Color getGridColor() {
return gridColor;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bgColor == null) ? 0 : bgColor.hashCode());
result = prime * result + ((gridColor == null) ? 0 : gridColor.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Theme other = (Theme) obj;
if (bgColor == null) {
if (other.bgColor != null)
return false;
} else if (!bgColor.equals(other.bgColor))
return false;
if (gridColor == null) {
if (other.gridColor != null)
return false;
} else if (!gridColor.equals(other.gridColor))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return name;
}
}
@@ -1,11 +0,0 @@
package org.diylc.core;
public class ValidationException extends Exception {
private static final long serialVersionUID = 1L;
public ValidationException(String message) {
super(message);
}
}
@@ -3,9 +3,6 @@ package org.diylc.core.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.diylc.core.AllowAllValidator;
import org.diylc.core.IPropertyValidator;
/**
* Used to annotate editable component property. Editable property XYZ must have
* both getter and setter named <code>getXYZ</code> and <code>setXYZ</code>
@@ -33,10 +30,4 @@ public @interface EditableProperty {
* @return
*/
boolean defaultable() default true;
/**
* Class of validator to use to
* @return
*/
Class<? extends IPropertyValidator> validatorClass() default AllowAllValidator.class;
}
@@ -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.");
}
}
}
@@ -2,7 +2,7 @@ package org.diylc.core.measures;
public enum CapacitanceUnit implements Unit {
pF(1, "pF"), nF(1e3, "nF"), uF(1e6, "uF"), mF(1e9, "mF"), F(1e12, "F");
pF(1, "pF"), nF(1e3, "nF"), uF(1e6, "\u03bcF"), mF(1e9, "mF"), F(1e12, "F");
double factor;
String display;
@@ -1,20 +1,9 @@
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
@@ -30,42 +19,6 @@ public class Resistance extends AbstractMeasure<ResistanceUnit> {
return new Resistance(value, unit);
}
public Color[] getColorCode(ResistorColorCode resistorColorCode) {
Color[] bands;
double base = getValue() * getUnit().getFactor();
int multiplier = 0;
while (base > (resistorColorCode == ResistorColorCode._4_BAND ? 99 : 999)) {
multiplier += 1;
base /= 10;
}
while (base < (resistorColorCode == ResistorColorCode._4_BAND ? 10 : 100)) {
multiplier -= 1;
base *= 10;
}
if (multiplier > 6 || multiplier < -2) {
// Out of range.
return new Color[] {};
}
switch (resistorColorCode) {
case _4_BAND:
bands = new Color[3];
bands[0] = COLOR_DIGITS[(int) (base / 10)];
bands[1] = COLOR_DIGITS[(int) (base % 10)];
bands[2] = COLOR_MULTIPLIER[multiplier + 2];
break;
case _5_BAND:
bands = new Color[4];
bands[0] = COLOR_DIGITS[(int) (base / 100)];
bands[1] = COLOR_DIGITS[(int) (base / 10 % 10)];
bands[2] = COLOR_DIGITS[(int) (base % 10)];
bands[3] = COLOR_MULTIPLIER[multiplier + 2];
break;
default:
bands = new Color[] {};
}
return bands;
}
public static Resistance parseResistance(String value) {
for (ResistanceUnit unit : ResistanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
+3 -8
View File
@@ -2,7 +2,7 @@ package org.diylc.core.measures;
import org.diylc.utils.Constants;
public class Size extends AbstractMeasure<SizeUnit> implements Comparable<Size> {
public class Size extends AbstractMeasure<SizeUnit> {
private static final long serialVersionUID = 1L;
@@ -16,13 +16,13 @@ public class Size extends AbstractMeasure<SizeUnit> implements Comparable<Size>
// TODO Auto-generated constructor stub
}
public double convertToPixels() {
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 getValue() * getUnit().getFactor() / SizeUnit.in.getFactor() * Constants.PIXELS_PER_INCH;
return (int) (getValue() * getUnit().getFactor() / SizeUnit.in.getFactor() * Constants.PIXELS_PER_INCH);
}
@Override
@@ -39,9 +39,4 @@ public class Size extends AbstractMeasure<SizeUnit> implements Comparable<Size>
}
throw new IllegalArgumentException("Could not parse size: " + value);
}
@Override
public int compareTo(Size o) {
return new Double(value * unit.getFactor()).compareTo(o.getValue() * o.getUnit().getFactor());
}
}
+1 -2
View File
@@ -30,8 +30,7 @@ public enum IconLoader {
"faq.png"), Component("component.png"), Plugin("plugin.png"), Manual("manual.png"), Donate(
"donate.png"), Bug("bug.png"), IconLarge("icon_large.png"), IconMedium(
"icon_medium.png"), IconSmall("icon_small.png"), DocumentEdit("document_edit.png"), EditComponent(
"edit_component.png"), Size("size.png"), Front("front.png"), Back("back.png"), Pens(
"pens.png");
"edit_component.png"), Size("size.png"), Front("front.png"), Back("back.png");
protected String name;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 922 B

+2 -2
View File
@@ -13,8 +13,8 @@ public class CalcUtils {
* @return
*/
public static int roundToGrid(int x, Size gridSpacing) {
double grid = gridSpacing.convertToPixels();
return (int) (Math.round(1f * x / grid) * grid);
int grid = gridSpacing.convertToPixels();
return (Math.round(1f * x / grid) * grid);
}
public static void snapPointToGrid(Point point, Size gridSpacing) {
@@ -19,7 +19,6 @@ 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;
@@ -36,8 +35,7 @@ public class ComponentProcessor {
private static ComponentProcessor instance;
private Map<String, List<PropertyWrapper>> propertyCache;
private Map<String, IPropertyValidator> propertyValidatorCache;
private Map<Class<?>, List<PropertyWrapper>> propertyCache;
private Map<String, ComponentType> componentTypeMap;
private Cloner cloner;
@@ -52,9 +50,8 @@ public class ComponentProcessor {
private ComponentProcessor() {
super();
this.cloner = new Cloner();
this.propertyCache = new HashMap<String, List<PropertyWrapper>>();
this.propertyCache = new HashMap<Class<?>, List<PropertyWrapper>>();
this.componentTypeMap = new HashMap<String, ComponentType>();
this.propertyValidatorCache = new HashMap<String, IPropertyValidator>();
}
public ComponentType extractComponentTypeFrom(Class<? extends IDIYComponent<?>> clazz) {
@@ -120,8 +117,8 @@ public class ComponentProcessor {
* @return
*/
public List<PropertyWrapper> extractProperties(Class<?> clazz) {
if (propertyCache.containsKey(clazz.getName())) {
return cloner.deepClone(propertyCache.get(clazz.getName()));
if (propertyCache.containsKey(clazz)) {
return cloner.deepClone(propertyCache.get(clazz));
}
List<PropertyWrapper> properties = new ArrayList<PropertyWrapper>();
for (Method method : clazz.getMethods()) {
@@ -136,13 +133,10 @@ public class ComponentProcessor {
} 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);
method.getReturnType(), method, setter, annotation.defaultable());
properties.add(property);
}
} catch (NoSuchMethodException e) {
@@ -152,7 +146,7 @@ public class ComponentProcessor {
}
}
propertyCache.put(clazz.getName(), properties);
propertyCache.put(clazz, properties);
return cloner.deepClone(properties);
}
@@ -193,19 +187,4 @@ public class ComponentProcessor {
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;
}
}
+34 -123
View File
@@ -16,17 +16,14 @@ 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.IPlugInPort;
import org.diylc.common.ObjectCache;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.utils.Constants;
@@ -41,20 +38,16 @@ import com.diyfever.gui.simplemq.MessageDispatcher;
*/
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 final String THEME_KEY = "theme";
public static String DEBUG_COMPONENT_AREAS = "org.diylc.debugComponentAreas";
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;
private Theme theme = new Theme("Light", Constants.CANVAS_COLOR, GRID_COLOR);
// 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
@@ -63,88 +56,33 @@ public class DrawingManager {
private Composite slotComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
private Composite lockedComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
private List<IDIYComponent<?>> failedComponents = new ArrayList<IDIYComponent<?>>();
private double zoomLevel = 1d;// ConfigurationManager.getInstance().readDouble(ZOOM_KEY,
// 1d);
private MessageDispatcher<EventType> messageDispatcher;
private boolean debugComponentAreas;
public DrawingManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.messageDispatcher = messageDispatcher;
componentAreaMap = new HashMap<IDIYComponent<?>, Area>();
lastDrawnStateMap = new HashMap<IDIYComponent<?>, ComponentState>();
String debugComponentAreasStr = System.getProperty(DEBUG_COMPONENT_AREAS);
debugComponentAreas = debugComponentAreasStr != null
&& debugComponentAreasStr.equalsIgnoreCase("true");
Theme theme = (Theme) ConfigurationManager.getInstance().readObject(THEME_KEY, null);
if (theme != null) {
this.theme = theme;
}
}
/**
* 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();
public void 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) {
if (project == null) {
return failedComponents;
return;
}
G2DWrapper g2dWrapper = new G2DWrapper(g2d);
if (drawOptions.contains(DrawOption.ANTIALIASING)) {
if (drawOptions.contains(DrawOption.ANTIALIASING)
&& ConfigurationManager.getInstance().readBoolean(ANTIALIASING_KEY, true)) {
g2d
.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} else {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
if (ConfigurationManager.getInstance()
.readBoolean(IPlugInPort.HI_QUALITY_RENDER_KEY, false)) {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
} else {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
double zoom = 1d;
@@ -157,11 +95,12 @@ public class DrawingManager {
// AffineTransform initialTx = g2d.getTransform();
Dimension d = getCanvasDimensions(project, zoom, true);
g2dWrapper.setColor(theme.getBgColor());
g2dWrapper.setColor(Constants.CANVAS_COLOR);
g2dWrapper.fillRect(0, 0, d.width, d.height);
g2d.clip(new Rectangle(new Point(0, 0), d));
g2d.setClip(new Rectangle(new Point(0, 0), d));
GridType gridType = GridType.LINES;
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) {
@@ -173,7 +112,7 @@ public class DrawingManager {
10f, new float[] { 1f, (float) zoomStep - 1 }, 0f));
}
g2dWrapper.setColor(theme.getGridColor());
g2dWrapper.setColor(GRID_COLOR);
for (double i = zoomStep; i < d.width; i += zoomStep) {
g2dWrapper.drawLine((int) i, 0, (int) i, d.height - 1);
}
@@ -219,14 +158,9 @@ public class DrawingManager {
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);
}
component.draw(g2dWrapper, state, project, g2dWrapper);
Area area = g2dWrapper.finishedDrawingComponent();
if (trackArea && area != null && !area.isEmpty()) {
if (trackArea) {
componentAreaMap.put(component, area);
lastDrawnStateMap.put(component, state);
}
@@ -235,24 +169,22 @@ public class DrawingManager {
// Draw control points.
if (drawOptions.contains(DrawOption.CONTROL_POINTS)) {
// Draw unselected points first to make sure they are below.
if (dragInProgress) {
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);
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);
}
Point controlPoint = component.getControlPoint(i);
int pointSize = CONTROL_POINT_SIZE - 2;
g2dWrapper.fillOval(controlPoint.x - pointSize / 2, controlPoint.y
- pointSize / 2, pointSize, pointSize);
}
}
}
@@ -282,12 +214,7 @@ public class DrawingManager {
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);
}
componentSlot.draw(g2dWrapper, ComponentState.NORMAL, project, g2dWrapper);
g2dWrapper.finishedDrawingComponent();
}
@@ -324,15 +251,13 @@ public class DrawingManager {
}
// Draw component area for test
if (debugComponentAreas) {
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() {
@@ -354,10 +279,6 @@ public class DrawingManager {
return componentAreaMap.get(component);
}
public void clearComponentAreaMap() {
componentAreaMap.clear();
}
public List<IDIYComponent<?>> findComponentsAt(Point point, Project project) {
List<IDIYComponent<?>> components = new ArrayList<IDIYComponent<?>>();
for (int i = 0; i < project.getComponents().size(); i++) {
@@ -371,7 +292,7 @@ public class DrawingManager {
public Dimension getCanvasDimensions(Project project, Double zoomLevel, boolean useZoom) {
double width = project.getWidth().convertToPixels();
double height = project.getHeight().convertToPixels();
int height = project.getHeight().convertToPixels();
if (useZoom) {
width *= zoomLevel;
height *= zoomLevel;
@@ -386,14 +307,4 @@ public class DrawingManager {
messageDispatcher.dispatchMessage(EventType.ZOOM_CHANGED, zoomLevel);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
public Theme getTheme() {
return theme;
}
public void setTheme(Theme theme) {
this.theme = theme;
ConfigurationManager.getInstance().writeValue(THEME_KEY, theme);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
}
@@ -179,7 +179,6 @@ class G2DWrapper extends Graphics2D implements IDrawingObserver {
width, thickness);
Area area = new Area(rect);
area.transform(AffineTransform.getRotateInstance(theta, midX, midY));
// area.transform(currentTx);
appendShape(area);
// Set the prev point to line end
prevPoint = nextPoint;
@@ -1,41 +0,0 @@
package org.diylc.presenter;
import java.awt.Point;
import org.diylc.utils.Constants;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* Serializes {@link Point} objects by converting coordinates from pixels to
* inches, thus avoiding the resolution to affect point placement.
*
* @author Branislav Stojkovic
*/
public class PointConverter implements Converter {
@Override
public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) {
Point point = (Point) object;
writer.addAttribute("x", Double.toString(1d * point.x / Constants.PIXELS_PER_INCH));
writer.addAttribute("y", Double.toString(1d * point.y / Constants.PIXELS_PER_INCH));
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
double x = Double.parseDouble(reader.getAttribute("x"));
double y = Double.parseDouble(reader.getAttribute("y"));
return new Point((int) Math.round(x * Constants.PIXELS_PER_INCH), (int) Math.round(y
* Constants.PIXELS_PER_INCH));
}
@SuppressWarnings("unchecked")
@Override
public boolean canConvert(Class clazz) {
return Point.class.isAssignableFrom(clazz);
}
}
+132 -241
View File
@@ -19,8 +19,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.diylc.common.ComponentType;
import org.diylc.common.DrawOption;
@@ -29,11 +27,9 @@ import org.diylc.common.IComponentFiler;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.common.PropertyWrapper;
import org.diylc.components.connectivity.SolderPad;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IView;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.measures.SizeUnit;
import org.diylc.swing.plugins.edit.ComponentTransferable;
import org.diylc.utils.Constants;
@@ -54,8 +50,9 @@ public class Presenter implements IPlugInPort {
private static final Logger LOG = Logger.getLogger(Presenter.class);
public static final VersionNumber CURRENT_VERSION = new VersionNumber(3, 0, 8);
public static final VersionNumber CURRENT_VERSION = new VersionNumber(3, 0, 4);
public static final String DEFAULTS_KEY_PREFIX = "default.";
public static final String METRIC_KEY = "metric";
public static final List<IDIYComponent<?>> EMPTY_SELECTION = Collections.emptyList();
@@ -94,6 +91,8 @@ public class Presenter implements IPlugInPort {
private Point previousDragPoint = null;
private Project preDragProject = null;
private boolean snapToGrid = true;
public Presenter(IView view) {
super();
this.view = view;
@@ -181,7 +180,6 @@ public class Presenter implements IPlugInPort {
public void loadProject(Project project, boolean freshStart) {
LOG.info(String.format("loadProject(%s, %s)", project.getTitle(), freshStart));
this.currentProject = project;
drawingManager.clearComponentAreaMap();
updateSelection(EMPTY_SELECTION);
messageDispatcher.dispatchMessage(EventType.PROJECT_LOADED, project, freshStart);
messageDispatcher.dispatchMessage(EventType.REPAINT);
@@ -242,11 +240,10 @@ public class Presenter implements IPlugInPort {
}
@Override
public void saveProjectToFile(String fileName, boolean isBackup) {
public void saveProjectToFile(String fileName) {
LOG.info(String.format("saveProjectToFile(%s)", fileName));
try {
currentProject.setFileVersion(CURRENT_VERSION);
projectFileManager.serializeProjectToFile(currentProject, fileName, isBackup);
projectFileManager.serializeProjectToFile(currentProject, fileName);
} catch (Exception ex) {
LOG.error("Could not save file", ex);
view.showMessage("Could not save file " + fileName + ". Check the log for details.",
@@ -302,8 +299,7 @@ public class Presenter implements IPlugInPort {
groupedComponents.add(component);
}
}
// Don't draw the component in the slot if both control points
// match.
// Don't draw the component in the slot if both control points match.
IDIYComponent<?> componentSlotToDraw;
if (instantiationManager.getFirstControlPoint() != null
&& instantiationManager.getPotentialControlPoint() != null
@@ -313,23 +309,10 @@ public class Presenter implements IPlugInPort {
} else {
componentSlotToDraw = instantiationManager.getComponentSlot();
}
List<IDIYComponent<?>> failedComponents = drawingManager.drawProject(g2d, currentProject,
drawOptions, filter, selectionRect, selectedComponents, getLockedComponents(),
groupedComponents, Arrays.asList(instantiationManager.getFirstControlPoint(),
instantiationManager.getPotentialControlPoint()), componentSlotToDraw,
dragInProgress);
List<String> failedComponentNames = new ArrayList<String>();
for (IDIYComponent<?> component : failedComponents) {
failedComponentNames.add(component.getName());
}
Collections.sort(failedComponentNames);
if (!failedComponentNames.isEmpty()) {
messageDispatcher.dispatchMessage(EventType.STATUS_MESSAGE_CHANGED,
"<html><font color='red'>Failed to draw components: "
+ Utils.toCommaString(failedComponentNames) + "</font></html>");
} else {
messageDispatcher.dispatchMessage(EventType.STATUS_MESSAGE_CHANGED, "");
}
drawingManager.drawProject(g2d, currentProject, drawOptions, filter, selectionRect,
selectedComponents, getLockedComponents(), groupedComponents, Arrays.asList(
instantiationManager.getFirstControlPoint(), instantiationManager
.getPotentialControlPoint()), componentSlotToDraw, dragInProgress);
}
/**
@@ -351,162 +334,108 @@ public class Presenter implements IPlugInPort {
}
@Override
public void mouseClicked(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown,
int clickCount) {
public void mouseClicked(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown) {
LOG.debug(String
.format("mouseClicked(%s, %s, %s, %s)", point, ctrlDown, shiftDown, altDown));
Point scaledPoint = scalePoint(point);
if (clickCount >= 2) {
editSelection();
} else {
if (instantiationManager.getComponentTypeSlot() != null) {
// Keep the reference to component type for later.
ComponentType componentTypeSlot = instantiationManager.getComponentTypeSlot();
Project oldProject = cloner.deepClone(currentProject);
switch (componentTypeSlot.getCreationMethod()) {
case SINGLE_CLICK:
try {
if (ConfigurationManager.getInstance().readBoolean(
IPlugInPort.SNAP_TO_GRID_KEY, true)) {
CalcUtils.snapPointToGrid(scaledPoint, currentProject.getGridSpacing());
}
IDIYComponent<?> component = instantiationManager.instantiateComponent(
componentTypeSlot, scaledPoint, currentProject);
addComponent(component, componentTypeSlot, true);
// Select the new component
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
// selectedComponents);
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
// calculateSelectionDimension());
messageDispatcher.dispatchMessage(EventType.REPAINT);
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>();
newSelection.add(component);
updateSelection(newSelection);
} catch (Exception e) {
LOG.error("Error instatiating component of type: "
+ componentTypeSlot.getInstanceClass().getName(), e);
}
if (ConfigurationManager.getInstance().readBoolean(IPlugInPort.AUTO_EDIT_KEY,
false)) {
editSelection();
}
if (ConfigurationManager.getInstance().readBoolean(
IPlugInPort.CONTINUOUS_CREATION_KEY, false)) {
setNewComponentTypeSlot(componentTypeSlot);
} else {
setNewComponentTypeSlot(null);
}
break;
case POINT_BY_POINT:
// First click is just to set the controlPointSlot and
// componentSlot.
if (ConfigurationManager.getInstance().readBoolean(
IPlugInPort.SNAP_TO_GRID_KEY, true)) {
if (instantiationManager.getComponentTypeSlot() != null) {
// Keep the reference to component type for later.
ComponentType componentTypeSlot = instantiationManager.getComponentTypeSlot();
Project oldProject = cloner.deepClone(currentProject);
switch (componentTypeSlot.getCreationMethod()) {
case SINGLE_CLICK:
try {
if (snapToGrid) {
CalcUtils.snapPointToGrid(scaledPoint, currentProject.getGridSpacing());
}
if (instantiationManager.getComponentSlot() == null) {
try {
instantiationManager
.instatiatePointByPoint(scaledPoint, currentProject);
} catch (Exception e) {
view.showMessage("Could not create component. Check log for details.",
"Error", IView.ERROR_MESSAGE);
LOG.error("Could not create component", e);
}
messageDispatcher.dispatchMessage(EventType.SLOT_CHANGED,
componentTypeSlot, instantiationManager.getFirstControlPoint());
messageDispatcher.dispatchMessage(EventType.REPAINT);
} else {
// On the second click, add the component to the
// project.
IDIYComponent<?> componentSlot = instantiationManager.getComponentSlot();
componentSlot.setControlPoint(scaledPoint, 1);
addComponent(componentSlot, componentTypeSlot, true);
// Select the new component if it's not locked.
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>();
if (!isComponentLocked(componentSlot)) {
newSelection.add(componentSlot);
}
updateSelection(newSelection);
messageDispatcher.dispatchMessage(EventType.REPAINT);
if (ConfigurationManager.getInstance().readBoolean(
IPlugInPort.AUTO_EDIT_KEY, false)) {
editSelection();
}
if (ConfigurationManager.getInstance().readBoolean(
IPlugInPort.CONTINUOUS_CREATION_KEY, false)) {
setNewComponentTypeSlot(componentTypeSlot);
} else {
setNewComponentTypeSlot(null);
}
IDIYComponent<?> component = instantiationManager.instantiateComponent(
componentTypeSlot, scaledPoint, currentProject);
addComponent(component, componentTypeSlot);
// Select the new component
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
// selectedComponents);
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
// calculateSelectionDimension());
messageDispatcher.dispatchMessage(EventType.REPAINT);
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>();
newSelection.add(component);
updateSelection(newSelection);
} catch (Exception e) {
LOG.error("Error instatiating component of type: "
+ componentTypeSlot.getInstanceClass().getName(), e);
}
setNewComponentTypeSlot(null);
break;
case POINT_BY_POINT:
// First click is just to set the controlPointSlot and
// componentSlot.
if (snapToGrid) {
CalcUtils.snapPointToGrid(scaledPoint, currentProject.getGridSpacing());
}
if (instantiationManager.getComponentSlot() == null) {
try {
instantiationManager.instatiatePointByPoint(scaledPoint, currentProject);
} catch (Exception e) {
view.showMessage("Could not create component. Check log for details.",
"Error", IView.ERROR_MESSAGE);
LOG.error("Could not create component", e);
}
break;
default:
LOG.error("Unknown creation method: " + componentTypeSlot.getCreationMethod());
}
// Notify the listeners.
if (!oldProject.equals(currentProject)) {
messageDispatcher.dispatchMessage(EventType.PROJECT_MODIFIED, oldProject,
cloner.deepClone(currentProject), "Add " + componentTypeSlot.getName());
projectFileManager.notifyFileChange();
}
} else {
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>(
selectedComponents);
List<IDIYComponent<?>> components = findComponentsAt(scaledPoint);
// If there's nothing under mouse cursor deselect all.
if (components.isEmpty()) {
newSelection.clear();
messageDispatcher.dispatchMessage(EventType.SLOT_CHANGED, componentTypeSlot,
instantiationManager.getFirstControlPoint());
messageDispatcher.dispatchMessage(EventType.REPAINT);
} else {
IDIYComponent<?> component = components.get(components.size() - 1);
// If ctrl is pressed just toggle the component under mouse
// cursor.
if (ctrlDown) {
if (newSelection.contains(component)) {
newSelection.removeAll(findAllGroupedComponents(component));
} else {
newSelection.addAll(findAllGroupedComponents(component));
}
// On the second click, add the component to the project.
IDIYComponent<?> componentSlot = instantiationManager.getComponentSlot();
componentSlot.setControlPoint(scaledPoint, 1);
addComponent(componentSlot, componentTypeSlot);
// Select the new component if it's not locked.
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>();
if (!isComponentLocked(componentSlot)) {
newSelection.add(componentSlot);
}
updateSelection(newSelection);
messageDispatcher.dispatchMessage(EventType.REPAINT);
setNewComponentTypeSlot(null);
}
break;
default:
LOG.error("Unknown creation method: " + componentTypeSlot.getCreationMethod());
}
// Notify the listeners.
if (!oldProject.equals(currentProject)) {
messageDispatcher.dispatchMessage(EventType.PROJECT_MODIFIED, oldProject, cloner
.deepClone(currentProject), "Add " + componentTypeSlot.getName());
projectFileManager.notifyFileChange();
}
} else {
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>(
selectedComponents);
List<IDIYComponent<?>> components = findComponentsAt(scaledPoint);
// If there's nothing under mouse cursor deselect all.
if (components.isEmpty()) {
newSelection.clear();
} else {
IDIYComponent<?> component = components.get(components.size() - 1);
// If ctrl is pressed just toggle the component under mouse
// cursor.
if (ctrlDown) {
if (newSelection.contains(component)) {
newSelection.removeAll(findAllGroupedComponents(component));
} else {
// Otherwise just select that one component.
newSelection.clear();
newSelection.addAll(findAllGroupedComponents(component));
}
}
updateSelection(newSelection);
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
// selectedComponents);
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
// calculateSelectionDimension());
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
}
}
@Override
public void editSelection() {
List<PropertyWrapper> properties = getMutualSelectionProperties();
if (properties != null && !properties.isEmpty()) {
Set<PropertyWrapper> defaultedProperties = new HashSet<PropertyWrapper>();
boolean edited = view.editProperties(properties, defaultedProperties);
if (edited) {
try {
applyPropertiesToSelection(properties);
} catch (Exception e1) {
view.showMessage(
"Error occured while editing selection. Check the log for details.",
"Error", JOptionPane.ERROR_MESSAGE);
LOG.error("Error applying properties", e1);
}
// Save default values.
for (PropertyWrapper property : defaultedProperties) {
if (property.getValue() != null) {
setSelectionDefaultPropertyValue(property.getName(), property.getValue());
}
} else {
// Otherwise just select that one component.
newSelection.clear();
newSelection.addAll(findAllGroupedComponents(component));
}
}
updateSelection(newSelection);
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
// selectedComponents);
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
// calculateSelectionDimension());
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
}
@@ -515,7 +444,7 @@ public class Presenter implements IPlugInPort {
Map<IDIYComponent<?>, Set<Integer>> components = new HashMap<IDIYComponent<?>, Set<Integer>>();
Point scaledPoint = scalePoint(point);
if (instantiationManager.getComponentTypeSlot() != null) {
if (ConfigurationManager.getInstance().readBoolean(IPlugInPort.SNAP_TO_GRID_KEY, true)) {
if (snapToGrid) {
CalcUtils.snapPointToGrid(scaledPoint, currentProject.getGridSpacing());
}
boolean refresh = false;
@@ -524,8 +453,7 @@ public class Presenter implements IPlugInPort {
refresh = instantiationManager.updatePointByPoint(scaledPoint);
break;
case SINGLE_CLICK:
refresh = instantiationManager.updateSingleClick(scaledPoint, ConfigurationManager
.getInstance().readBoolean(IPlugInPort.SNAP_TO_GRID_KEY, true),
refresh = instantiationManager.updateSingleClick(scaledPoint, snapToGrid,
currentProject.getGridSpacing());
break;
}
@@ -601,7 +529,7 @@ public class Presenter implements IPlugInPort {
LOG.debug(String.format("dragStarted(%s)", point));
if (instantiationManager.getComponentTypeSlot() != null) {
LOG.debug("Cannot start drag because a new component is being created.");
mouseClicked(point, ctrlDown, shiftDown, altDown, 1);
mouseClicked(point, ctrlDown, shiftDown, altDown);
return;
}
dragInProgress = true;
@@ -651,12 +579,7 @@ public class Presenter implements IPlugInPort {
}
}
// Expand control points to include all stuck components.
boolean sticky = ConfigurationManager.getInstance().readBoolean(
IPlugInPort.STICKY_POINTS_KEY, true);
if (ctrlDown) {
sticky = !sticky;
}
if (sticky) {
if (!ctrlDown) {
includeStuckComponents(controlPointMap);
}
}
@@ -670,7 +593,7 @@ public class Presenter implements IPlugInPort {
*/
private void includeStuckComponents(Map<IDIYComponent<?>, Set<Integer>> controlPointMap) {
int oldSize = controlPointMap.size();
LOG.trace("Expanding selected component map");
LOG.debug("Expanding selected component map");
for (IDIYComponent<?> component : currentProject.getComponents()) {
ComponentType componentType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
@@ -705,7 +628,7 @@ public class Presenter implements IPlugInPort {
}
}
if (componentMatches) {
LOG.trace("Including component: " + component);
LOG.debug("Including component: " + component);
Set<Integer> indices = new HashSet<Integer>();
// For stretchable components just add the
// matching component. Otherwise, add all control
@@ -730,10 +653,10 @@ public class Presenter implements IPlugInPort {
int newSize = controlPointMap.size();
// As long as we're adding new components, do another iteration.
if (newSize > oldSize) {
LOG.trace("Component count changed, trying one more time.");
LOG.debug("Component count changed, trying one more time.");
includeStuckComponents(controlPointMap);
} else {
LOG.trace("Component count didn't change, done with expanding.");
LOG.debug("Component count didn't change, done with expanding.");
}
}
@@ -753,9 +676,8 @@ public class Presenter implements IPlugInPort {
int actualDy = 0;
// For each component, do a simulation of the move to see if any of
// them will overlap or go out of bounds.
int width = (int) currentProject.getWidth().convertToPixels();
int height = (int) currentProject.getHeight().convertToPixels();
// them will
// overlap.
boolean isFirst = true;
for (Map.Entry<IDIYComponent<?>, Set<Integer>> entry : controlPointMap.entrySet()) {
IDIYComponent<?> component = entry.getKey();
@@ -767,26 +689,19 @@ public class Presenter implements IPlugInPort {
if (entry.getValue().contains(index)) {
if (isFirst) {
isFirst = false;
Point testPoint = new Point(controlPoints[index]);
testPoint.translate(dx, dy);
if (ConfigurationManager.getInstance().readBoolean(
IPlugInPort.SNAP_TO_GRID_KEY, true)) {
CalcUtils.snapPointToGrid(testPoint, currentProject
controlPoints[index].translate(dx, dy);
if (snapToGrid) {
CalcUtils.snapPointToGrid(controlPoints[index], currentProject
.getGridSpacing());
}
actualDx = testPoint.x - component.getControlPoint(index).x;
actualDy = testPoint.y - component.getControlPoint(index).y;
actualDx = controlPoints[index].x - component.getControlPoint(index).x;
actualDy = controlPoints[index].y - component.getControlPoint(index).y;
if (actualDx == 0 && actualDy == 0) {
// Nothing to move.
return true;
}
}
controlPoints[index].translate(actualDx, actualDy);
if (controlPoints[index].x < 0 || controlPoints[index].y < 0
|| controlPoints[index].x > width
|| controlPoints[index].y > height) {
// At least one control point went out of bounds.
return true;
} else {
controlPoints[index].translate(actualDx, actualDy);
}
}
// For control points that may overlap, just write null,
@@ -800,7 +715,7 @@ public class Presenter implements IPlugInPort {
for (int j = i + 1; j < controlPoints.length; j++) {
if (controlPoints[i] != null && controlPoints[j] != null
&& controlPoints[i].equals(controlPoints[j])) {
// Control points collision detected, cannot make this move.
LOG.error("Control points collision detected, cannot make this move.");
return true;
}
}
@@ -885,12 +800,12 @@ public class Presenter implements IPlugInPort {
for (IDIYComponent<?> component : components) {
for (int i = 0; i < component.getControlPointCount(); i++) {
Point point = new Point(component.getControlPoint(i));
point.translate((int) currentProject.getGridSpacing().convertToPixels(),
(int) currentProject.getGridSpacing().convertToPixels());
point.translate(currentProject.getGridSpacing().convertToPixels(), currentProject
.getGridSpacing().convertToPixels());
component.setControlPoint(point, i);
}
addComponent(component, ComponentProcessor.getInstance().extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass()), false);
(Class<? extends IDIYComponent<?>>) component.getClass()));
}
messageDispatcher.dispatchMessage(EventType.PROJECT_MODIFIED, oldProject, cloner
.deepClone(currentProject), "Add");
@@ -1006,7 +921,9 @@ public class Presenter implements IPlugInPort {
ComponentType componentBeforeType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) componentBefore.getClass());
Collections.swap(currentProject.getComponents(), index, index - 1);
if (componentType.getZOrder() == componentBeforeType.getZOrder()) {
Collections.swap(currentProject.getComponents(), index, index - 1);
}
}
}
if (!oldProject.equals(currentProject)) {
@@ -1033,7 +950,9 @@ public class Presenter implements IPlugInPort {
ComponentType componentAfterType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) componentAfter.getClass());
Collections.swap(currentProject.getComponents(), index, index + 1);
if (componentType.getZOrder() == componentAfterType.getZOrder()) {
Collections.swap(currentProject.getComponents(), index, index + 1);
}
}
}
if (!oldProject.equals(currentProject)) {
@@ -1044,21 +963,6 @@ public class Presenter implements IPlugInPort {
}
}
@Override
public void refresh() {
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
@Override
public Theme getSelectedTheme() {
return drawingManager.getTheme();
}
@Override
public void setSelectedTheme(Theme theme) {
drawingManager.setTheme(theme);
}
/**
* Updates the selection with the specified {@link ComponentTransferable}.
* Also, updates control point map with all components that are stuck to the
@@ -1076,9 +980,7 @@ public class Presenter implements IPlugInPort {
}
controlPointMap.put(component, indices);
}
if (ConfigurationManager.getInstance().readBoolean(IPlugInPort.STICKY_POINTS_KEY, true)) {
includeStuckComponents(controlPointMap);
}
includeStuckComponents(controlPointMap);
messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED, selectedComponents,
controlPointMap.keySet());
}
@@ -1155,8 +1057,7 @@ public class Presenter implements IPlugInPort {
* @param component
* @param componentType
*/
private void addComponent(IDIYComponent<?> component, ComponentType componentType,
boolean canCreatePads) {
private void addComponent(IDIYComponent<?> component, ComponentType componentType) {
int index = 0;
while (index < currentProject.getComponents().size()
&& componentType.getZOrder() >= ComponentProcessor.getInstance()
@@ -1170,17 +1071,6 @@ public class Presenter implements IPlugInPort {
} else {
currentProject.getComponents().add(component);
}
if (canCreatePads
&& ConfigurationManager.getInstance().readBoolean(IPlugInPort.AUTO_PADS_KEY, false)) {
for (int i = 0; i < component.getControlPointCount(); i++) {
if (component.isControlPointSticky(i)) {
SolderPad pad = new SolderPad();
pad.setControlPoint(component.getControlPoint(i), 0);
addComponent(pad, ComponentProcessor.getInstance().extractComponentTypeFrom(
SolderPad.class), false);
}
}
}
}
@Override
@@ -1194,7 +1084,8 @@ public class Presenter implements IPlugInPort {
}
}
private void applyPropertiesToSelection(List<PropertyWrapper> properties) {
@Override
public void applyPropertiesToSelection(List<PropertyWrapper> properties) {
LOG.debug(String.format("applyPropertiesToSelection(%s)", properties));
Project oldProject = cloner.deepClone(currentProject);
try {
@@ -23,17 +23,14 @@ 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.RadialElectrolytic;
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.LED;
import org.diylc.components.semiconductors.TransistorTO92;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.measures.Capacitance;
@@ -68,9 +65,6 @@ public class ProjectFileManager {
}
private XStream xStream;
// Legacy deserializer for 3.0.1 through 3.0.7, loads Points referenced in
// pixels.
private XStream xStreamOld;
private String currentFileName = null;
private boolean modified = false;
@@ -81,32 +75,24 @@ public class ProjectFileManager {
super();
this.xStream = new XStream(new DomDriver());
xStream.autodetectAnnotations(true);
xStream.registerConverter(new PointConverter());
this.xStreamOld = new XStream(new DomDriver());
xStreamOld.autodetectAnnotations(true);
this.messageDispatcher = messageDispatcher;
}
public void startNewFile() {
currentFileName = null;
modified = false;
fireFileStatusChanged();
}
public void serializeProjectToFile(Project project, String fileName, boolean isBackup)
throws IOException {
if (!isBackup) {
LOG.info(String.format("saveProjectToFile(%s)", fileName));
}
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();
if (!isBackup) {
this.currentFileName = fileName;
this.modified = false;
fireFileStatusChanged();
}
this.currentFileName = fileName;
this.modified = false;
fireFileStatusChanged();
}
public Project deserializeProjectFromFile(String fileName, List<String> warnings)
@@ -172,8 +158,8 @@ public class ProjectFileManager {
int height = Integer.parseInt(root.getAttribute("Height")) + 1;
int boardWidth = (int) (width * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue());
int boardHeight = (int) (height * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue());
int projectWidth = (int) project.getWidth().convertToPixels();
int projectHeight = (int) project.getHeight().convertToPixels();
int projectWidth = project.getWidth().convertToPixels();
int projectHeight = project.getHeight().convertToPixels();
int x = (projectWidth - boardWidth) / 2;
int y = (projectHeight - boardHeight) / 2;
AbstractBoard board;
@@ -189,11 +175,11 @@ public class ProjectFileManager {
throw new IllegalArgumentException("Unrecognized board type: " + type);
}
board.setName("Main board");
Point referencePoint = new Point(CalcUtils.roundToGrid(x, V1_GRID_SPACING), CalcUtils
.roundToGrid(y, V1_GRID_SPACING));
Point referencePoint = new Point(roundToGrid(x, V1_GRID_SPACING), roundToGrid(y,
V1_GRID_SPACING));
board.setControlPoint(referencePoint, 0);
board.setControlPoint(new Point(CalcUtils.roundToGrid(x + boardWidth, V1_GRID_SPACING),
CalcUtils.roundToGrid(y + boardHeight, V1_GRID_SPACING)), 1);
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();
@@ -265,16 +251,6 @@ public class ProjectFileManager {
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();
@@ -284,8 +260,8 @@ public class ProjectFileManager {
} 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.setWidth(new Size(6d, SizeUnit.mm));
resistor.setHeight(new Size(2d, SizeUnit.mm));
resistor.setControlPoint(point1, 0);
resistor.setControlPoint(point2, 1);
component = resistor;
@@ -298,14 +274,14 @@ public class ProjectFileManager {
} 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.setWidth(new Size(6d, SizeUnit.mm));
capacitor.setHeight(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("electrolyte")) {
LOG.debug("Recognized " + nodeName);
RadialElectrolytic capacitor = new RadialElectrolytic();
ElectrolyticRadial capacitor = new ElectrolyticRadial();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
@@ -314,13 +290,13 @@ public class ProjectFileManager {
}
String sizeAttr = node.getAttributes().getNamedItem("Size").getNodeValue();
if (sizeAttr.equalsIgnoreCase("small")) {
capacitor.setLength(new Size(3.5d, SizeUnit.mm));
capacitor.setWidth(new Size(3d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("medium")) {
capacitor.setLength(new Size(5d, SizeUnit.mm));
capacitor.setWidth(new Size(5d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("large")) {
capacitor.setLength(new Size(7d, SizeUnit.mm));
capacitor.setWidth(new Size(7d, SizeUnit.mm));
} else {
capacitor.setLength(new Size(4d, SizeUnit.mm));
capacitor.setWidth(new Size(4d, SizeUnit.mm));
}
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
@@ -334,43 +310,11 @@ public class ProjectFileManager {
} 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.setWidth(new Size(6d, SizeUnit.mm));
capacitor.setHeight(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("led")) {
LOG.debug("Recognized " + nodeName);
LED led = new LED();
led.setName(nameAttr);
led.setValue(valueAttr);
led.setBodyColor(Color.red);
led.setBorderColor(Color.red.darker());
led.setLength(new Size(3d, SizeUnit.mm));
led.setControlPoint(point1, 0);
led.setControlPoint(point2, 1);
component = led;
} else if (nodeName.equalsIgnoreCase("transistor")) {
LOG.debug("Recognized " + nodeName);
TransistorTO92 transistor = new TransistorTO92();
transistor.setName(nameAttr);
try {
transistor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
transistor.setControlPoint(point1, 0);
if (point1.y > point2.y) {
transistor.setOrientation(Orientation._180);
} else if (point1.y < point2.y) {
transistor.setOrientation(Orientation.DEFAULT);
} else if (point1.x < point2.x) {
transistor.setOrientation(Orientation._270);
} else if (point1.x > point2.x) {
transistor.setOrientation(Orientation._90);
}
// capacitor.setControlPoint(point2, 1);
component = transistor;
} else if (nodeName.equalsIgnoreCase("ic")) {
LOG.debug("Recognized " + nodeName);
DIL_IC ic = new DIL_IC();
@@ -442,15 +386,13 @@ public class ProjectFileManager {
private Project parseV3File(String fileName) throws IOException {
Project project;
FileInputStream fis = new FileInputStream(fileName);
try {
project = (Project) xStream.fromXML(fis);
} catch (Exception e) {
LOG.warn("Could not open with the new xStream, trying the old one");
fis.close();
fis = new FileInputStream(fileName);
project = (Project) xStreamOld.fromXML(fis);
}
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);
}
}
+24 -85
View File
@@ -16,8 +16,6 @@ import org.diylc.common.IPlugInPort;
import org.diylc.common.ITask;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IView;
import org.diylc.core.Theme;
import org.diylc.images.IconLoader;
import org.diylc.swing.gui.DialogFactory;
import org.diylc.swing.gui.editor.PropertyEditorDialog;
@@ -30,7 +28,6 @@ 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.diyfever.gui.miscutils.ConfigurationManager;
import com.rits.cloning.Cloner;
public class ActionFactory {
@@ -127,26 +124,15 @@ public class ActionFactory {
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);
}
// Config actions.
public ConfigAction createConfigAction(IPlugInPort plugInPort, String title, String configKey,
boolean defaultValue) {
return new ConfigAction(plugInPort, title, configKey, defaultValue);
}
public ThemeAction createThemeAction(IPlugInPort plugInPort, Theme theme) {
return new ThemeAction(plugInPort, theme);
}
// File menu actions.
public static class NewAction extends AbstractAction {
@@ -159,8 +145,6 @@ public class ActionFactory {
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());
}
@@ -200,8 +184,6 @@ public class ActionFactory {
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());
}
@@ -250,8 +232,6 @@ public class ActionFactory {
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());
}
@@ -268,7 +248,7 @@ public class ActionFactory {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + file.getAbsolutePath());
plugInPort.saveProjectToFile(file.getAbsolutePath(), false);
plugInPort.saveProjectToFile(file.getAbsolutePath());
return null;
}
@@ -289,7 +269,7 @@ public class ActionFactory {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + plugInPort.getCurrentFileName());
plugInPort.saveProjectToFile(plugInPort.getCurrentFileName(), false);
plugInPort.saveProjectToFile(plugInPort.getCurrentFileName());
return null;
}
@@ -319,8 +299,6 @@ public class ActionFactory {
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());
}
@@ -336,7 +314,7 @@ public class ActionFactory {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + file.getAbsolutePath());
plugInPort.saveProjectToFile(file.getAbsolutePath(), false);
plugInPort.saveProjectToFile(file.getAbsolutePath());
return null;
}
@@ -479,8 +457,6 @@ public class ActionFactory {
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());
}
@@ -681,6 +657,8 @@ public class ActionFactory {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Edit Project");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.DocumentEdit.getIcon());
}
@@ -727,7 +705,19 @@ public class ActionFactory {
LOG.info("Nothing to edit");
return;
}
plugInPort.editSelection();
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());
}
}
}
}
@@ -751,7 +741,7 @@ public class ActionFactory {
plugInPort.deleteSelectedComponents();
}
}
public static class SendToBackAction extends AbstractAction {
private static final long serialVersionUID = 1L;
@@ -761,7 +751,7 @@ public class ActionFactory {
public SendToBackAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Send Backward");
putValue(AbstractAction.NAME, "Send to Back");
putValue(AbstractAction.SMALL_ICON, IconLoader.Back.getIcon());
}
@@ -771,7 +761,7 @@ public class ActionFactory {
plugInPort.sendSelectionToBack();
}
}
public static class BringToFrontAction extends AbstractAction {
private static final long serialVersionUID = 1L;
@@ -781,7 +771,7 @@ public class ActionFactory {
public BringToFrontAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Bring Forward");
putValue(AbstractAction.NAME, "Bring to Front");
putValue(AbstractAction.SMALL_ICON, IconLoader.Front.getIcon());
}
@@ -791,55 +781,4 @@ public class ActionFactory {
plugInPort.bringSelectionToFront();
}
}
public static class ConfigAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private String configKey;
public ConfigAction(IPlugInPort plugInPort, String title, String configKey,
boolean defaultValue) {
super();
this.plugInPort = plugInPort;
this.configKey = configKey;
putValue(AbstractAction.NAME, title);
putValue(IView.CHECK_BOX_MENU_ITEM, true);
putValue(AbstractAction.SELECTED_KEY, ConfigurationManager.getInstance().readBoolean(
configKey, defaultValue));
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info(getValue(AbstractAction.NAME) + " triggered");
ConfigurationManager.getInstance().writeValue(configKey,
getValue(AbstractAction.SELECTED_KEY));
plugInPort.refresh();
}
}
public static class ThemeAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private Theme theme;
public ThemeAction(IPlugInPort plugInPort, Theme theme) {
super();
this.plugInPort = plugInPort;
this.theme = theme;
putValue(AbstractAction.NAME, theme.getName());
putValue(IView.RADIO_BUTTON_GROUP_KEY, "theme");
putValue(AbstractAction.SELECTED_KEY, plugInPort.getSelectedTheme().getName().equals(
theme.getName()));
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info(getValue(AbstractAction.NAME) + " triggered");
plugInPort.setSelectedTheme(theme);
}
}
}
+3 -47
View File
@@ -11,13 +11,11 @@ import java.awt.event.WindowEvent;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
@@ -26,7 +24,6 @@ import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.Timer;
@@ -37,15 +34,11 @@ import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.common.ITask;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IView;
import org.diylc.images.IconLoader;
import org.diylc.presenter.Presenter;
import org.diylc.swing.ISwingUI;
import org.diylc.swing.gui.editor.PropertyEditorDialog;
import org.diylc.swing.plugins.autosave.AutoSavePlugin;
import org.diylc.swing.plugins.canvas.CanvasPlugin;
import org.diylc.swing.plugins.config.ConfigPlugin;
import org.diylc.swing.plugins.edit.EditMenuPlugin;
import org.diylc.swing.plugins.file.FileMenuPlugin;
import org.diylc.swing.plugins.help.HelpMenuPlugin;
@@ -53,9 +46,6 @@ import org.diylc.swing.plugins.layers.LayersMenuPlugin;
import org.diylc.swing.plugins.statusbar.StatusBar;
import org.diylc.swing.plugins.toolbox.ToolBox;
import com.diyfever.gui.ButtonDialog;
import com.diyfever.gui.miscutils.ConfigurationManager;
public class MainFrame extends JFrame implements ISwingUI {
private static final Logger LOG = Logger.getLogger(MainFrame.class);
@@ -72,7 +62,6 @@ public class MainFrame extends JFrame implements ISwingUI {
private JMenuBar mainMenuBar;
private Map<String, JMenu> menuMap;
private Map<String, ButtonGroup> buttonGroupMap;
private CanvasPlugin canvasPlugin;
@@ -82,7 +71,6 @@ public class MainFrame extends JFrame implements ISwingUI {
setPreferredSize(new Dimension(800, 600));
createBasePanels();
menuMap = new HashMap<String, JMenu>();
buttonGroupMap = new HashMap<String, ButtonGroup>();
setIconImages(Arrays.asList(IconLoader.IconSmall.getImage(), IconLoader.IconMedium
.getImage(), IconLoader.IconLarge.getImage()));
DialogFactory.getInstance().initialize(this);
@@ -92,7 +80,6 @@ public class MainFrame extends JFrame implements ISwingUI {
presenter.installPlugin(new ToolBox(this));
presenter.installPlugin(new FileMenuPlugin(this));
presenter.installPlugin(new EditMenuPlugin(this));
presenter.installPlugin(new ConfigPlugin(this));
presenter.installPlugin(new LayersMenuPlugin(this));
// presenter.installPlugin(new OnlineManager());
presenter.installPlugin(new HelpMenuPlugin(this));
@@ -101,7 +88,6 @@ public class MainFrame extends JFrame implements ISwingUI {
canvasPlugin = new CanvasPlugin(this);
presenter.installPlugin(canvasPlugin);
presenter.installPlugin(new FramePlugin());
presenter.installPlugin(new AutoSavePlugin(this));
presenter.createNewProject();
@@ -110,8 +96,6 @@ public class MainFrame extends JFrame implements ISwingUI {
@Override
public void windowClosed(WindowEvent e) {
if (presenter.allowFileAction()) {
ConfigurationManager.getInstance().writeValue(IPlugInPort.ABNORMAL_EXIT_KEY,
false);
dispose();
presenter.dispose();
System.exit(0);
@@ -121,8 +105,6 @@ public class MainFrame extends JFrame implements ISwingUI {
@Override
public void windowClosing(WindowEvent e) {
if (presenter.allowFileAction()) {
ConfigurationManager.getInstance().writeValue(IPlugInPort.ABNORMAL_EXIT_KEY,
false);
dispose();
presenter.dispose();
System.exit(0);
@@ -134,10 +116,6 @@ public class MainFrame extends JFrame implements ISwingUI {
// getGlassPane().setVisible(true);
}
public Presenter getPresenter() {
return presenter;
}
@Override
public void setVisible(boolean b) {
super.setVisible(b);
@@ -209,16 +187,6 @@ public class MainFrame extends JFrame implements ISwingUI {
return JOptionPane.showConfirmDialog(this, message, title, optionType, messageType);
}
@Override
public boolean editProperties(List<PropertyWrapper> properties,
Set<PropertyWrapper> defaultedProperties) {
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Selection");
editor.setVisible(true);
defaultedProperties.addAll(editor.getDefaultedProperties());
return ButtonDialog.OK.equals(editor.getSelectedButtonCaption());
}
private JMenu findOrCreateMenu(String menuName) {
JMenu menu;
if (menuMap.containsKey(menuName)) {
@@ -265,21 +233,9 @@ public class MainFrame extends JFrame implements ISwingUI {
if (action == null) {
menu.addSeparator();
} else {
Boolean isCheckBox = (Boolean) action.getValue(IView.CHECK_BOX_MENU_ITEM);
String groupName = (String) action.getValue(IView.RADIO_BUTTON_GROUP_KEY);
Boolean isCheckBox = (Boolean) action.getValue(IPlugInPort.CHECK_BOX_MENU_ITEM);
if (isCheckBox != null && isCheckBox) {
menu.add(new JCheckBoxMenuItem(action));
} else if (groupName != null) {
ButtonGroup group;
if (buttonGroupMap.containsKey(groupName)) {
group = buttonGroupMap.get(groupName);
} else {
group = new ButtonGroup();
buttonGroupMap.put(groupName, group);
}
JRadioButtonMenuItem item = new JRadioButtonMenuItem(action);
group.add(item);
menu.add(item);
} else {
menu.add(action);
}
@@ -343,7 +299,7 @@ public class MainFrame extends JFrame implements ISwingUI {
fileName = "Untitled";
}
String modified = (Boolean) params[1] ? " (modified)" : "";
setTitle(String.format("DIYLC %s beta - %s %s", plugInPort
setTitle(String.format("DIYLC %s alpha - %s %s", plugInPort
.getCurrentVersionNumber(), fileName, modified));
}
}
@@ -1,285 +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 java.util.Set;
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.common.PropertyWrapper;
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);
}
@Override
public boolean editProperties(List<PropertyWrapper> properties, Set<PropertyWrapper> defaultedProperties) {
return false;
}
});
// 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());
}
});
}
}
@@ -2,7 +2,6 @@ package org.diylc.swing.gui.editor;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
@@ -38,22 +37,8 @@ public class FieldEditorFactory {
}
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;
}
if (Font.class.isAssignableFrom(property.getType())) {
FontEditor editor = new FontEditor(property);
return editor;
}
if (Integer.class.isAssignableFrom(property.getType())
|| int.class.isAssignableFrom(property.getType())) {
IntEditor editor = new IntEditor(property);
return editor;
ByteEditor byteEditor = new ByteEditor(property);
return byteEditor;
}
LOG.error("Unrecognized parameter type: " + property.getType().getName());
return new JLabel("Unrecognized");
@@ -1,33 +1,51 @@
package org.diylc.swing.gui.editor;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
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;
import com.diyfever.gui.FontChooserComboBox;
public class FontEditor extends FontChooserComboBox {
public class FontEditor extends JLabel {
private static final long serialVersionUID = 1L;
private final PropertyWrapper property;
public FontEditor(PropertyWrapper property) {
this.property = property;
setSelectedItem(((Font) property.getValue()).getName());
addItemListener(new ItemListener() {
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 itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
Font oldFont = (Font) FontEditor.this.property.getValue();
Font newFont = new Font(getSelectedItem().toString(), oldFont.getStyle(),
oldFont.getSize());
FontEditor.this.property.setValue(newFont);
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,26 +0,0 @@
package org.diylc.swing.gui.editor;
import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.diylc.common.PropertyWrapper;
import com.diyfever.gui.DoubleTextField;
public class IntEditor extends DoubleTextField {
private static final long serialVersionUID = 1L;
public IntEditor(final PropertyWrapper property) {
setLayout(new BorderLayout());
setValue((double) (Integer) property.getValue());
addPropertyChangeListener(DoubleTextField.VALUE_PROPERTY, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
property.setValue(((Double) evt.getNewValue()).intValue());
}
});
}
}
@@ -18,12 +18,10 @@ import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.apache.log4j.Logger;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.ValidationException;
import com.diyfever.gui.ButtonDialog;
@@ -67,23 +65,6 @@ public class PropertyEditorDialog extends ButtonDialog {
// setLocationRelativeTo(owner);
}
@Override
protected boolean validateInput(String button) {
if (button.equals(ButtonDialog.OK)) {
for (PropertyWrapper property : properties) {
try {
property.getValidator().validate(property.getValue());
} catch (ValidationException ve) {
JOptionPane.showMessageDialog(PropertyEditorDialog.this, "Input error for \""
+ property.getName() + "\": " + ve.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
return true;
}
private JPanel createEditorFields() {
JPanel editorPanel = new JPanel(new GridBagLayout());
editorPanel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
@@ -1,73 +0,0 @@
package org.diylc.swing.plugins.autosave;
import java.io.File;
import java.util.EnumSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.SwingUtilities;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IView;
import com.diyfever.gui.miscutils.ConfigurationManager;
public class AutoSavePlugin implements IPlugIn {
private static final String AUTO_SAVE_FILE_NAME = "autoSave.diy";
private ExecutorService executor;
private IPlugInPort plugInPort;
private IView view;
public AutoSavePlugin(IView view) {
this.view = view;
executor = Executors.newSingleThreadExecutor();
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
boolean wasAbnormal = ConfigurationManager.getInstance().readBoolean(
IPlugInPort.ABNORMAL_EXIT_KEY, false);
if (wasAbnormal && new File(AUTO_SAVE_FILE_NAME).exists()) {
int decision = view
.showConfirmDialog(
"It appears that aplication was not closed normally in the previous session. Do you want to open the last auto-saved file?",
"Auto-Save", IView.YES_NO_OPTION, IView.QUESTION_MESSAGE);
if (decision == IView.YES_OPTION) {
AutoSavePlugin.this.plugInPort.loadProjectFromFile(AUTO_SAVE_FILE_NAME);
}
}
// Set abnormal flag to true, GUI side of the app must flip to
// false when app closes regularly.
ConfigurationManager.getInstance().writeValue(IPlugInPort.ABNORMAL_EXIT_KEY, true);
}
});
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.PROJECT_MODIFIED);
}
@Override
public void processMessage(EventType eventType, Object... params) {
if (eventType == EventType.PROJECT_MODIFIED) {
executor.execute(new Runnable() {
@Override
public void run() {
plugInPort.saveProjectToFile(AUTO_SAVE_FILE_NAME, true);
}
});
}
}
}
@@ -21,6 +21,7 @@ import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.VolatileImage;
import java.util.EnumSet;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
@@ -28,8 +29,11 @@ import javax.swing.KeyStroke;
import org.diylc.common.DrawOption;
import org.diylc.common.IPlugInPort;
import org.diylc.common.PropertyWrapper;
import org.diylc.swing.gui.DialogFactory;
import org.diylc.swing.gui.editor.PropertyEditorDialog;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.diyfever.gui.ButtonDialog;
/**
* GUI class used to draw onto.
@@ -45,11 +49,9 @@ class CanvasPanel extends JComponent implements Autoscroll {
private Image bufferImage;
private GraphicsConfiguration screenGraphicsConfiguration;
private static boolean USE_HARDWARE_ACCELLERATION = false;
private static boolean USE_HARDWARE_ACCELLERATION = true;
static final EnumSet<DrawOption> DRAW_OPTIONS = EnumSet.of(DrawOption.GRID,
DrawOption.SELECTION, DrawOption.ZOOM, DrawOption.CONTROL_POINTS);
static final EnumSet<DrawOption> DRAW_OPTIONS_ANTI_ALIASING = EnumSet.of(DrawOption.GRID,
DrawOption.SELECTION, DrawOption.ZOOM, DrawOption.ANTIALIASING,
DrawOption.CONTROL_POINTS);
@@ -73,8 +75,7 @@ class CanvasPanel extends JComponent implements Autoscroll {
private void initializeDnD() {
// Initialize drag source recognizer.
DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE | DnDConstants.ACTION_LINK,
new CanvasGestureListener(plugInPort));
DnDConstants.ACTION_COPY_OR_MOVE | DnDConstants.ACTION_LINK, new CanvasGestureListener(plugInPort));
// Initialize drop target.
new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,
new CanvasTargetListener(plugInPort), true);
@@ -102,6 +103,8 @@ class CanvasPanel extends JComponent implements Autoscroll {
} else {
bufferImage = createImage(getWidth(), getHeight());
}
Graphics2D g2d = (Graphics2D) bufferImage.getGraphics();
plugInPort.draw(g2d, DRAW_OPTIONS, null);
}
@Override
@@ -111,12 +114,10 @@ class CanvasPanel extends JComponent implements Autoscroll {
}
if (bufferImage == null) {
createBufferImage();
} else {
Graphics2D g2d = (Graphics2D) bufferImage.getGraphics();
plugInPort.draw(g2d, DRAW_OPTIONS, null);
}
Graphics2D g2d = (Graphics2D) bufferImage.getGraphics();
g2d.setClip(getVisibleRect());
plugInPort.draw(g2d, ConfigurationManager.getInstance().readBoolean(
IPlugInPort.ANTI_ALIASING_KEY, true) ? DRAW_OPTIONS_ANTI_ALIASING : DRAW_OPTIONS,
null);
if (USE_HARDWARE_ACCELLERATION) {
VolatileImage volatileImage = (VolatileImage) bufferImage;
do {
@@ -124,11 +125,10 @@ class CanvasPanel extends JComponent implements Autoscroll {
if (volatileImage.contentsLost()) {
createBufferImage();
}
// int validation =
// volatileImage.validate(screenGraphicsConfiguration);
// if (validation == VolatileImage.IMAGE_INCOMPATIBLE) {
// createBufferImage();
// }
// int validation = volatileImage.validate(screenGraphicsConfiguration);
// if (validation == VolatileImage.IMAGE_INCOMPATIBLE) {
// createBufferImage();
// }
g.drawImage(bufferImage, 0, 0, this);
} catch (NullPointerException e) {
createBufferImage();
@@ -136,7 +136,7 @@ class CanvasPanel extends JComponent implements Autoscroll {
} while (volatileImage == null || volatileImage.contentsLost());
} else {
g.drawImage(bufferImage, 0, 0, this);
// bufferImage.flush();
bufferImage.flush();
}
}
@@ -154,18 +154,18 @@ class CanvasPanel extends JComponent implements Autoscroll {
invalidate();
}
});
// addKeyListener(new KeyAdapter() {
//
// @Override
// public void keyPressed(KeyEvent e) {
// if (e.getKeyCode() == KeyEvent.VK_DELETE) {
// plugInPort.deleteSelectedComponents();
// }
// // plugInPort.mouseMoved(getMousePosition(), e.isControlDown(),
// // e.isShiftDown(), e
// // .isAltDown());
// }
// });
// addKeyListener(new KeyAdapter() {
//
// @Override
// public void keyPressed(KeyEvent e) {
// if (e.getKeyCode() == KeyEvent.VK_DELETE) {
// plugInPort.deleteSelectedComponents();
// }
// // plugInPort.mouseMoved(getMousePosition(), e.isControlDown(),
// // e.isShiftDown(), e
// // .isAltDown());
// }
// });
addMouseMotionListener(new MouseAdapter() {
@Override
@@ -180,8 +180,53 @@ class CanvasPanel extends JComponent implements Autoscroll {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
plugInPort.mouseClicked(e.getPoint(), e.isControlDown(), e.isShiftDown(), e
.isAltDown(), e.getClickCount());
if (e.getClickCount() == 2) {
List<PropertyWrapper> properties = plugInPort
.getMutualSelectionProperties();
if (properties == null || properties.isEmpty()) {
// 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());
// }
// }
// }
} else {
PropertyEditorDialog editor = DialogFactory.getInstance()
.createPropertyEditorDialog(properties, "Edit Selection");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
try {
plugInPort.applyPropertiesToSelection(properties);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setSelectionDefaultPropertyValue(property.getName(),
property.getValue());
}
}
}
}
} else {
plugInPort.mouseClicked(e.getPoint(), e.isControlDown(), e.isShiftDown(), e
.isAltDown());
}
}
}
});
@@ -29,7 +29,6 @@ import org.diylc.swing.plugins.edit.ComponentTransferable;
import org.diylc.swing.plugins.file.ProjectDrawingProvider;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.diyfever.gui.miscutils.IConfigListener;
import com.diyfever.gui.ruler.IRulerListener;
import com.diyfever.gui.ruler.RulerScrollPane;
@@ -37,6 +36,8 @@ 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;
@@ -56,8 +57,6 @@ public class CanvasPlugin implements IPlugIn, ClipboardOwner {
private Clipboard clipboard;
private double zoomLevel = 1;
public CanvasPlugin(ISwingUI swingUI) {
this.swingUI = swingUI;
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
@@ -111,20 +110,11 @@ public class CanvasPlugin implements IPlugIn, ClipboardOwner {
private RulerScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new RulerScrollPane(getCanvasPanel(), new ProjectDrawingProvider(
plugInPort, true, false), new Size(1d, SizeUnit.cm).convertToPixels(),
new Size(1d, SizeUnit.in).convertToPixels());
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(
IPlugInPort.WHEEL_ZOOM_KEY, false);
ConfigurationManager.getInstance().addConfigListener(IPlugInPort.WHEEL_ZOOM_KEY,
new IConfigListener() {
@Override
public void valueChanged(String key, Object value) {
scrollPane.setWheelScrollingEnabled(!(Boolean) value);
}
});
boolean wheelZoom = ConfigurationManager.getInstance().readBoolean(WHEEL_ZOOM, false);
scrollPane.setMetric(metric);
scrollPane.setWheelScrollingEnabled(!wheelZoom);
scrollPane.addUnitListener(new IRulerListener() {
@@ -134,32 +124,30 @@ public class CanvasPlugin implements IPlugIn, ClipboardOwner {
plugInPort.setMetric(isMetric);
}
});
scrollPane.addMouseWheelListener(new MouseWheelListener() {
if (wheelZoom) {
scrollPane.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
boolean wheelZoom = ConfigurationManager.getInstance().readBoolean(
IPlugInPort.WHEEL_ZOOM_KEY, false);
if (!wheelZoom) {
return;
}
double d = plugInPort.getZoomLevel();
Double[] availableZoomLevels = plugInPort.getAvailableZoomLevels();
if (e.getWheelRotation() > 0) {
int i = availableZoomLevels.length - 1;
while (i > 0 && availableZoomLevels[i] >= d) {
i--;
@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]);
}
plugInPort.setZoomLevel(availableZoomLevels[i]);
} else {
int i = 0;
while (i < availableZoomLevels.length - 1 && availableZoomLevels[i] <= d) {
i++;
}
plugInPort.setZoomLevel(availableZoomLevels[i]);
}
}
});
});
}
}
return scrollPane;
}
@@ -213,8 +201,7 @@ public class CanvasPlugin implements IPlugIn, ClipboardOwner {
public ActionFactory.DeleteSelectionAction getDeleteSelectionAction() {
if (deleteSelectionAction == null) {
deleteSelectionAction = ActionFactory.getInstance().createDeleteSelectionAction(
plugInPort);
deleteSelectionAction = ActionFactory.getInstance().createDeleteSelectionAction(plugInPort);
}
return deleteSelectionAction;
}
@@ -232,14 +219,14 @@ public class CanvasPlugin implements IPlugIn, ClipboardOwner {
}
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);
@@ -270,19 +257,11 @@ public class CanvasPlugin implements IPlugIn, ClipboardOwner {
canvasPanel.scrollRectToVisible(visibleRect);
canvasPanel.revalidate();
}
// canvasPanel.validate();
// canvasPanel.repaint();
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();
@@ -25,7 +25,7 @@ class CanvasSourceListener implements DragSourceListener {
@Override
public void dragDropEnd(DragSourceDropEvent dsde) {
presenter.dragEnded(null);
// presenter.dragEnded(null);
}
@Override
@@ -1,88 +0,0 @@
package org.diylc.swing.plugins.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.EnumSet;
import org.apache.log4j.Logger;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.Theme;
import org.diylc.images.IconLoader;
import org.diylc.swing.ActionFactory;
import org.diylc.swing.ISwingUI;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* Controls configuration menu.
*
* @author Branislav Stojkovic
*/
public class ConfigPlugin implements IPlugIn {
private static final Logger LOG = Logger.getLogger(ConfigPlugin.class);
private static final String CONFIG_MENU = "Config";
private static final String THEME_MENU = "Theme";
private ISwingUI swingUI;
public ConfigPlugin(ISwingUI swingUI) {
super();
this.swingUI = swingUI;
}
@Override
public void connect(IPlugInPort plugInPort) {
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Anti-Aliasing", IPlugInPort.ANTI_ALIASING_KEY, true), CONFIG_MENU);
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Auto-Create Pads", IPlugInPort.AUTO_PADS_KEY, false), CONFIG_MENU);
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Auto-Edit Mode", IPlugInPort.AUTO_EDIT_KEY, false), CONFIG_MENU);
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Continuous Creation", IPlugInPort.CONTINUOUS_CREATION_KEY, false), CONFIG_MENU);
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Export Grid", IPlugInPort.EXPORT_GRID_KEY, false), CONFIG_MENU);
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Hi-Quality Rendering", IPlugInPort.HI_QUALITY_RENDER_KEY, false), CONFIG_MENU);
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Mouse Wheel Zoom", IPlugInPort.WHEEL_ZOOM_KEY, false), CONFIG_MENU);
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Snap to Grid", IPlugInPort.SNAP_TO_GRID_KEY, true), CONFIG_MENU);
swingUI.injectMenuAction(ActionFactory.getInstance().createConfigAction(plugInPort,
"Sticky Points", IPlugInPort.STICKY_POINTS_KEY, true), CONFIG_MENU);
File themeDir = new File("themes");
if (themeDir.exists()) {
XStream xStream = new XStream(new DomDriver());
swingUI.injectSubmenu(THEME_MENU, IconLoader.Pens.getIcon(), CONFIG_MENU);
for (File file : themeDir.listFiles()) {
if (file.getName().toLowerCase().endsWith(".xml")) {
try {
InputStream in = new FileInputStream(file);
Theme theme = (Theme) xStream.fromXML(in);
LOG.debug("Found theme: " + theme.getName());
swingUI.injectMenuAction(ActionFactory.getInstance().createThemeAction(
plugInPort, theme), THEME_MENU);
} catch (Exception e) {
LOG.error("Could not load theme file " + file.getName(), e);
}
}
}
}
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.noneOf(EventType.class);
}
@Override
public void processMessage(EventType eventType, Object... params) {
}
}
@@ -31,7 +31,7 @@ public class FileMenuPlugin implements IPlugIn {
@Override
public void connect(IPlugInPort plugInPort) {
this.drawingProvider = new ProjectDrawingProvider(plugInPort, false, true);
this.drawingProvider = new ProjectDrawingProvider(plugInPort, false);
this.traceMaskDrawingProvider = new TraceMaskDrawingProvider(plugInPort);
ActionFactory actionFactory = ActionFactory.getInstance();
@@ -9,7 +9,6 @@ import org.diylc.common.DrawOption;
import org.diylc.common.IPlugInPort;
import com.diyfever.gui.IDrawingProvider;
import com.diyfever.gui.miscutils.ConfigurationManager;
/**
* {@link IDrawingProvider} implementation that uses {@link IPlugInPort} to draw
@@ -21,14 +20,11 @@ public class ProjectDrawingProvider implements IDrawingProvider {
private IPlugInPort plugInPort;
private boolean useZoom;
private boolean showGridWhenNeeded;
public ProjectDrawingProvider(IPlugInPort plugInPort, boolean useZoom,
boolean showGridWhenNeeded) {
public ProjectDrawingProvider(IPlugInPort plugInPort, boolean useZoom) {
super();
this.plugInPort = plugInPort;
this.useZoom = useZoom;
this.showGridWhenNeeded = showGridWhenNeeded;
}
@Override
@@ -37,11 +33,6 @@ public class ProjectDrawingProvider implements IDrawingProvider {
if (useZoom) {
options.add(DrawOption.ZOOM);
}
if (showGridWhenNeeded
&& ConfigurationManager.getInstance().readBoolean(IPlugInPort.EXPORT_GRID_KEY,
false)) {
options.add(DrawOption.GRID);
}
plugInPort.draw((Graphics2D) g, options, null);
}
@@ -10,8 +10,6 @@ import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
@@ -20,7 +18,6 @@ import javax.swing.JPanel;
import org.diylc.common.DrawOption;
import org.diylc.common.IPlugInPort;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IView;
import org.diylc.core.Project;
import org.diylc.presenter.Presenter;
@@ -61,11 +58,6 @@ public class ProjectPreview extends JPanel implements PropertyChangeListener, IF
@Override
public void showMessage(String message, String title, int messageType) {
}
@Override
public boolean editProperties(List<PropertyWrapper> properties, Set<PropertyWrapper> defaultedProperties) {
return false;
}
});
xStream = new XStream(new DomDriver());
@@ -5,9 +5,7 @@ import java.util.EnumSet;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
@@ -16,7 +14,6 @@ import org.diylc.swing.ISwingUI;
import org.diylc.swing.gui.DialogFactory;
import com.diyfever.gui.AboutDialog;
import com.diyfever.gui.LinkLabel;
import com.diyfever.gui.miscutils.Utils;
/**
@@ -110,11 +107,7 @@ public class HelpMenuPlugin implements IPlugIn {
@Override
public void actionPerformed(ActionEvent e) {
try {
Utils.openURL(url);
} catch (Exception e1) {
Logger.getLogger(LinkLabel.class).error("Could not launch default browser", e1);
}
Utils.openURL(url);
}
}
}
@@ -13,7 +13,6 @@ import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IView;
import org.diylc.swing.ISwingUI;
public class LayersMenuPlugin implements IPlugIn {
@@ -37,7 +36,7 @@ public class LayersMenuPlugin implements IPlugIn {
(Boolean) getValue(Action.SELECTED_KEY));
}
};
action.putValue(IView.CHECK_BOX_MENU_ITEM, true);
action.putValue(IPlugInPort.CHECK_BOX_MENU_ITEM, true);
lockActionMap.put(layer, action);
swingUI.injectMenuAction(action, LOCK_LAYERS_TITLE);
}
@@ -66,7 +66,6 @@ public class StatusBar extends JPanel implements IPlugIn {
private List<String> componentNamesUnderCursor;
private List<String> selectedComponentNames;
private List<String> stuckComponentNames;
private String statusMessage;
public StatusBar(ISwingUI swingUI) {
super();
@@ -197,8 +196,7 @@ public class StatusBar extends JPanel implements IPlugIn {
@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);
EventType.AVAILABLE_CTRL_POINTS_CHANGED, EventType.SELECTION_CHANGED);
}
@SuppressWarnings("unchecked")
@@ -249,13 +247,11 @@ public class StatusBar extends JPanel implements IPlugIn {
Collections.sort(componentNamesUnderCursor);
refreshStatusText();
break;
case STATUS_MESSAGE_CHANGED:
statusMessage = (String) params[0];
}
}
private void refreshStatusText() {
String statusText = this.statusMessage;
String statusText = "";
if (componentSlot == null) {
if (componentNamesUnderCursor != null && !componentNamesUnderCursor.isEmpty()) {
String formattedNames = Utils.toCommaString(componentNamesUnderCursor);
@@ -269,6 +265,8 @@ public class StatusBar extends JPanel implements IPlugIn {
builder.append(")");
}
statusText = "<html>Selection: " + builder.toString() + "</html>";
} else {
statusText = "";
}
} else {
switch (componentSlot.getCreationMethod()) {
@@ -279,13 +277,12 @@ public class StatusBar extends JPanel implements IPlugIn {
} 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>";
statusText = "Click on the canvas to set the " + count + " control point of a new "
+ componentSlot.getName() + " or press Esc to cancel";
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>";
statusText = "Click on the canvas to create a new " + componentSlot.getName()
+ " or press Esc to cancel";
break;
}
}
@@ -11,9 +11,9 @@ import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.ScrollPaneConstants;
import org.diylc.common.ComponentType;
import org.diylc.common.IPlugInPort;
@@ -42,13 +42,6 @@ class ComponentTabbedPane extends JTabbedPane {
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) {
@@ -94,13 +87,13 @@ class ComponentTabbedPane extends JTabbedPane {
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 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();
@@ -18,9 +18,6 @@ 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;
@@ -28,20 +25,12 @@ public class ToolBox implements IPlugIn {
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
try {
swingUI.injectGUIComponent(getComponentTabbedPane(), SwingConstants.TOP);
swingUI.injectGUIComponent(new ComponentTabbedPane(plugInPort), 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() {
+1 -1
View File
@@ -7,7 +7,7 @@ import java.awt.Toolkit;
public class Constants {
public static final int PIXELS_PER_INCH = 200;
public static final int PIXELS_PER_INCH = 150;
public static final double PIXEL_SIZE = 1d * PIXELS_PER_INCH
/ Toolkit.getDefaultToolkit().getScreenResolution();
@@ -0,0 +1,657 @@
package org.diylc.utils.dnd;
/* Copyright (c) 2003-2006 Timothy Wall, All Rights Reserved */
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
/**
* Provide a method for consistently augmenting the appearance of a given
* component by painting something on it <i>after</i> the component itself gets
* painted. If not explicitly removed via {@link #dispose}, an instance of this
* object will live as long as its target component.
* <p>
* By default, the decorator matches the location and size of the decorated
* component, but the bounds can be adjusted by overriding
* {@link #getDecorationBounds()}. The {@link #synch()} method should be called
* whenever the bounds returned by {@link #getDecorationBounds()} would change.
* <p>
* The decoration is clipped to the bounds set on the decoration, which does not
* necessarily need to be the same as the decorated component bounds. The
* decoration may extend beyond the decorated component bounds, or it may be
* reduced to a smaller region.
*/
// TODO: should probably do some locking on Component.getTreeLock()
// TODO: synch underlying cursor when decorator covers more than
// one component; the cursor should change if the decoration exceeds the
// component's bounds
public abstract class AbstractComponentDecorator {
public static final Rectangle DEFAULT_BOUNDS = null;
public static final int TOP = 0;
// Disabled for now, since it doesn't work properly
private static final int BOTTOM = -1;
/**
* Account for the difference between the decorator actual origin and the
* logical origin we want to pass to the {@link #paint} method.
*/
private Point originOffset = new Point(0, 0);
private Painter painter;
private JComponent component;
private Container parent;
private Listener listener;
private int layerOffset;
private int position;
private Rectangle bounds;
/** Create a decorator for the given component. */
public AbstractComponentDecorator(JComponent c) {
this(c, 1);
}
/**
* Create a decorator for the given component, indicating the layer offset
* from the target component. Negative values mean the decoration is painted
* <em>before</em> the target component is painted.
*/
public AbstractComponentDecorator(JComponent c, int layerOffset) {
this(c, layerOffset, TOP);
}
/**
* Create a decorator with the given position within its layer. Use
* {@link #TOP} to cover other decorations, or {@link #BOTTOM} to be covered
* by other decorations.
* <p>
* WARNING: BOTTOM doesn't currently work, probably a JLayeredPane bug in
* either the code or documentation.
*
* @see JLayeredPane
*/
public AbstractComponentDecorator(JComponent c, int layerOffset, int position) {
component = c;
this.layerOffset = layerOffset;
this.position = position;
this.bounds = DEFAULT_BOUNDS;
parent = c.getParent();
painter = new Painter();
listener = new Listener();
component.addHierarchyListener(listener);
component.addComponentListener(listener);
component.addPropertyChangeListener(listener);
attach();
}
/**
* Set the text to be displayed when the mouse is over the decoration.
*
* @see JComponent#setToolTipText(String)
*/
public void setToolTipText(String text) {
painter.setToolTipText(text);
}
/**
* Return the currently set default tooltip text.
*
* @see JComponent#setToolTipText
*/
public String getToolTipText() {
return painter.getToolTipText();
}
/**
* Provide for different tool tips depending on the actual location over the
* decoration. Note that if you <em>only</em> override this method, you must
* also invoke {@link #setToolTipText(String)} with a non-<span
* class="javakeyword">null</span> argument.
*
* @see JComponent#getToolTipText(MouseEvent)
*/
public String getToolTipText(MouseEvent e) {
return getToolTipText();
}
/**
* Indicate whether any of the decoration is visible. The decoration may be
* clipped by ancestor scroll panes or by being moved outside if the visible
* region of its parent window.
*/
public boolean isVisible() {
return painter.isVisible();
}
/** Use this to change the visibility of the decoration. */
public void setVisible(boolean visible) {
painter.setVisible(visible);
}
protected void attach() {
Window w = SwingUtilities.getWindowAncestor(component);
if (w instanceof RootPaneContainer) {
JLayeredPane lp = ((RootPaneContainer) w).getLayeredPane();
Component layeredChild = component;
int layer = JLayeredPane.DRAG_LAYER.intValue();
if (this instanceof BackgroundPainter) {
layer = ((BackgroundPainter) this).layer;
painter.setDecoratedLayer(layer);
} else if (layeredChild == lp) {
// Is this the best layer to use?
painter.setDecoratedLayer(layer);
} else {
while (layeredChild.getParent() != lp) {
layeredChild = layeredChild.getParent();
}
int base = lp.getLayer(layeredChild);
// NOTE: JLayeredPane doesn't properly repaint an overlapping
// child when an obscured child calls repaint() if the two
// are in the same layer, so we use the next-higher layer
// instead of simply using a different position within the
// layer.
layer = base + layerOffset;
if (layerOffset < 0) {
BackgroundPainter bp = (BackgroundPainter) lp
.getClientProperty(BackgroundPainter.key(base));
if (bp == null) {
bp = new BackgroundPainter(lp, base);
}
}
painter.setDecoratedLayer(base);
}
lp.add(painter, new Integer(layer), position);
} else {
// Always detach when the target component's window is null
// or is not a suitable container,
// otherwise we might prevent GC of the component
Container parent = painter.getParent();
if (parent != null) {
parent.remove(painter);
}
}
// Track size changes in any viewport parent
if (parent != null) {
parent.removeComponentListener(listener);
}
parent = component.getParent();
if (parent != null) {
parent.addComponentListener(listener);
}
synch();
}
/**
* Ensure the size of the decorator matches the current decoration bounds
* with appropriate clipping to viewports.
*/
protected void synch() {
Container painterParent = painter.getParent();
if (painterParent != null) {
Rectangle decorated = getDecorationBounds();
Rectangle clipRect = clipDecorationBounds(decorated);
Point pt = SwingUtilities
.convertPoint(component, clipRect.x, clipRect.y, painterParent);
if (clipRect.width <= 0 || clipRect.height <= 0) {
setPainterBounds(-1, -1, 0, 0);
setVisible(false);
} else {
setPainterBounds(pt.x, pt.y, clipRect.width, clipRect.height);
setVisible(true);
}
}
painter.repaint();
}
/**
* Adjust the painting offsets and size of the decoration to account for
* ancestor clipping. This might be due to scroll panes or having the
* decoration lie outside the parent layered pane.
*/
protected Rectangle clipDecorationBounds(Rectangle decorated) {
// Amount we have to translate the Graphics context
originOffset.x = decorated.x;
originOffset.y = decorated.y;
// If the the component is obscured (by a viewport or some
// other means), use the painter bounds to clip to the visible
// bounds. Doing may change the actual origin, so adjust our
// origin offset accordingly
Rectangle visible = getClippingRect(component, decorated);
Rectangle clipRect = decorated.intersection(visible);
if (decorated.x < visible.x)
originOffset.x += visible.x - decorated.x;
if (decorated.y < visible.y)
originOffset.y += visible.y - decorated.y;
return clipRect;
}
/**
* Return any clipping rectangle detected above the given component, in the
* coordinate space of the given component. The given rectangle is desired
* to be visible.
*/
private Rectangle getClippingRect(Container component, Rectangle desired) {
Rectangle clip = component instanceof JComponent ? ((JComponent) component)
.getVisibleRect()
: new Rectangle(0, 0, component.getWidth(), component.getHeight());
if (desired.x >= clip.x && desired.y >= clip.y
&& desired.x + desired.width <= clip.x + clip.width
&& desired.y + desired.height <= clip.y + clip.height) {
// desired rect is within the current clip rect
} else if (component.getParent() != null) {
// Only apply the clip if it is actually smaller than the
// component's visible area
if (component != painter.getParent() && clip.x > 0 && clip.y > 0
&& clip.width < component.getWidth() && clip.height < component.getHeight()) {
// Don't alter the original rectangle
desired = new Rectangle(desired);
// Check for clipping further up the hierarchy
desired.x += component.getX();
desired.y += component.getY();
clip = getClippingRect(component.getParent(), desired);
clip.x -= component.getX();
clip.y -= component.getY();
}
}
return clip;
}
/**
* Return the bounds, relative to the decorated component, of the
* decoration. The default covers the entire component. Note that this
* method will be called from the constructor, so be careful when overriding
* and referencing derived class state.
*/
protected Rectangle getDecorationBounds() {
return bounds != DEFAULT_BOUNDS ? bounds : new Rectangle(0, 0, component.getWidth(),
component.getHeight());
}
/**
* Change the bounds of the decoration, relative to the decorated component.
* The special value {@link #DEFAULT_BOUNDS} means the bounds will track the
* component bounds.
*/
public void setDecorationBounds(Rectangle bounds) {
if (bounds == DEFAULT_BOUNDS) {
this.bounds = bounds;
} else {
this.bounds = new Rectangle(bounds);
}
synch();
}
/**
* Change the bounds of the decoration, relative to the decorated component.
*/
public void setDecorationBounds(int x, int y, int w, int h) {
setDecorationBounds(new Rectangle(x, y, w, h));
}
protected void setPainterBounds(int x, int y, int w, int h) {
painter.setLocation(x, y);
painter.setSize(w, h);
repaint();
}
protected JComponent getComponent() {
return component;
}
protected JComponent getPainter() {
return painter;
}
/** Set the cursor to appear anywhere over the decoration bounds. */
public void setCursor(Cursor cursor) {
painter.setCursor(cursor);
}
/** Force a refresh of the underlying component and its decoration. */
public void repaint() {
component.repaint();
painter.repaint();
}
/** Stop decorating. */
public void dispose() {
component.removeHierarchyListener(listener);
component.removeComponentListener(listener);
component.removePropertyChangeListener(listener);
if (parent != null) {
parent.removeComponentListener(listener);
parent = null;
}
Container painterParent = painter.getParent();
if (painterParent != null) {
Rectangle bounds = painter.getBounds();
painterParent.remove(painter);
painterParent.repaint(bounds.x, bounds.y, bounds.width, bounds.height);
}
component.repaint();
component = null;
}
/**
* Define the decoration's appearance. The point (0,0) represents the upper
* left corner of the decorated component. The default clip mask will be the
* extents of the decoration bounds, as indicated by
* {@link #getDecorationBounds()}, which defaults to the decorated component
* bounds.
*/
public abstract void paint(Graphics g);
public String toString() {
return super.toString() + " on " + getComponent();
}
private static Field nComponents;
static {
try {
nComponents = Container.class.getDeclaredField("ncomponents");
nComponents.setAccessible(true);
} catch (Exception e) {
nComponents = null;
}
}
private static boolean useSimpleBackground() {
return nComponents == null;
}
/** Used to hook into the Swing painting architecture. */
private class Painter extends JComponent {
private int base;
private Cursor cursor;
public JComponent getComponent() {
return AbstractComponentDecorator.this.getComponent();
}
public void setDecoratedLayer(int base) {
this.base = base;
}
public int getDecoratedLayer() {
return base;
}
public boolean isBackgroundDecoration() {
return layerOffset < 0;
}
/** Set the cursor to something else. */
public void setCursor(Cursor cursor) {
Cursor oldCursor = getCursor();
// Make sure the cursor actually changed, otherwise
// we get cursor flicker (notably on w32 title bars)
if (oldCursor == null && cursor != null || oldCursor != null
&& !oldCursor.equals(cursor)) {
this.cursor = cursor;
super.setCursor(cursor);
}
}
/**
* Returns the cursor of the decorated component, or the last cursor set
* by {@link #setCursor}.
*/
public Cursor getCursor() {
return cursor != null ? cursor : component.getCursor();
}
/**
* Delegate to the containing decorator to perform the paint.
*/
public void paint(Graphics g) {
if (!component.isShowing())
return;
Graphics g2 = g.create();
g2.translate(-originOffset.x, -originOffset.y);
AbstractComponentDecorator.this.paint(g2);
g2.dispose();
/*
* g = g.create(); g.setClip(null); g.setColor(Color.red);
* g.drawRect(0, 0, getWidth()-1, getHeight()-1);
*/
}
/**
* Provide a decorator-specific tooltip, shown when within the
* decorator's bounds.
*/
public String getToolTipText(MouseEvent e) {
return AbstractComponentDecorator.this.getToolTipText(e);
}
public String toString() {
return "Painter for " + AbstractComponentDecorator.this;
}
}
/**
* Provides a shared background painting mechanism for multiple decorations.
* This ensures that the background is only painted once if more than one
* background decorator is applied.
*/
private static class BackgroundPainter extends AbstractComponentDecorator {
private static String key(int layer) {
return "backgroundPainter for layer " + layer;
}
private String key;
private int layer;
public BackgroundPainter(JLayeredPane p, int layer) {
super(p, 0, TOP);
this.layer = layer;
key = key(layer);
p.putClientProperty(key, this);
}
private int hideChildren(Container c) {
if (c == null)
return 0;
int value = c.getComponentCount();
try {
nComponents.set(c, new Integer(0));
} catch (Exception e) {
return c.getComponentCount();
}
return value;
}
private void restoreChildren(Container c, int count) {
if (c != null) {
try {
nComponents.set(c, new Integer(count));
} catch (Exception e) {
}
}
}
private void paintBackground(Graphics g, Component parent, JComponent jc) {
int x = jc.getX();
int y = jc.getY();
int w = jc.getWidth();
int h = jc.getHeight();
paintBackground(g.create(x, y, w, h), jc);
}
private void paintBackground(Graphics g, JComponent jc) {
if (jc.isOpaque()) {
if (useSimpleBackground()) {
g.setColor(jc.getBackground());
g.fillRect(0, 0, jc.getWidth(), jc.getHeight());
} else {
int count = hideChildren(jc);
boolean db = jc.isDoubleBuffered();
if (db)
jc.setDoubleBuffered(false);
jc.paint(g);
if (db)
jc.setDoubleBuffered(true);
restoreChildren(jc, count);
}
}
Component[] kids = jc.getComponents();
for (int i = 0; i < kids.length; i++) {
if (kids[i] instanceof JComponent) {
paintBackground(g, jc, (JComponent) kids[i]);
}
}
}
private List findOpaque(Component root) {
List list = new ArrayList();
if (root.isOpaque() && root instanceof JComponent) {
list.add(root);
((JComponent) root).setOpaque(false);
}
if (root instanceof Container) {
Component[] kids = ((Container) root).getComponents();
for (int i = 0; i < kids.length; i++) {
list.addAll(findOpaque(kids[i]));
}
}
return list;
}
private List findDoubleBuffered(Component root) {
List list = new ArrayList();
if (root.isDoubleBuffered() && root instanceof JComponent) {
list.add(root);
((JComponent) root).setDoubleBuffered(false);
}
if (root instanceof Container) {
Component[] kids = ((Container) root).getComponents();
for (int i = 0; i < kids.length; i++) {
list.addAll(findDoubleBuffered(kids[i]));
}
}
return list;
}
private void paintForeground(Graphics g, JComponent jc) {
List opaque = findOpaque(jc);
List db = findDoubleBuffered(jc);
jc.paint(g);
for (Iterator i = opaque.iterator(); i.hasNext();) {
((JComponent) i.next()).setOpaque(true);
}
for (Iterator i = db.iterator(); i.hasNext();) {
((JComponent) i.next()).setDoubleBuffered(true);
}
}
/** Walk the list of "background" decorators and paint them. */
public void paint(Graphics g) {
JLayeredPane lp = (JLayeredPane) getComponent();
Component[] kids = lp.getComponents();
// Construct an area of the intersection of all decorators
Area area = new Area();
List painters = new ArrayList();
List components = new ArrayList();
for (int i = kids.length - 1; i >= 0; i--) {
if (kids[i] instanceof Painter) {
Painter p = (Painter) kids[i];
if (p.isBackgroundDecoration() && p.getDecoratedLayer() == layer
&& p.isShowing()) {
painters.add(p);
area.add(new Area(p.getBounds()));
}
} else if (lp.getLayer(kids[i]) == layer && kids[i] instanceof JComponent) {
components.add(kids[i]);
}
}
if (painters.size() == 0) {
dispose();
return;
}
g.setClip(area);
// Paint background for that area
for (Iterator i = components.iterator(); i.hasNext();) {
JComponent c = (JComponent) i.next();
paintBackground(g, lp, c);
}
// Paint the bg decorators
for (Iterator i = painters.iterator(); i.hasNext();) {
Painter p = (Painter) i.next();
p.paint(g.create(p.getX(), p.getY(), p.getWidth(), p.getHeight()));
}
// Paint foreground for the area
for (Iterator i = components.iterator(); i.hasNext();) {
JComponent c = (JComponent) i.next();
paintForeground(g.create(c.getX(), c.getY(), c.getWidth(), c.getHeight()), c);
}
}
public void dispose() {
getComponent().putClientProperty(key, null);
super.dispose();
}
public String toString() {
return key + " on " + getComponent();
}
}
/** Tracks changes to component configuration. */
private final class Listener extends ComponentAdapter implements HierarchyListener,
PropertyChangeListener {
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
attach();
}
}
public void propertyChange(PropertyChangeEvent e) {
if (JLayeredPane.LAYER_PROPERTY.equals(e.getPropertyName())) {
attach();
}
}
public void componentMoved(ComponentEvent e) {
// FIXME figure out why attach works and synch doesn't
// when painting a selection marquee over a decorated background
attach();
}
public void componentResized(ComponentEvent e) {
// FIXME figure out why attach works and synch doesn't
// when painting a selection marquee over a decorated background
attach();
}
public void componentHidden(ComponentEvent e) {
setVisible(false);
}
public void componentShown(ComponentEvent e) {
setVisible(true);
}
}
}
@@ -0,0 +1,216 @@
package org.diylc.utils.dnd;
/* Copyright 2006 Timothy Wall All Rights Reserved. */
import java.awt.AlphaComposite;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
/**
* Provide a ghosted drag image which will appear on any instances of
* {@link RootPaneContainer} in the current VM. Its location in screen
* coordinates may be set via {@link #move}.
* <p>
* When the image is no longer needed, invoke {@link #dispose}, which hides the
* graphic immediately, or {@link #returnToOrigin}, which moves the image to its
* original location prior to invoking {@link #dispose}.
*/
public class GhostedDragImage extends AbstractComponentDecorator {
private Icon icon;
// drag origin, relative to drag source
private Point origin;
// current drag location, relative to drag source
private Point location;
// offset of the image from the cursor
private Point imageOffset;
private List ghosts = new ArrayList();
private Component dragSource;
private float ghostAlpha = 0.5f;
/**
* Create a ghosted drag image, using the given icon.
*
* @param dragSource
* source of the drag
* @param screenLocation
* screen location where the drag started
* @param icon
* image to be drawn
* @param imageOffset
* offset of the image from the cursor
*/
public GhostedDragImage(JComponent dragSource, Point screenLocation, Icon icon,
Point imageOffset) {
this(dragSource, dragSource.getRootPane().getLayeredPane(), screenLocation, icon,
imageOffset, true);
}
/**
* Create a ghosted drag image.
*
* @param dragSource
* source of the drag
* @param root
* layered pane on which ghosted image is drawn
* @param screenLocation
* initial location of image, in screen coordinates
* @param icon
* icon to use for the ghost image
* @param imageOffset
* offset of the image within the drag source
* @param trackFrames
* if true, creates additional ghosts for all extant frames which
* contain a {@link JLayeredPane} where the image can be painted.
*/
protected GhostedDragImage(JComponent dragSource, JLayeredPane root, Point screenLocation,
Icon icon, Point imageOffset, boolean trackFrames) {
super(root);
this.dragSource = dragSource;
this.icon = icon;
this.imageOffset = imageOffset;
Point loc = root.getLocationOnScreen();
setLocation(screenLocation.x - loc.x + imageOffset.x, screenLocation.y - loc.y
+ imageOffset.y);
if (trackFrames) {
Window w = SwingUtilities.getWindowAncestor(root);
Frame[] frames = Frame.getFrames();
// Log.debug("track " + frames.length + " other frames");
for (int i = 0; i < frames.length; i++) {
Frame frame = frames[i];
if (frame instanceof RootPaneContainer && frame.isShowing() && frame != w) {
// Log.debug("Track " + frame);
JLayeredPane p = ((RootPaneContainer) frame).getLayeredPane();
GhostedDragImage slave = new GhostedDragImage(dragSource, p, screenLocation,
icon, imageOffset, false);
ghosts.add(slave);
slave.move(screenLocation);
}
}
}
}
/** Set the transparency of the ghosted image. */
public void setAlpha(float alpha) {
ghostAlpha = alpha;
}
/**
* Ensure the decorator cursor matches the drag cursor, or we get cursor
* flicker when autoscrolling.
*/
public void setCursor(Cursor cursor) {
super.setCursor(cursor);
for (Iterator i = ghosts.iterator(); i.hasNext();) {
GhostedDragImage slave = (GhostedDragImage) i.next();
slave.setCursor(cursor);
}
}
/** Make all ghosted images go away. */
public void dispose() {
location = origin;
super.dispose();
for (Iterator i = ghosts.iterator(); i.hasNext();) {
GhostedDragImage slave = (GhostedDragImage) i.next();
slave.dispose();
}
}
/**
* Sets the location of the decoration within the layered pane. Keeps track
* of the location relative to the drag source to facilitate moving back
* with {@link #returnToOrigin}.
*/
private void setLocation(int x, int y) {
location = SwingUtilities.convertPoint(getComponent(), x, y, dragSource);
if (origin == null)
origin = location;
setDecorationBounds(x, y, icon.getIconWidth(), icon.getIconHeight());
}
// Setting this non-zero provides some buffer around the drag image
// which helps avoid cursor flicker as the cursor moves (especially
// repomgr, probably due to slow repaint times).
private static final int CURSOR_SIZE = 32;
/**
* Adjust the bounds of the painting component to allow some buffer to avoid
* cursor flicker when moving.
*/
protected Rectangle clipDecorationBounds(Rectangle decorated) {
decorated.x -= CURSOR_SIZE;
decorated.y -= CURSOR_SIZE;
decorated.width += CURSOR_SIZE * 2;
decorated.height += CURSOR_SIZE * 2;
return super.clipDecorationBounds(decorated);
}
/**
* Move the ghosted image to the requested location.
*
* @param screen
* Where to draw the image, in screen coordinates
*/
public void move(Point screen) {
// Log.debug("Move to " + screen);
Point loc = getComponent().getLocationOnScreen();
setLocation(screen.x - loc.x + imageOffset.x, screen.y - loc.y + imageOffset.y);
for (Iterator i = ghosts.iterator(); i.hasNext();) {
GhostedDragImage g = (GhostedDragImage) i.next();
// Log.debug("Move on other frame");
g.move(screen);
}
}
/** Paint the supplied image with transparency. */
public void paint(Graphics graphics) {
Rectangle r = getDecorationBounds();
Graphics2D g = (Graphics2D) graphics.create();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, ghostAlpha));
g.translate(CURSOR_SIZE, CURSOR_SIZE);
icon.paintIcon(getPainter(), g, r.x, r.y);
g.dispose();
}
private static final int SLIDE_INTERVAL = 1000 / 24;
/** Animate the ghosted image returning to its origin. */
public void returnToOrigin() {
setCursor(null);
final Timer timer = new Timer(SLIDE_INTERVAL, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int dx = (origin.x - location.x) / 2;
int dy = (origin.y - location.y) / 2;
if (dx != 0 || dy != 0) {
Point loc = dragSource.getLocationOnScreen();
Point where = new Point(loc.x + location.x + dx - imageOffset.x, loc.y
+ location.y + dy - imageOffset.y);
move(where);
} else {
timer.stop();
dispose();
}
}
});
timer.start();
}
}
-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>
@@ -8,7 +8,6 @@ import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
@@ -46,7 +45,7 @@ public class MockDIYComponent implements IDIYComponent<Capacitance> {
public MockDIYComponent() {
super();
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
-15
View File
@@ -1,15 +0,0 @@
<org.diylc.core.Theme>
<name>Blueprint</name>
<bgColor>
<red>3</red>
<green>122</green>
<blue>198</blue>
<alpha>255</alpha>
</bgColor>
<gridColor>
<red>29</red>
<green>140</green>
<blue>193</blue>
<alpha>255</alpha>
</gridColor>
</org.diylc.core.Theme>
-15
View File
@@ -1,15 +0,0 @@
<org.diylc.core.Theme>
<name>Dark</name>
<bgColor>
<red>0</red>
<green>0</green>
<blue>0</blue>
<alpha>255</alpha>
</bgColor>
<gridColor>
<red>40</red>
<green>40</green>
<blue>40</blue>
<alpha>255</alpha>
</gridColor>
</org.diylc.core.Theme>
-15
View File
@@ -1,15 +0,0 @@
<org.diylc.core.Theme>
<name>Light</name>
<bgColor>
<red>255</red>
<green>255</green>
<blue>255</blue>
<alpha>255</alpha>
</bgColor>
<gridColor>
<red>240</red>
<green>240</green>
<blue>240</blue>
<alpha>240</alpha>
</gridColor>
</org.diylc.core.Theme>
+17 -244
View File
@@ -11,19 +11,23 @@
<changes>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Copy/paste between two instances of the application</description>
<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>
<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>
<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>
<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>
@@ -31,7 +35,8 @@
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Allow shape control points of curves to overlap</description>
<description>Allow shape control points of curves to overlap
</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
@@ -39,7 +44,8 @@
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Added transparency to the potentiometer</description>
<description>Added transparency to the potentiometer
</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
@@ -47,11 +53,14 @@
</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>
<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>
<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>
@@ -73,241 +82,5 @@
<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>
<com.diyfever.gui.update.Version>
<versionNumber>
<major>3</major>
<minor>0</minor>
<build>6</build>
</versionNumber>
<releaseDate>2011-02-07 20:00:00.000 CET</releaseDate>
<name></name>
<changes>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Copy/paste doesn't work for some components (potentiometer, transistor, etc)</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Resistor color codes are sometimes wrong</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Resistors can specify power handling</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Capacitors can specify voltage handling</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Fixed lead alignment issue</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Better scaling, grid lines are more precise</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Improved performance</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added resistor schematic symbol</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added capacitor schematic symbol</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added eyelet/turret component</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added Marshall/Trainwreck style boards</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added few types of trimmers</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Configurable rendering quality to improve speed</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>7</build>
</versionNumber>
<releaseDate>2011-02-27 20:00:00.000 CET</releaseDate>
<name></name>
<changes>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Resistor and capacitor symbols are not clickable</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Boards sometimes render holes/pads on the edge</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Download link doesn't work on Mac</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Ruler ticks don't always match with the grid</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Micro symbol doesn't get exported to PDF</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>DIL IC now has more pin options</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Send to Back/Bring to Front are more flexible and renamed to match what they do</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Auto-save project and restore if app crashes</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added support for themes</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Added tube socket</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Sticky points may be turned off</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Snap to Grid may be turned off</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Auto-create solder pads</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Auto-edit mode</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Continuous component creation</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>8</build>
</versionNumber>
<releaseDate>2011-03-03 20:00:00.000 CET</releaseDate>
<name></name>
<changes>
<com.diyfever.gui.update.Change>
<changeType>BUG_FIX</changeType>
<description>Sometimes it's not possible to click on a component, especially when layout is large</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>IMPROVEMENT</changeType>
<description>Curved traces and wires can have 2, 3 and 4 control points</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Switchable wheel zoom</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Automatic standing resistors, capacitors and diodes</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Vertical vero board</description>
</com.diyfever.gui.update.Change>
<com.diyfever.gui.update.Change>
<changeType>NEW_FEATURE</changeType>
<description>Label has editable font</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>
+1 -1
View File
@@ -2,8 +2,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 combineaccessrules="false" kind="src" path="/DIYLC"/>
<classpathentry kind="output" path="bin"/>
</classpath>
-3
View File
@@ -46,9 +46,6 @@
<target name="jar" depends="clean, lib.copy, resource.copy, compile">
<jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}" />
<copy todir="../DIYLC/library" overwrite="true">
<fileset dir="${jar.dir}" includes="${ant.project.name}.jar" />
</copy>
</target>
<target name="javadoc">
Binary file not shown.
@@ -5,14 +5,12 @@ import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
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.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
@@ -28,9 +26,8 @@ public abstract class AbstractBoard extends AbstractTransparentComponent<String>
public static Size DEFAULT_HEIGHT = new Size(1.2d, SizeUnit.in);
protected String value = "";
protected Point[] controlPoints = new Point[] {
new Point(0, 0),
new Point((int) DEFAULT_WIDTH.convertToPixels(), (int) DEFAULT_HEIGHT.convertToPixels()) };
protected Point[] 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();
@@ -4,13 +4,11 @@ import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
@@ -22,32 +20,19 @@ public class EyeletBoard extends AbstractBoard {
private static final long serialVersionUID = 1L;
public static Color BOARD_COLOR = Color.decode("#CCFFCC");
public static Color BORDER_COLOR = BOARD_COLOR.darker();
public static Color EYELET_COLOR = Color.decode("#C3E4ED");
public static Size SPACING = new Size(0.5d, SizeUnit.in);
public static Size EYELET_SIZE = new Size(0.2d, SizeUnit.in);
public static Size HOLE_SIZE = new Size(0.1d, SizeUnit.in);
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;
public EyeletBoard() {
super();
this.boardColor = BOARD_COLOR;
this.borderColor = BORDER_COLOR;
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
Shape clip = g2d.getClip();
if (checkPointsClipped(clip) && !clip.contains(firstPoint.x, secondPoint.y)
&& !clip.contains(secondPoint.x, firstPoint.y)) {
return;
}
super.draw(g2d, componentState, project, drawingObserver);
if (componentState != ComponentState.DRAGGING) {
if (alpha < MAX_ALPHA) {
@@ -55,14 +40,14 @@ public class EyeletBoard extends AbstractBoard {
/ MAX_ALPHA));
}
Point p = new Point(firstPoint);
int diameter = getClosestOdd((int) EYELET_SIZE.convertToPixels());
int holeDiameter = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int spacing = (int) this.spacing.convertToPixels();
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 - diameter) {
while (p.x < secondPoint.x - spacing) {
p.x += spacing;
g2d.setColor(eyeletColor);
g2d.fillOval(p.x - diameter / 2, p.y - diameter / 2, diameter, diameter);
@@ -1,109 +0,0 @@
package org.diylc.components.boards;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
@ComponentDescriptor(name = "Marshall Style Perf Board", category = "Boards", author = "Branislav Stojkovic", zOrder = IDIYComponent.BOARD, instanceNamePrefix = "Board", description = "Perforated board as found on some Marshall and Trainwreck amps")
public class MarshallPerfBoard extends AbstractBoard {
private static final long serialVersionUID = 1L;
public static Color BOARD_COLOR = Color.decode("#CD8500");
public static Color BORDER_COLOR = BOARD_COLOR.darker();
public static Size SPACING = new Size(3 / 8d, SizeUnit.in);
public static Size HOLE_SIZE = new Size(1 / 8d, SizeUnit.in);
// private Area copperArea;
protected Size spacing = SPACING;
public MarshallPerfBoard() {
super();
this.boardColor = BOARD_COLOR;
this.borderColor = BORDER_COLOR;
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
Shape clip = g2d.getClip();
if (checkPointsClipped(clip) && !clip.contains(firstPoint.x, secondPoint.y)
&& !clip.contains(secondPoint.x, firstPoint.y)) {
return;
}
super.draw(g2d, componentState, project, drawingObserver);
if (componentState != ComponentState.DRAGGING) {
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
Point p = new Point(firstPoint);
int holeDiameter = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int spacing = (int) this.spacing.convertToPixels();
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
while (p.x < secondPoint.x - spacing - holeDiameter) {
p.x += spacing;
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeDiameter / 2, p.y - holeDiameter / 2, holeDiameter,
holeDiameter);
g2d.setColor(borderColor);
g2d.drawOval(p.x - holeDiameter / 2, p.y - holeDiameter / 2, holeDiameter,
holeDiameter);
}
}
}
}
@EditableProperty
public Size getSpacing() {
return spacing;
}
public void setSpacing(Size spacing) {
this.spacing = spacing;
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BOARD_COLOR);
g2d.fillRect(2, 2, width - 4, height - 4);
g2d.setColor(BORDER_COLOR);
g2d.drawRect(2, 2, width - 4, height - 4);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(width / 3 - 2, width / 3 - 2, 5, 5);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(width / 3 - 2, width / 3 - 2, 5, 5);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(2 * width / 3 - 2, width / 3 - 2, 5, 5);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(2 * width / 3 - 2, width / 3 - 2, 5, 5);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(width / 3 - 2, 2 * width / 3 - 2, 5, 5);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(width / 3 - 2, 2 * width / 3 - 2, 5, 5);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(2 * width / 3 - 2, 2 * width / 3 - 2, 5, 5);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(2 * width / 3 - 2, 2 * width / 3 - 2, 5, 5);
}
}
@@ -4,13 +4,11 @@ import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
@@ -35,11 +33,6 @@ public class PerfBoard extends AbstractBoard {
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
Shape clip = g2d.getClip();
if (checkPointsClipped(clip) && !clip.contains(firstPoint.x, secondPoint.y)
&& !clip.contains(secondPoint.x, firstPoint.y)) {
return;
}
super.draw(g2d, componentState, project, drawingObserver);
if (componentState != ComponentState.DRAGGING) {
if (alpha < MAX_ALPHA) {
@@ -47,14 +40,14 @@ public class PerfBoard extends AbstractBoard {
/ MAX_ALPHA));
}
Point p = new Point(firstPoint);
int diameter = getClosestOdd((int) PAD_SIZE.convertToPixels());
int holeDiameter = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int spacing = (int) this.spacing.convertToPixels();
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 - diameter) {
while (p.x < secondPoint.x - spacing) {
p.x += spacing;
g2d.setColor(padColor);
g2d.fillOval(p.x - diameter / 2, p.y - diameter / 2, diameter, diameter);
@@ -5,9 +5,7 @@ import java.awt.Color;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import org.diylc.common.OrientationHV;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
@@ -32,17 +30,12 @@ public class VeroBoard extends AbstractBoard {
protected Size spacing = SPACING;
protected Color stripColor = STRIP_COLOR;
protected OrientationHV orientation = OrientationHV.HORIZONTAL;
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
Shape clip = g2d.getClip();
if (checkPointsClipped(clip) && !clip.contains(firstPoint.x, secondPoint.y)
&& !clip.contains(secondPoint.x, firstPoint.y)) {
return;
}
super.draw(g2d, componentState, project, drawingObserver);
if (componentState != ComponentState.DRAGGING) {
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
@@ -50,45 +43,25 @@ public class VeroBoard extends AbstractBoard {
/ MAX_ALPHA));
}
Point p = new Point(firstPoint);
int stripSize = getClosestOdd((int) STRIP_SIZE.convertToPixels());
int holeSize = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int spacing = (int) this.spacing.convertToPixels();
int stripSize = getClosestOdd(STRIP_SIZE.convertToPixels());
int holeSize = getClosestOdd(HOLE_SIZE.convertToPixels());
int spacing = this.spacing.convertToPixels();
if (orientation == OrientationHV.HORIZONTAL) {
while (p.y < secondPoint.y - spacing) {
p.x = firstPoint.x;
p.y += spacing;
g2d.setColor(stripColor);
g2d.fillRect(p.x + spacing / 2, p.y - stripSize / 2, secondPoint.x - spacing
- p.x, stripSize);
g2d.setColor(stripColor.darker());
g2d.drawRect(p.x + spacing / 2, p.y - stripSize / 2, secondPoint.x - spacing
- p.x, stripSize);
while (p.x < secondPoint.x - spacing - holeSize) {
p.x += spacing;
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
g2d.setColor(stripColor.darker());
g2d.drawOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
}
}
} else {
while (p.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;
p.y = firstPoint.y;
g2d.setColor(stripColor);
g2d.fillRect(p.x - stripSize / 2, p.y + spacing / 2, stripSize, secondPoint.y
- spacing - p.y);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
g2d.setColor(stripColor.darker());
g2d.drawRect(p.x - stripSize / 2, p.y + spacing / 2, stripSize, secondPoint.y
- spacing - p.y);
while (p.y < secondPoint.y - spacing - holeSize) {
p.y += spacing;
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
g2d.setColor(stripColor.darker());
g2d.drawOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
}
g2d.drawOval(p.x - holeSize / 2, p.y - holeSize / 2, holeSize, holeSize);
}
}
g2d.setComposite(oldComposite);
@@ -113,15 +86,6 @@ public class VeroBoard extends AbstractBoard {
this.spacing = spacing;
}
@EditableProperty
public OrientationHV getOrientation() {
return orientation;
}
public void setOrientation(OrientationHV orientation) {
this.orientation = orientation;
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BOARD_COLOR);
@@ -15,7 +15,7 @@ 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)
@ComponentDescriptor(name = "Copper Trace", author = "Branislav Stojkovic", category = "Connectivity", creationMethod = CreationMethod.POINT_BY_POINT, instanceNamePrefix = "Trace", description = "", zOrder = IDIYComponent.TRACE)
public class CopperTrace extends AbstractLeadedComponent<Void> {
private static final long serialVersionUID = 1L;
@@ -24,7 +24,7 @@ public class CopperTrace extends AbstractLeadedComponent<Void> {
public static Color COLOR = Color.black;
private Color leadColor = COLOR;
private Size thickness = THICKNESS;
private Size leadThickness = THICKNESS;
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
@@ -53,18 +53,14 @@ public class CopperTrace extends AbstractLeadedComponent<Void> {
this.leadColor = leadColor;
}
@EditableProperty(name = "Width")
public Size getThickness() {
return thickness;
@Override
@EditableProperty(name = "Thickness")
public Size getLeadThickness() {
return leadThickness;
}
public void setThickness(Size thickness) {
this.thickness = thickness;
}
@Override
protected int getLeadThickness() {
return (int) getThickness().convertToPixels();
public void setLeadThickness(Size leadThickness) {
this.leadThickness = leadThickness;
}
@Override
@@ -72,51 +68,69 @@ public class CopperTrace extends AbstractLeadedComponent<Void> {
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();
}
@Override
public Size getLength() {
return super.getLength();
}
@Deprecated
@Override
public Size getWidth() {
return super.getWidth();
}
@Deprecated
@Override
public Size getHeight() {
return super.getHeight();
}
@Deprecated
@Override
public Void getValue() {
return null;
}
@Deprecated
@Override
public void setValue(Void value) {
}
@Override
protected Color getDefaultBodyColor() {
return null;
}
@Override
protected Color getDefaultBorderColor() {
return null;
}
@Override
protected Shape getBodyShape() {
return null;
}
@Override
protected Size getDefaultWidth() {
protected Size getDefaultHeight() {
return null;
}
@Override
protected Size getDefaultLength() {
protected Size getDefaultWidth() {
return null;
}
}
@@ -8,7 +8,7 @@ import org.diylc.common.ObjectCache;
import org.diylc.components.AbstractCurvedComponent;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
@@ -31,13 +31,17 @@ public class CurvedTrace extends AbstractCurvedComponent<Void> {
@Override
protected void drawCurve(CubicCurve2D curve, Graphics2D g2d, ComponentState componentState) {
int thickness = (int) size.convertToPixels();
int thickness = size.convertToPixels();
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(thickness));
Color curveColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color;
g2d.setColor(curveColor);
g2d.setColor(componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color);
g2d.draw(curve);
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.NEVER;
}
@EditableProperty(name = "Width")
public Size getSize() {
@@ -48,6 +52,7 @@ public class CurvedTrace extends AbstractCurvedComponent<Void> {
this.size = size;
}
@Deprecated
@Override
public Void getValue() {
return null;
@@ -57,6 +62,7 @@ public class CurvedTrace extends AbstractCurvedComponent<Void> {
public void setValue(Void value) {
}
@Deprecated
@Override
public Byte getAlpha() {
return super.getAlpha();
@@ -1,140 +0,0 @@
package org.diylc.components.connectivity;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import org.diylc.components.AbstractComponent;
import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.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", category = "Connectivity", author = "Branislav Stojkovic", description = "Eyelet or turret terminal", instanceNamePrefix = "Eyelet", stretchable = false, zOrder = IDIYComponent.TRACE + 0.1)
public class Eyelet extends AbstractComponent<String> {
private static final long serialVersionUID = 1L;
public static Size SIZE = new Size(0.2d, SizeUnit.in);
public static Size HOLE_SIZE = new Size(0.1d, SizeUnit.in);
public static Color COLOR = Color.decode("#C3E4ED");
private Size size = SIZE;
private Size holeSize = HOLE_SIZE;
private Color color = COLOR;
private Point point = new Point(0, 0);
private String value = "";
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
if (checkPointsClipped(g2d.getClip())) {
return;
}
int diameter = getClosestOdd((int) size.convertToPixels());
int holeDiameter = getClosestOdd((int) holeSize.convertToPixels());
g2d.setColor(color);
g2d.fillOval(point.x - diameter / 2, point.y - diameter / 2, diameter, diameter);
g2d.setColor(componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color.darker());
g2d.drawOval(point.x - diameter / 2, point.y - diameter / 2, diameter, diameter);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(point.x - holeDiameter / 2, point.y - holeDiameter / 2, holeDiameter,
holeDiameter);
g2d.setColor(componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color.darker());
g2d.drawOval(point.x - holeDiameter / 2, point.y - holeDiameter / 2, holeDiameter,
holeDiameter);
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
int diameter = getClosestOdd(width / 2);
int holeDiameter = 5;
g2d.setColor(COLOR);
g2d.fillOval((width - diameter) / 2, (height - diameter) / 2, diameter, diameter);
g2d.setColor(COLOR.darker());
g2d.drawOval((width - diameter) / 2, (height - diameter) / 2, diameter, diameter);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval((width - holeDiameter) / 2, (height - holeDiameter) / 2, holeDiameter,
holeDiameter);
g2d.setColor(COLOR.darker());
g2d.drawOval((width - holeDiameter) / 2, (height - holeDiameter) / 2, holeDiameter,
holeDiameter);
}
@EditableProperty
public Size getSize() {
return size;
}
public void setSize(Size size) {
this.size = size;
}
@EditableProperty(name = "Hole size")
public Size getHoleSize() {
return holeSize;
}
public void setHoleSize(Size holeSize) {
this.holeSize = holeSize;
}
@Override
public String getName() {
return super.getName();
}
@Override
public int getControlPointCount() {
return 1;
}
@Override
public boolean isControlPointSticky(int index) {
return true;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.NEVER;
}
@Override
public Point getControlPoint(int index) {
return point;
}
@Override
public void setControlPoint(Point point, int index) {
this.point.setLocation(point);
}
@EditableProperty(name = "Color")
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
@Override
@EditableProperty
public String getValue() {
return value;
}
@Override
public void setValue(String value) {
this.value = value;
}
}
@@ -29,11 +29,11 @@ public class HookupWire extends AbstractCurvedComponent<Void> {
@Override
protected void drawCurve(CubicCurve2D curve, Graphics2D g2d, ComponentState componentState) {
int thickness = (int) (Math.pow(Math.E, -1.12436 - 0.11594 * gauge.getValue())
int thickness = (int) (Math.
pow(Math.E, -1.12436 - 0.11594 * gauge.getValue())
* Constants.PIXELS_PER_INCH * (1 + 2 * INSULATION_THICKNESS_PCT));
Color curveColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color.darker();
g2d.setColor(curveColor);
g2d.setColor(componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color.darker());
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(thickness));
g2d.draw(curve);
if (componentState == ComponentState.NORMAL) {
@@ -19,79 +19,83 @@ public class Jumper extends AbstractLeadedComponent<Void> {
private static final long serialVersionUID = 1L;
public static Color COLOR = Color.blue;
private Color color = COLOR;
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(3));
g2d.setColor(COLOR.darker());
g2d.drawLine(1, height - 2, width - 2, 1);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
g2d.setColor(COLOR);
g2d.drawLine(1, height - 2, width - 2, 1);
}
@Override
@EditableProperty(name = "Color")
public Color getLeadColor(ComponentState componentState) {
return componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color;
}
@EditableProperty
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : COLOR;
}
@Deprecated
public Color getBodyColor() {
return super.getBodyColor();
}
@Deprecated
@Override
public Color getBorderColor() {
return super.getBorderColor();
}
@Deprecated
@Override
public Byte getAlpha() {
return super.getAlpha();
}
@Override
public Size getLength() {
return super.getLength();
}
@Deprecated
@Override
public Size getWidth() {
return super.getWidth();
}
@Deprecated
@Override
public Size getHeight() {
return super.getHeight();
}
@Deprecated
@Override
public Void getValue() {
return null;
}
@Deprecated
@Override
public void setValue(Void value) {
}
@Override
protected Color getDefaultBodyColor() {
return null;
}
@Override
protected Color getDefaultBorderColor() {
return null;
}
@Override
protected Shape getBodyShape() {
return null;
}
@Override
protected Size getDefaultWidth() {
protected Size getDefaultHeight() {
return null;
}
@Override
protected Size getDefaultLength() {
protected Size getDefaultWidth() {
return null;
}
}
@@ -9,7 +9,6 @@ import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
@@ -29,23 +28,15 @@ public class SolderPad extends AbstractComponent<Void> {
private Size size = SIZE;
private Color color = COLOR;
private Point point = new Point(0, 0);
private Type type = Type.ROUND;
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
if (checkPointsClipped(g2d.getClip())) {
return;
}
int diameter = getClosestOdd((int) size.convertToPixels());
int holeDiameter = getClosestOdd((int) HOLE_SIZE.convertToPixels());
int diameter = getClosestOdd(size.convertToPixels());
int holeDiameter = getClosestOdd(HOLE_SIZE.convertToPixels());
g2d.setColor(componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : color);
if (type == Type.ROUND) {
g2d.fillOval(point.x - diameter / 2, point.y - diameter / 2, diameter, diameter);
} else {
g2d.fillRect(point.x - diameter / 2, point.y - diameter / 2, diameter, diameter);
}
g2d.fillOval(point.x - diameter / 2, point.y - diameter / 2, diameter, diameter);
g2d.setColor(Constants.CANVAS_COLOR);
g2d.fillOval(point.x - holeDiameter / 2, point.y - holeDiameter / 2, holeDiameter,
holeDiameter);
@@ -71,6 +62,7 @@ public class SolderPad extends AbstractComponent<Void> {
this.size = size;
}
@Deprecated
@Override
public String getName() {
return super.getName();
@@ -110,15 +102,7 @@ public class SolderPad extends AbstractComponent<Void> {
this.color = color;
}
@EditableProperty
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
@Deprecated
@Override
public Void getValue() {
return null;
@@ -127,13 +111,4 @@ public class SolderPad extends AbstractComponent<Void> {
@Override
public void setValue(Void value) {
}
static enum Type {
ROUND, SQUARE;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
}
@@ -16,7 +16,7 @@ import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Trace Cut", category = "Connectivity", author = "Branislav Stojkovic", description = "Designates the place where a trace on the vero board needs to be cut", instanceNamePrefix = "Cut", stretchable = false, zOrder = IDIYComponent.BOARD + 1)
@ComponentDescriptor(name = "Trace Cut", category = "Connectivity", author = "Branislav Stojkovic", description = "test", instanceNamePrefix = "Cut", stretchable = false, zOrder = IDIYComponent.BOARD + 1)
public class TraceCut extends AbstractComponent<Void> {
private static final long serialVersionUID = 1L;
@@ -35,10 +35,7 @@ public class TraceCut extends AbstractComponent<Void> {
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
if (checkPointsClipped(g2d.getClip())) {
return;
}
int size = getClosestOdd((int) this.size.convertToPixels());
int size = getClosestOdd(this.size.convertToPixels());
int dotDiameter = size - 6;
g2d.setColor(fillColor);
g2d.fillRect(point.x - size / 2, point.y - size / 2, size, size);
@@ -89,11 +86,13 @@ public class TraceCut extends AbstractComponent<Void> {
this.point.setLocation(point);
}
@Deprecated
@Override
public Void getValue() {
return null;
}
@Deprecated
@Override
public void setValue(Void value) {
}
@@ -125,6 +124,7 @@ public class TraceCut extends AbstractComponent<Void> {
this.borderColor = borderColor;
}
@Deprecated
@Override
public String getName() {
return super.getName();
@@ -14,14 +14,13 @@ import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Mini Toggle Switch", category = "Electromechanical", author = "Branislav Stojkovic", description = "Panel mounted mini toggle switch", stretchable = false, zOrder = IDIYComponent.COMPONENT, instanceNamePrefix = "SW")
@ComponentDescriptor(name = "Mini Toggle Switch", category = "Electromechanical", author = "Branislav Stojkovic", description = "", stretchable = false, zOrder = IDIYComponent.COMPONENT, instanceNamePrefix = "SW")
public class MiniToggleSwitch extends AbstractTransparentComponent<ToggleSwitchType> {
private static final long serialVersionUID = 1L;
@@ -38,7 +37,7 @@ public class MiniToggleSwitch extends AbstractTransparentComponent<ToggleSwitchT
private static Color LUG_COLOR = Color.decode("#00B2EE");
protected Point[] controlPoints = new Point[] { new Point(0, 0) };
transient protected RoundRectangle2D body;
protected RoundRectangle2D body;
protected String name;
protected ToggleSwitchType switchType = ToggleSwitchType.DPDT;
@@ -49,7 +48,7 @@ public class MiniToggleSwitch extends AbstractTransparentComponent<ToggleSwitchT
private void updateControlPoints() {
Point firstPoint = controlPoints[0];
int spacing = (int) SPACING.convertToPixels();
int spacing = SPACING.convertToPixels();
switch (switchType) {
case SPST:
controlPoints = new Point[] { firstPoint,
@@ -117,12 +116,12 @@ public class MiniToggleSwitch extends AbstractTransparentComponent<ToggleSwitchT
public Point getControlPoint(int index) {
return controlPoints[index];
}
@Override
public boolean isControlPointSticky(int index) {
return true;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.NEVER;
@@ -168,9 +167,6 @@ public class MiniToggleSwitch extends AbstractTransparentComponent<ToggleSwitchT
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
if (checkPointsClipped(g2d.getClip())) {
return;
}
Shape body = getBody();
// Draw body if available.
if (body != null) {
@@ -191,9 +187,9 @@ public class MiniToggleSwitch extends AbstractTransparentComponent<ToggleSwitchT
// so far.
drawingObserver.stopTracking();
// Draw lugs.
int circleDiameter = getClosestOdd((int) CIRCLE_SIZE.convertToPixels());
int lugWidth = getClosestOdd((int) LUG_WIDTH.convertToPixels());
int lugHeight = getClosestOdd((int) LUG_HEIGHT.convertToPixels());
int circleDiameter = getClosestOdd(CIRCLE_SIZE.convertToPixels());
int lugWidth = getClosestOdd(LUG_WIDTH.convertToPixels());
int lugHeight = getClosestOdd(LUG_HEIGHT.convertToPixels());
for (Point p : controlPoints) {
g2d.setColor(CIRCLE_COLOR);
g2d.fillOval(p.x - circleDiameter / 2, p.y - circleDiameter / 2, circleDiameter,
@@ -206,8 +202,8 @@ public class MiniToggleSwitch extends AbstractTransparentComponent<ToggleSwitchT
public RoundRectangle2D getBody() {
if (body == null) {
Point firstPoint = controlPoints[0];
int margin = (int) MARGIN.convertToPixels();
int spacing = (int) SPACING.convertToPixels();
int margin = MARGIN.convertToPixels();
int spacing = SPACING.convertToPixels();
switch (switchType) {
case SPST:
body = new RoundRectangle2D.Double(firstPoint.x - margin, firstPoint.y - margin,
@@ -14,7 +14,6 @@ import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
@@ -74,9 +73,9 @@ public class BOM extends AbstractComponent<Void> {
}
}
// Calculate maximum entry size.
int maxEntrySize = maxNameWidth + maxValueWidth + 2 * (int) SPACING.convertToPixels();
int columnCount = (int) size.convertToPixels() / maxEntrySize;
int columnWidth = (int) size.convertToPixels() / columnCount;
int maxEntrySize = maxNameWidth + maxValueWidth + 2 * SPACING.convertToPixels();
int columnCount = size.convertToPixels() / maxEntrySize;
int columnWidth = size.convertToPixels() / columnCount;
int entriesPerColumn = (int) Math.ceil(1.d * bom.size() / columnCount);
if (entriesPerColumn == 0) {
g2d.drawString(DEFAULT_TEXT, point.x, point.y);
@@ -160,6 +159,7 @@ public class BOM extends AbstractComponent<Void> {
this.size = size;
}
@Deprecated
@Override
public Void getValue() {
return null;
@@ -48,14 +48,9 @@ public class IconImageConverter implements Converter {
writer.addAttribute("width", Integer.toString(width));
writer.addAttribute("height", Integer.toString(height));
StringBuilder dataBuilder = new StringBuilder();
int n = 0;
for (int pixel : pixels) {
dataBuilder.append(Integer.toString(pixel, 16));
dataBuilder.append(",");
n++;
if (n % 16 == 0) {
dataBuilder.append("\n");
}
}
writer.addAttribute("data", dataBuilder.toString());
}
@@ -66,15 +61,11 @@ public class IconImageConverter implements Converter {
int height = Integer.parseInt(reader.getAttribute("height"));
LOG.debug("Reading image from file: " + width + "x" + height);
int[] pixels = new int[width * height];
String data = reader.getAttribute("data").replace("\n", "");
String data = reader.getAttribute("data");
String[] splitData = data.split(",");
for (int i = 0; i < Math.min(splitData.length, pixels.length); i++) {
if (!splitData[i].trim().isEmpty()) {
try {
pixels[i] = Integer.parseInt(splitData[i].trim(), 16);
} catch (Exception e) {
pixels[i] = 0;
}
for (int i = 0; i < splitData.length; i++) {
if (!splitData[i].isEmpty()) {
pixels[i] = Integer.parseInt(splitData[i], 16);
}
}
@@ -4,7 +4,6 @@ import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import javax.swing.ImageIcon;
@@ -13,7 +12,6 @@ import org.diylc.core.ComponentState;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.VisibilityPolicy;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
@@ -44,27 +42,20 @@ public class Image extends AbstractTransparentComponent<Void> {
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
double s = 1d * scale / DEFAULT_SCALE;
Point endPoint = new Point((int) (image.getIconWidth() * s),
(int) (image.getIconHeight() * s));
Shape clip = g2d.getClip();
if (!clip.contains(point) && !clip.contains(endPoint)
&& !clip.contains(point.x, endPoint.y) && !clip.contains(endPoint.x, point.y)) {
return;
}
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
double s = 1d * scale / DEFAULT_SCALE;
g2d.scale(s, s);
g2d.drawImage(image.getImage(), (int) (point.x / s), (int) (point.y / s), null);
if (componentState == ComponentState.SELECTED) {
g2d.setComposite(oldComposite);
g2d.scale(1 / s, 1 / s);
g2d.setColor(SELECTION_COLOR);
g2d.drawRect(point.x, point.y, endPoint.x, endPoint.y);
g2d.drawRect(point.x, point.y, (int) (image.getIconWidth() * s), (int) (image
.getIconHeight() * s));
}
}
@@ -121,6 +112,7 @@ public class Image extends AbstractTransparentComponent<Void> {
return super.getName();
}
@Deprecated
@Override
public Void getValue() {
return null;
@@ -72,69 +72,6 @@ public class Label extends AbstractComponent<Void> {
g2d.drawString("Abc", x, y);
}
@EditableProperty
public Font getFont() {
return font;
}
public void setFont(Font font) {
this.font = font;
}
// Bold and italic fields are named to be alphabetically after Font. This is
// important!
@EditableProperty(name = "Font Bold")
public boolean getBold() {
return font.isBold();
}
public void setBold(boolean bold) {
if (bold) {
if (font.isItalic()) {
font = font.deriveFont(Font.BOLD + Font.ITALIC);
} else {
font = font.deriveFont(Font.BOLD);
}
} else {
if (font.isItalic()) {
font = font.deriveFont(Font.ITALIC);
} else {
font = font.deriveFont(Font.PLAIN);
}
}
}
@EditableProperty(name = "Font Italic")
public boolean getItalic() {
return font.isItalic();
}
public void setItalic(boolean italic) {
if (italic) {
if (font.isBold()) {
font = font.deriveFont(Font.BOLD + Font.ITALIC);
} else {
font = font.deriveFont(Font.ITALIC);
}
} else {
if (font.isBold()) {
font = font.deriveFont(Font.BOLD);
} else {
font = font.deriveFont(Font.PLAIN);
}
}
}
@EditableProperty(name = "Font Size")
public int getFontSize() {
return font.getSize();
}
public void setFontSize(int size) {
font = font.deriveFont((float) size);
}
@Override
public int getControlPointCount() {
return 1;
@@ -191,6 +128,7 @@ public class Label extends AbstractComponent<Void> {
return super.getName();
}
@Deprecated
@Override
public Void getValue() {
return null;
@@ -0,0 +1,108 @@
package org.diylc.components.misc;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import org.diylc.components.AbstractComponent;
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.measures.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Project Information", author = "Branislav Stojkovic", category = "Misc", description = "Draws a box with general project information", instanceNamePrefix = "BOM", zOrder = IDIYComponent.TEXT, stretchable = false)
public class ProjectInformation extends AbstractComponent<Void> {
public static Size DEFAULT_SIZE = new Size(10d, SizeUnit.cm);
public static Color COLOR = Color.black;
public static String DEFAULT_TEXT = "No components to show in the Bill of Materials";
private static final long serialVersionUID = 1L;
private Point point = new Point(0, 0);
@Override
public void draw(Graphics2D g2d, ComponentState componentState, Project project,
IDrawingObserver drawingObserver) {
g2d.setFont(LABEL_FONT);
g2d.setColor(componentState == ComponentState.DRAGGING
|| componentState == ComponentState.SELECTED ? SELECTION_COLOR : COLOR);
// FontMetrics fontMetrics = g2d.getFontMetrics();
g2d.drawString(project.getTitle(), point.x, point.y);
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(Color.white);
g2d.fillRect(width / 8, 0, 6 * width / 8, height - 1);
g2d.setColor(Color.black);
g2d.drawRect(width / 8, 0, 6 * width / 8, height - 1);
g2d.setFont(LABEL_FONT.deriveFont(1f * 9 * width / 32).deriveFont(Font.PLAIN));
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds("BOM", g2d);
int textHeight = (int) (rect.getHeight());
int textWidth = (int) (rect.getWidth());
// Center text horizontally and vertically.
int x = (width - textWidth) / 2 + 1;
int y = textHeight + 2;
g2d.drawString("BOM", x, y);
g2d.setFont(g2d.getFont().deriveFont(1f * 5 * width / 32));
fontMetrics = g2d.getFontMetrics();
rect = fontMetrics.getStringBounds("resistors", g2d);
x = (width - textWidth) / 2 + 1;
y = height / 2 + 2;
g2d.drawString("resistors", x, y);
y += rect.getHeight() - 1;
g2d.drawString("tubes", x, y);
y += rect.getHeight() - 1;
g2d.drawString("diodes", x, y);
}
@Override
public int getControlPointCount() {
return 1;
}
@Override
public Point getControlPoint(int index) {
return point;
}
@Override
public boolean isControlPointSticky(int index) {
return false;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.NEVER;
}
@Override
public void setControlPoint(Point point, int index) {
this.point.setLocation(point);
}
@Deprecated
@Override
public Void getValue() {
return null;
}
@Override
public void setValue(Void value) {
}
}
@@ -1,136 +0,0 @@
package org.diylc.components.passive;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import org.diylc.common.ObjectCache;
import org.diylc.components.AbstractLeadedComponent;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Theme;
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.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Electrolytic Capacitor (axial)", author = "Branislav Stojkovic", category = "Passive", creationMethod = CreationMethod.POINT_BY_POINT, instanceNamePrefix = "C", description = "Axial electrolytic capacitor, similar to Sprague Atom, F&T, etc", zOrder = IDIYComponent.COMPONENT)
public class AxialElectrolyticCapacitor extends AbstractLeadedComponent<Capacitance> {
private static final long serialVersionUID = 1L;
public static Size DEFAULT_WIDTH = new Size(1d / 2, SizeUnit.in);
public static Size DEFAULT_HEIGHT = new Size(1d / 8, SizeUnit.in);
public static Color BODY_COLOR = Color.decode("#EAADEA");
public static Color BORDER_COLOR = BODY_COLOR.darker();
public static Color MARKER_COLOR = Color.gray;
public static Color TICK_COLOR = Color.white;
private Capacitance value = new Capacitance(1d, CapacitanceUnit.uF);
private Voltage voltage = Voltage._63V;
private Color markerColor = MARKER_COLOR;
private Color tickColor = TICK_COLOR;
private boolean polarized = true;
public AxialElectrolyticCapacitor() {
super();
this.bodyColor = BODY_COLOR;
this.borderColor = BORDER_COLOR;
}
@EditableProperty
public Capacitance getValue() {
return value;
}
public void setValue(Capacitance value) {
this.value = value;
}
@EditableProperty
public Voltage getVoltage() {
return voltage;
}
public void setVoltage(Voltage voltage) {
this.voltage = voltage;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.rotate(-Math.PI / 4, width / 2, height / 2);
g2d.setColor(LEAD_COLOR);
g2d.drawLine(0, height / 2, width, height / 2);
g2d.setColor(BODY_COLOR);
g2d.fillRect(4, height / 2 - 3, width - 8, 6);
g2d.setColor(MARKER_COLOR);
g2d.fillRect(width - 9, height / 2 - 3, 5, 6);
g2d.setColor(TICK_COLOR);
g2d.drawLine(width - 6, height / 2 - 1, width - 6, height / 2 + 1);
g2d.setColor(BORDER_COLOR);
g2d.drawRect(4, height / 2 - 3, width - 8, 6);
}
@Override
protected Size getDefaultWidth() {
return DEFAULT_HEIGHT;
}
@Override
protected Size getDefaultLength() {
return DEFAULT_WIDTH;
}
@EditableProperty(name = "Marker")
public Color getMarkerColor() {
return markerColor;
}
public void setMarkerColor(Color coverColor) {
this.markerColor = coverColor;
}
@EditableProperty(name = "Tick")
public Color getTickColor() {
return tickColor;
}
public void setTickColor(Color tickColor) {
this.tickColor = tickColor;
}
@EditableProperty(name = "Polarized")
public boolean getPolarized() {
return polarized;
}
public void setPolarized(boolean polarized) {
this.polarized = polarized;
}
@Override
protected Shape getBodyShape() {
return new Rectangle2D.Double(0f, 0f, getLength().convertToPixels(),
getClosestOdd(getWidth().convertToPixels()));
}
@Override
protected void decorateComponentBody(Graphics2D g2d) {
if (polarized) {
int markerLength = (int) (getLength().convertToPixels() * 0.2);
g2d.setColor(markerColor);
int width = getClosestOdd(getWidth().convertToPixels());
g2d
.fillRect((int) getLength().convertToPixels() - markerLength, 0, markerLength,
width);
g2d.setColor(tickColor);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(2));
g2d.drawLine((int) getLength().convertToPixels() - markerLength / 2,
(int) (width / 2 - width * 0.15), (int) getLength().convertToPixels()
- markerLength / 2, (int) (width / 2 + width * 0.15));
}
}
}
@@ -25,18 +25,10 @@ public class AxialFilmCapacitor extends AbstractLeadedComponent<Capacitance> {
public static Color BODY_COLOR = Color.decode("#FFE303");
public static Color BORDER_COLOR = BODY_COLOR.darker();
private Capacitance value = new Capacitance(22d, CapacitanceUnit.nF);
private Voltage voltage = Voltage._63V;
private Capacitance value = new Capacitance(123d, CapacitanceUnit.nF);
public AxialFilmCapacitor() {
super();
this.bodyColor = BODY_COLOR;
this.borderColor = BORDER_COLOR;
}
@Override
protected boolean supportsStandingMode() {
return true;
}
@EditableProperty
@@ -47,16 +39,6 @@ public class AxialFilmCapacitor extends AbstractLeadedComponent<Capacitance> {
public void setValue(Capacitance value) {
this.value = value;
}
@EditableProperty
public Voltage getVoltage() {
return voltage;
}
public void setVoltage(Voltage voltage) {
this.voltage = voltage;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.rotate(-Math.PI / 4, width / 2, height / 2);
@@ -69,18 +51,28 @@ public class AxialFilmCapacitor extends AbstractLeadedComponent<Capacitance> {
}
@Override
protected Size getDefaultWidth() {
protected Size getDefaultHeight() {
return DEFAULT_HEIGHT;
}
@Override
protected Size getDefaultLength() {
protected Size getDefaultWidth() {
return DEFAULT_WIDTH;
}
@Override
protected Color getDefaultBodyColor() {
return BODY_COLOR;
}
@Override
protected Color getDefaultBorderColor() {
return BORDER_COLOR;
}
@Override
protected Shape getBodyShape() {
return new Rectangle2D.Double(0f, 0f, getLength().convertToPixels(),
getClosestOdd(getWidth().convertToPixels()));
return new Rectangle2D.Double(0f, 0f, getWidth().convertToPixels(),
getClosestOdd(getHeight().convertToPixels()));
}
}
@@ -1,101 +0,0 @@
package org.diylc.components.passive;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import org.diylc.components.AbstractSchematicLeadedSymbol;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Theme;
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.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Capacitor (schematic symbol)", author = "Branislav Stojkovic", category = "Passive", creationMethod = CreationMethod.POINT_BY_POINT, instanceNamePrefix = "C", description = "Capacitor schematic symbol with an optional polarity sign", zOrder = IDIYComponent.COMPONENT)
public class CapacitorSymbol extends AbstractSchematicLeadedSymbol<Capacitance> {
private static final long serialVersionUID = 1L;
public static Size DEFAULT_LENGTH = new Size(0.05, SizeUnit.in);
public static Size DEFAULT_WIDTH = new Size(0.15, SizeUnit.in);
private Capacitance value = new Capacitance(22d, CapacitanceUnit.nF);
private Voltage voltage = Voltage._63V;
private boolean polarized = false;
@EditableProperty
public Capacitance getValue() {
return value;
}
public void setValue(Capacitance value) {
this.value = value;
}
@EditableProperty
public Voltage getVoltage() {
return voltage;
}
public void setVoltage(Voltage voltage) {
this.voltage = voltage;
}
@EditableProperty
public boolean getPolarized() {
return polarized;
}
public void setPolarized(boolean polarized) {
this.polarized = polarized;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.rotate(-Math.PI / 4, width / 2, height / 2);
g2d.setColor(LEAD_COLOR);
g2d.drawLine(0, height / 2, 13, height / 2);
g2d.drawLine(width - 13, height / 2, width, height / 2);
g2d.setColor(COLOR);
g2d.drawLine(14, height / 2 - 6, 14, height / 2 + 6);
g2d.drawLine(width - 14, height / 2 - 6, width - 14, height / 2 + 6);
}
@Override
protected Size getDefaultWidth() {
return DEFAULT_WIDTH;
}
@Override
protected Size getDefaultLength() {
return DEFAULT_LENGTH;
}
@Override
protected Shape getBodyShape() {
GeneralPath polyline = new GeneralPath();
double length = getLength().convertToPixels();
double width = getWidth().convertToPixels();
polyline.moveTo(0, 0);
polyline.lineTo(0, width);
polyline.moveTo(length, 0);
polyline.lineTo(length, width);
return polyline;
}
@Override
protected void decorateComponentBody(Graphics2D g2d) {
if (polarized) {
// Draw + sign.
g2d.setColor(getBorderColor());
int plusSize = getClosestOdd(getWidth().convertToPixels() / 4);
int x = -plusSize;
int y = plusSize;
g2d.drawLine(x - plusSize / 2, y, x + plusSize / 2, y);
g2d.drawLine(x, y - plusSize / 2, x, y + plusSize / 2);
}
}
}
@@ -0,0 +1,102 @@
package org.diylc.components.passive;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import org.diylc.components.AbstractLeadedComponent;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
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.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Electrolytic Capacitor", author = "Branislav Stojkovic", category = "Passive", creationMethod = CreationMethod.POINT_BY_POINT, instanceNamePrefix = "C", description = "test", zOrder = IDIYComponent.COMPONENT)
public class ElectrolyticRadial extends AbstractLeadedComponent<Capacitance> {
private static final long serialVersionUID = 1L;
public static Size DEFAULT_SIZE = new Size(1d / 2, SizeUnit.in);
public static Color BODY_COLOR = Color.decode("#27408B");
public static Color BORDER_COLOR = BODY_COLOR.darker();
public static Color COVER_COLOR = Color.decode("#C3E4ED");
private Capacitance value = new Capacitance(1d, CapacitanceUnit.uF);
public ElectrolyticRadial() {
super();
}
@EditableProperty
public Capacitance getValue() {
return value;
}
public void setValue(Capacitance value) {
this.value = value;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BODY_COLOR);
g2d.fillOval(6, 6, width - 12, width - 12);
g2d.setColor(BORDER_COLOR);
g2d.drawOval(6, 6, width - 12, width - 12);
}
@Override
protected void decorateComponentBody(Graphics2D g2d) {
int totalDiameter = getClosestOdd(getWidth().convertToPixels());
int coverDiameter = getClosestOdd(totalDiameter * 3 / 4);
g2d.setColor(COVER_COLOR);
int position = (totalDiameter - coverDiameter) / 2;
g2d.fillOval(position, position, coverDiameter, coverDiameter);
g2d.setColor(COVER_COLOR.darker());
g2d.drawLine(position + coverDiameter / 5, position + coverDiameter / 5, position + 4
* coverDiameter / 5, position + 4 * coverDiameter / 5);
g2d.drawLine(position + coverDiameter / 5, position + 4 * coverDiameter / 5, position + 4
* coverDiameter / 5, position + coverDiameter / 5);
}
@Override
protected Size getDefaultHeight() {
return null;
}
@Deprecated
@Override
public Size getHeight() {
return super.getHeight();
}
@Override
protected Size getDefaultWidth() {
// We'll reuse width property to set the diameter.
return DEFAULT_SIZE;
}
@EditableProperty(name = "Diameter")
@Override
public Size getWidth() {
return super.getWidth();
}
@Override
protected Color getDefaultBodyColor() {
return BODY_COLOR;
}
@Override
protected Color getDefaultBorderColor() {
return BORDER_COLOR;
}
@Override
protected Shape getBodyShape() {
return new Ellipse2D.Double(0f, 0f, getClosestOdd(getWidth().convertToPixels()),
getClosestOdd(getWidth().convertToPixels()));
}
}
@@ -17,7 +17,6 @@ import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IDrawingObserver;
import org.diylc.core.Project;
import org.diylc.core.Theme;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.measures.Size;
@@ -40,7 +39,7 @@ public class PotentiometerPanel extends AbstractPotentiometer {
protected Color bodyColor = BODY_COLOR;
protected Color borderColor = BORDER_COLOR;
// Array of 7 elements: 3 lug connectors, 1 pot body and 3 lugs
transient protected Area[] body = null;
protected Area[] body = null;
public PotentiometerPanel() {
controlPoints = new Point[] { new Point(0, 0), new Point(0, 0), new Point(0, 0) };
@@ -48,7 +47,7 @@ public class PotentiometerPanel extends AbstractPotentiometer {
}
protected void updateControlPoints() {
int spacing = (int) this.spacing.convertToPixels();
int spacing = this.spacing.convertToPixels();
switch (orientation) {
case DEFAULT:
controlPoints[1].setLocation(controlPoints[0].x + spacing, controlPoints[0].y);
@@ -72,7 +71,7 @@ public class PotentiometerPanel extends AbstractPotentiometer {
}
public Area[] getBody() {
int spacing = (int) this.spacing.convertToPixels();
int spacing = this.spacing.convertToPixels();
int diameter = getClosestOdd(bodyDiameter.convertToPixels());
if (body == null) {
body = new Area[7];
@@ -109,7 +108,7 @@ public class PotentiometerPanel extends AbstractPotentiometer {
break;
case _180:
body[3] = new Area(new Ellipse2D.Double(
controlPoints[0].x - spacing - diameter / 2, controlPoints[0].y + spacing
controlPoints[0].x + spacing - diameter / 2, controlPoints[0].y + spacing
/ 2, diameter, diameter));
for (int i = 0; i < 3; i++) {
body[i] = new Area(new Rectangle2D.Double(
@@ -213,7 +212,7 @@ public class PotentiometerPanel extends AbstractPotentiometer {
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
int margin = 4 * width / 32;
int spacing = width / 3 - 1;
int spacing = width / 3;
g2d.setColor(BORDER_COLOR);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(2 * width / 32));
g2d.drawLine(width / 2 - spacing, height / 2, width / 2 - spacing, height - margin);
@@ -1,18 +0,0 @@
package org.diylc.components.passive;
public enum Power {
EIGHT("1/8W"), QUARTER("1/4W"), HALF("1/2W"), ONE("1W"), TWO("2W"), FIVE("5W"), TEN("10W"), FIFTY(
"50W"), HUNDRED("100W");
String label;
Power(String label) {
this.label = label;
}
@Override
public String toString() {
return label;
}
}
@@ -25,13 +25,10 @@ public class RadialCeramicDiskCapacitor extends AbstractLeadedComponent<Capacita
public static Color BODY_COLOR = Color.decode("#F0E68C");
public static Color BORDER_COLOR = BODY_COLOR.darker();
private Capacitance value = new Capacitance(470d, CapacitanceUnit.pF);
private Voltage voltage = Voltage._63V;
private Capacitance value = new Capacitance(123d, CapacitanceUnit.nF);
public RadialCeramicDiskCapacitor() {
super();
this.bodyColor = BODY_COLOR;
this.borderColor = BORDER_COLOR;
}
@EditableProperty
@@ -42,15 +39,6 @@ public class RadialCeramicDiskCapacitor extends AbstractLeadedComponent<Capacita
public void setValue(Capacitance value) {
this.value = value;
}
@EditableProperty
public Voltage getVoltage() {
return voltage;
}
public void setVoltage(Voltage voltage) {
this.voltage = voltage;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.rotate(-Math.PI / 4, width / 2, height / 2);
@@ -63,18 +51,28 @@ public class RadialCeramicDiskCapacitor extends AbstractLeadedComponent<Capacita
}
@Override
protected Size getDefaultWidth() {
protected Size getDefaultHeight() {
return DEFAULT_HEIGHT;
}
@Override
protected Size getDefaultLength() {
protected Size getDefaultWidth() {
return DEFAULT_WIDTH;
}
@Override
protected Color getDefaultBodyColor() {
return BODY_COLOR;
}
@Override
protected Color getDefaultBorderColor() {
return BORDER_COLOR;
}
@Override
protected Shape getBodyShape() {
return new Ellipse2D.Double(0f, 0f, getLength().convertToPixels(), getClosestOdd(getWidth()
return new Ellipse2D.Double(0f, 0f, getWidth().convertToPixels(), getClosestOdd(getHeight()
.convertToPixels()));
}
}
@@ -1,171 +0,0 @@
package org.diylc.components.passive;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import org.diylc.common.ObjectCache;
import org.diylc.components.AbstractLeadedComponent;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Theme;
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.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Electrolytic Capacitor", author = "Branislav Stojkovic", category = "Passive", creationMethod = CreationMethod.POINT_BY_POINT, instanceNamePrefix = "C", description = "Vertical mounted electrolytic capacitor, polarized or bipolar", zOrder = IDIYComponent.COMPONENT)
public class RadialElectrolytic extends AbstractLeadedComponent<Capacitance> {
private static final long serialVersionUID = 1L;
public static Size DEFAULT_SIZE = new Size(1d / 2, SizeUnit.in);
public static Color BODY_COLOR = Color.decode("#EAADEA");
public static Color BORDER_COLOR = BODY_COLOR.darker();
public static Color MARKER_COLOR = Color.gray;
public static Color TICK_COLOR = Color.white;
private Capacitance value = new Capacitance(1d, CapacitanceUnit.uF);
private Voltage voltage = Voltage._63V;
private Color markerColor = MARKER_COLOR;
private Color tickColor = TICK_COLOR;
private boolean polarized = true;
public RadialElectrolytic() {
super();
this.bodyColor = BODY_COLOR;
this.borderColor = BORDER_COLOR;
}
@EditableProperty
public Capacitance getValue() {
return value;
}
public void setValue(Capacitance value) {
this.value = value;
}
@EditableProperty
public Voltage getVoltage() {
return voltage;
}
public void setVoltage(Voltage voltage) {
this.voltage = voltage;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(BODY_COLOR);
int margin = 3;
Ellipse2D body = new Ellipse2D.Double(margin, margin, getClosestOdd(width - 2 * margin),
getClosestOdd(width - 2 * margin));
g2d.fill(body);
Area marker = new Area(body);
marker.subtract(new Area(new Rectangle2D.Double(margin, margin, width - 4 * margin,
getClosestOdd(width - 2 * margin))));
g2d.setColor(MARKER_COLOR);
g2d.fill(marker);
g2d.setColor(TICK_COLOR);
g2d.drawLine(width - 2 * margin, height / 2 - 2, width - 2 * margin, height / 2 + 2);
g2d.setColor(BORDER_COLOR);
g2d.draw(body);
// g2d.setColor(COVER_COLOR.darker());
// g2d.drawLine(innerMargin + 2, innerMargin + 2, width - innerMargin -
// 2, width - innerMargin
// - 2);
// g2d.drawLine(innerMargin + 2, width - innerMargin - 2, width -
// innerMargin - 2,
// innerMargin + 2);
}
@Override
protected void decorateComponentBody(Graphics2D g2d) {
if (polarized) {
int totalDiameter = getClosestOdd(getLength().convertToPixels());
Area area = new Area(getBodyShape());
area
.subtract(new Area(new Rectangle2D.Double(0, 0, totalDiameter * 0.8,
totalDiameter)));
g2d.setColor(markerColor);
g2d.fill(area);
g2d.setColor(tickColor);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(2));
g2d.drawLine((int) (totalDiameter * 0.9), totalDiameter / 2
- (int) (totalDiameter * 0.05), (int) (totalDiameter * 0.9), totalDiameter / 2
+ (int) (totalDiameter * 0.05));
}
// int coverDiameter = getClosestOdd(totalDiameter * 3 / 4);
// g2d.setColor(coverColor);
// int position = (totalDiameter - coverDiameter) / 2;
// g2d.fillOval(position, position, coverDiameter, coverDiameter);
// g2d.setColor(coverColor.darker());
// g2d.drawLine(position + coverDiameter / 5, position + coverDiameter /
// 5, position + 4
// * coverDiameter / 5, position + 4 * coverDiameter / 5);
// g2d.drawLine(position + coverDiameter / 5, position + 4 *
// coverDiameter / 5, position + 4
// * coverDiameter / 5, position + coverDiameter / 5);
}
@Override
protected Size getDefaultWidth() {
return null;
}
@Override
public Size getWidth() {
return super.getWidth();
}
@Override
protected Size getDefaultLength() {
// We'll reuse width property to set the diameter.
return DEFAULT_SIZE;
}
@EditableProperty(name = "Diameter")
@Override
public Size getLength() {
return super.getLength();
}
@EditableProperty(name = "Marker")
public Color getMarkerColor() {
return markerColor;
}
public void setMarkerColor(Color coverColor) {
this.markerColor = coverColor;
}
@EditableProperty(name = "Tick")
public Color getTickColor() {
return tickColor;
}
public void setTickColor(Color tickColor) {
this.tickColor = tickColor;
}
@EditableProperty(name = "Polarized")
public boolean getPolarized() {
return polarized;
}
public void setPolarized(boolean polarized) {
this.polarized = polarized;
}
@Override
protected Shape getBodyShape() {
return new Ellipse2D.Double(0f, 0f, getClosestOdd(getLength().convertToPixels()),
getClosestOdd(getLength().convertToPixels()));
}
}
@@ -26,12 +26,9 @@ public class RadialFilmCapacitor extends AbstractLeadedComponent<Capacitance> {
public static Color BORDER_COLOR = BODY_COLOR.darker();
private Capacitance value = new Capacitance(123d, CapacitanceUnit.nF);
private Voltage voltage = Voltage._63V;
public RadialFilmCapacitor() {
super();
this.bodyColor = BODY_COLOR;
this.borderColor = BORDER_COLOR;
}
@EditableProperty
@@ -42,16 +39,6 @@ public class RadialFilmCapacitor extends AbstractLeadedComponent<Capacitance> {
public void setValue(Capacitance value) {
this.value = value;
}
@EditableProperty
public Voltage getVoltage() {
return voltage;
}
public void setVoltage(Voltage voltage) {
this.voltage = voltage;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.rotate(-Math.PI / 4, width / 2, height / 2);
@@ -64,19 +51,29 @@ public class RadialFilmCapacitor extends AbstractLeadedComponent<Capacitance> {
}
@Override
protected Size getDefaultWidth() {
protected Size getDefaultHeight() {
return DEFAULT_HEIGHT;
}
@Override
protected Size getDefaultLength() {
protected Size getDefaultWidth() {
return DEFAULT_WIDTH;
}
@Override
protected Color getDefaultBodyColor() {
return BODY_COLOR;
}
@Override
protected Color getDefaultBorderColor() {
return BORDER_COLOR;
}
@Override
protected Shape getBodyShape() {
double radius = getWidth().convertToPixels() * 0.7;
return new RoundRectangle2D.Double(0f, 0f, getLength().convertToPixels(),
getClosestOdd(getWidth().convertToPixels()), radius, radius);
double radius = getHeight().convertToPixels() * 0.7;
return new RoundRectangle2D.Double(0f, 0f, getWidth().convertToPixels(),
getClosestOdd(getHeight().convertToPixels()), radius, radius);
}
}
@@ -5,15 +5,11 @@ import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import org.diylc.common.ObjectCache;
import org.diylc.common.ResistorColorCode;
import org.diylc.components.AbstractLeadedComponent;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Theme;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
import org.diylc.core.annotations.PositiveMeasureValidator;
import org.diylc.core.measures.Resistance;
import org.diylc.core.measures.ResistanceUnit;
import org.diylc.core.measures.Size;
@@ -30,21 +26,12 @@ public class Resistor extends AbstractLeadedComponent<Resistance> {
public static Color BORDER_COLOR = BODY_COLOR.darker();
private Resistance value = new Resistance(123d, ResistanceUnit.K);
private Power power = Power.HALF;
private ResistorColorCode colorCode = ResistorColorCode._5_BAND;
public Resistor() {
super();
this.bodyColor = BODY_COLOR;
this.borderColor = BORDER_COLOR;
}
@Override
protected boolean supportsStandingMode() {
return true;
}
@EditableProperty(validatorClass = PositiveMeasureValidator.class)
@EditableProperty
public Resistance getValue() {
return value;
}
@@ -53,70 +40,39 @@ public class Resistor extends AbstractLeadedComponent<Resistance> {
this.value = value;
}
@EditableProperty
public Power getPower() {
return power;
}
public void setPower(Power power) {
this.power = power;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.rotate(-Math.PI / 4, width / 2, height / 2);
g2d.setColor(LEAD_COLOR);
g2d.drawLine(0, height / 2, width, height / 2);
g2d.setColor(BODY_COLOR);
g2d.fillRect(4, height / 2 - 3, width - 8, 6);
g2d.setColor(Color.red);
g2d.drawLine(7, height / 2 - 3, 7, height / 2 + 3);
g2d.setColor(Color.orange);
g2d.drawLine(11, height / 2 - 3, 11, height / 2 + 3);
g2d.setColor(Color.black);
g2d.drawLine(15, height / 2 - 3, 15, height / 2 + 3);
g2d.setColor(BORDER_COLOR);
g2d.drawRect(4, height / 2 - 3, width - 8, 6);
}
@Override
protected Size getDefaultWidth() {
protected Size getDefaultHeight() {
return DEFAULT_HEIGHT;
}
@Override
protected Size getDefaultLength() {
protected Size getDefaultWidth() {
return DEFAULT_WIDTH;
}
@EditableProperty(name = "Color code")
public ResistorColorCode getColorCode() {
return colorCode;
@Override
protected Color getDefaultBodyColor() {
return BODY_COLOR;
}
public void setColorCode(ResistorColorCode colorCode) {
this.colorCode = colorCode;
@Override
protected Color getDefaultBorderColor() {
return BORDER_COLOR;
}
@Override
protected Shape getBodyShape() {
return new Rectangle2D.Double(0f, 0f, getLength().convertToPixels(),
getClosestOdd(getWidth().convertToPixels()));
}
@Override
protected void decorateComponentBody(Graphics2D g2d) {
// int width = getWidth().convertToPixels();
if (colorCode == ResistorColorCode.NONE) {
return;
}
int height = getClosestOdd(getWidth().convertToPixels());
Color[] bands = value.getColorCode(colorCode);
int x = 4;
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(2));
for (int i = 0; i < bands.length; i++) {
g2d.setColor(bands[i]);
g2d.drawLine(x, 1, x, height - 1);
x += 5;
}
return new Rectangle2D.Double(0f, 0f, getWidth().convertToPixels(),
getClosestOdd(getHeight().convertToPixels()));
}
}
@@ -1,84 +0,0 @@
package org.diylc.components.passive;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import org.diylc.components.AbstractSchematicLeadedSymbol;
import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
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 = "Resistor (schematic symbol)", author = "Branislav Stojkovic", category = "Passive", creationMethod = CreationMethod.POINT_BY_POINT, instanceNamePrefix = "R", description = "", zOrder = IDIYComponent.COMPONENT)
public class ResistorSymbol extends AbstractSchematicLeadedSymbol<Resistance> {
private static final long serialVersionUID = 1L;
public static Size DEFAULT_LENGTH = new Size(0.3, SizeUnit.in);
public static Size DEFAULT_WIDTH = new Size(0.08, SizeUnit.in);
private Resistance value = new Resistance(100d, ResistanceUnit.K);
private Power power = Power.HALF;
@EditableProperty
public Resistance getValue() {
return value;
}
public void setValue(Resistance value) {
this.value = value;
}
@EditableProperty
public Power getPower() {
return power;
}
public void setPower(Power power) {
this.power = power;
}
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.rotate(-Math.PI / 4, width / 2, height / 2);
g2d.setColor(LEAD_COLOR);
g2d.drawLine(0, height / 2, 4, height / 2);
g2d.drawLine(width - 4, height / 2, width, height / 2);
g2d.setColor(COLOR);
g2d.drawPolyline(new int[] { 4, 6, 10, 14, 18, 22, 26, 28 }, new int[] { height / 2,
height / 2 + 2, height / 2 - 2, height / 2 + 2, height / 2 - 2, height / 2 + 2,
height / 2 - 2, height / 2 }, 8);
}
@Override
protected Size getDefaultWidth() {
return DEFAULT_WIDTH;
}
@Override
protected Size getDefaultLength() {
return DEFAULT_LENGTH;
}
@Override
protected Shape getBodyShape() {
GeneralPath polyline = new GeneralPath();
double length = getLength().convertToPixels();
double width = getWidth().convertToPixels();
polyline.moveTo(0, width / 2);
polyline.lineTo(length / 16, width);
polyline.lineTo(3 * length / 16, 0);
polyline.lineTo(5 * length / 16, width);
polyline.lineTo(7 * length / 16, 0);
polyline.lineTo(9 * length / 16, width);
polyline.lineTo(11 * length / 16, 0);
polyline.lineTo(13 * length / 16, width);
polyline.lineTo(15 * length / 16, 0);
polyline.lineTo(length, width / 2);
return polyline;
}
}
@@ -1,28 +0,0 @@
package org.diylc.components.passive;
import org.diylc.core.measures.Resistance;
public class ResistorValue {
private Resistance resistance;
private Power power;
public ResistorValue(Resistance resistance, Power power) {
super();
this.resistance = resistance;
this.power = power;
}
public Resistance getResistance() {
return resistance;
}
public Power getPower() {
return power;
}
@Override
public String toString() {
return resistance.toString() + power.toString();
}
}

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