Compare commits

..

1 Commits

Author SHA1 Message Date
bancika 2e2f42eaaa 2011-01-23 18:36:27 +00:00
139 changed files with 1744 additions and 4588 deletions
+1
View File
@@ -10,6 +10,7 @@
<classpathentry kind="lib" path="lib/cloning-1.5.jar"/>
<classpathentry kind="lib" path="lib/objenesis-1.1.jar"/>
<classpathentry kind="lib" path="lib/bancika-gui-framework.jar"/>
<classpathentry kind="lib" path="lib/HttpProxy.jar"/>
<classpathentry kind="lib" path="lib/jettison-1.0.1.jar"/>
<classpathentry kind="lib" path="lib/poi-3.5-FINAL-20090928.jar"/>
<classpathentry kind="lib" path="library/main.jar"/>
+1 -1
View File
@@ -11,5 +11,5 @@
<stringAttribute key="org.eclipse.debug.core.source_locator_memento" value="&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt;&#13;&#10;&lt;sourceLookupDirector&gt;&#13;&#10;&lt;sourceContainers duplicates=&quot;false&quot;&gt;&#13;&#10;&lt;container memento=&quot;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; standalone=&amp;quot;no&amp;quot;?&amp;gt;&amp;#13;&amp;#10;&amp;lt;javaProject name=&amp;quot;Library&amp;quot;/&amp;gt;&amp;#13;&amp;#10;&quot; typeId=&quot;org.eclipse.jdt.launching.sourceContainer.javaProject&quot;/&gt;&#13;&#10;&lt;container memento=&quot;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; standalone=&amp;quot;no&amp;quot;?&amp;gt;&amp;#13;&amp;#10;&amp;lt;javaProject name=&amp;quot;DIYLC&amp;quot;/&amp;gt;&amp;#13;&amp;#10;&quot; typeId=&quot;org.eclipse.jdt.launching.sourceContainer.javaProject&quot;/&gt;&#13;&#10;&lt;container memento=&quot;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; standalone=&amp;quot;no&amp;quot;?&amp;gt;&amp;#13;&amp;#10;&amp;lt;default/&amp;gt;&amp;#13;&amp;#10;&quot; typeId=&quot;org.eclipse.debug.core.containerType.default&quot;/&gt;&#13;&#10;&lt;/sourceContainers&gt;&#13;&#10;&lt;/sourceLookupDirector&gt;&#13;&#10;"/>
<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.diylc.DIYLCStarter"/>
<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="DIYLC"/>
<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-Xms256m -Xmx512m"/>
<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-Xms64m -Xmx256m"/>
</launchConfiguration>
+1 -9
View File
@@ -1,7 +1,7 @@
<map>
<entry>
<string>lastPath</string>
<string>C:\Documents and Settings\Branislav Stojkovic\Desktop\oldFiles</string>
<string>C:\Documents and Settings\Branislav Stojkovic\Desktop</string>
</entry>
<entry>
<string>zoom</string>
@@ -11,12 +11,4 @@
<string>metric</string>
<boolean>true</boolean>
</entry>
<entry>
<string>showTemplatesAtStartup</string>
<boolean>false</boolean>
</entry>
<entry>
<string>default.org.diylc.components.semiconductors.TransistorTO92:Orientation</string>
<org.diylc.common.Orientation>DEFAULT</org.diylc.common.Orientation>
</entry>
</map>
Binary file not shown.
Binary file not shown.
Binary file not shown.
+4 -14
View File
@@ -8,11 +8,9 @@ import javax.swing.UIManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.diylc.gui.MainFrame;
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;
/**
@@ -39,7 +37,7 @@ public class DIYLCStarter {
} catch (Exception e) {
LOG.error("Could not initialize log4j configuration", e);
}
LOG.info("Starting DIYLC with working directory " + System.getProperty("user.dir"));
try {
@@ -51,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 {
@@ -70,5 +59,6 @@ public class DIYLCStarter {
} catch (Exception e) {
LOG.error("Could not read config.properties file", e);
}
}
}
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.edit;
package org.diylc.common;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
@@ -10,24 +10,33 @@ import java.util.List;
import org.diylc.core.IDIYComponent;
/**
* Represents component selection as a {@link List} of {@link IDIYComponent}
* objects. Implements {@link Transferable}, so it is suitable for clipboard
* usage.
* Represents component selection as a {@link List} of
* {@link IDIYComponent} objects. Implements {@link Transferable}, so it is
* suitable for clipboard usage.
*
* @author Branislav Stojkovic
*/
public class ComponentTransferable extends ArrayList<IDIYComponent<?>> implements Transferable {
public class ComponentSelection extends ArrayList<IDIYComponent<?>> implements Transferable {
private static final long serialVersionUID = 1L;
public static final DataFlavor listFlavor = new DataFlavor(ComponentTransferable.class, "application/diylc");
public static final DataFlavor listFlavor = new DataFlavor(List.class, "Java List");
public static final ComponentSelection EMPTY_SELECTION = new ComponentSelection();
public static ComponentSelection of(IDIYComponent<?> component) {
ComponentSelection selection = new ComponentSelection();
selection.add(component);
return selection;
}
public ComponentTransferable() {
public ComponentSelection() {
super();
}
public ComponentTransferable(Collection<IDIYComponent<?>> selectedComponents) {
public ComponentSelection(Collection<IDIYComponent<?>> selectedComponents) {
super(selectedComponents);
}
+6 -8
View File
@@ -48,6 +48,10 @@ public enum EventType {
* object containing selection size (x = width, y = height). Size is
* expressed in the default measure (cm for metric, inches for imperial).
*/
SELECTION_SIZE_CHANGED,
/**
* Called when display needs to be repainted. No parameters are passed.
*/
REPAINT,
/**
* Called when new component slot has been changed. The only parameter is
@@ -72,12 +76,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;
;
}
+53 -28
View File
@@ -4,11 +4,16 @@ import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.SwingConstants;
import javax.swing.JPopupMenu.Separator;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
@@ -29,7 +34,7 @@ import com.diyfever.gui.update.VersionNumber;
* @see EventType
*/
public interface IPlugInPort {
public static final String CHECK_BOX_MENU_ITEM = "org.diylc.checkBoxMenuItem";
/**
@@ -127,6 +132,49 @@ public interface IPlugInPort {
*/
void draw(Graphics2D g2d, Set<DrawOption> drawOptions, IComponentFiler filter);
/**
* Injects a custom GUI panels provided by the plug-in and desired position
* in the window. Application will layout plug-in panels accordingly. <br>
* Valid positions are:
* <ul>
* <li> {@link SwingConstants#TOP}</li>
* <li> {@link SwingConstants#BOTTOM}</li>
* <li> {@link SwingConstants#LEFT}</li>
* <li> {@link SwingConstants#RIGHT}</li>
* </ul>
*
* Center position is reserved for the main canvas panel and cannot be used.
*
* @param component
* @param position
* @throws BadPositionException
* in case invalid position is specified
*/
void injectGUIComponent(JComponent component, int position) throws BadPositionException;
/**
* Injects a custom menu action into application's main menu. If
* <code>action</code> is set to null {@link Separator} will be added. If
* the specified menu does not exist it will be automatically created.
*
* @param action
* {@link Action} to inser
* @param menuName
* name of the menu to insert into
*/
void injectMenuAction(Action action, String menuName);
/**
* Injects a custom submenu into application's main menu. If
* <code>action</code> is set to null {@link Separator} will be added. If
* the specified menu does not exist it will be automatically created.
*
* @param name
* @param icon
* @param parentMenuName
*/
void injectSubmenu(String name, Icon icon, String parentMenuName);
Double[] getAvailableZoomLevels();
/**
@@ -170,11 +218,11 @@ public interface IPlugInPort {
void mouseMoved(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown);
/**
* Returns the current {@link ComponentTransferable}.
* Returns the current {@link ComponentSelection}.
*
* @return
*/
List<IDIYComponent<?>> getSelectedComponents();
ComponentSelection getSelectedComponents();
/**
* Selects all components in the project.
@@ -303,29 +351,6 @@ public interface IPlugInPort {
* Ungroups all selected components.
*/
void ungroupSelectedComponents();
/**
* Locks or unlocks the specified layer. All components within +- 0.5 range
* will be affected by the change as well.
*
* @param layerZOrder
* @param locked
*/
void setLayerLocked(int layerZOrder, boolean locked);
/**
* @return selection size expressed in either inches or centimeters, based
* on the user preference.
*/
Point2D calculateSelectionDimension();
/**
* Sends each of the selected components one step back.
*/
void sendSelectionToBack();
/**
* Brings each of the selected components one step to front.
*/
void bringSelectionToFront();
}
-34
View File
@@ -1,34 +0,0 @@
package org.diylc.common;
/**
* Abstract layer between the app and platform worker thread implementation.
*
* @author Branislav Stojkovic
*
* @param <T>
*/
public interface ITask<T> {
/**
* Runs in background thread.
*
* @return
* @throws Exception
*/
T doInBackground() throws Exception;
/**
* Called if background thread fails.
*
* @param e
*/
void failed(Exception e);
/**
* Called if background thread is executed correctly, the result is passed
* as a parameter.
*
* @param result
*/
void complete(T result);
}
+1 -1
View File
@@ -32,7 +32,7 @@ public class ObjectCache {
if (basicStrokeMap.containsKey(width)) {
return basicStrokeMap.get(width);
}
Stroke stroke = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
Stroke stroke = new BasicStroke(width);
basicStrokeMap.put(width, stroke);
return stroke;
}
-5
View File
@@ -1,5 +0,0 @@
package org.diylc.common;
public enum Power {
}
@@ -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();
}
}
@@ -35,11 +35,6 @@ public abstract class AbstractComponent<T> implements IDIYComponent<T> {
public void setName(String name) {
this.name = name;
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
}
@Override
public String toString() {
@@ -105,13 +105,7 @@ public abstract class AbstractCurvedComponent<T> extends AbstractTransparentComp
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public boolean canControlPointOverlap(int index) {
// Only shape control points may overlap.
return index == 1 || index == 2;
return index == 0 || index == 3 ? VisibilityPolicy.ALWAYS : VisibilityPolicy.WHEN_SELECTED;
}
@Override
@@ -35,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(DEFAULT_SIZE.convertToPixels() / 2, 0) };
protected Color bodyColor = Color.white;
protected Color borderColor = Color.black;
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) {
@@ -145,16 +145,16 @@ public abstract class AbstractLeadedComponent<T> extends AbstractTransparentComp
}
/**
* @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
@@ -162,6 +162,16 @@ 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.
*/
@@ -220,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;
}
@@ -238,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,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 {
}
}
+11 -20
View File
@@ -30,11 +30,15 @@ import org.diylc.core.annotations.EditableProperty;
*/
public interface IDIYComponent<T> extends Serializable {
public static final int CHASSIS = 1;
public static final int BOARD = 2;
public static final int TRACE = 3;
public static final int COMPONENT = 4;
public static final int TEXT = 5;
public static final int BELOW_CHASSIS = 1;
public static final int CHASSIS = 2;
public static final int ABOVE_CHASSIS = 3;
public static final int BELOW_BOARD = 4;
public static final int BOARD = 5;
public static final int ABOVE_BOARD = 6;
public static final int BELOW_COMPONENT = 7;
public static final int COMPONENT = 8;
public static final int ABOVE_COMPONENT = 9;
/**
* @return component instance name.
@@ -80,22 +84,9 @@ public interface IDIYComponent<T> extends Serializable {
* @param index
*/
void setControlPoint(Point point, int index);
/**
* @param index
* @return true, if the specified control point may stick to control points
* of other components.
*/
boolean isControlPointSticky(int index);
/**
* @param index
* @return true, if the specified control point may overlap with other
* control points <b>of the same component</b>. The other control
* point must be able to overlap too.
*/
boolean canControlPointOverlap(int index);
VisibilityPolicy getControlPointVisibilityPolicy(int index);
/**
@@ -1,16 +0,0 @@
package org.diylc.core;
/**
* Interface for validating property value changes.
*
* @author Branislav Stojkovic
*/
public interface IPropertyValidator {
/**
* @param value
* @throws ValidationException
* if validation fails. Message will contain the reason.
*/
void validate(Object value) throws ValidationException;
}
-28
View File
@@ -1,28 +0,0 @@
package org.diylc.core;
/**
* Base interface for the main GUI component.
*
* @author Branislav Stojkovic
*/
public interface IView {
public static final int ERROR_MESSAGE = 0;
public static final int INFORMATION_MESSAGE = 1;
public static final int WARNING_MESSAGE = 2;
public static final int QUESTION_MESSAGE = 3;
public static final int PLAIN_MESSAGE = -1;
public static final int DEFAULT_OPTION = -1;
public static final int YES_NO_OPTION = 0;
public static final int YES_NO_CANCEL_OPTION = 1;
public static final int OK_CANCEL_OPTION = 2;
public static final int YES_OPTION = 0;
public static final int NO_OPTION = 1;
public static final int CANCEL_OPTION = 2;
public static final int OK_OPTION = 0;
void showMessage(String message, String title, int messageType);
int showConfirmDialog(String message, String title, int optionType, int messageType);
}
+3 -19
View File
@@ -7,7 +7,6 @@ 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;
@@ -93,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;
}
@@ -119,7 +118,7 @@ public class Project implements Serializable {
public Set<Set<IDIYComponent<?>>> getGroups() {
return groups;
}
public Set<Integer> getLockedLayers() {
return lockedLayers;
}
@@ -178,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
@@ -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.");
}
}
}
@@ -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) Math.round(base / 10)];
bands[1] = COLOR_DIGITS[(int) Math.round(base % 10)];
bands[2] = COLOR_MULTIPLIER[multiplier + 2];
break;
case _5_BAND:
bands = new Color[4];
bands[0] = COLOR_DIGITS[(int) Math.round(base / 100)];
bands[1] = COLOR_DIGITS[(int) Math.round(base / 10 % 10)];
bands[2] = COLOR_DIGITS[(int) Math.round(base % 10)];
bands[3] = COLOR_MULTIPLIER[multiplier + 2];
break;
default:
bands = new Color[] {};
}
return bands;
}
public static Resistance parseResistance(String value) {
for (ResistanceUnit unit : ResistanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
+1 -6
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;
@@ -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,4 +1,4 @@
package org.diylc.swing.gui;
package org.diylc.gui;
import java.awt.Graphics;
import java.awt.Graphics2D;
@@ -1,4 +1,4 @@
package org.diylc.swing.gui;
package org.diylc.gui;
import java.io.File;
import java.util.List;
@@ -9,13 +9,13 @@ import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;
import org.diylc.common.PropertyWrapper;
import org.diylc.swing.gui.components.OverwritePromptFileChooser;
import org.diylc.swing.gui.editor.PropertyEditorDialog;
import org.diylc.swing.plugins.file.BomDialog;
import org.diylc.swing.plugins.file.BomEntry;
import org.diylc.swing.plugins.online.view.LoginDialog;
import org.diylc.swing.plugins.online.view.NewUserDialog;
import org.diylc.swing.plugins.online.view.UploadDialog;
import org.diylc.gui.components.OverwritePromptFileChooser;
import org.diylc.gui.editor.PropertyEditorDialog;
import org.diylc.plugins.file.BomDialog;
import org.diylc.plugins.file.BomEntry;
import org.diylc.plugins.online.view.LoginDialog;
import org.diylc.plugins.online.view.NewUserDialog;
import org.diylc.plugins.online.view.UploadDialog;
import com.diyfever.gui.AboutDialog;
import com.diyfever.gui.IFileChooserAccessory;
+54
View File
@@ -0,0 +1,54 @@
package org.diylc.gui;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import org.diylc.common.BadPositionException;
import org.diylc.common.IPlugInPort;
/**
* Base interface for the main GUI component.
*
* @author Branislav Stojkovic
*/
public interface IView {
/**
* Adds a component to the view.
*
* @param component
* component to insert
* @param position
* target position
* @throws BadPositionException
*
* @see IPlugInPort#injectGUIComponent
*/
void addComponent(JComponent component, int position) throws BadPositionException;
/**
* Adds a menu action.
*
* @param action
* action to insert
* @param menuName
* target menu name
*
* @see IPlugInPort#injectMenuAction
*/
void addMenuAction(Action action, String menuName);
/**
* Adds a submenu to an existing menu.
*
* @param name
* @param icon
* @param parentMenuName
*/
void addSubmenu(String name, Icon icon, String parentMenuName);
void showMessage(String message, String title, int messageType);
int showConfirmDialog(String message, String title, int optionType, int messageType);
}
@@ -1,8 +1,7 @@
package org.diylc.swing.gui;
package org.diylc.gui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@@ -24,29 +23,23 @@ import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.common.ITask;
import org.diylc.images.IconLoader;
import org.diylc.plugins.canvas.CanvasPlugin;
import org.diylc.plugins.clipboard.EditMenuPlugin;
import org.diylc.plugins.file.FileMenuPlugin;
import org.diylc.plugins.help.HelpMenuPlugin;
import org.diylc.plugins.layers.LayersMenuPlugin;
import org.diylc.plugins.statusbar.StatusBar;
import org.diylc.plugins.toolbox.ToolBox;
import org.diylc.presenter.Presenter;
import org.diylc.swing.ISwingUI;
import org.diylc.swing.plugins.canvas.CanvasPlugin;
import org.diylc.swing.plugins.edit.EditMenuPlugin;
import org.diylc.swing.plugins.file.FileMenuPlugin;
import org.diylc.swing.plugins.help.HelpMenuPlugin;
import org.diylc.swing.plugins.layers.LayersMenuPlugin;
import org.diylc.swing.plugins.statusbar.StatusBar;
import org.diylc.swing.plugins.toolbox.ToolBox;
public class MainFrame extends JFrame implements ISwingUI {
private static final Logger LOG = Logger.getLogger(MainFrame.class);
public class MainFrame extends JFrame implements IView {
private static final long serialVersionUID = 1L;
@@ -75,15 +68,15 @@ public class MainFrame extends JFrame implements ISwingUI {
this.presenter = new Presenter(this);
presenter.installPlugin(new ToolBox(this));
presenter.installPlugin(new FileMenuPlugin(this));
presenter.installPlugin(new EditMenuPlugin(this));
presenter.installPlugin(new LayersMenuPlugin(this));
presenter.installPlugin(new ToolBox());
presenter.installPlugin(new FileMenuPlugin());
presenter.installPlugin(new EditMenuPlugin());
presenter.installPlugin(new LayersMenuPlugin());
// presenter.installPlugin(new OnlineManager());
presenter.installPlugin(new HelpMenuPlugin(this));
presenter.installPlugin(new HelpMenuPlugin());
presenter.installPlugin(new StatusBar(this));
canvasPlugin = new CanvasPlugin(this);
presenter.installPlugin(new StatusBar());
canvasPlugin = new CanvasPlugin();
presenter.installPlugin(canvasPlugin);
presenter.installPlugin(new FramePlugin());
@@ -113,10 +106,6 @@ public class MainFrame extends JFrame implements ISwingUI {
// setGlassPane(new CustomGlassPane());
// getGlassPane().setVisible(true);
}
public Presenter getPresenter() {
return presenter;
}
@Override
public void setVisible(boolean b) {
@@ -180,31 +169,7 @@ public class MainFrame extends JFrame implements ISwingUI {
// IView
@Override
public void showMessage(String message, String title, int messageType) {
JOptionPane.showMessageDialog(this, message, title, messageType);
}
@Override
public int showConfirmDialog(String message, String title, int optionType, int messageType) {
return JOptionPane.showConfirmDialog(this, message, title, optionType, messageType);
}
private JMenu findOrCreateMenu(String menuName) {
JMenu menu;
if (menuMap.containsKey(menuName)) {
menu = menuMap.get(menuName);
} else {
menu = new JMenu(menuName);
menuMap.put(menuName, menu);
getMainMenuBar().add(menu);
}
return menu;
}
@Override
public void injectGUIComponent(JComponent component, int position) throws BadPositionException {
LOG.info(String.format("injectGUIComponent(%s, %s)", component.getClass().getName(),
position));
public void addComponent(JComponent component, int position) throws BadPositionException {
switch (position) {
case SwingConstants.TOP:
topPanel.add(component);
@@ -228,9 +193,7 @@ public class MainFrame extends JFrame implements ISwingUI {
}
@Override
public void injectMenuAction(Action action, String menuName) {
LOG.info(String.format("injectMenuAction(%s, %s)", action == null ? "Separator" : action
.getValue(Action.NAME), menuName));
public void addMenuAction(Action action, String menuName) {
JMenu menu = findOrCreateMenu(menuName);
if (action == null) {
menu.addSeparator();
@@ -245,8 +208,7 @@ public class MainFrame extends JFrame implements ISwingUI {
}
@Override
public void injectSubmenu(String name, Icon icon, String parentMenuName) {
LOG.info(String.format("injectSubmenu(%s, icon, %s)", name, parentMenuName));
public void addSubmenu(String name, Icon icon, String parentMenuName) {
JMenu menu = findOrCreateMenu(parentMenuName);
JMenu submenu = new JMenu(name);
submenu.setIcon(icon);
@@ -255,28 +217,25 @@ public class MainFrame extends JFrame implements ISwingUI {
}
@Override
public <T extends Object> void executeBackgroundTask(final ITask<T> task) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
SwingWorker<T, Void> worker = new SwingWorker<T, Void>() {
public void showMessage(String message, String title, int messageType) {
JOptionPane.showMessageDialog(this, message, title, messageType);
}
@Override
protected T doInBackground() throws Exception {
return task.doInBackground();
}
@Override
public int showConfirmDialog(String message, String title, int optionType, int messageType) {
return JOptionPane.showConfirmDialog(this, message, title, optionType, messageType);
}
@Override
protected void done() {
try {
T result = get();
task.complete(result);
} catch (Exception e) {
LOG.error("Task failed", e);
task.failed(e);
}
setCursor(Cursor.getDefaultCursor());
}
};
worker.execute();
private JMenu findOrCreateMenu(String menuName) {
JMenu menu;
if (menuMap.containsKey(menuName)) {
menu = menuMap.get(menuName);
} else {
menu = new JMenu(menuName);
menuMap.put(menuName, menu);
getMainMenuBar().add(menu);
}
return menu;
}
class FramePlugin implements IPlugIn {
@@ -301,10 +260,9 @@ 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,4 +1,4 @@
package org.diylc.swing.gui.components;
package org.diylc.gui.components;
import java.io.File;
@@ -1,4 +1,4 @@
package org.diylc.swing.gui.editor;
package org.diylc.gui.editor;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
@@ -1,4 +1,4 @@
package org.diylc.swing.gui.editor;
package org.diylc.gui.editor;
import java.awt.Color;
import java.awt.Cursor;
@@ -1,4 +1,4 @@
package org.diylc.swing.gui.editor;
package org.diylc.gui.editor;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
@@ -1,9 +1,8 @@
package org.diylc.swing.gui.editor;
package org.diylc.gui.editor;
import java.awt.Color;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import org.apache.log4j.Logger;
@@ -27,23 +26,14 @@ public class FieldEditorFactory {
MeasureEditor editor = new MeasureEditor(property);
return editor;
}
if (ImageIcon.class.isAssignableFrom(property.getType())) {
ImageEditor editor = new ImageEditor(property);
return editor;
}
if (property.getType().isEnum()) {
EnumEditor editor = new EnumEditor(property);
return editor;
}
if (Byte.class.isAssignableFrom(property.getType())
|| byte.class.isAssignableFrom(property.getType())) {
ByteEditor editor = new ByteEditor(property);
return editor;
}
if (Boolean.class.isAssignableFrom(property.getType())
|| boolean.class.isAssignableFrom(property.getType())) {
BooleanEditor editor = new BooleanEditor(property);
return editor;
ByteEditor byteEditor = new ByteEditor(property);
return byteEditor;
}
LOG.error("Unrecognized parameter type: " + property.getType().getName());
return new JLabel("Unrecognized");
@@ -1,4 +1,4 @@
package org.diylc.swing.gui.editor;
package org.diylc.gui.editor;
import java.awt.Color;
import java.awt.Cursor;
@@ -1,4 +1,4 @@
package org.diylc.swing.gui.editor;
package org.diylc.gui.editor;
import java.awt.BorderLayout;
import java.awt.Container;
@@ -1,4 +1,4 @@
package org.diylc.swing.gui.editor;
package org.diylc.gui.editor;
import java.awt.Component;
import java.awt.Dimension;
@@ -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,4 +1,4 @@
package org.diylc.swing.gui.editor;
package org.diylc.gui.editor;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
+1 -1
View File
@@ -30,7 +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");
"edit_component.png");
protected String name;
Binary file not shown.

Before

Width:  |  Height:  |  Size: 537 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 535 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 550 B

@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.canvas;
package org.diylc.plugins.canvas;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.canvas;
package org.diylc.plugins.canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
@@ -16,6 +16,7 @@ import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
@@ -30,8 +31,8 @@ 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 org.diylc.gui.DialogFactory;
import org.diylc.gui.editor.PropertyEditorDialog;
import com.diyfever.gui.ButtonDialog;
@@ -154,18 +155,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
@@ -0,0 +1,150 @@
package org.diylc.plugins.canvas;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.EnumSet;
import javax.swing.SwingConstants;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.plugins.file.ProjectDrawingProvider;
import org.diylc.presenter.Presenter;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.diyfever.gui.ruler.IRulerListener;
import com.diyfever.gui.ruler.RulerScrollPane;
public class CanvasPlugin implements IPlugIn {
private static final Logger LOG = Logger.getLogger(CanvasPlugin.class);
private RulerScrollPane scrollPane;
private CanvasPanel canvasPanel;
private IPlugInPort plugInPort;
public CanvasPlugin() {
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
try {
plugInPort.injectGUIComponent(getScrollPane(), SwingConstants.CENTER);
} catch (BadPositionException e) {
LOG.error("Could not install canvas plugin", e);
}
}
public CanvasPanel getCanvasPanel() {
if (canvasPanel == null) {
canvasPanel = new CanvasPanel(plugInPort);
}
return canvasPanel;
}
private RulerScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new RulerScrollPane(getCanvasPanel(), new ProjectDrawingProvider(
plugInPort, true), new Size(1d, SizeUnit.cm).convertToPixels(), new Size(1d,
SizeUnit.in).convertToPixels());
boolean metric = ConfigurationManager.getInstance().readBoolean(Presenter.METRIC_KEY,
true);
scrollPane.setMetric(metric);
scrollPane.setWheelScrollingEnabled(false);
scrollPane.addUnitListener(new IRulerListener() {
@Override
public void unitsChanged(boolean isMetric) {
plugInPort.setMetric(isMetric);
}
});
scrollPane.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
double d = plugInPort.getZoomLevel();
Double[] availableZoomLevels = plugInPort.getAvailableZoomLevels();
if (e.getWheelRotation() > 0) {
int i = availableZoomLevels.length - 1;
while (i > 0 && availableZoomLevels[i] >= d) {
i--;
}
plugInPort.setZoomLevel(availableZoomLevels[i]);
} else {
int i = 0;
while (i < availableZoomLevels.length - 1 && availableZoomLevels[i] <= d) {
i++;
}
plugInPort.setZoomLevel(availableZoomLevels[i]);
}
}
});
}
return scrollPane;
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.PROJECT_LOADED, EventType.ZOOM_CHANGED, EventType.REPAINT);
}
@Override
public void processMessage(final EventType eventType, Object... params) {
// SwingUtilities.invokeLater(new Runnable() {
//
// @Override
// public void run() {
// LOG.debug("event: " + eventType);
switch (eventType) {
case PROJECT_LOADED:
refreshSize();
if ((Boolean) params[1]) {
// Scroll to the center.
Rectangle visibleRect = canvasPanel.getVisibleRect();
visibleRect.setLocation((canvasPanel.getWidth() - visibleRect.width) / 2,
(canvasPanel.getHeight() - visibleRect.height) / 2);
canvasPanel.scrollRectToVisible(visibleRect);
canvasPanel.revalidate();
}
// canvasPanel.validate();
// canvasPanel.repaint();
break;
case ZOOM_CHANGED:
refreshSize();
break;
case REPAINT:
canvasPanel.repaint();
break;
}
// }
// });
}
private void refreshSize() {
Dimension d = plugInPort.getCanvasDimensions(true);
canvasPanel.setSize(d);
canvasPanel.setPreferredSize(d);
getScrollPane().setZoomLevel(plugInPort.getZoomLevel());
}
/**
* Causes ruller scroll pane to refresh by sending a fake mouse moved
* message to the canvasPanel.
*/
public void refresh() {
MouseEvent event = new MouseEvent(canvasPanel, MouseEvent.MOUSE_MOVED, System
.currentTimeMillis(), 0, 1, 1,// canvasPanel.getWidth() / 2,
// canvasPanel.getHeight() / 2,
0, false);
canvasPanel.dispatchEvent(event);
}
}
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.canvas;
package org.diylc.plugins.canvas;
import java.awt.Point;
import java.awt.dnd.DragSourceDragEvent;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.canvas;
package org.diylc.plugins.canvas;
import java.awt.Point;
import java.awt.dnd.DnDConstants;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.canvas;
package org.diylc.plugins.canvas;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.canvas;
package org.diylc.plugins.canvas;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.canvas;
package org.diylc.plugins.canvas;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
@@ -0,0 +1,316 @@
package org.diylc.plugins.clipboard;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.EnumSet;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.KeyStroke;
import org.apache.log4j.Logger;
import org.diylc.common.ComponentSelection;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.gui.DialogFactory;
import org.diylc.gui.editor.PropertyEditorDialog;
import org.diylc.images.IconLoader;
import com.diyfever.gui.ButtonDialog;
import com.diyfever.gui.undo.IUndoListener;
import com.diyfever.gui.undo.UndoHandler;
import com.rits.cloning.Cloner;
public class EditMenuPlugin implements IPlugIn, ClipboardOwner {
private static final Logger LOG = Logger.getLogger(EditMenuPlugin.class);
private static final String EDIT_TITLE = "Edit";
private IPlugInPort plugInPort;
private Clipboard clipboard;
private Cloner cloner;
// private CutAction cutAction;
private CopyAction copyAction;
private PasteAction pasteAction;
private UndoHandler<Project> undoHandler;
public EditMenuPlugin() {
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
cloner = new Cloner();
undoHandler = new UndoHandler<Project>(new IUndoListener<Project>() {
@Override
public void actionPerformed(Project currentState) {
plugInPort.loadProject(currentState, false);
}
});
clipboard.addFlavorListener(new FlavorListener() {
@Override
public void flavorsChanged(FlavorEvent e) {
refreshActions();
}
});
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
plugInPort.injectMenuAction(undoHandler.getUndoAction(), EDIT_TITLE);
plugInPort.injectMenuAction(undoHandler.getRedoAction(), EDIT_TITLE);
plugInPort.injectMenuAction(null, EDIT_TITLE);
// cutAction = new CutAction();
// plugInPort.injectMenuAction(cutAction, EDIT_TITLE);
copyAction = new CopyAction();
plugInPort.injectMenuAction(copyAction, EDIT_TITLE);
pasteAction = new PasteAction();
plugInPort.injectMenuAction(pasteAction, EDIT_TITLE);
plugInPort.injectMenuAction(null, EDIT_TITLE);
plugInPort.injectMenuAction(new SelectAllAction(), EDIT_TITLE);
plugInPort.injectMenuAction(null, EDIT_TITLE);
plugInPort.injectMenuAction(new EditSelectionAction(), EDIT_TITLE);
plugInPort.injectMenuAction(new EditProjectAction(), EDIT_TITLE);
plugInPort.injectMenuAction(null, EDIT_TITLE);
plugInPort.injectMenuAction(new GroupAction(), EDIT_TITLE);
plugInPort.injectMenuAction(new UngroupAction(), EDIT_TITLE);
refreshActions();
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.SELECTION_CHANGED, EventType.PROJECT_MODIFIED);
}
@Override
public void processMessage(EventType eventType, Object... params) {
switch (eventType) {
case SELECTION_CHANGED:
refreshActions();
break;
case PROJECT_MODIFIED:
undoHandler.stateChanged((Project) params[0], (Project) params[1], (String) params[2]);
break;
}
}
private void refreshActions() {
boolean enabled = !plugInPort.getSelectedComponents().isEmpty();
// cutAction.setEnabled(enabled);
copyAction.setEnabled(enabled);
try {
pasteAction.setEnabled(clipboard.isDataFlavorAvailable(ComponentSelection.listFlavor));
} catch (Exception e) {
pasteAction.setEnabled(false);
}
}
class CutAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public CutAction() {
super();
putValue(AbstractAction.NAME, "Cut");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Cut.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Cut triggered");
}
}
class CopyAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public CopyAction() {
super();
putValue(AbstractAction.NAME, "Copy");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Copy.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Copy triggered");
clipboard.setContents(cloner.deepClone(plugInPort.getSelectedComponents()),
EditMenuPlugin.this);
}
}
class PasteAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public PasteAction() {
super();
putValue(AbstractAction.NAME, "Paste");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Paste.getIcon());
}
@SuppressWarnings("unchecked")
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Paste triggered");
try {
List<IDIYComponent<?>> components = (List<IDIYComponent<?>>) clipboard
.getData(ComponentSelection.listFlavor);
plugInPort.pasteComponents(cloner.deepClone(components));
} catch (Exception ex) {
LOG.error("Coule not paste.", ex);
}
}
}
class SelectAllAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public SelectAllAction() {
super();
putValue(AbstractAction.NAME, "Select All");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Selection.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Select All triggered");
plugInPort.selectAll();
}
}
class GroupAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public GroupAction() {
super();
putValue(AbstractAction.NAME, "Group Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_G,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Group.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Group Selection triggered");
plugInPort.groupSelectedComponents();
}
}
class UngroupAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public UngroupAction() {
super();
putValue(AbstractAction.NAME, "Ungroup Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_U,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Ungroup.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Ungroup Selection triggered");
plugInPort.ungroupSelectedComponents();
}
}
class EditProjectAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public EditProjectAction() {
super();
putValue(AbstractAction.NAME, "Edit Project");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.DocumentEdit.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Edit Project triggered");
List<PropertyWrapper> properties = plugInPort.getProjectProperties();
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Project");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToProject(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setProjectDefaultPropertyValue(property.getName(), property
.getValue());
}
}
}
}
class EditSelectionAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public EditSelectionAction() {
super();
putValue(AbstractAction.NAME, "Edit Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.EditComponent.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Edit Selection triggered");
List<PropertyWrapper> properties = plugInPort.getMutualSelectionProperties();
if (properties == null || properties.isEmpty()) {
LOG.info("Nothing to edit");
return;
}
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Selection");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToSelection(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setSelectionDefaultPropertyValue(property.getName(), property
.getValue());
}
}
}
}
// ClipboardOwner
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
refreshActions();
}
}
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.file;
package org.diylc.plugins.file;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
@@ -15,8 +15,8 @@ import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.diylc.gui.DialogFactory;
import org.diylc.images.IconLoader;
import org.diylc.swing.gui.DialogFactory;
import com.diyfever.gui.export.TableExporter;
import com.diyfever.gui.objecttable.ObjectListTable;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.file;
package org.diylc.plugins.file;
public class BomEntry {
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.file;
package org.diylc.plugins.file;
import java.util.ArrayList;
import java.util.Collections;
@@ -1,15 +1,14 @@
package org.diylc.swing.plugins.file;
package org.diylc.plugins.file;
import java.io.File;
import javax.swing.filechooser.FileFilter;
public enum FileFilterEnum {
enum FileFilterEnum {
PNG("PNG Images (*.png)", "png"), PDF("PDF Files (*.pdf)", "pdf"), DIY(
"DIY Project Files (*.diy)", "diy"), EXCEL("Excel Workbooks (*.xls)", "xls"), CSV(
"Comma Separated Files (*.csv)", "csv"), HTML("HTML Files (*.html)", "html"), IMAGES(
"Image Files (*.png, *.jpg, *.gif)", "png", "jpg", "gif");
"Comma Separated Files (*.csv)", "csv"), HTML("HTML Files (*.html)", "html");
FileFilter filter;
String[] extensions;
@@ -0,0 +1,289 @@
package org.diylc.plugins.file;
import java.awt.event.ActionEvent;
import java.awt.print.PrinterException;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.EnumSet;
import java.util.List;
import javax.swing.AbstractAction;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.common.PropertyWrapper;
import org.diylc.gui.DialogFactory;
import org.diylc.gui.editor.PropertyEditorDialog;
import org.diylc.images.IconLoader;
import com.diyfever.gui.ButtonDialog;
import com.diyfever.gui.IDrawingProvider;
import com.diyfever.gui.export.DrawingExporter;
import com.lowagie.text.DocumentException;
/**
* Entry point class for File management utilities.
*
* @author Branislav Stojkovic
*/
public class FileMenuPlugin implements IPlugIn {
private static final String FILE_TITLE = "File";
private static final String TRACE_MASK_TITLE = "Trace Mask";
private IPlugInPort plugInPort;
private ProjectDrawingProvider drawingProvider;
private TraceMaskDrawingProvider traceMaskDrawingProvider;
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
this.drawingProvider = new ProjectDrawingProvider(plugInPort, false);
this.traceMaskDrawingProvider = new TraceMaskDrawingProvider(plugInPort);
plugInPort.injectMenuAction(new NewAction(), FILE_TITLE);
plugInPort.injectMenuAction(new OpenAction(), FILE_TITLE);
plugInPort.injectMenuAction(new SaveAction(), FILE_TITLE);
plugInPort.injectMenuAction(new SaveAsAction(), FILE_TITLE);
plugInPort.injectMenuAction(null, FILE_TITLE);
plugInPort.injectMenuAction(new ExportPDFAction(drawingProvider), FILE_TITLE);
plugInPort.injectMenuAction(new ExportPNGAction(drawingProvider), FILE_TITLE);
plugInPort.injectMenuAction(new PrintAction(drawingProvider), FILE_TITLE);
plugInPort.injectSubmenu(TRACE_MASK_TITLE, IconLoader.TraceMask.getIcon(), FILE_TITLE);
plugInPort
.injectMenuAction(new ExportPDFAction(traceMaskDrawingProvider), TRACE_MASK_TITLE);
plugInPort
.injectMenuAction(new ExportPNGAction(traceMaskDrawingProvider), TRACE_MASK_TITLE);
plugInPort.injectMenuAction(new PrintAction(traceMaskDrawingProvider), TRACE_MASK_TITLE);
plugInPort.injectMenuAction(new CreateBomAction(), FILE_TITLE);
plugInPort.injectMenuAction(null, FILE_TITLE);
plugInPort.injectMenuAction(new ExitAction(), FILE_TITLE);
}
class NewAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public NewAction() {
super();
putValue(AbstractAction.NAME, "New");
putValue(AbstractAction.SMALL_ICON, IconLoader.DocumentPlainYellow.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
if (!plugInPort.allowFileAction()) {
return;
}
plugInPort.createNewProject();
List<PropertyWrapper> properties = plugInPort.getProjectProperties();
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Project");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToProject(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setProjectDefaultPropertyValue(property.getName(), property.getValue());
}
}
}
}
class OpenAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public OpenAction() {
super();
putValue(AbstractAction.NAME, "Open");
putValue(AbstractAction.SMALL_ICON, IconLoader.FolderOut.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
if (!plugInPort.allowFileAction()) {
return;
}
File file = DialogFactory.getInstance().showOpenDialog(FileFilterEnum.DIY.getFilter(),
null, FileFilterEnum.DIY.getExtensions()[0], null);
if (file != null) {
plugInPort.loadProjectFromFile(file.getAbsolutePath());
}
}
}
class SaveAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public SaveAction() {
super();
putValue(AbstractAction.NAME, "Save");
putValue(AbstractAction.SMALL_ICON, IconLoader.DiskBlue.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
if (plugInPort.getCurrentFileName() == null) {
File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.DIY.getFilter(), null,
FileFilterEnum.DIY.getExtensions()[0], null);
if (file != null) {
plugInPort.saveProjectToFile(file.getAbsolutePath());
}
} else {
plugInPort.saveProjectToFile(plugInPort.getCurrentFileName());
}
}
}
class SaveAsAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public SaveAsAction() {
super();
putValue(AbstractAction.NAME, "Save As");
putValue(AbstractAction.SMALL_ICON, IconLoader.DiskBlue.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
File file = DialogFactory.getInstance().showSaveDialog(FileFilterEnum.DIY.getFilter(),
null, FileFilterEnum.DIY.getExtensions()[0], null);
if (file != null) {
plugInPort.saveProjectToFile(file.getAbsolutePath());
}
}
}
class CreateBomAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public CreateBomAction() {
super();
putValue(AbstractAction.NAME, "Create B.O.M.");
putValue(AbstractAction.SMALL_ICON, IconLoader.BOM.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
List<BomEntry> bom = BomMaker.getInstance().createBom(
plugInPort.getCurrentProject().getComponents());
BomDialog dialog = DialogFactory.getInstance().createBomDialog(bom);
dialog.setVisible(true);
}
}
class ExportPDFAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
public ExportPDFAction(IDrawingProvider drawingProvider) {
super();
this.drawingProvider = drawingProvider;
putValue(AbstractAction.NAME, "Export to PDF");
putValue(AbstractAction.SMALL_ICON, IconLoader.PDF.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
File file = DialogFactory.getInstance().showSaveDialog(FileFilterEnum.PDF.getFilter(),
null, FileFilterEnum.PDF.getExtensions()[0], null);
if (file != null) {
try {
DrawingExporter.getInstance().exportPDF(this.drawingProvider, file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
class ExportPNGAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
public ExportPNGAction(IDrawingProvider drawingProvider) {
super();
this.drawingProvider = drawingProvider;
putValue(AbstractAction.NAME, "Export to PNG");
putValue(AbstractAction.SMALL_ICON, IconLoader.Image.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
File file = DialogFactory.getInstance().showSaveDialog(FileFilterEnum.PNG.getFilter(),
null, FileFilterEnum.PNG.getExtensions()[0], null);
if (file != null) {
DrawingExporter.getInstance().exportPNG(this.drawingProvider, file);
}
}
}
class PrintAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
public PrintAction(IDrawingProvider drawingProvider) {
super();
this.drawingProvider = drawingProvider;
putValue(AbstractAction.NAME, "Print...");
putValue(AbstractAction.SMALL_ICON, IconLoader.Print.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
try {
DrawingExporter.getInstance().print(this.drawingProvider);
} catch (PrinterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public ExitAction() {
super();
putValue(AbstractAction.NAME, "Exit");
putValue(AbstractAction.SMALL_ICON, IconLoader.Exit.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
if (plugInPort.allowFileAction()) {
System.exit(0);
}
}
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return null;
}
@Override
public void processMessage(EventType eventType, Object... params) {
// TODO Auto-generated method stub
}
}
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.file;
package org.diylc.plugins.file;
import java.awt.Dimension;
import java.awt.Graphics;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.file;
package org.diylc.plugins.file;
import java.awt.Color;
import java.awt.Dimension;
@@ -11,15 +11,18 @@ import java.io.File;
import java.io.FileInputStream;
import java.util.EnumSet;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.diylc.common.BadPositionException;
import org.diylc.common.DrawOption;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IView;
import org.diylc.core.Project;
import org.diylc.gui.IView;
import org.diylc.presenter.Presenter;
import com.diyfever.gui.IFileChooserAccessory;
@@ -49,6 +52,19 @@ public class ProjectPreview extends JPanel implements PropertyChangeListener, IF
setPreferredSize(new Dimension(140, 128));
presenter = new Presenter(new IView() {
@Override
public void addComponent(JComponent component, int position)
throws BadPositionException {
}
@Override
public void addMenuAction(Action action, String menuName) {
}
@Override
public void addSubmenu(String name, Icon icon, String parentMenuName) {
}
@Override
public int showConfirmDialog(String message, String title, int optionType,
int messageType) {
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.file;
package org.diylc.plugins.file;
import java.awt.Dimension;
import java.awt.Graphics;
@@ -27,7 +27,7 @@ public class TraceMaskDrawingProvider implements IDrawingProvider {
public TraceMaskDrawingProvider(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
this.filter = new ComponentZOrderFiler(IDIYComponent.TRACE);
this.filter = new ComponentZOrderFiler(IDIYComponent.ABOVE_BOARD);
}
@Override
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.help;
package org.diylc.plugins.help;
import java.awt.event.ActionEvent;
import java.util.EnumSet;
@@ -9,9 +9,8 @@ import javax.swing.Icon;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.gui.DialogFactory;
import org.diylc.images.IconLoader;
import org.diylc.swing.ISwingUI;
import org.diylc.swing.gui.DialogFactory;
import com.diyfever.gui.AboutDialog;
import com.diyfever.gui.miscutils.Utils;
@@ -35,26 +34,24 @@ public class HelpMenuPlugin implements IPlugIn {
private IPlugInPort plugInPort;
private AboutDialog aboutDialog;
public HelpMenuPlugin(ISwingUI swingUI) {
swingUI.injectMenuAction(new NavigateURLAction("User Manual", IconLoader.Manual.getIcon(),
MANUAL_URL), HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("FAQ", IconLoader.Faq.getIcon(), FAQ_URL),
HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("Component API", IconLoader.Component
.getIcon(), COMPONENT_URL), HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("Plugin API", IconLoader.Plugin.getIcon(),
PLUGIN_URL), HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("Submit a Bug", IconLoader.Bug.getIcon(),
BUG_URL), HELP_TITLE);
swingUI.injectMenuAction(null, HELP_TITLE);
swingUI.injectMenuAction(new NavigateURLAction("Donate", IconLoader.Donate.getIcon(),
DONATE_URL), HELP_TITLE);
swingUI.injectMenuAction(new AboutAction(), HELP_TITLE);
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
plugInPort.injectMenuAction(new NavigateURLAction("User Manual", IconLoader.Manual
.getIcon(), MANUAL_URL), HELP_TITLE);
plugInPort.injectMenuAction(
new NavigateURLAction("FAQ", IconLoader.Faq.getIcon(), FAQ_URL), HELP_TITLE);
plugInPort.injectMenuAction(new NavigateURLAction("Component API", IconLoader.Component
.getIcon(), COMPONENT_URL), HELP_TITLE);
plugInPort.injectMenuAction(new NavigateURLAction("Plugin API",
IconLoader.Plugin.getIcon(), PLUGIN_URL), HELP_TITLE);
plugInPort.injectMenuAction(new NavigateURLAction("Submit a Bug", IconLoader.Bug.getIcon(),
BUG_URL), HELP_TITLE);
plugInPort.injectMenuAction(null, HELP_TITLE);
plugInPort.injectMenuAction(new NavigateURLAction("Donate", IconLoader.Donate.getIcon(),
DONATE_URL), HELP_TITLE);
plugInPort.injectMenuAction(new AboutAction(), HELP_TITLE);
}
@Override
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.layers;
package org.diylc.plugins.layers;
import java.awt.event.ActionEvent;
import java.util.EnumSet;
@@ -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.swing.ISwingUI;
public class LayersMenuPlugin implements IPlugIn {
@@ -22,7 +21,13 @@ public class LayersMenuPlugin implements IPlugIn {
private IPlugInPort plugInPort;
private Map<Layer, Action> lockActionMap;
public LayersMenuPlugin(ISwingUI swingUI) {
public LayersMenuPlugin() {
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
lockActionMap = new HashMap<Layer, Action>();
for (Layer layer : Layer.values()) {
final int zOrder = layer.getZOrder();
@@ -38,15 +43,10 @@ public class LayersMenuPlugin implements IPlugIn {
};
action.putValue(IPlugInPort.CHECK_BOX_MENU_ITEM, true);
lockActionMap.put(layer, action);
swingUI.injectMenuAction(action, LOCK_LAYERS_TITLE);
plugInPort.injectMenuAction(action, LOCK_LAYERS_TITLE);
}
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.LAYER_STATE_CHANGED);
@@ -65,9 +65,12 @@ public class LayersMenuPlugin implements IPlugIn {
}
static enum Layer {
CHASSIS("Chassis", IDIYComponent.CHASSIS), BOARD("Board", IDIYComponent.BOARD), TRACE(
"Trace", IDIYComponent.TRACE), COMPONENT("Component", IDIYComponent.COMPONENT), TEXT(
"Text", IDIYComponent.TEXT);
BELOW_CHASSIS("Below Chassis", IDIYComponent.BELOW_CHASSIS), CHASSIS("Chassis",
IDIYComponent.CHASSIS), ABOVE_CHASSIS("Above Chassis", IDIYComponent.ABOVE_CHASSIS), BELOW_BOARD(
"Below Board", IDIYComponent.BELOW_BOARD), BOARD("Board", IDIYComponent.BOARD), ABOVE_BOARD(
"Above Board", IDIYComponent.ABOVE_BOARD), BELOW_COMPONENT("Below Component",
IDIYComponent.BELOW_COMPONENT), COMPONENT("Component", IDIYComponent.COMPONENT), ABOVE_COMPONENT(
"Above Component", IDIYComponent.ABOVE_COMPONENT);
String title;
int zOrder;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online;
package org.diylc.plugins.online;
import java.awt.event.ActionEvent;
import java.util.EnumSet;
@@ -9,12 +9,12 @@ import javax.swing.SwingWorker;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.gui.DialogFactory;
import org.diylc.images.IconLoader;
import org.diylc.swing.gui.DialogFactory;
import org.diylc.swing.plugins.online.presenter.LibraryPresenter;
import org.diylc.swing.plugins.online.view.LoginDialog;
import org.diylc.swing.plugins.online.view.NewUserDialog;
import org.diylc.swing.plugins.online.view.UploadDialog;
import org.diylc.plugins.online.presenter.LibraryPresenter;
import org.diylc.plugins.online.view.LoginDialog;
import org.diylc.plugins.online.view.NewUserDialog;
import org.diylc.plugins.online.view.UploadDialog;
import com.diyfever.gui.ProgressDialog;
@@ -32,13 +32,13 @@ public class OnlineManager implements IPlugIn {
initialize();
// plugInPort.injectMenuAction(new LibraryAction(), ONLINE_TITLE);
// plugInPort.injectMenuAction(null, ONLINE_TITLE);
// plugInPort.injectMenuAction(new LoginAction(), ONLINE_TITLE);
// plugInPort.injectMenuAction(new CreateAccountAction(), ONLINE_TITLE);
// plugInPort.injectMenuAction(null, ONLINE_TITLE);
// plugInPort.injectMenuAction(new UploadAction(), ONLINE_TITLE);
// plugInPort.injectMenuAction(new ManageProjectsAction(), ONLINE_TITLE);
plugInPort.injectMenuAction(new LibraryAction(), ONLINE_TITLE);
plugInPort.injectMenuAction(null, ONLINE_TITLE);
plugInPort.injectMenuAction(new LoginAction(), ONLINE_TITLE);
plugInPort.injectMenuAction(new CreateAccountAction(), ONLINE_TITLE);
plugInPort.injectMenuAction(null, ONLINE_TITLE);
plugInPort.injectMenuAction(new UploadAction(), ONLINE_TITLE);
plugInPort.injectMenuAction(new ManageProjectsAction(), ONLINE_TITLE);
}
private void initialize() {
@@ -1,7 +1,7 @@
package org.diylc.swing.plugins.online;
package org.diylc.plugins.online;
import org.apache.log4j.BasicConfigurator;
import org.diylc.swing.plugins.online.presenter.LibraryPresenter;
import org.diylc.plugins.online.presenter.LibraryPresenter;
public class Test {
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.model;
package org.diylc.plugins.online.model;
import java.awt.event.ActionEvent;
import java.io.Serializable;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.presenter;
package org.diylc.plugins.online.presenter;
public class AlreadyExistsException extends Exception {
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.presenter;
package org.diylc.plugins.online.presenter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -10,7 +10,7 @@ import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.diylc.swing.plugins.online.model.ProjectEntity;
import org.diylc.plugins.online.model.ProjectEntity;
public class LibraryPresenter {
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.presenter;
package org.diylc.plugins.online.presenter;
import java.sql.Connection;
import java.sql.Driver;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.presenter;
package org.diylc.plugins.online.presenter;
public class NotConnectedException extends Exception {
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.presenter;
package org.diylc.plugins.online.presenter;
public class NotExistsException extends Exception {
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.presenter;
package org.diylc.plugins.online.presenter;
public class NotLoggedInException extends Exception {
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.view;
package org.diylc.plugins.online.view;
import javax.swing.JFrame;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.view;
package org.diylc.plugins.online.view;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.view;
package org.diylc.plugins.online.view;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.online.view;
package org.diylc.plugins.online.view;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.statusbar;
package org.diylc.plugins.statusbar;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
@@ -6,8 +6,6 @@ import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.text.DecimalFormat;
import java.text.Format;
@@ -22,20 +20,18 @@ import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.ComponentSelection;
import org.diylc.common.ComponentType;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IDIYComponent;
import org.diylc.images.IconLoader;
import org.diylc.presenter.Presenter;
import org.diylc.swing.ISwingUI;
import com.diyfever.gui.MemoryBar;
import com.diyfever.gui.miscutils.ConfigurationManager;
@@ -47,10 +43,8 @@ public class StatusBar extends JPanel implements IPlugIn {
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(StatusBar.class);
public static String UPDATE_URL = "http://www.diy-fever.com/update.xml";
private static final Format sizeFormat = new DecimalFormat("0.##");
private static final Format sizeFormat = new DecimalFormat("0.00");
private JComboBox zoomBox;
private UpdateLabel updateLabel;
@@ -66,18 +60,12 @@ 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) {
public StatusBar() {
super();
// setLayout(new FlowLayout(FlowLayout.TRAILING));
setLayout(new GridBagLayout());
try {
swingUI.injectGUIComponent(this, SwingUtilities.BOTTOM);
} catch (BadPositionException e) {
LOG.error("Could not install status bar", e);
}
}
private JComboBox getZoomBox() {
@@ -125,27 +113,11 @@ public class StatusBar extends JPanel implements IPlugIn {
public JLabel getSizeLabel() {
if (sizeLabel == null) {
sizeLabel = new JLabel(IconLoader.Size.getIcon());
sizeLabel.setFocusable(true);
sizeLabel.setToolTipText("Click to calculate selection size");
sizeLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Point2D size = plugInPort.calculateSelectionDimension();
boolean metric = ConfigurationManager.getInstance().readBoolean(
Presenter.METRIC_KEY, true);
String text;
if (size == null) {
text = "Selection is empty.";
} else {
text = "Selection size: " + sizeFormat.format(size.getX()) + " x "
+ sizeFormat.format(size.getY()) + (metric ? " cm" : " in");
}
JOptionPane.showMessageDialog(SwingUtilities.getRootPane(StatusBar.this), text,
"Information", JOptionPane.INFORMATION_MESSAGE);
}
});
sizeLabel = new JLabel("N/A");
sizeLabel.setToolTipText("Selection Size");
sizeLabel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(
0, 1, 0, 1, UIManager.getColor("Separator.shadow")), BorderFactory
.createEmptyBorder(0, 4, 0, 4)));
}
return sizeLabel;
}
@@ -169,10 +141,10 @@ public class StatusBar extends JPanel implements IPlugIn {
gbc.gridx = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0;
add(zoomPanel, gbc);
add(getSizeLabel(), gbc);
gbc.gridx = 2;
add(getSizeLabel(), gbc);
add(zoomPanel, gbc);
gbc.gridx = 3;
add(getUpdateLabel(), gbc);
@@ -192,13 +164,20 @@ public class StatusBar extends JPanel implements IPlugIn {
this.plugInPort = plugInPort;
layoutComponents();
try {
plugInPort.injectGUIComponent(this, SwingUtilities.BOTTOM);
} catch (BadPositionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@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_SIZE_CHANGED,
EventType.SELECTION_CHANGED);
}
@SuppressWarnings("unchecked")
@@ -218,7 +197,7 @@ public class StatusBar extends JPanel implements IPlugIn {
}
break;
case SELECTION_CHANGED:
List<IDIYComponent<?>> selection = (List<IDIYComponent<?>>) params[0];
ComponentSelection selection = (ComponentSelection) params[0];
Collection<IDIYComponent<?>> stuckComponents = (Collection<IDIYComponent<?>>) params[1];
Collection<String> componentNames = new HashSet<String>();
for (IDIYComponent<?> component : selection) {
@@ -235,6 +214,18 @@ public class StatusBar extends JPanel implements IPlugIn {
Collections.sort(this.stuckComponentNames);
refreshStatusText();
break;
case SELECTION_SIZE_CHANGED:
Point2D size = (Point2D) params[0];
boolean metric = ConfigurationManager.getInstance().readBoolean(Presenter.METRIC_KEY,
true);
if (size == null) {
getSizeLabel().setText("N/A");
} else {
getSizeLabel().setText(
sizeFormat.format(size.getX()) + " x " + sizeFormat.format(size.getY())
+ (metric ? " cm" : " in"));
}
break;
case SLOT_CHANGED:
componentSlot = (ComponentType) params[0];
controlPointSlot = (Point) params[1];
@@ -249,13 +240,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 +258,8 @@ public class StatusBar extends JPanel implements IPlugIn {
builder.append(")");
}
statusText = "<html>Selection: " + builder.toString() + "</html>";
} else {
statusText = "";
}
} else {
switch (componentSlot.getCreationMethod()) {
@@ -279,13 +270,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;
}
}
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.toolbox;
package org.diylc.plugins.toolbox;
import java.awt.Insets;
import java.awt.dnd.DnDConstants;
@@ -0,0 +1,113 @@
package org.diylc.plugins.toolbox;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.ScrollPaneConstants;
import org.diylc.common.ComponentType;
import org.diylc.common.IPlugInPort;
import org.diylc.presenter.ComparatorFactory;
import org.diylc.presenter.Presenter;
/**
* Tabbed pane that shows all available components categorized into tabs.
*
* @author Branislav Stojkovic
*/
class ComponentTabbedPane extends JTabbedPane {
public static int SCROLL_STEP = Presenter.ICON_SIZE + ComponentButton.MARGIN * 2 + 2;
private static final long serialVersionUID = 1L;
private final IPlugInPort plugInPort;
public ComponentTabbedPane(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
Map<String, List<ComponentType>> componentTypes = plugInPort.getComponentTypes();
List<String> categories = new ArrayList<String>(componentTypes.keySet());
Collections.sort(categories);
for (String category : categories) {
JPanel panel = createTab((componentTypes.get(category)));
addTab(category, panel);
}
setPreferredSize(new Dimension(-1, Presenter.ICON_SIZE + ComponentButton.MARGIN * 2 + 38));
}
private JPanel createTab(List<ComponentType> componentTypes) {
JPanel panel = new JPanel(new BorderLayout());
final JScrollPane scrollPane = createComponentScrollBar(componentTypes);
panel.setOpaque(false);
JButton leftButton = new JButton("<");
leftButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Rectangle rect = scrollPane.getVisibleRect();
if (rect.x > SCROLL_STEP) {
rect.translate(-SCROLL_STEP, 0);
} else {
rect.translate(-rect.x, 0);
}
}
});
leftButton.setMargin(new Insets(0, 2, 0, 2));
JButton rightButton = new JButton(">");
rightButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Rectangle rect = scrollPane.getVisibleRect();
if (rect.x + rect.width < scrollPane.getViewport().getSize().width - SCROLL_STEP) {
rect.translate(SCROLL_STEP, 0);
} else {
rect.translate(scrollPane.getViewport().getSize().width - rect.x - rect.width,
0);
}
}
});
rightButton.setMargin(new Insets(0, 2, 0, 2));
panel.add(leftButton, BorderLayout.WEST);
panel.add(scrollPane);
panel.add(rightButton, BorderLayout.EAST);
return panel;
}
private JScrollPane createComponentScrollBar(List<ComponentType> componentTypes) {
JScrollPane scrollPane = new JScrollPane(createComponentPanel(componentTypes));
scrollPane.setOpaque(false);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
return scrollPane;
}
private Component createComponentPanel(List<ComponentType> componentTypes) {
Container toolbar = new Container();
Collections.sort(componentTypes, ComparatorFactory.getInstance()
.getComponentTypeComparator());
toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.X_AXIS));
for (ComponentType componentType : componentTypes) {
JButton button = new ComponentButton(plugInPort, componentType);
toolbar.add(button);
}
return toolbar;
}
}
@@ -0,0 +1,36 @@
package org.diylc.plugins.toolbox;
import java.util.EnumSet;
import javax.swing.SwingConstants;
import org.diylc.common.BadPositionException;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
public class ToolBox implements IPlugIn {
@Override
public void connect(IPlugInPort plugInPort) {
try {
plugInPort.injectGUIComponent(new ComponentTabbedPane(plugInPort), SwingConstants.TOP);
} catch (BadPositionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
// TODO Auto-generated method stub
return null;
}
@Override
public void processMessage(EventType eventType, Object... params) {
// TODO Auto-generated method stub
}
}
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.toolbox;
package org.diylc.plugins.toolbox;
import java.awt.Cursor;
import java.awt.datatransfer.StringSelection;
@@ -1,4 +1,4 @@
package org.diylc.swing.plugins.toolbox;
package org.diylc.plugins.toolbox;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
@@ -1,6 +1,7 @@
package org.diylc.presenter;
import java.util.Comparator;
import java.util.List;
import org.diylc.common.ComponentType;
import org.diylc.common.PropertyWrapper;
@@ -13,7 +14,6 @@ public class ComparatorFactory {
private Comparator<IDIYComponent<?>> componentNameComparator;
private Comparator<ComponentType> componentTypeComparator;
private Comparator<PropertyWrapper> propertyNameComparator;
private Comparator<IDIYComponent<?>> componentZOrderComparator;
public static ComparatorFactory getInstance() {
if (instance == null) {
@@ -53,6 +53,20 @@ public class ComparatorFactory {
return componentTypeComparator;
}
public Comparator<IDIYComponent<?>> getComponentZOrderComparator(
final List<IDIYComponent<?>> components) {
Comparator<IDIYComponent<?>> componentZOrderComparator = new Comparator<IDIYComponent<?>>() {
@Override
public int compare(IDIYComponent<?> o1, IDIYComponent<?> o2) {
int index1 = components.indexOf(o1);
int index2 = components.indexOf(o2);
return new Integer(index1).compareTo(index2);
}
};
return componentZOrderComparator;
}
public Comparator<PropertyWrapper> getPropertyNameComparator() {
if (propertyNameComparator == null) {
propertyNameComparator = new Comparator<PropertyWrapper>() {
@@ -66,23 +80,4 @@ public class ComparatorFactory {
}
return propertyNameComparator;
}
public Comparator<IDIYComponent<?>> getComponentZOrderComparator() {
if (componentZOrderComparator == null) {
componentZOrderComparator = new Comparator<IDIYComponent<?>>() {
@Override
public int compare(IDIYComponent<?> o1, IDIYComponent<?> o2) {
ComponentType type1 = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) o1.getClass());
ComponentType type2 = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) o2.getClass());
return new Double(type1.getZOrder()).compareTo(type2.getZOrder());
}
};
}
return componentZOrderComparator;
}
}
@@ -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,9 +35,7 @@ public class ComponentProcessor {
private static ComponentProcessor instance;
private Map<String, List<PropertyWrapper>> propertyCache;
private Map<String, IPropertyValidator> propertyValidatorCache;
private Map<String, ComponentType> componentTypeMap;
private Map<Class<?>, List<PropertyWrapper>> propertyCache;
private Cloner cloner;
@@ -52,15 +49,10 @@ public class ComponentProcessor {
private ComponentProcessor() {
super();
this.cloner = new Cloner();
this.propertyCache = new HashMap<String, List<PropertyWrapper>>();
this.componentTypeMap = new HashMap<String, ComponentType>();
this.propertyValidatorCache = new HashMap<String, IPropertyValidator>();
this.propertyCache = new HashMap<Class<?>, List<PropertyWrapper>>();
}
public ComponentType extractComponentTypeFrom(Class<? extends IDIYComponent<?>> clazz) {
if (componentTypeMap.containsKey(clazz.getName())) {
return componentTypeMap.get(clazz.getName());
}
public ComponentType createComponentTypeFrom(Class<? extends IDIYComponent<?>> clazz) {
String name;
String description;
CreationMethod creationMethod;
@@ -109,7 +101,6 @@ public class ComponentProcessor {
}
ComponentType componentType = new ComponentType(name, description, creationMethod,
category, namePrefix, author, icon, clazz, zOrder, stretchable);
componentTypeMap.put(clazz.getName(), componentType);
return componentType;
}
@@ -120,8 +111,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 +127,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 +140,7 @@ public class ComponentProcessor {
}
}
propertyCache.put(clazz.getName(), properties);
propertyCache.put(clazz, properties);
return cloner.deepClone(properties);
}
@@ -193,19 +181,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;
}
}
@@ -16,7 +16,7 @@ public class ComponentZOrderFiler implements IComponentFiler {
@SuppressWarnings("unchecked")
@Override
public boolean testComponent(IDIYComponent<?> component) {
ComponentType componentType = ComponentProcessor.getInstance().extractComponentTypeFrom(
ComponentType componentType = ComponentProcessor.getInstance().createComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass());
return Math.round(componentType.getZOrder()) == zOrder;
}
@@ -11,12 +11,13 @@ import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.Area;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.diylc.common.ComponentSelection;
import org.diylc.common.DrawOption;
import org.diylc.common.EventType;
import org.diylc.common.GridType;
@@ -39,8 +40,6 @@ 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";
@@ -59,7 +58,6 @@ 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);
@@ -73,31 +71,12 @@ public class DrawingManager {
lastDrawnStateMap = new HashMap<IDIYComponent<?>, ComponentState>();
}
/**
* Paints the project onto the canvas and returns the list of components
* that failed to draw.
*
* @param g2d
* @param project
* @param drawOptions
* @param filter
* @param selectionRect
* @param selectedComponents
* @param lockedComponents
* @param groupedComponents
* @param controlPointSlot
* @param componentSlot
* @param dragInProgress
* @return
*/
public List<IDIYComponent<?>> drawProject(Graphics2D g2d, Project project,
Set<DrawOption> drawOptions, IComponentFiler filter, Rectangle selectionRect,
List<IDIYComponent<?>> selectedComponents, Set<IDIYComponent<?>> lockedComponents,
Set<IDIYComponent<?>> groupedComponents, List<Point> controlPointSlot,
IDIYComponent<?> componentSlot, boolean dragInProgress) {
failedComponents.clear();
public void drawProject(Graphics2D g2d, Project project, Set<DrawOption> drawOptions,
IComponentFiler filter, Rectangle selectionRect, ComponentSelection 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);
@@ -181,12 +160,7 @@ 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) {
componentAreaMap.put(component, area);
@@ -242,12 +216,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();
}
@@ -291,8 +260,6 @@ public class DrawingManager {
g2d.draw(area);
}
}
return failedComponents;
}
public double getZoomLevel() {
@@ -316,12 +283,14 @@ public class DrawingManager {
public List<IDIYComponent<?>> findComponentsAt(Point point, Project project) {
List<IDIYComponent<?>> components = new ArrayList<IDIYComponent<?>>();
for (int i = 0; i < project.getComponents().size(); i++) {
Area area = componentAreaMap.get(project.getComponents().get(i));
if (area != null && area.contains(point)) {
components.add(project.getComponents().get(i));
for (Map.Entry<IDIYComponent<?>, Area> entry : componentAreaMap.entrySet()) {
if (entry.getValue().contains(point)) {
components.add(entry.getKey());
}
}
// Sort by z-order.
Collections.sort(components, ComparatorFactory.getInstance().getComponentZOrderComparator(
project.getComponents()));
return components;
}
@@ -492,9 +492,8 @@ class G2DWrapper extends Graphics2D implements IDrawingObserver {
@Override
public boolean drawImage(Image img, int x, int y, ImageObserver observer) {
boolean result = canvasGraphics.drawImage(img, x, y, observer);
appendShape(new Rectangle2D.Double(x, y, img.getWidth(observer), img.getHeight(observer)));
return result;
// FIXME: map
return canvasGraphics.drawImage(img, x, y, observer);
}
@Override
@@ -31,7 +31,7 @@ public class InstantiationManager {
private Point potentialControlPoint;
public InstantiationManager() {
cloner = new Cloner();
// TODO Auto-generated constructor stub
}
public ComponentType getComponentTypeSlot() {
@@ -80,22 +80,14 @@ public class InstantiationManager {
componentSlot.setControlPoint(firstControlPoint, 1);
}
/**
* Updates component in the slot with the new second control point.
*
* @param scaledPoint
* @return true, if any change is made
*/
public boolean updatePointByPoint(Point scaledPoint) {
boolean changeMade = !scaledPoint.equals(potentialControlPoint);
public void updatePointByPoint(Point scaledPoint) {
potentialControlPoint = scaledPoint;
if (componentSlot != null) {
componentSlot.setControlPoint(scaledPoint, 1);
}
return changeMade;
}
public boolean updateSingleClick(Point scaledPoint, boolean snapToGrid, Size gridSpacing) {
public void updateSingleClick(Point scaledPoint, boolean snapToGrid, Size gridSpacing) {
if (potentialControlPoint == null) {
potentialControlPoint = new Point(0, 0);
}
@@ -107,7 +99,7 @@ public class InstantiationManager {
}
// Only repaint if there's an actual change.
if (dx == 0 && dy == 0) {
return false;
return;
}
potentialControlPoint.translate(dx, dy);
if (componentSlot == null) {
@@ -120,7 +112,6 @@ public class InstantiationManager {
componentSlot.setControlPoint(p, i);
}
}
return true;
}
public IDIYComponent<?> instantiateComponent(ComponentType componentType, Point point,
+142 -214
View File
@@ -19,7 +19,14 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.ComponentSelection;
import org.diylc.common.ComponentType;
import org.diylc.common.DrawOption;
import org.diylc.common.EventType;
@@ -28,10 +35,9 @@ import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IDIYComponent;
import org.diylc.core.IView;
import org.diylc.core.Project;
import org.diylc.core.measures.SizeUnit;
import org.diylc.swing.plugins.edit.ComponentTransferable;
import org.diylc.gui.IView;
import org.diylc.utils.Constants;
import com.diyfever.gui.miscutils.ConfigurationManager;
@@ -50,20 +56,19 @@ public class Presenter implements IPlugInPort {
private static final Logger LOG = Logger.getLogger(Presenter.class);
public static final VersionNumber CURRENT_VERSION = new VersionNumber(3, 0, 5);
public static final VersionNumber CURRENT_VERSION = new VersionNumber(3, 0, 3);
public static final String DEFAULTS_KEY_PREFIX = "default.";
public static final String METRIC_KEY = "metric";
public static final List<IDIYComponent<?>> EMPTY_SELECTION = Collections.emptyList();
public static final int ICON_SIZE = 32;
private Project currentProject;
private Map<String, List<ComponentType>> componentTypes;
// Maps component class names to ComponentType objects.
private Map<String, ComponentType> componentTypeMap;
private List<IPlugIn> plugIns;
private List<IDIYComponent<?>> selectedComponents;
private ComponentSelection selectedComponents;
// Maps components that have at least one dragged point to set of indices
// that designate which of their control points are being dragged.
private Map<IDIYComponent<?>, Set<Integer>> controlPointMap;
@@ -98,7 +103,7 @@ public class Presenter implements IPlugInPort {
this.view = view;
plugIns = new ArrayList<IPlugIn>();
messageDispatcher = new MessageDispatcher<EventType>(true);
selectedComponents = new ArrayList<IDIYComponent<?>>();
selectedComponents = new ComponentSelection();
lockedComponents = new HashSet<IDIYComponent<?>>();
currentProject = new Project();
cloner = new Cloner();
@@ -180,7 +185,7 @@ 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;
updateSelection(EMPTY_SELECTION);
updateSelection(ComponentSelection.EMPTY_SELECTION);
messageDispatcher.dispatchMessage(EventType.PROJECT_LOADED, project, freshStart);
messageDispatcher.dispatchMessage(EventType.REPAINT);
messageDispatcher.dispatchMessage(EventType.LAYER_STATE_CHANGED, currentProject
@@ -194,11 +199,11 @@ public class Presenter implements IPlugInPort {
Project project = new Project();
instantiationManager.fillWithDefaultProperties(project);
loadProject(project, true);
projectFileManager.startNewFile();
projectFileManager.fireFileStatusChanged();
} catch (Exception e) {
LOG.error("Could not create new file", e);
view.showMessage("Could not create a new file. Check the log for details.", "Error",
IView.ERROR_MESSAGE);
JOptionPane.ERROR_MESSAGE);
}
}
@@ -206,25 +211,13 @@ public class Presenter implements IPlugInPort {
public void loadProjectFromFile(String fileName) {
LOG.info(String.format("loadProjectFromFile(%s)", fileName));
try {
List<String> warnings = new ArrayList<String>();
Project project = (Project) projectFileManager.deserializeProjectFromFile(fileName,
warnings);
Project project = (Project) projectFileManager.deserializeProjectFromFile(fileName);
loadProject(project, true);
projectFileManager.fireFileStatusChanged();
if (!warnings.isEmpty()) {
StringBuilder builder = new StringBuilder(
"<html>File was opened, but there were some issues with it:<br><br>");
for (String warning : warnings) {
builder.append(warning);
builder.append("<br>");
}
builder.append("</html");
view.showMessage(builder.toString(), "Warning", IView.WARNING_MESSAGE);
}
} catch (Exception ex) {
LOG.error("Could not load file", ex);
view.showMessage("Could not open file " + fileName + ". Check the log for details.",
"Error", IView.ERROR_MESSAGE);
"Error", JOptionPane.ERROR_MESSAGE);
}
}
@@ -233,8 +226,8 @@ public class Presenter implements IPlugInPort {
if (projectFileManager.isModified()) {
int response = view.showConfirmDialog(
"There are unsaved changes. Are you sure you want to abandon these changes?",
"Warning", IView.YES_NO_OPTION, IView.WARNING_MESSAGE);
return response == IView.YES_OPTION;
"Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
return response == JOptionPane.YES_OPTION;
}
return true;
}
@@ -247,7 +240,7 @@ public class Presenter implements IPlugInPort {
} catch (Exception ex) {
LOG.error("Could not save file", ex);
view.showMessage("Could not save file " + fileName + ". Check the log for details.",
"Error", IView.ERROR_MESSAGE);
"Error", JOptionPane.ERROR_MESSAGE);
}
}
@@ -267,12 +260,14 @@ public class Presenter implements IPlugInPort {
if (componentTypes == null) {
LOG.info("Loading component types.");
componentTypes = new HashMap<String, List<ComponentType>>();
componentTypeMap = new HashMap<String, ComponentType>();
List<Class<?>> componentTypeClasses = JarScanner.getInstance().scanFolder("library/",
IDIYComponent.class);
for (Class<?> clazz : componentTypeClasses) {
if (!Modifier.isAbstract(clazz.getModifiers())) {
ComponentType componentType = ComponentProcessor.getInstance()
.extractComponentTypeFrom((Class<? extends IDIYComponent<?>>) clazz);
.createComponentTypeFrom((Class<? extends IDIYComponent<?>>) clazz);
componentTypeMap.put(componentType.getInstanceClass().getName(), componentType);
List<ComponentType> nestedList;
if (componentTypes.containsKey(componentType.getCategory())) {
nestedList = componentTypes.get(componentType.getCategory());
@@ -299,8 +294,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
@@ -310,23 +304,30 @@ 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);
}
@Override
public void injectGUIComponent(JComponent component, int position) throws BadPositionException {
LOG.info(String.format("injectGUIComponent(%s, %s)", component.getClass().getName(),
position));
view.addComponent(component, position);
}
@Override
public void injectMenuAction(Action action, String menuName) {
LOG.info(String.format("injectMenuAction(%s, %s)", action == null ? "Separator" : action
.getValue(Action.NAME), menuName));
view.addMenuAction(action, menuName);
}
@Override
public void injectSubmenu(String name, Icon icon, String parentMenuName) {
LOG.info(String.format("injectSubmenu(%s, icon, %s)", name, parentMenuName));
view.addSubmenu(name, icon, parentMenuName);
}
/**
@@ -371,9 +372,7 @@ public class Presenter implements IPlugInPort {
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
// calculateSelectionDimension());
messageDispatcher.dispatchMessage(EventType.REPAINT);
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>();
newSelection.add(component);
updateSelection(newSelection);
updateSelection(ComponentSelection.of(component));
} catch (Exception e) {
LOG.error("Error instatiating component of type: "
+ componentTypeSlot.getInstanceClass().getName(), e);
@@ -391,7 +390,7 @@ public class Presenter implements IPlugInPort {
instantiationManager.instatiatePointByPoint(scaledPoint, currentProject);
} catch (Exception e) {
view.showMessage("Could not create component. Check log for details.",
"Error", IView.ERROR_MESSAGE);
"Error", JOptionPane.ERROR_MESSAGE);
LOG.error("Could not create component", e);
}
messageDispatcher.dispatchMessage(EventType.SLOT_CHANGED, componentTypeSlot,
@@ -403,11 +402,8 @@ public class Presenter implements IPlugInPort {
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);
updateSelection(isComponentLocked(componentSlot) ? ComponentSelection.EMPTY_SELECTION
: ComponentSelection.of(componentSlot));
messageDispatcher.dispatchMessage(EventType.REPAINT);
setNewComponentTypeSlot(null);
}
@@ -422,8 +418,7 @@ public class Presenter implements IPlugInPort {
projectFileManager.notifyFileChange();
}
} else {
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>(
selectedComponents);
ComponentSelection newSelection = new ComponentSelection(selectedComponents);
List<IDIYComponent<?>> components = findComponentsAt(scaledPoint);
// If there's nothing under mouse cursor deselect all.
if (components.isEmpty()) {
@@ -461,26 +456,21 @@ public class Presenter implements IPlugInPort {
if (snapToGrid) {
CalcUtils.snapPointToGrid(scaledPoint, currentProject.getGridSpacing());
}
boolean refresh = false;
switch (instantiationManager.getComponentTypeSlot().getCreationMethod()) {
case POINT_BY_POINT:
refresh = instantiationManager.updatePointByPoint(scaledPoint);
instantiationManager.updatePointByPoint(scaledPoint);
break;
case SINGLE_CLICK:
refresh = instantiationManager.updateSingleClick(scaledPoint, snapToGrid,
currentProject.getGridSpacing());
instantiationManager.updateSingleClick(scaledPoint, snapToGrid, currentProject
.getGridSpacing());
break;
}
if (refresh) {
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
messageDispatcher.dispatchMessage(EventType.REPAINT);
} else {
// Go backwards so we take the highest z-order components first.
for (int i = currentProject.getComponents().size() - 1; i >= 0; i--) {
IDIYComponent<?> component = currentProject.getComponents().get(i);
ComponentType componentType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass());
ComponentType componentType = componentTypeMap.get(component.getClass().getName());
for (int pointIndex = 0; pointIndex < component.getControlPointCount(); pointIndex++) {
Point controlPoint = component.getControlPoint(pointIndex);
// Only consider selected components that are not grouped.
@@ -505,6 +495,11 @@ public class Presenter implements IPlugInPort {
}
}
}
// // If CTRL is pressed, we only care about the top most
// component.
// if (altDown && components.size() > 0) {
// break;
// }
}
}
@@ -518,14 +513,14 @@ public class Presenter implements IPlugInPort {
}
@Override
public List<IDIYComponent<?>> getSelectedComponents() {
return selectedComponents;
public ComponentSelection getSelectedComponents() {
return new ComponentSelection(selectedComponents);
}
@Override
public void selectAll() {
LOG.info("selectAll()");
updateSelection(new ArrayList<IDIYComponent<?>>(currentProject.getComponents()));
updateSelection(new ComponentSelection(currentProject.getComponents()));
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
// selectedComponents);
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
@@ -543,7 +538,6 @@ 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);
return;
}
dragInProgress = true;
@@ -553,7 +547,7 @@ public class Presenter implements IPlugInPort {
List<IDIYComponent<?>> components = findComponentsAt(scaledPoint);
if (!controlPointMap.isEmpty()) {
// If we're dragging control points reset selection.
updateSelection(new ArrayList<IDIYComponent<?>>(controlPointMap.keySet()));
updateSelection(new ComponentSelection(controlPointMap.keySet()));
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
// selectedComponents);
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
@@ -561,7 +555,7 @@ public class Presenter implements IPlugInPort {
messageDispatcher.dispatchMessage(EventType.REPAINT);
} else if (components.isEmpty()) {
// If there are no components are under the cursor, reset selection.
updateSelection(EMPTY_SELECTION);
updateSelection(ComponentSelection.EMPTY_SELECTION);
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
// selectedComponents);
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
@@ -573,7 +567,7 @@ public class Presenter implements IPlugInPort {
// If the component under the cursor is not already selected, make
// it into the only selected component.
if (!selectedComponents.contains(component)) {
updateSelection(new ArrayList<IDIYComponent<?>>(findAllGroupedComponents(component)));
updateSelection(new ComponentSelection(findAllGroupedComponents(component)));
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
// selectedComponents);
// messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
@@ -609,18 +603,13 @@ public class Presenter implements IPlugInPort {
int oldSize = controlPointMap.size();
LOG.debug("Expanding selected component map");
for (IDIYComponent<?> component : currentProject.getComponents()) {
ComponentType componentType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass());
ComponentType componentType = componentTypeMap.get(component.getClass().getName());
// Check if there's a control point in the current selection
// that matches with one of its control points.
for (int i = 0; i < component.getControlPointCount(); i++) {
// Do not process a control point if it's already in the map and
// if it's locked.
if ((!controlPointMap.containsKey(component) || !controlPointMap.get(component)
.contains(i))
&& !isComponentLocked(component)) {
// Do not process a component if it's already in the map and if it's locked.
if (!controlPointMap.containsKey(component) && !isComponentLocked(component)) {
// Check if there's a control point in the current selection
// that matches with one of its control points.
for (int i = 0; i < component.getControlPointCount(); i++) {
if (component.isControlPointSticky(i)) {
boolean componentMatches = false;
for (Map.Entry<IDIYComponent<?>, Set<Integer>> entry : controlPointMap
@@ -645,8 +634,8 @@ public class Presenter implements IPlugInPort {
LOG.debug("Including component: " + component);
Set<Integer> indices = new HashSet<Integer>();
// For stretchable components just add the
// matching component. Otherwise, add all control
// points.
// matching component.
// Otherwise, add all control points.
if (componentType.isStretchable()) {
indices.add(i);
} else {
@@ -654,11 +643,7 @@ public class Presenter implements IPlugInPort {
indices.add(k);
}
}
if (controlPointMap.containsKey(component)) {
controlPointMap.get(component).addAll(indices);
} else {
controlPointMap.put(component, indices);
}
controlPointMap.put(component, indices);
}
}
}
@@ -680,6 +665,7 @@ public class Presenter implements IPlugInPort {
return false;
}
Point scaledPoint = scalePoint(point);
boolean repaint = false;
if (!controlPointMap.isEmpty()) {
// We're dragging control point(s).
int dx = (scaledPoint.x - previousDragPoint.x);
@@ -689,46 +675,24 @@ public class Presenter implements IPlugInPort {
int actualDx = 0;
int actualDy = 0;
// For each component, do a simulation of the move to see if any of
// them will
// overlap.
boolean isFirst = true;
// Do a simulation of the move to see if any of them will
// collide.
for (Map.Entry<IDIYComponent<?>, Set<Integer>> entry : controlPointMap.entrySet()) {
IDIYComponent<?> component = entry.getKey();
Point[] controlPoints = new Point[component.getControlPointCount()];
for (int index = 0; index < component.getControlPointCount(); index++) {
controlPoints[index] = new Point(component.getControlPoint(index));
// When the first point is moved, calculate how much it
// actually moved after snapping.
if (entry.getValue().contains(index)) {
if (isFirst) {
isFirst = false;
controlPoints[index].translate(dx, dy);
if (snapToGrid) {
CalcUtils.snapPointToGrid(controlPoints[index], currentProject
.getGridSpacing());
}
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;
}
} else {
controlPoints[index].translate(actualDx, actualDy);
IDIYComponent<?> c = entry.getKey();
Point[] controlPoints = new Point[c.getControlPointCount()];
for (int i = 0; i < controlPoints.length; i++) {
controlPoints[i] = new Point(c.getControlPoint(i));
if (entry.getValue().contains(i)) {
controlPoints[i].translate(dx, dy);
if (snapToGrid) {
CalcUtils.snapPointToGrid(controlPoints[i], currentProject
.getGridSpacing());
}
}
// For control points that may overlap, just write null,
// we'll ignore them later.
if (component.canControlPointOverlap(index)) {
controlPoints[index] = null;
}
}
for (int i = 0; i < controlPoints.length - 1; i++) {
for (int j = i + 1; j < controlPoints.length; j++) {
if (controlPoints[i] != null && controlPoints[j] != null
&& controlPoints[i].equals(controlPoints[j])) {
if (controlPoints[i].equals(controlPoints[j])) {
LOG.error("Control points collision detected, cannot make this move.");
return true;
}
@@ -739,14 +703,26 @@ public class Presenter implements IPlugInPort {
// Update all points.
for (Map.Entry<IDIYComponent<?>, Set<Integer>> entry : controlPointMap.entrySet()) {
IDIYComponent<?> c = entry.getKey();
drawingManager.invalidateComponent(c);
// drawingManager.invalidateComponent(c);
for (Integer index : entry.getValue()) {
Point p = new Point(c.getControlPoint(index));
p.translate(actualDx, actualDy);
p.translate(dx, dy);
if (snapToGrid) {
CalcUtils.snapPointToGrid(p, currentProject.getGridSpacing());
}
// When the first point is moved, calculate how much it
// actually moved after snapping.
if (actualDx == 0 && actualDy == 0) {
actualDx = p.x - c.getControlPoint(index).x;
actualDy = p.y - c.getControlPoint(index).y;
}
c.setControlPoint(p, index);
}
}
previousDragPoint.translate(actualDx, actualDy);
if (actualDx != 0 || actualDy != 0) {
previousDragPoint.translate(actualDx, actualDy);
repaint = true;
}
} else if (selectedComponents.isEmpty()
&& instantiationManager.getComponentTypeSlot() == null) {
// If there's no selection, the only thing to do is update the
@@ -754,13 +730,15 @@ public class Presenter implements IPlugInPort {
Rectangle oldSelectionRect = selectionRect == null ? null
: new Rectangle(selectionRect);
this.selectionRect = Utils.createRectangle(scaledPoint, previousDragPoint);
if (selectionRect.equals(oldSelectionRect)) {
return true;
}
repaint = !selectionRect.equals(oldSelectionRect);
// messageDispatcher.dispatchMessage(EventType.SELECTION_RECT_CHANGED,
// selectionRect);
}
messageDispatcher.dispatchMessage(EventType.REPAINT);
if (repaint) {
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
calculateSelectionDimension());
return true;
}
@@ -777,7 +755,7 @@ public class Presenter implements IPlugInPort {
if (scaledPoint != null) {
this.selectionRect = Utils.createRectangle(scaledPoint, previousDragPoint);
}
List<IDIYComponent<?>> newSelection = new ArrayList<IDIYComponent<?>>();
ComponentSelection newSelection = new ComponentSelection();
for (IDIYComponent<?> component : currentProject.getComponents()) {
if (!isComponentLocked(component)) {
Area area = drawingManager.getComponentArea(component);
@@ -818,13 +796,12 @@ public class Presenter implements IPlugInPort {
.getGridSpacing().convertToPixels());
component.setControlPoint(point, i);
}
addComponent(component, ComponentProcessor.getInstance().extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass()));
addComponent(component, componentTypeMap.get(component.getClass().getName()));
}
messageDispatcher.dispatchMessage(EventType.PROJECT_MODIFIED, oldProject, cloner
.deepClone(currentProject), "Add");
projectFileManager.notifyFileChange();
updateSelection(new ArrayList<IDIYComponent<?>>(components));
updateSelection(new ComponentSelection(components));
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
@@ -846,7 +823,7 @@ public class Presenter implements IPlugInPort {
messageDispatcher.dispatchMessage(EventType.PROJECT_MODIFIED, oldProject, cloner
.deepClone(currentProject), "Delete");
projectFileManager.notifyFileChange();
updateSelection(EMPTY_SELECTION);
updateSelection(ComponentSelection.EMPTY_SELECTION);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
@@ -872,6 +849,8 @@ public class Presenter implements IPlugInPort {
@Override
public void setMetric(boolean isMetric) {
ConfigurationManager.getInstance().writeValue(Presenter.METRIC_KEY, isMetric);
messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
calculateSelectionDimension());
}
@Override
@@ -900,91 +879,32 @@ public class Presenter implements IPlugInPort {
messageDispatcher.dispatchMessage(EventType.REPAINT);
if (!oldProject.equals(currentProject)) {
messageDispatcher.dispatchMessage(EventType.PROJECT_MODIFIED, oldProject, cloner
.deepClone(currentProject), "Ungroup");
.deepClone(currentProject), "Group");
projectFileManager.notifyFileChange();
}
}
@Override
public void setLayerLocked(int layerZOrder, boolean locked) {
LOG.info(String.format("setLayerLocked(%s, %s)", layerZOrder, locked));
if (locked) {
currentProject.getLockedLayers().add(layerZOrder);
} else {
currentProject.getLockedLayers().remove(layerZOrder);
}
updateSelection(EMPTY_SELECTION);
updateSelection(ComponentSelection.EMPTY_SELECTION);
messageDispatcher.dispatchMessage(EventType.REPAINT);
messageDispatcher.dispatchMessage(EventType.LAYER_STATE_CHANGED, currentProject
.getLockedLayers());
}
@Override
public void sendSelectionToBack() {
LOG.info("sendSelectionToBack()");
Project oldProject = cloner.deepClone(currentProject);
for (IDIYComponent<?> component : selectedComponents) {
ComponentType componentType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass());
int index = currentProject.getComponents().indexOf(component);
if (index < 0) {
LOG.warn("Component not found in the project: " + component.getName());
} else if (index > 0) {
IDIYComponent<?> componentBefore = currentProject.getComponents().get(index - 1);
ComponentType componentBeforeType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) componentBefore.getClass());
if (componentType.getZOrder() == componentBeforeType.getZOrder()) {
Collections.swap(currentProject.getComponents(), index, index - 1);
}
}
}
if (!oldProject.equals(currentProject)) {
messageDispatcher.dispatchMessage(EventType.PROJECT_MODIFIED, oldProject, cloner
.deepClone(currentProject), "Send to Back");
projectFileManager.notifyFileChange();
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
}
@Override
public void bringSelectionToFront() {
LOG.info("bringSelectionToFront()");
Project oldProject = cloner.deepClone(currentProject);
for (IDIYComponent<?> component : selectedComponents) {
ComponentType componentType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass());
int index = currentProject.getComponents().indexOf(component);
if (index < 0) {
LOG.warn("Component not found in the project: " + component.getName());
} else if (index < currentProject.getComponents().size() - 1) {
IDIYComponent<?> componentAfter = currentProject.getComponents().get(index + 1);
ComponentType componentAfterType = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) componentAfter.getClass());
if (componentType.getZOrder() == componentAfterType.getZOrder()) {
Collections.swap(currentProject.getComponents(), index, index + 1);
}
}
}
if (!oldProject.equals(currentProject)) {
messageDispatcher.dispatchMessage(EventType.PROJECT_MODIFIED, oldProject, cloner
.deepClone(currentProject), "Bring to Front");
projectFileManager.notifyFileChange();
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
}
/**
* Updates the selection with the specified {@link ComponentTransferable}.
* Updates the selection with the specified {@link ComponentSelection}.
* Also, updates control point map with all components that are stuck to the
* newly selected components.
*
* @param newSelection
*/
private void updateSelection(List<IDIYComponent<?>> newSelection) {
private void updateSelection(ComponentSelection newSelection) {
this.selectedComponents = newSelection;
Map<IDIYComponent<?>, Set<Integer>> controlPointMap = new HashMap<IDIYComponent<?>, Set<Integer>>();
for (IDIYComponent<?> component : selectedComponents) {
@@ -997,6 +917,12 @@ public class Presenter implements IPlugInPort {
includeStuckComponents(controlPointMap);
messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED, selectedComponents,
controlPointMap.keySet());
fireSelectionSizeChanged();
}
private void fireSelectionSizeChanged() {
messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
calculateSelectionDimension());
}
/**
@@ -1038,8 +964,11 @@ public class Presenter implements IPlugInPort {
return components;
}
@Override
public Point2D calculateSelectionDimension() {
/**
* @return selection size expressed in either inches or centimeters, based
* on the user preference.
*/
private Point2D calculateSelectionDimension() {
if (selectedComponents.isEmpty()) {
return null;
}
@@ -1074,10 +1003,8 @@ public class Presenter implements IPlugInPort {
private void addComponent(IDIYComponent<?> component, ComponentType componentType) {
int index = 0;
while (index < currentProject.getComponents().size()
&& componentType.getZOrder() >= ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) currentProject.getComponents()
.get(index).getClass()).getZOrder()) {
&& componentType.getZOrder() >= componentTypeMap.get(
currentProject.getComponents().get(index).getClass().getName()).getZOrder()) {
index++;
}
if (index < currentProject.getComponents().size()) {
@@ -1113,7 +1040,7 @@ public class Presenter implements IPlugInPort {
LOG.error("Could not apply selection properties", e);
view.showMessage(
"Could not apply changes to the selection. Check the log for details.",
"Error", IView.ERROR_MESSAGE);
"Error", JOptionPane.ERROR_MESSAGE);
} finally {
// Notify the listeners.
if (!oldProject.equals(currentProject)) {
@@ -1122,6 +1049,8 @@ public class Presenter implements IPlugInPort {
projectFileManager.notifyFileChange();
}
messageDispatcher.dispatchMessage(EventType.REPAINT);
messageDispatcher.dispatchMessage(EventType.SELECTION_SIZE_CHANGED,
calculateSelectionDimension());
}
}
@@ -1152,7 +1081,7 @@ public class Presenter implements IPlugInPort {
} catch (Exception e) {
LOG.error("Could not apply project properties", e);
view.showMessage("Could not apply changes to the project. Check the log for details.",
"Error", IView.ERROR_MESSAGE);
"Error", JOptionPane.ERROR_MESSAGE);
} finally {
// Notify the listeners.
if (!oldProject.equals(currentProject)) {
@@ -1171,7 +1100,7 @@ public class Presenter implements IPlugInPort {
try {
instantiationManager.setComponentTypeSlot(componentType, currentProject);
if (componentType != null) {
updateSelection(EMPTY_SELECTION);
updateSelection(ComponentSelection.EMPTY_SELECTION);
}
messageDispatcher.dispatchMessage(EventType.REPAINT);
// messageDispatcher.dispatchMessage(EventType.SELECTION_CHANGED,
@@ -1183,7 +1112,7 @@ public class Presenter implements IPlugInPort {
} catch (Exception e) {
LOG.error("Could not set component type slot", e);
view.showMessage("Could not set component type slot. Check log for details.", "Error",
IView.ERROR_MESSAGE);
JOptionPane.ERROR_MESSAGE);
}
}
@@ -1198,8 +1127,7 @@ public class Presenter implements IPlugInPort {
}
private boolean isComponentLocked(IDIYComponent<?> component) {
ComponentType componentType = ComponentProcessor.getInstance().extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass());
ComponentType componentType = componentTypeMap.get(component.getClass().getName());
return currentProject.getLockedLayers().contains(
(int) Math.round(componentType.getZOrder()));
}
@@ -6,10 +6,6 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -23,16 +19,11 @@ import org.diylc.components.boards.BlankBoard;
import org.diylc.components.boards.PerfBoard;
import org.diylc.components.boards.VeroBoard;
import org.diylc.components.connectivity.CopperTrace;
import org.diylc.components.connectivity.HookupWire;
import org.diylc.components.connectivity.Jumper;
import org.diylc.components.connectivity.SolderPad;
import org.diylc.components.misc.Label;
import org.diylc.components.passive.ElectrolyticRadial;
import org.diylc.components.passive.RadialFilmCapacitor;
import org.diylc.components.passive.Resistor;
import org.diylc.components.semiconductors.DIL_IC;
import org.diylc.components.semiconductors.DiodePlastic;
import org.diylc.components.semiconductors.TransistorTO92;
import org.diylc.core.IDIYComponent;
import org.diylc.core.Project;
import org.diylc.core.measures.Capacitance;
@@ -54,19 +45,10 @@ public class ProjectFileManager {
private static final Logger LOG = Logger.getLogger(ProjectFileManager.class);
// private static final int V1_PIXELS_PER_INCH = 200;
private static final int V1_PIXELS_PER_INCH = 200;
private static final Size V1_GRID_SPACING = new Size(0.1d, SizeUnit.in);
private static final Map<String, Color> V1_COLOR_MAP = new HashMap<String, Color>();
static {
V1_COLOR_MAP.put("red", Color.red);
V1_COLOR_MAP.put("blue", Color.blue);
V1_COLOR_MAP.put("white", Color.white);
V1_COLOR_MAP.put("green", Color.green.darker());
V1_COLOR_MAP.put("black", Color.black);
V1_COLOR_MAP.put("yellow", Color.yellow);
}
private XStream xStream;
private XStream xStream = new XStream(new DomDriver());
private String currentFileName = null;
private boolean modified = false;
@@ -75,17 +57,9 @@ public class ProjectFileManager {
public ProjectFileManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.xStream = new XStream(new DomDriver());
xStream.autodetectAnnotations(true);
this.messageDispatcher = messageDispatcher;
}
public void startNewFile() {
currentFileName = null;
modified = false;
fireFileStatusChanged();
}
public void serializeProjectToFile(Project project, String fileName) throws IOException {
LOG.info(String.format("saveProjectToFile(%s)", fileName));
FileOutputStream fos;
@@ -97,8 +71,8 @@ public class ProjectFileManager {
fireFileStatusChanged();
}
public Project deserializeProjectFromFile(String fileName, List<String> warnings)
throws SAXException, IOException, ParserConfigurationException {
public Project deserializeProjectFromFile(String fileName) throws SAXException, IOException,
ParserConfigurationException {
LOG.info(String.format("loadProjectFromFile(%s)", fileName));
Project project;
File file = new File(fileName);
@@ -116,7 +90,7 @@ public class ProjectFileManager {
String formatVersion = doc.getDocumentElement().getAttribute("formatVersion");
if (formatVersion == null || formatVersion.trim().isEmpty()) {
LOG.debug("Detected v1 file.");
project = parseV1File(doc.getDocumentElement(), warnings);
project = parseV1File(doc.getDocumentElement());
} else if (formatVersion.equals("2.0")) {
LOG.debug("Detected v2 file.");
project = parseV2File(doc.getDocumentElement());
@@ -124,7 +98,6 @@ public class ProjectFileManager {
throw new IllegalArgumentException("Unknown file format version: " + formatVersion);
}
}
Collections.sort(warnings);
this.currentFileName = fileName;
this.modified = false;
return project;
@@ -148,7 +121,7 @@ public class ProjectFileManager {
isModified());
}
private Project parseV1File(Element root, List<String> warnings) {
private Project parseV1File(Element root) {
Project project = new Project();
project.setTitle(root.getAttribute("Project"));
project.setAuthor(root.getAttribute("Credits"));
@@ -200,11 +173,6 @@ public class ProjectFileManager {
Point point2 = null;
Integer x2Attr = null;
Integer y2Attr = null;
Color color = null;
if (node.getAttributes().getNamedItem("Color") != null) {
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
color = V1_COLOR_MAP.get(colorAttr.toLowerCase());
}
if (node.getAttributes().getNamedItem("X2") != null
&& node.getAttributes().getNamedItem("Y2") != null) {
x2Attr = Integer.parseInt(node.getAttributes().getNamedItem("X2")
@@ -214,35 +182,20 @@ public class ProjectFileManager {
point2 = convertV1CoordinatesToV3Point(referencePoint, x2Attr, y2Attr);
}
IDIYComponent<?> component = null;
if (nodeName.equalsIgnoreCase("text")) {
LOG.debug("Recognized " + nodeName);
Label label = new Label();
label.setName(nameAttr);
if (color != null) {
label.setColor(color);
}
label.setText(valueAttr);
label.setCenter(false);
label.setControlPoint(convertV1CoordinatesToV3Point(referencePoint, x1Attr,
y1Attr), 0);
component = label;
} else if (nodeName.equalsIgnoreCase("pad")) {
if (nodeName.equalsIgnoreCase("pad")) {
LOG.debug("Recognized " + nodeName);
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
SolderPad pad = new SolderPad();
pad.setName(nameAttr);
if (color != null) {
pad.setColor(color);
}
// pad.setColor(Color.getColor(colorAttr));
pad.setControlPoint(convertV1CoordinatesToV3Point(referencePoint, x1Attr,
y1Attr), 0);
component = pad;
} else if (nodeName.equalsIgnoreCase("trace")) {
LOG.debug("Recognized " + nodeName);
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
CopperTrace trace = new CopperTrace();
trace.setName(nameAttr);
if (color != null) {
trace.setLeadColor(color);
}
trace.setControlPoint(point1, 0);
trace.setControlPoint(point2, 1);
component = trace;
@@ -253,16 +206,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();
@@ -272,8 +215,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;
@@ -286,68 +229,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("electrolyte")) {
LOG.debug("Recognized " + nodeName);
ElectrolyticRadial capacitor = new ElectrolyticRadial();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
String sizeAttr = node.getAttributes().getNamedItem("Size").getNodeValue();
if (sizeAttr.equalsIgnoreCase("small")) {
capacitor.setLength(new Size(3d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("medium")) {
capacitor.setLength(new Size(5d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("large")) {
capacitor.setLength(new Size(7d, SizeUnit.mm));
} else {
capacitor.setLength(new Size(4d, SizeUnit.mm));
}
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("diode")) {
LOG.debug("Recognized " + nodeName);
DiodePlastic capacitor = new DiodePlastic();
capacitor.setName(nameAttr);
try {
capacitor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
capacitor.setLength(new Size(6d, SizeUnit.mm));
capacitor.setWidth(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("transistor")) {
LOG.debug("Recognized " + nodeName);
TransistorTO92 transistor = new TransistorTO92();
transistor.setName(nameAttr);
try {
transistor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
transistor.setControlPoint(point1, 0);
if (point1.y > point2.y) {
transistor.setOrientation(Orientation._180);
} else if (point1.y < point2.y) {
transistor.setOrientation(Orientation.DEFAULT);
} else if (point1.x < point2.x) {
transistor.setOrientation(Orientation._270);
} else if (point1.x > point2.x) {
transistor.setOrientation(Orientation._90);
}
// capacitor.setControlPoint(point2, 1);
component = transistor;
} else if (nodeName.equalsIgnoreCase("ic")) {
LOG.debug("Recognized " + nodeName);
DIL_IC ic = new DIL_IC();
@@ -364,28 +250,17 @@ public class ProjectFileManager {
}
}
ic.setName(nameAttr);
// Translate control points.
for (int j = 0; j < ic.getControlPointCount(); j++) {
Point p = new Point(ic.getControlPoint(j));
p.translate(point1.x, point1.y);
ic.setControlPoint(p, j);
}
ic.setControlPoint(point1, 0);
ic.setValue(valueAttr);
component = ic;
} else {
String message = "Could not recognize component type " + nodeName;
LOG.debug(message);
if (!warnings.contains(message)) {
warnings.add(message);
}
LOG.debug("Could not recognize component type " + nodeName);
}
if (component != null) {
project.getComponents().add(component);
}
}
}
Collections.sort(project.getComponents(), ComparatorFactory.getInstance()
.getComponentZOrderComparator());
return project;
}
@@ -1,792 +0,0 @@
package org.diylc.swing;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.print.PrinterException;
import java.io.File;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.KeyStroke;
import org.apache.log4j.Logger;
import org.diylc.common.IPlugInPort;
import org.diylc.common.ITask;
import org.diylc.common.PropertyWrapper;
import org.diylc.core.IDIYComponent;
import org.diylc.images.IconLoader;
import org.diylc.swing.gui.DialogFactory;
import org.diylc.swing.gui.editor.PropertyEditorDialog;
import org.diylc.swing.plugins.edit.ComponentTransferable;
import org.diylc.swing.plugins.file.BomDialog;
import org.diylc.swing.plugins.file.BomEntry;
import org.diylc.swing.plugins.file.BomMaker;
import org.diylc.swing.plugins.file.FileFilterEnum;
import com.diyfever.gui.ButtonDialog;
import com.diyfever.gui.IDrawingProvider;
import com.diyfever.gui.export.DrawingExporter;
import com.rits.cloning.Cloner;
public class ActionFactory {
private static final Logger LOG = Logger.getLogger(ActionFactory.class);
private static ActionFactory instance;
private static Cloner cloner = new Cloner();
public static ActionFactory getInstance() {
if (instance == null) {
instance = new ActionFactory();
}
return instance;
}
private ActionFactory() {
}
// File menu actions.
public NewAction createNewAction(IPlugInPort plugInPort) {
return new NewAction(plugInPort);
}
public OpenAction createOpenAction(IPlugInPort plugInPort, ISwingUI swingUI) {
return new OpenAction(plugInPort, swingUI);
}
public SaveAction createSaveAction(IPlugInPort plugInPort, ISwingUI swingUI) {
return new SaveAction(plugInPort, swingUI);
}
public SaveAsAction createSaveAsAction(IPlugInPort plugInPort, ISwingUI swingUI) {
return new SaveAsAction(plugInPort, swingUI);
}
public CreateBomAction createBomAction(IPlugInPort plugInPort) {
return new CreateBomAction(plugInPort);
}
public ExportPDFAction createExportPDFAction(IDrawingProvider drawingProvider, ISwingUI swingUI) {
return new ExportPDFAction(drawingProvider, swingUI);
}
public ExportPNGAction createExportPNGAction(IDrawingProvider drawingProvider, ISwingUI swingUI) {
return new ExportPNGAction(drawingProvider, swingUI);
}
public PrintAction createPrintAction(IDrawingProvider drawingProvider) {
return new PrintAction(drawingProvider);
}
public ExitAction createExitAction(IPlugInPort plugInPort) {
return new ExitAction(plugInPort);
}
// Edit menu actions.
public CutAction createCutAction(IPlugInPort plugInPort, Clipboard clipboard,
ClipboardOwner clipboardOwner) {
return new CutAction(plugInPort, clipboard, clipboardOwner);
}
public CopyAction createCopyAction(IPlugInPort plugInPort, Clipboard clipboard,
ClipboardOwner clipboardOwner) {
return new CopyAction(plugInPort, clipboard, clipboardOwner);
}
public PasteAction createPasteAction(IPlugInPort plugInPort, Clipboard clipboard) {
return new PasteAction(plugInPort, clipboard);
}
public SelectAllAction createSelectAllAction(IPlugInPort plugInPort) {
return new SelectAllAction(plugInPort);
}
public GroupAction createGroupAction(IPlugInPort plugInPort) {
return new GroupAction(plugInPort);
}
public UngroupAction createUngroupAction(IPlugInPort plugInPort) {
return new UngroupAction(plugInPort);
}
public EditProjectAction createEditProjectAction(IPlugInPort plugInPort) {
return new EditProjectAction(plugInPort);
}
public EditSelectionAction createEditSelectionAction(IPlugInPort plugInPort) {
return new EditSelectionAction(plugInPort);
}
public DeleteSelectionAction createDeleteSelectionAction(IPlugInPort plugInPort) {
return new DeleteSelectionAction(plugInPort);
}
public SendToBackAction createSendToBackAction(IPlugInPort plugInPort) {
return new SendToBackAction(plugInPort);
}
public BringToFrontAction createBringToFrontAction(IPlugInPort plugInPort) {
return new BringToFrontAction(plugInPort);
}
// File menu actions.
public static class NewAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public NewAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "New");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.DocumentPlainYellow.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("NewAction triggered");
if (!plugInPort.allowFileAction()) {
return;
}
plugInPort.createNewProject();
List<PropertyWrapper> properties = plugInPort.getProjectProperties();
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Project");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToProject(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setProjectDefaultPropertyValue(property.getName(), property
.getValue());
}
}
}
}
public static class OpenAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private ISwingUI swingUI;
public OpenAction(IPlugInPort plugInPort, ISwingUI swingUI) {
super();
this.plugInPort = plugInPort;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Open");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.FolderOut.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("OpenAction triggered");
if (!plugInPort.allowFileAction()) {
return;
}
final File file = DialogFactory.getInstance().showOpenDialog(
FileFilterEnum.DIY.getFilter(), null, FileFilterEnum.DIY.getExtensions()[0],
null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Opening from " + file.getAbsolutePath());
plugInPort.loadProjectFromFile(file.getAbsolutePath());
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not open file. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class SaveAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private ISwingUI swingUI;
public SaveAction(IPlugInPort plugInPort, ISwingUI swingUI) {
super();
this.plugInPort = plugInPort;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Save");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.DiskBlue.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("SaveAction triggered");
if (plugInPort.getCurrentFileName() == null) {
final File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.DIY.getFilter(), null,
FileFilterEnum.DIY.getExtensions()[0], null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + file.getAbsolutePath());
plugInPort.saveProjectToFile(file.getAbsolutePath());
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not save to file. " + e.getMessage(),
"Error", ISwingUI.ERROR_MESSAGE);
}
});
}
} else {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + plugInPort.getCurrentFileName());
plugInPort.saveProjectToFile(plugInPort.getCurrentFileName());
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not save to file. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class SaveAsAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private ISwingUI swingUI;
public SaveAsAction(IPlugInPort plugInPort, ISwingUI swingUI) {
super();
this.plugInPort = plugInPort;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Save As");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S,
ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.DiskBlue.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("SaveAsAction triggered");
final File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.DIY.getFilter(), null, FileFilterEnum.DIY.getExtensions()[0],
null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Saving to " + file.getAbsolutePath());
plugInPort.saveProjectToFile(file.getAbsolutePath());
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not save to file. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class CreateBomAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public CreateBomAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Create B.O.M.");
putValue(AbstractAction.SMALL_ICON, IconLoader.BOM.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("CreateBomAction triggered");
List<BomEntry> bom = BomMaker.getInstance().createBom(
plugInPort.getCurrentProject().getComponents());
BomDialog dialog = DialogFactory.getInstance().createBomDialog(bom);
dialog.setVisible(true);
}
}
public static class ExportPDFAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
private ISwingUI swingUI;
public ExportPDFAction(IDrawingProvider drawingProvider, ISwingUI swingUI) {
super();
this.drawingProvider = drawingProvider;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Export to PDF");
putValue(AbstractAction.SMALL_ICON, IconLoader.PDF.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("ExportPDFAction triggered");
final File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.PDF.getFilter(), null, FileFilterEnum.PDF.getExtensions()[0],
null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Exporting to " + file.getAbsolutePath());
DrawingExporter.getInstance().exportPDF(
ExportPDFAction.this.drawingProvider, file);
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not export to PDF. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class ExportPNGAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
private ISwingUI swingUI;
public ExportPNGAction(IDrawingProvider drawingProvider, ISwingUI swingUI) {
super();
this.drawingProvider = drawingProvider;
this.swingUI = swingUI;
putValue(AbstractAction.NAME, "Export to PNG");
putValue(AbstractAction.SMALL_ICON, IconLoader.Image.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("ExportPNGAction triggered");
final File file = DialogFactory.getInstance().showSaveDialog(
FileFilterEnum.PNG.getFilter(), null, FileFilterEnum.PNG.getExtensions()[0],
null);
if (file != null) {
swingUI.executeBackgroundTask(new ITask<Void>() {
@Override
public Void doInBackground() throws Exception {
LOG.debug("Exporting to " + file.getAbsolutePath());
DrawingExporter.getInstance().exportPNG(
ExportPNGAction.this.drawingProvider, file);
return null;
}
@Override
public void complete(Void result) {
}
@Override
public void failed(Exception e) {
swingUI.showMessage("Could not export to PNG. " + e.getMessage(), "Error",
ISwingUI.ERROR_MESSAGE);
}
});
}
}
}
public static class PrintAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IDrawingProvider drawingProvider;
public PrintAction(IDrawingProvider drawingProvider) {
super();
this.drawingProvider = drawingProvider;
putValue(AbstractAction.NAME, "Print...");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Print.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("ExportPNGAction triggered");
try {
DrawingExporter.getInstance().print(this.drawingProvider);
} catch (PrinterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public static class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public ExitAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Exit");
putValue(AbstractAction.SMALL_ICON, IconLoader.Exit.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
if (plugInPort.allowFileAction()) {
System.exit(0);
}
}
}
// Edit menu actions.
public static class CutAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private Clipboard clipboard;
private ClipboardOwner clipboardOwner;
public CutAction(IPlugInPort plugInPort, Clipboard clipboard, ClipboardOwner clipboardOwner) {
super();
this.plugInPort = plugInPort;
this.clipboard = clipboard;
this.clipboardOwner = clipboardOwner;
putValue(AbstractAction.NAME, "Cut");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Cut.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Cut triggered");
clipboard.setContents(new ComponentTransferable(cloner.deepClone(plugInPort
.getSelectedComponents())), clipboardOwner);
plugInPort.deleteSelectedComponents();
}
}
public static class CopyAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private Clipboard clipboard;
private ClipboardOwner clipboardOwner;
public CopyAction(IPlugInPort plugInPort, Clipboard clipboard, ClipboardOwner clipboardOwner) {
super();
this.plugInPort = plugInPort;
this.clipboard = clipboard;
this.clipboardOwner = clipboardOwner;
putValue(AbstractAction.NAME, "Copy");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Copy.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Copy triggered");
clipboard.setContents(new ComponentTransferable(cloner.deepClone(plugInPort
.getSelectedComponents())), clipboardOwner);
}
}
public static class PasteAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
private Clipboard clipboard;
public PasteAction(IPlugInPort plugInPort, Clipboard clipboard) {
super();
this.plugInPort = plugInPort;
this.clipboard = clipboard;
putValue(AbstractAction.NAME, "Paste");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Paste.getIcon());
}
@SuppressWarnings("unchecked")
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Paste triggered");
try {
List<IDIYComponent<?>> components = (List<IDIYComponent<?>>) clipboard
.getData(ComponentTransferable.listFlavor);
plugInPort.pasteComponents(cloner.deepClone(components));
} catch (Exception ex) {
LOG.error("Coule not paste.", ex);
}
}
}
public static class SelectAllAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public SelectAllAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Select All");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Selection.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Select All triggered");
plugInPort.selectAll();
}
}
public static class GroupAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public GroupAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Group Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_G,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Group.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Group Selection triggered");
plugInPort.groupSelectedComponents();
}
}
public static class UngroupAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public UngroupAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Ungroup Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_U,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.Ungroup.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Ungroup Selection triggered");
plugInPort.ungroupSelectedComponents();
}
}
public static class EditProjectAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public EditProjectAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Edit Project");
putValue(AbstractAction.SMALL_ICON, IconLoader.DocumentEdit.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Edit Project triggered");
List<PropertyWrapper> properties = plugInPort.getProjectProperties();
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Project");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToProject(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setProjectDefaultPropertyValue(property.getName(), property
.getValue());
}
}
}
}
public static class EditSelectionAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public EditSelectionAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Edit Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E,
ActionEvent.CTRL_MASK));
putValue(AbstractAction.SMALL_ICON, IconLoader.EditComponent.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Edit Selection triggered");
List<PropertyWrapper> properties = plugInPort.getMutualSelectionProperties();
if (properties == null || properties.isEmpty()) {
LOG.info("Nothing to edit");
return;
}
PropertyEditorDialog editor = DialogFactory.getInstance().createPropertyEditorDialog(
properties, "Edit Selection");
editor.setVisible(true);
if (ButtonDialog.OK.equals(editor.getSelectedButtonCaption())) {
plugInPort.applyPropertiesToSelection(properties);
}
// Save default values.
for (PropertyWrapper property : editor.getDefaultedProperties()) {
if (property.getValue() != null) {
plugInPort.setSelectionDefaultPropertyValue(property.getName(), property
.getValue());
}
}
}
}
public static class DeleteSelectionAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public DeleteSelectionAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Delete Selection");
putValue(AbstractAction.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
putValue(AbstractAction.SMALL_ICON, IconLoader.Delete.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Delete Selection triggered");
plugInPort.deleteSelectedComponents();
}
}
public static class SendToBackAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public SendToBackAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Send to Back");
putValue(AbstractAction.SMALL_ICON, IconLoader.Back.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Send to Back triggered");
plugInPort.sendSelectionToBack();
}
}
public static class BringToFrontAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private IPlugInPort plugInPort;
public BringToFrontAction(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
putValue(AbstractAction.NAME, "Bring to Front");
putValue(AbstractAction.SMALL_ICON, IconLoader.Front.getIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("Bring to Front triggered");
plugInPort.bringSelectionToFront();
}
}
}
-64
View File
@@ -1,64 +0,0 @@
package org.diylc.swing;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.SwingConstants;
import javax.swing.JPopupMenu.Separator;
import org.diylc.common.BadPositionException;
import org.diylc.common.ITask;
import org.diylc.core.IView;
/**
* Interface for plugin access to the swing front end.
*
* @author Branislav Stojkovic
*/
public interface ISwingUI extends IView {
/**
* Injects a custom GUI panels provided by the plug-in and desired position
* in the window. Application will layout plug-in panels accordingly. <br>
* Valid positions are:
* <ul>
* <li> {@link SwingConstants#TOP}</li>
* <li> {@link SwingConstants#BOTTOM}</li>
* <li> {@link SwingConstants#LEFT}</li>
* <li> {@link SwingConstants#RIGHT}</li>
* </ul>
*
* Center position is reserved for the main canvas panel and cannot be used.
*
* @param component
* @param position
* @throws BadPositionException
* in case invalid position is specified
*/
void injectGUIComponent(JComponent component, int position) throws BadPositionException;
/**
* Injects a custom menu action into application's main menu. If
* <code>action</code> is set to null {@link Separator} will be added. If
* the specified menu does not exist it will be automatically created.
*
* @param action
* {@link Action} to inser
* @param menuName
* name of the menu to insert into
*/
void injectMenuAction(Action action, String menuName);
/**
* Injects a custom submenu into application's main menu. If
* <code>action</code> is set to null {@link Separator} will be added. If
* the specified menu does not exist it will be automatically created.
*
* @param name
* @param icon
* @param parentMenuName
*/
void injectSubmenu(String name, Icon icon, String parentMenuName);
<T extends Object> void executeBackgroundTask(ITask<T> task);
}
@@ -1,278 +0,0 @@
package org.diylc.swing.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.log4j.Logger;
import org.diylc.common.DrawOption;
import org.diylc.common.IPlugInPort;
import org.diylc.core.IView;
import org.diylc.presenter.Presenter;
import com.diyfever.gui.miscutils.ConfigurationManager;
public class TemplateDialog extends JDialog {
private static final long serialVersionUID = 1L;
private static final Logger LOG = Logger.getLogger(TemplateDialog.class);
private static final Dimension panelSize = new Dimension(400, 300);
public static final String SHOW_TEMPLATES_KEY = "showTemplatesAtStartup";
private IPlugInPort plugInPort;
private JList fileList;
private JPanel canvasPanel;
private Presenter presenter;
private List<File> files;
private JCheckBox showTemplatesBox;
private JPanel mainPanel;
private JButton loadButton;
private JPanel infoPanel;
public TemplateDialog(JFrame owner, IPlugInPort plugInPort) {
super(owner, "Templates");
setModal(true);
setResizable(false);
this.plugInPort = plugInPort;
this.presenter = new Presenter(new IView() {
@Override
public int showConfirmDialog(String message, String title, int optionType,
int messageType) {
return JOptionPane.showConfirmDialog(TemplateDialog.this, message, title,
optionType, messageType);
}
@Override
public void showMessage(String message, String title, int messageType) {
JOptionPane.showMessageDialog(TemplateDialog.this, message, title, messageType);
}
});
// this.presenter.installPlugin(new IPlugIn() {
//
// @Override
// public void connect(IPlugInPort plugInPort) {
// }
//
// @Override
// public EnumSet<EventType> getSubscribedEventTypes() {
// return EnumSet.of(EventType.REPAINT);
// }
//
// @Override
// public void processMessage(EventType eventType, Object... params) {
// if (eventType == EventType.REPAINT) {
// getCanvasPanel().repaint();
// }
// }
// });
setContentPane(getMainPanel());
pack();
setLocationRelativeTo(owner);
}
public JPanel getMainPanel() {
if (mainPanel == null) {
mainPanel = new JPanel(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 0;
c.weighty = 1;
c.weightx = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(0, 0, 4, 0);
mainPanel.add(getInfoPanel(), c);
c.gridy = 1;
c.weightx = 0;
c.gridwidth = 1;
c.insets = new Insets(0, 0, 0, 0);
JScrollPane scrollPane = new JScrollPane(getFileList());
mainPanel.add(scrollPane, c);
c.gridx = 1;
c.weightx = 1;
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(scrollPane.getBorder());
panel.add(getCanvasPanel(), BorderLayout.CENTER);
mainPanel.add(panel, c);
c.gridx = 0;
c.gridy = 2;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.LAST_LINE_START;
c.fill = GridBagConstraints.NONE;
mainPanel.add(getShowTemplatesBox(), c);
c.gridx = 1;
c.anchor = GridBagConstraints.LAST_LINE_END;
c.insets = new Insets(4, 0, 0, 0);
mainPanel.add(getLoadButton(), c);
}
return mainPanel;
}
public JButton getLoadButton() {
if (loadButton == null) {
loadButton = new JButton("Load Template");
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
plugInPort.loadProject(presenter.getCurrentProject(), true);
dispose();
}
});
}
return loadButton;
}
public JPanel getInfoPanel() {
if (infoPanel == null) {
infoPanel = new JPanel();
infoPanel.setBackground(Color.decode("#FFFFCC"));
infoPanel.setBorder(new JTextField().getBorder());
JLabel infoLabel = new JLabel(
"<html>Templates are semi-product layouts that are used as a starting point for your projects.<br>"
+ "Pick a templete in the left list and click \"Load Template\" to load it or close this dialog to continue.<br>"
+ "You can create your own templates by placing a DIY file into <b>diylc/templates</b> directory.</html>");
infoLabel.setOpaque(false);
infoPanel.add(infoLabel);
}
return infoPanel;
}
public JList getFileList() {
if (fileList == null) {
fileList = new JList(getFiles().toArray());
fileList.setPreferredSize(new Dimension(128, -1));
fileList.setCellRenderer(new DefaultListCellRenderer() {
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value instanceof File) {
label.setText(((File) value).getName());
}
return label;
}
});
fileList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
File file = (File) fileList.getSelectedValue();
if (file != null) {
presenter.loadProjectFromFile(file.getAbsolutePath());
Dimension dim = presenter.getCanvasDimensions(true);
double xFactor = panelSize.getWidth() / dim.getWidth();
double yFactor = panelSize.getHeight() / dim.getHeight();
presenter.setZoomLevel(Math.min(xFactor, yFactor));
getCanvasPanel().repaint();
}
}
});
fileList.setSelectedIndex(0);
}
return fileList;
}
public JCheckBox getShowTemplatesBox() {
if (showTemplatesBox == null) {
showTemplatesBox = new JCheckBox("Show this dialog at startup");
showTemplatesBox.setSelected(true);
showTemplatesBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ConfigurationManager.getInstance().writeValue(SHOW_TEMPLATES_KEY,
showTemplatesBox.isSelected());
}
});
}
return showTemplatesBox;
}
public List<File> getFiles() {
if (files == null) {
files = new ArrayList<File>();
File dir = new File("templates");
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().toLowerCase().endsWith(".diy")) {
files.add(f);
}
}
}
LOG.debug("Found " + files.size() + " templates");
}
return files;
}
public JPanel getCanvasPanel() {
if (canvasPanel == null) {
canvasPanel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
public void paint(Graphics g) {
super.paint(g);
// Graphics2D g2d = (Graphics2D) g;
// AffineTransform transform = g2d.getTransform();
presenter.draw((Graphics2D) g, EnumSet.of(DrawOption.ZOOM,
DrawOption.ANTIALIASING), null);
// g2d.setTransform(transform);
// Rectangle rect = canvasPanel.getBounds();
// BorderFactory.createEtchedBorder().paintBorder(canvasPanel,
// g, 0, 0,
// (int) rect.getWidth(), (int) rect.getHeight());
}
};
canvasPanel.setBackground(Color.white);
canvasPanel.setPreferredSize(panelSize);
}
return canvasPanel;
}
}
@@ -1,26 +0,0 @@
package org.diylc.swing.gui.editor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import org.diylc.common.PropertyWrapper;
public class BooleanEditor extends JCheckBox {
private static final long serialVersionUID = 1L;
public BooleanEditor(final PropertyWrapper property) {
super();
setSelected((Boolean) property.getValue());
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
property.setValue(isSelected());
}
});
}
}
@@ -1,44 +0,0 @@
package org.diylc.swing.gui.editor;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import org.diylc.common.PropertyWrapper;
import org.diylc.swing.gui.DialogFactory;
import org.diylc.swing.plugins.file.FileFilterEnum;
public class ImageEditor extends JButton {
private static final long serialVersionUID = 1L;
public ImageEditor(final PropertyWrapper property) {
super("Click to load file");
addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
File file = DialogFactory.getInstance().showOpenDialog(
FileFilterEnum.IMAGES.getFilter(), null,
FileFilterEnum.IMAGES.getExtensions()[0], null);
if (file != null) {
ImageIcon image = new ImageIcon(file.getAbsolutePath());
property.setValue(image);
}
}
});
}
@Override
public void setBackground(Color bg) {
if (bg.getRed() < 127 || bg.getBlue() < 127 || bg.getGreen() < 127) {
setForeground(Color.white);
} else {
setForeground(Color.black);
}
super.setBackground(bg);
}
}
@@ -1,309 +0,0 @@
package org.diylc.swing.plugins.canvas;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.EnumSet;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import org.apache.log4j.Logger;
import org.diylc.common.BadPositionException;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
import org.diylc.presenter.Presenter;
import org.diylc.swing.ActionFactory;
import org.diylc.swing.ISwingUI;
import org.diylc.swing.plugins.edit.ComponentTransferable;
import org.diylc.swing.plugins.file.ProjectDrawingProvider;
import com.diyfever.gui.miscutils.ConfigurationManager;
import com.diyfever.gui.ruler.IRulerListener;
import com.diyfever.gui.ruler.RulerScrollPane;
public class CanvasPlugin implements IPlugIn, ClipboardOwner {
private static final Logger LOG = Logger.getLogger(CanvasPlugin.class);
private static final String WHEEL_ZOOM = "wheelZoom";
private RulerScrollPane scrollPane;
private CanvasPanel canvasPanel;
private JPopupMenu popupMenu;
private ActionFactory.CutAction cutAction;
private ActionFactory.CopyAction copyAction;
private ActionFactory.PasteAction pasteAction;
private ActionFactory.EditSelectionAction editSelectionAction;
private ActionFactory.DeleteSelectionAction deleteSelectionAction;
private ActionFactory.GroupAction groupAction;
private ActionFactory.UngroupAction ungroupAction;
private ActionFactory.SendToBackAction sendToBackAction;
private ActionFactory.BringToFrontAction bringToFrontAction;
private IPlugInPort plugInPort;
private ISwingUI swingUI;
private Clipboard clipboard;
private double zoomLevel = 1;
public CanvasPlugin(ISwingUI swingUI) {
this.swingUI = swingUI;
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
try {
swingUI.injectGUIComponent(getScrollPane(), SwingConstants.CENTER);
} catch (BadPositionException e) {
LOG.error("Could not install canvas plugin", e);
}
}
public CanvasPanel getCanvasPanel() {
if (canvasPanel == null) {
canvasPanel = new CanvasPanel(plugInPort);
canvasPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
// Enable actions.
boolean enabled = !plugInPort.getSelectedComponents().isEmpty();
getCutAction().setEnabled(enabled);
getCopyAction().setEnabled(enabled);
try {
getPasteAction()
.setEnabled(
clipboard
.isDataFlavorAvailable(ComponentTransferable.listFlavor));
} catch (Exception ex) {
getPasteAction().setEnabled(false);
}
getEditSelectionAction().setEnabled(enabled);
getDeleteSelectionAction().setEnabled(enabled);
getGroupAction().setEnabled(enabled);
getUngroupAction().setEnabled(enabled);
getSendToBackAction().setEnabled(enabled);
getBringToFrontAction().setEnabled(enabled);
getPopupMenu().show(canvasPanel, e.getX(), e.getY());
}
}
});
}
return canvasPanel;
}
private RulerScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new RulerScrollPane(getCanvasPanel(), new ProjectDrawingProvider(
plugInPort, true), new Size(1d, SizeUnit.cm).convertToPixels(), new Size(1d,
SizeUnit.in).convertToPixels());
boolean metric = ConfigurationManager.getInstance().readBoolean(Presenter.METRIC_KEY,
true);
boolean wheelZoom = ConfigurationManager.getInstance().readBoolean(WHEEL_ZOOM, false);
scrollPane.setMetric(metric);
scrollPane.setWheelScrollingEnabled(!wheelZoom);
scrollPane.addUnitListener(new IRulerListener() {
@Override
public void unitsChanged(boolean isMetric) {
plugInPort.setMetric(isMetric);
}
});
if (wheelZoom) {
scrollPane.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
double d = plugInPort.getZoomLevel();
Double[] availableZoomLevels = plugInPort.getAvailableZoomLevels();
if (e.getWheelRotation() > 0) {
int i = availableZoomLevels.length - 1;
while (i > 0 && availableZoomLevels[i] >= d) {
i--;
}
plugInPort.setZoomLevel(availableZoomLevels[i]);
} else {
int i = 0;
while (i < availableZoomLevels.length - 1
&& availableZoomLevels[i] <= d) {
i++;
}
plugInPort.setZoomLevel(availableZoomLevels[i]);
}
}
});
}
}
return scrollPane;
}
public JPopupMenu getPopupMenu() {
if (popupMenu == null) {
popupMenu = new JPopupMenu();
popupMenu.add(getCutAction());
popupMenu.add(getCopyAction());
popupMenu.add(getPasteAction());
popupMenu.addSeparator();
popupMenu.add(getEditSelectionAction());
popupMenu.add(getDeleteSelectionAction());
popupMenu.add(getGroupAction());
popupMenu.add(getUngroupAction());
popupMenu.add(getSendToBackAction());
popupMenu.add(getBringToFrontAction());
popupMenu.addSeparator();
popupMenu.add(ActionFactory.getInstance().createEditProjectAction(plugInPort));
}
return popupMenu;
}
public ActionFactory.CutAction getCutAction() {
if (cutAction == null) {
cutAction = ActionFactory.getInstance().createCutAction(plugInPort, clipboard, this);
}
return cutAction;
}
public ActionFactory.CopyAction getCopyAction() {
if (copyAction == null) {
copyAction = ActionFactory.getInstance().createCopyAction(plugInPort, clipboard, this);
}
return copyAction;
}
public ActionFactory.PasteAction getPasteAction() {
if (pasteAction == null) {
pasteAction = ActionFactory.getInstance().createPasteAction(plugInPort, clipboard);
}
return pasteAction;
}
public ActionFactory.EditSelectionAction getEditSelectionAction() {
if (editSelectionAction == null) {
editSelectionAction = ActionFactory.getInstance().createEditSelectionAction(plugInPort);
}
return editSelectionAction;
}
public ActionFactory.DeleteSelectionAction getDeleteSelectionAction() {
if (deleteSelectionAction == null) {
deleteSelectionAction = ActionFactory.getInstance().createDeleteSelectionAction(
plugInPort);
}
return deleteSelectionAction;
}
public ActionFactory.GroupAction getGroupAction() {
if (groupAction == null) {
groupAction = ActionFactory.getInstance().createGroupAction(plugInPort);
}
return groupAction;
}
public ActionFactory.UngroupAction getUngroupAction() {
if (ungroupAction == null) {
ungroupAction = ActionFactory.getInstance().createUngroupAction(plugInPort);
}
return ungroupAction;
}
public ActionFactory.SendToBackAction getSendToBackAction() {
if (sendToBackAction == null) {
sendToBackAction = ActionFactory.getInstance().createSendToBackAction(plugInPort);
}
return sendToBackAction;
}
public ActionFactory.BringToFrontAction getBringToFrontAction() {
if (bringToFrontAction == null) {
bringToFrontAction = ActionFactory.getInstance().createBringToFrontAction(plugInPort);
}
return bringToFrontAction;
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.PROJECT_LOADED, EventType.ZOOM_CHANGED, EventType.REPAINT);
}
@Override
public void processMessage(final EventType eventType, Object... params) {
// SwingUtilities.invokeLater(new Runnable() {
//
// @Override
// public void run() {
// LOG.debug("event: " + eventType);
switch (eventType) {
case PROJECT_LOADED:
refreshSize();
if ((Boolean) params[1]) {
// Scroll to the center.
Rectangle visibleRect = canvasPanel.getVisibleRect();
visibleRect.setLocation((canvasPanel.getWidth() - visibleRect.width) / 2,
(canvasPanel.getHeight() - visibleRect.height) / 2);
canvasPanel.scrollRectToVisible(visibleRect);
canvasPanel.revalidate();
}
break;
case ZOOM_CHANGED:
Rectangle visibleRect = canvasPanel.getVisibleRect();
refreshSize();
// Try to set the visible area to be centered with the previous
// one.
double zoomFactor = (Double) params[0] / zoomLevel;
visibleRect.setBounds((int) (visibleRect.x * zoomFactor),
(int) (visibleRect.y * zoomFactor), visibleRect.width, visibleRect.height);
canvasPanel.scrollRectToVisible(visibleRect);
canvasPanel.revalidate();
zoomLevel = (Double) params[0];
break;
case REPAINT:
canvasPanel.repaint();
break;
}
// }
// });
}
private void refreshSize() {
Dimension d = plugInPort.getCanvasDimensions(true);
canvasPanel.setSize(d);
canvasPanel.setPreferredSize(d);
getScrollPane().setZoomLevel(plugInPort.getZoomLevel());
}
/**
* Causes ruler scroll pane to refresh by sending a fake mouse moved message
* to the canvasPanel.
*/
public void refresh() {
MouseEvent event = new MouseEvent(canvasPanel, MouseEvent.MOUSE_MOVED, System
.currentTimeMillis(), 0, 1, 1,// canvasPanel.getWidth() / 2,
// canvasPanel.getHeight() / 2,
0, false);
canvasPanel.dispatchEvent(event);
}
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
// TODO Auto-generated method stub
}
}
@@ -1,200 +0,0 @@
package org.diylc.swing.plugins.edit;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.Transferable;
import java.util.EnumSet;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.core.Project;
import org.diylc.swing.ActionFactory;
import org.diylc.swing.ISwingUI;
import com.diyfever.gui.undo.IUndoListener;
import com.diyfever.gui.undo.UndoHandler;
public class EditMenuPlugin implements IPlugIn, ClipboardOwner {
private static final String EDIT_TITLE = "Edit";
private IPlugInPort plugInPort;
private ISwingUI swingUI;
private Clipboard clipboard;
private ActionFactory.CutAction cutAction;
private ActionFactory.CopyAction copyAction;
private ActionFactory.PasteAction pasteAction;
private ActionFactory.EditSelectionAction editSelectionAction;
private ActionFactory.DeleteSelectionAction deleteSelectionAction;
private ActionFactory.GroupAction groupAction;
private ActionFactory.UngroupAction ungroupAction;
private ActionFactory.SendToBackAction sendToBackAction;
private ActionFactory.BringToFrontAction bringToFrontAction;
private UndoHandler<Project> undoHandler;
public EditMenuPlugin(ISwingUI swingUI) {
this.swingUI = swingUI;
// SecurityManager securityManager = System.getSecurityManager();
// if (securityManager != null) {
// try {
// securityManager.checkSystemClipboardAccess();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
undoHandler = new UndoHandler<Project>(new IUndoListener<Project>() {
@Override
public void actionPerformed(Project currentState) {
plugInPort.loadProject(currentState, false);
}
});
clipboard.addFlavorListener(new FlavorListener() {
@Override
public void flavorsChanged(FlavorEvent e) {
refreshActions();
}
});
}
public ActionFactory.CutAction getCutAction() {
if (cutAction == null) {
cutAction = ActionFactory.getInstance().createCutAction(plugInPort, clipboard, this);
}
return cutAction;
}
public ActionFactory.CopyAction getCopyAction() {
if (copyAction == null) {
copyAction = ActionFactory.getInstance().createCopyAction(plugInPort, clipboard, this);
}
return copyAction;
}
public ActionFactory.PasteAction getPasteAction() {
if (pasteAction == null) {
pasteAction = ActionFactory.getInstance().createPasteAction(plugInPort, clipboard);
}
return pasteAction;
}
public ActionFactory.EditSelectionAction getEditSelectionAction() {
if (editSelectionAction == null) {
editSelectionAction = ActionFactory.getInstance().createEditSelectionAction(plugInPort);
}
return editSelectionAction;
}
public ActionFactory.DeleteSelectionAction getDeleteSelectionAction() {
if (deleteSelectionAction == null) {
deleteSelectionAction = ActionFactory.getInstance().createDeleteSelectionAction(
plugInPort);
}
return deleteSelectionAction;
}
public ActionFactory.GroupAction getGroupAction() {
if (groupAction == null) {
groupAction = ActionFactory.getInstance().createGroupAction(plugInPort);
}
return groupAction;
}
public ActionFactory.UngroupAction getUngroupAction() {
if (ungroupAction == null) {
ungroupAction = ActionFactory.getInstance().createUngroupAction(plugInPort);
}
return ungroupAction;
}
public ActionFactory.SendToBackAction getSendToBackAction() {
if (sendToBackAction == null) {
sendToBackAction = ActionFactory.getInstance().createSendToBackAction(plugInPort);
}
return sendToBackAction;
}
public ActionFactory.BringToFrontAction getBringToFrontAction() {
if (bringToFrontAction == null) {
bringToFrontAction = ActionFactory.getInstance().createBringToFrontAction(plugInPort);
}
return bringToFrontAction;
}
@Override
public void connect(IPlugInPort plugInPort) {
this.plugInPort = plugInPort;
ActionFactory actionFactory = ActionFactory.getInstance();
swingUI.injectMenuAction(undoHandler.getUndoAction(), EDIT_TITLE);
swingUI.injectMenuAction(undoHandler.getRedoAction(), EDIT_TITLE);
swingUI.injectMenuAction(null, EDIT_TITLE);
swingUI.injectMenuAction(getCutAction(), EDIT_TITLE);
swingUI.injectMenuAction(getCopyAction(), EDIT_TITLE);
swingUI.injectMenuAction(getPasteAction(), EDIT_TITLE);
swingUI.injectMenuAction(null, EDIT_TITLE);
swingUI.injectMenuAction(actionFactory.createSelectAllAction(plugInPort), EDIT_TITLE);
swingUI.injectMenuAction(getEditSelectionAction(), EDIT_TITLE);
swingUI.injectMenuAction(getDeleteSelectionAction(), EDIT_TITLE);
swingUI.injectMenuAction(getGroupAction(), EDIT_TITLE);
swingUI.injectMenuAction(getUngroupAction(), EDIT_TITLE);
swingUI.injectMenuAction(getSendToBackAction(), EDIT_TITLE);
swingUI.injectMenuAction(getBringToFrontAction(), EDIT_TITLE);
swingUI.injectMenuAction(null, EDIT_TITLE);
swingUI.injectMenuAction(actionFactory.createEditProjectAction(plugInPort), EDIT_TITLE);
refreshActions();
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return EnumSet.of(EventType.SELECTION_CHANGED, EventType.PROJECT_MODIFIED);
}
@Override
public void processMessage(EventType eventType, Object... params) {
switch (eventType) {
case SELECTION_CHANGED:
refreshActions();
break;
case PROJECT_MODIFIED:
undoHandler.stateChanged((Project) params[0], (Project) params[1], (String) params[2]);
break;
}
}
private void refreshActions() {
boolean enabled = !plugInPort.getSelectedComponents().isEmpty();
getCutAction().setEnabled(enabled);
getCopyAction().setEnabled(enabled);
try {
getPasteAction().setEnabled(
clipboard.isDataFlavorAvailable(ComponentTransferable.listFlavor));
} catch (Exception e) {
getPasteAction().setEnabled(false);
}
getEditSelectionAction().setEnabled(enabled);
getDeleteSelectionAction().setEnabled(enabled);
getGroupAction().setEnabled(enabled);
getUngroupAction().setEnabled(enabled);
getSendToBackAction().setEnabled(enabled);
getBringToFrontAction().setEnabled(enabled);
}
// ClipboardOwner
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
refreshActions();
}
}
@@ -1,69 +0,0 @@
package org.diylc.swing.plugins.file;
import java.util.EnumSet;
import org.diylc.common.EventType;
import org.diylc.common.IPlugIn;
import org.diylc.common.IPlugInPort;
import org.diylc.images.IconLoader;
import org.diylc.swing.ActionFactory;
import org.diylc.swing.ISwingUI;
/**
* Entry point class for File management utilities.
*
* @author Branislav Stojkovic
*/
public class FileMenuPlugin implements IPlugIn {
private static final String FILE_TITLE = "File";
private static final String TRACE_MASK_TITLE = "Trace Mask";
private ProjectDrawingProvider drawingProvider;
private TraceMaskDrawingProvider traceMaskDrawingProvider;
private ISwingUI swingUI;
public FileMenuPlugin(ISwingUI swingUI) {
super();
this.swingUI = swingUI;
}
@Override
public void connect(IPlugInPort plugInPort) {
this.drawingProvider = new ProjectDrawingProvider(plugInPort, false);
this.traceMaskDrawingProvider = new TraceMaskDrawingProvider(plugInPort);
ActionFactory actionFactory = ActionFactory.getInstance();
swingUI.injectMenuAction(actionFactory.createNewAction(plugInPort), FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createOpenAction(plugInPort, swingUI), FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createSaveAction(plugInPort, swingUI), FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createSaveAsAction(plugInPort, swingUI), FILE_TITLE);
swingUI.injectMenuAction(null, FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createExportPDFAction(drawingProvider, swingUI),
FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createExportPNGAction(drawingProvider, swingUI),
FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createPrintAction(drawingProvider), FILE_TITLE);
swingUI.injectSubmenu(TRACE_MASK_TITLE, IconLoader.TraceMask.getIcon(), FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createExportPDFAction(traceMaskDrawingProvider,
swingUI), TRACE_MASK_TITLE);
swingUI.injectMenuAction(actionFactory.createExportPNGAction(traceMaskDrawingProvider,
swingUI), TRACE_MASK_TITLE);
swingUI.injectMenuAction(actionFactory.createPrintAction(traceMaskDrawingProvider),
TRACE_MASK_TITLE);
swingUI.injectMenuAction(actionFactory.createBomAction(plugInPort), FILE_TITLE);
swingUI.injectMenuAction(null, FILE_TITLE);
swingUI.injectMenuAction(actionFactory.createExitAction(plugInPort), FILE_TITLE);
}
@Override
public EnumSet<EventType> getSubscribedEventTypes() {
return null;
}
@Override
public void processMessage(EventType eventType, Object... params) {
// Do nothing.
}
}
@@ -1,116 +0,0 @@
package org.diylc.swing.plugins.toolbox;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.diylc.common.ComponentType;
import org.diylc.common.IPlugInPort;
import org.diylc.presenter.ComparatorFactory;
import org.diylc.presenter.Presenter;
/**
* Tabbed pane that shows all available components categorized into tabs.
*
* @author Branislav Stojkovic
*/
class ComponentTabbedPane extends JTabbedPane {
public static int SCROLL_STEP = Presenter.ICON_SIZE + ComponentButton.MARGIN * 2 + 2;
private static final long serialVersionUID = 1L;
private final IPlugInPort plugInPort;
public ComponentTabbedPane(IPlugInPort plugInPort) {
super();
this.plugInPort = plugInPort;
Map<String, List<ComponentType>> componentTypes = plugInPort.getComponentTypes();
List<String> categories = new ArrayList<String>(componentTypes.keySet());
Collections.sort(categories);
for (String category : categories) {
JPanel panel = createTab((componentTypes.get(category)));
addTab(category, panel);
}
addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
ComponentTabbedPane.this.plugInPort.setNewComponentTypeSlot(null);
}
});
}
private JPanel createTab(List<ComponentType> componentTypes) {
JPanel panel = new JPanel(new BorderLayout());
// final JScrollPane scrollPane =
// createComponentScrollBar(componentTypes);
panel.setOpaque(false);
panel.add(createComponentPanel(componentTypes), BorderLayout.CENTER);
// JButton leftButton = new JButton("<");
// leftButton.addActionListener(new ActionListener() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// Rectangle rect = scrollPane.getVisibleRect();
// if (rect.x > SCROLL_STEP) {
// rect.translate(-SCROLL_STEP, 0);
// } else {
// rect.translate(-rect.x, 0);
// }
// }
// });
// leftButton.setMargin(new Insets(0, 2, 0, 2));
// JButton rightButton = new JButton(">");
// rightButton.addActionListener(new ActionListener() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// Rectangle rect = scrollPane.getVisibleRect();
// if (rect.x + rect.width < scrollPane.getViewport().getSize().width -
// SCROLL_STEP) {
// rect.translate(SCROLL_STEP, 0);
// } else {
// rect.translate(scrollPane.getViewport().getSize().width - rect.x -
// rect.width,
// 0);
// }
// }
// });
// rightButton.setMargin(new Insets(0, 2, 0, 2));
// panel.add(leftButton, BorderLayout.WEST);
// panel.add(scrollPane);
// panel.add(rightButton, BorderLayout.EAST);
return panel;
}
// private JScrollPane createComponentScrollBar(List<ComponentType> componentTypes) {
// JScrollPane scrollPane = new JScrollPane(createComponentPanel(componentTypes));
// scrollPane.setOpaque(false);
// scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
// return scrollPane;
// }
private Component createComponentPanel(List<ComponentType> componentTypes) {
Container toolbar = new Container();
Collections.sort(componentTypes, ComparatorFactory.getInstance()
.getComponentTypeComparator());
toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.X_AXIS));
for (ComponentType componentType : componentTypes) {
JButton button = new ComponentButton(plugInPort, componentType);
toolbar.add(button);
}
return toolbar;
}
}

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