change format to ggl

This commit is contained in:
Branislav Stojkovic
2016-10-23 17:17:46 +02:00
parent 81a0ff1d44
commit 5ec0616a1e
236 changed files with 25772 additions and 27152 deletions
@@ -2,6 +2,6 @@ package org.diylc.common;
public class BadPositionException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
}
@@ -15,100 +15,99 @@ import org.diylc.core.annotations.BomPolicy;
*/
public class ComponentType {
private String name;
private String description;
private CreationMethod creationMethod;
private String category;
private String namePrefix;
private String author;
private Icon icon;
private Class<? extends IDIYComponent<?>> instanceClass;
private double zOrder;
private boolean flexibleZOrder;
private boolean stretchable;
private BomPolicy bomPolicy;
private boolean autoEdit;
private boolean rotatable;
private String name;
private String description;
private CreationMethod creationMethod;
private String category;
private String namePrefix;
private String author;
private Icon icon;
private Class<? extends IDIYComponent<?>> instanceClass;
private double zOrder;
private boolean flexibleZOrder;
private boolean stretchable;
private BomPolicy bomPolicy;
private boolean autoEdit;
private boolean rotatable;
public ComponentType(String name, String description, CreationMethod creationMethod,
String category, String namePrefix, String author, Icon icon,
Class<? extends IDIYComponent<?>> instanceClass, double zOrder, boolean flexibleZOrder,
boolean stretchable, BomPolicy bomPolicy, boolean autoEdit, boolean rotatable) {
super();
this.name = name;
this.description = description;
this.creationMethod = creationMethod;
this.category = category;
this.namePrefix = namePrefix;
this.author = author;
this.icon = icon;
this.instanceClass = instanceClass;
this.zOrder = zOrder;
this.flexibleZOrder = flexibleZOrder;
this.stretchable = stretchable;
this.bomPolicy = bomPolicy;
this.autoEdit = autoEdit;
this.rotatable = rotatable;
}
public ComponentType(String name, String description, CreationMethod creationMethod, String category,
String namePrefix, String author, Icon icon, Class<? extends IDIYComponent<?>> instanceClass, double zOrder,
boolean flexibleZOrder, boolean stretchable, BomPolicy bomPolicy, boolean autoEdit, boolean rotatable) {
super();
this.name = name;
this.description = description;
this.creationMethod = creationMethod;
this.category = category;
this.namePrefix = namePrefix;
this.author = author;
this.icon = icon;
this.instanceClass = instanceClass;
this.zOrder = zOrder;
this.flexibleZOrder = flexibleZOrder;
this.stretchable = stretchable;
this.bomPolicy = bomPolicy;
this.autoEdit = autoEdit;
this.rotatable = rotatable;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getDescription() {
return description;
}
public CreationMethod getCreationMethod() {
return creationMethod;
}
public CreationMethod getCreationMethod() {
return creationMethod;
}
public String getCategory() {
return category;
}
public String getCategory() {
return category;
}
public String getNamePrefix() {
return namePrefix;
}
public String getNamePrefix() {
return namePrefix;
}
public String getAuthor() {
return author;
}
public String getAuthor() {
return author;
}
public Icon getIcon() {
return icon;
}
public Icon getIcon() {
return icon;
}
public Class<? extends IDIYComponent<?>> getInstanceClass() {
return instanceClass;
}
public Class<? extends IDIYComponent<?>> getInstanceClass() {
return instanceClass;
}
public double getZOrder() {
return zOrder;
}
public boolean isFlexibleZOrder() {
return flexibleZOrder;
}
public double getZOrder() {
return zOrder;
}
public boolean isStretchable() {
return stretchable;
}
public BomPolicy getBomPolicy() {
return bomPolicy;
}
public boolean isAutoEdit() {
return autoEdit;
}
public boolean isRotatable() {
return rotatable;
}
public boolean isFlexibleZOrder() {
return flexibleZOrder;
}
@Override
public String toString() {
return name;
}
public boolean isStretchable() {
return stretchable;
}
public BomPolicy getBomPolicy() {
return bomPolicy;
}
public boolean isAutoEdit() {
return autoEdit;
}
public boolean isRotatable() {
return rotatable;
}
@Override
public String toString() {
return name;
}
}
@@ -2,10 +2,10 @@ package org.diylc.common;
public enum Display {
NAME, VALUE, NONE, BOTH;
NAME, VALUE, NONE, BOTH;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -11,30 +11,29 @@ import java.awt.Graphics;
*/
public enum DrawOption {
/**
* Selection rectangle will be drawn when needed and selected components may
* be rendered differently.
*/
SELECTION,
/**
* Selected zoom level will be applied to scale the {@link Graphics} before
* drawing.
*/
ZOOM,
/**
* Grid lines are drawn.
*/
GRID,
/**
* Control points are drawn.
*/
CONTROL_POINTS,
/**
* Anti-aliasing is used when drawing.
*/
ANTIALIASING,
/**
* Draw components in outline mode.
*/
OUTLINE_MODE;
/**
* Selection rectangle will be drawn when needed and selected components may be rendered
* differently.
*/
SELECTION,
/**
* Selected zoom level will be applied to scale the {@link Graphics} before drawing.
*/
ZOOM,
/**
* Grid lines are drawn.
*/
GRID,
/**
* Control points are drawn.
*/
CONTROL_POINTS,
/**
* Anti-aliasing is used when drawing.
*/
ANTIALIASING,
/**
* Draw components in outline mode.
*/
OUTLINE_MODE;
}
@@ -6,78 +6,74 @@ import java.awt.geom.Point2D;
import org.diylc.core.Project;
/**
* Enumerates all possible events between {@link IPlugInPort} and
* {@link IPlugIn}. Some events overlap so be careful which ones you subscribe
* for and how you process them.
* Enumerates all possible events between {@link IPlugInPort} and {@link IPlugIn}. Some events
* overlap so be careful which ones you subscribe for and how you process them.
*
* @author Branislav Stojkovic
*/
public enum EventType {
/**
* Called when zoom level changes. Typically only one parameter of type
* {@link Double} is passed with new zoom level.
*/
ZOOM_CHANGED,
/**
* Called when a new project is loaded. New {@link Project} is the first
* parameter. Boolean flag is the second parameter and it's true when new
* project is loaded, false when the same project has been either reloaded
* or loaded with undo/redo operations.
*/
PROJECT_LOADED,
/**
* Called when either current file name or modified flag are changed. The
* first parameter is the current file name, the second one is a boolean
* modified flag.
*/
FILE_STATUS_CHANGED,
/**
* Called when selection rectangle is changed. Object of type
* {@link Rectangle} is the only parameter and it contains the new selection
* rectangle.
*/
SELECTION_RECT_CHANGED,
/**
* Called when component selection is changed. New
* {@link ComponentSelection} is attached as a parameter.
*/
SELECTION_CHANGED,
/**
* Called when selection size changes, together with a {@link Point2D}
* object containing selection size (x = width, y = height). Size is
* expressed in the default measure (cm for metric, inches for imperial).
*/
REPAINT,
/**
* Called when new component slot has been changed. The only parameter is
* {@link ComponentType} and may be null.
*/
SLOT_CHANGED,
/**
* Called when the current project has been modified. Two instances of
* {@link Project} are passed as parameters, one before and one after the
* change. The third parameter is a string containing change description.
*/
PROJECT_MODIFIED,
/**
* Called when control points under the cursor are changed. A single
* parameter is passed, an instance of
* <code>Map<IDIYComponent<?>, Set<Integer>></code> containing all the
* components and indices of their control points that are under the cursor.
*/
AVAILABLE_CTRL_POINTS_CHANGED,
/**
* Called when mouse cursor is moved. Point object is passed, containing the
* 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;
/**
* Called when zoom level changes. Typically only one parameter of type {@link Double} is passed
* with new zoom level.
*/
ZOOM_CHANGED,
/**
* Called when a new project is loaded. New {@link Project} is the first parameter. Boolean flag
* is the second parameter and it's true when new project is loaded, false when the same project
* has been either reloaded or loaded with undo/redo operations.
*/
PROJECT_LOADED,
/**
* Called when either current file name or modified flag are changed. The first parameter is the
* current file name, the second one is a boolean modified flag.
*/
FILE_STATUS_CHANGED,
/**
* Called when selection rectangle is changed. Object of type {@link Rectangle} is the only
* parameter and it contains the new selection rectangle.
*/
SELECTION_RECT_CHANGED,
/**
* Called when component selection is changed. New {@link ComponentSelection} is attached as a
* parameter.
*/
SELECTION_CHANGED,
/**
* Called when selection size changes, together with a {@link Point2D} object containing selection
* size (x = width, y = height). Size is expressed in the default measure (cm for metric, inches
* for imperial).
*/
REPAINT,
/**
* Called when new component slot has been changed. The only parameter is {@link ComponentType}
* and may be null.
*/
SLOT_CHANGED,
/**
* Called when the current project has been modified. Two instances of {@link Project} are passed
* as parameters, one before and one after the change. The third parameter is a string containing
* change description.
*/
PROJECT_MODIFIED,
/**
* Called when control points under the cursor are changed. A single parameter is passed, an
* instance of <code>Map<IDIYComponent<?>, Set<Integer>></code> containing all the components and
* indices of their control points that are under the cursor.
*/
AVAILABLE_CTRL_POINTS_CHANGED,
/**
* Called when mouse cursor is moved. Point object is passed, containing the 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;
}
@@ -2,5 +2,5 @@ package org.diylc.common;
public enum GridType {
LINES, CROSSHAIR, DOT, NONE;
LINES, CROSSHAIR, DOT, NONE;
}
@@ -1,9 +1,9 @@
package org.diylc.common;
public enum HorizontalAlignment {
LEFT, CENTER, RIGHT;
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
LEFT, CENTER, RIGHT;
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -4,5 +4,5 @@ import org.diylc.core.IDIYComponent;
public interface IComponentFiler {
boolean testComponent(IDIYComponent<?> component);
boolean testComponent(IDIYComponent<?> component);
}
@@ -2,21 +2,20 @@ package org.diylc.common;
public interface IKeyProcessor {
public static final int VK_LEFT = 0x25;
public static final int VK_UP = 0x26;
public static final int VK_RIGHT = 0x27;
public static final int VK_DOWN = 0x28;
public static final int VK_LEFT = 0x25;
public static final int VK_UP = 0x26;
public static final int VK_RIGHT = 0x27;
public static final int VK_DOWN = 0x28;
/**
* Notifies the presenter that a key hes been pressed on the canvas.
*
* @param key
* @param ctrlDown
* @param shiftDown
* @param altDown
*
* @return true if the event should be consumed
*/
boolean keyPressed(int key, boolean ctrlDown, boolean shiftDown,
boolean altDown);
/**
* Notifies the presenter that a key hes been pressed on the canvas.
*
* @param key
* @param ctrlDown
* @param shiftDown
* @param altDown
*
* @return true if the event should be consumed
*/
boolean keyPressed(int key, boolean ctrlDown, boolean shiftDown, boolean altDown);
}
@@ -4,66 +4,65 @@ import java.awt.Point;
public interface IMouseProcessor {
/**
* Notifies the presenter that mouse is clicked.
*
* Note: point coordinates are display based, i.e. scaled for zoom factor.
*
* @param point
* @param button
* @param ctrlDown
* @param shiftDown
* @param altDown
* @param clickCount
*/
void mouseClicked(Point point, int button, boolean ctrlDown, boolean shiftDown, boolean altDown,
int clickCount);
/**
* Notifies the presenter that mouse is clicked.
*
* Note: point coordinates are display based, i.e. scaled for zoom factor.
*
* @param point
* @param button
* @param ctrlDown
* @param shiftDown
* @param altDown
* @param clickCount
*/
void mouseClicked(Point point, int button, boolean ctrlDown, boolean shiftDown, boolean altDown, int clickCount);
/**
* Notifies the presenter that mouse is moved.
*
* Note: point coordinates are display based, i.e. scaled for zoom factor.
*
* @param point
* @param ctrlDown
* @param shiftDown
* @param altDown
*/
void mouseMoved(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown);
/**
* Notifies the presenter that mouse is moved.
*
* Note: point coordinates are display based, i.e. scaled for zoom factor.
*
* @param point
* @param ctrlDown
* @param shiftDown
* @param altDown
*/
void mouseMoved(Point point, boolean ctrlDown, boolean shiftDown, boolean altDown);
/**
* Notification that drag has been started from the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @param dragAction
*/
void dragStarted(Point point, int dragAction);
/**
* Notification that drag has been started from the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @param dragAction
*/
void dragStarted(Point point, int dragAction);
/**
* Checks if it's possible to drop over the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @return
*/
boolean dragOver(Point point);
/**
* Checks if it's possible to drop over the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @return
*/
boolean dragOver(Point point);
/**
* Changes the current drag action during the dragging.
*
* @param dragAction
*/
void dragActionChanged(int dragAction);
/**
* Changes the current drag action during the dragging.
*
* @param dragAction
*/
void dragActionChanged(int dragAction);
/**
* Notification that drag has been ended in the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
*/
void dragEnded(Point point);
/**
* Notification that drag has been ended in the specified point.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
*/
void dragEnded(Point point);
}
@@ -9,11 +9,11 @@ import org.diylc.appframework.simplemq.IMessageListener;
*/
public interface IPlugIn extends IMessageListener<EventType> {
/**
* Method that connects the plug-in with {@link IPlugInPort}. Called by the
* application when plug-in is installed.
*
* @param plugInPort
*/
void connect(IPlugInPort plugInPort);
/**
* Method that connects the plug-in with {@link IPlugInPort}. Called by the application when
* plug-in is installed.
*
* @param plugInPort
*/
void connect(IPlugInPort plugInPort);
}
@@ -18,9 +18,9 @@ import org.diylc.core.Template;
import org.diylc.core.Theme;
/**
* Interface for communication between plug-ins and the application. Plug-ins
* may acquire information or make changes through this interface. Application
* events are dispatched to plug-ins through {@link MessageDispatcher}
* Interface for communication between plug-ins and the application. Plug-ins may acquire
* information or make changes through this interface. Application events are dispatched to plug-ins
* through {@link MessageDispatcher}
*
* @author Branislav Stojkovic
*
@@ -31,290 +31,277 @@ import org.diylc.core.Theme;
*/
public interface IPlugInPort extends ISelectionProcessor, IMouseProcessor, IKeyProcessor, ITemplateProcessor {
public static final String ANTI_ALIASING_KEY = "antiAliasing";
public static final String HI_QUALITY_RENDER_KEY = "hiQualityRender";
public static final String EXPORT_GRID_KEY = "exportGrid";
public static final String STICKY_POINTS_KEY = "stickyPoints";
public static final String METRIC_KEY = "metric";
public static final String SNAP_TO_GRID_KEY = "snapToGrid";
public static final String AUTO_PADS_KEY = "autoCreatePads";
public static final String CONTINUOUS_CREATION_KEY = "continuousCreation";
public static final String AUTO_EDIT_KEY = "autoEdit";
public static final String ABNORMAL_EXIT_KEY = "abnormalExit";
public static final String WHEEL_ZOOM_KEY = "wheelZoom";
public static final String OUTLINE_KEY = "outline";
public static final String THEME_KEY = "theme";
public static final String RECENT_COMPONENTS_KEY = "recentComponents";
public static final String ANTI_ALIASING_KEY = "antiAliasing";
public static final String HI_QUALITY_RENDER_KEY = "hiQualityRender";
public static final String EXPORT_GRID_KEY = "exportGrid";
public static final String STICKY_POINTS_KEY = "stickyPoints";
public static final String METRIC_KEY = "metric";
public static final String SNAP_TO_GRID_KEY = "snapToGrid";
public static final String AUTO_PADS_KEY = "autoCreatePads";
public static final String CONTINUOUS_CREATION_KEY = "continuousCreation";
public static final String AUTO_EDIT_KEY = "autoEdit";
public static final String ABNORMAL_EXIT_KEY = "abnormalExit";
public static final String WHEEL_ZOOM_KEY = "wheelZoom";
public static final String OUTLINE_KEY = "outline";
public static final String THEME_KEY = "theme";
public static final String RECENT_COMPONENTS_KEY = "recentComponents";
public static final int DND_TOGGLE_STICKY = 0x1;
public static final int DND_TOGGLE_SNAP = 0x40000000;
/**
* Mouse button constants.
*/
public static final int NOBUTTON = 0;
public static final int BUTTON1 = 1;
public static final int BUTTON2 = 2;
public static final int BUTTON3 = 3;
public static final int DND_TOGGLE_STICKY = 0x1;
public static final int DND_TOGGLE_SNAP = 0x40000000;
/**
* Returns size of the canvas that takes project dimensions into account as
* well as zoom level. Each dimension is calculated as the product of the
* actual size and the number of pixels per unit. If <code>useZoom</code> is
* set to true, the result is scaled by zoom factor.
*
* @param useZoom
*
* @return canvas dimensions
*/
Dimension getCanvasDimensions(boolean useZoom);
/**
* Mouse button constants.
*/
public static final int NOBUTTON = 0;
public static final int BUTTON1 = 1;
public static final int BUTTON2 = 2;
public static final int BUTTON3 = 3;
/**
* Returns an instance of {@link Cursor} that should be used at the
* specified location.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @return cursor
*/
Cursor getCursorAt(Point point);
/**
* Returns size of the canvas that takes project dimensions into account as well as zoom level.
* Each dimension is calculated as the product of the actual size and the number of pixels per
* unit. If <code>useZoom</code> is set to true, the result is scaled by zoom factor.
*
* @param useZoom
*
* @return canvas dimensions
*/
Dimension getCanvasDimensions(boolean useZoom);
/**
* Returns an instance of currently loaded project.
*
* @return
*/
Project getCurrentProject();
/**
* Returns an instance of {@link Cursor} that should be used at the specified location.
*
* Note: point coordinates are scaled for zoom factor.
*
* @param point
* @return cursor
*/
Cursor getCursorAt(Point point);
/**
* Loads specified {@link Project}.
*
* @param project
* @param freshStart
*/
void loadProject(Project project, boolean freshStart);
/**
* Returns an instance of currently loaded project.
*
* @return
*/
Project getCurrentProject();
/**
* Creates a new project.
*/
void createNewProject();
/**
* Loads specified {@link Project}.
*
* @param project
* @param freshStart
*/
void loadProject(Project project, boolean freshStart);
/**
* Loads a project from the specified file.
*
* @param fileName
*/
void loadProjectFromFile(String fileName);
/**
* Creates a new project.
*/
void createNewProject();
/**
* Saves the current project into the specified file.
*
* @param fileName
* @param isBackup
*/
void saveProjectToFile(String fileName, boolean isBackup);
/**
* Loads a project from the specified file.
*
* @param fileName
*/
void loadProjectFromFile(String fileName);
/**
* @return the current file name.
*/
String getCurrentFileName();
/**
* Saves the current project into the specified file.
*
* @param fileName
* @param isBackup
*/
void saveProjectToFile(String fileName, boolean isBackup);
/**
* @return true if the current project is modified.
*/
boolean isProjectModified();
/**
* @return the current file name.
*/
String getCurrentFileName();
/**
* Shows a user dialog if there are changes to confirm that it's safe to
* proceed.
*
* @return true, if file actions (new, open, close) can be taken
*/
boolean allowFileAction();
/**
* @return true if the current project is modified.
*/
boolean isProjectModified();
/**
* Returns all available {@link ComponentType}s classified by category.
* Result is a {@link Map} between category name to a {@link List} of all
* {@link ComponentType}s that share that category name.
*
* @return
*/
Map<String, List<ComponentType>> getComponentTypes();
/**
* Shows a user dialog if there are changes to confirm that it's safe to proceed.
*
* @return true, if file actions (new, open, close) can be taken
*/
boolean allowFileAction();
/**
* Draws project on the provided {@link Graphics2D}. If the provided filter
* is not null, it will be used to filter the components that are shown.
*
* @param g2d
* @param drawOptions
* specific drawing options
* @param filter
*/
void draw(Graphics2D g2d, Set<DrawOption> drawOptions, IComponentFiler filter);
/**
* Returns all available {@link ComponentType}s classified by category. Result is a {@link Map}
* between category name to a {@link List} of all {@link ComponentType}s that share that category
* name.
*
* @return
*/
Map<String, List<ComponentType>> getComponentTypes();
Double[] getAvailableZoomLevels();
/**
* Draws project on the provided {@link Graphics2D}. If the provided filter is not null, it will
* be used to filter the components that are shown.
*
* @param g2d
* @param drawOptions specific drawing options
* @param filter
*/
void draw(Graphics2D g2d, Set<DrawOption> drawOptions, IComponentFiler filter);
/**
* Returns current zoom level where <code>zoomLevel = 1.0d</code> means
* 100%.
*
* @return current zoom level
*/
double getZoomLevel();
Double[] getAvailableZoomLevels();
/**
* Changes current zoom level where <code>zoomLevel = 1.0d</code> means 100%
*
* @param zoomLevel
* new zoom leve
*/
void setZoomLevel(double zoomLevel);
/**
* Returns current zoom level where <code>zoomLevel = 1.0d</code> means 100%.
*
* @return current zoom level
*/
double getZoomLevel();
/**
* Returns current version number.
*
* @return
*/
VersionNumber getCurrentVersionNumber();
/**
* Changes current zoom level where <code>zoomLevel = 1.0d</code> means 100%
*
* @param zoomLevel new zoom leve
*/
void setZoomLevel(double zoomLevel);
/**
* Adds a list of components to the project.
*
* @param components
*/
void pasteComponents(List<IDIYComponent<?>> components);
/**
* Returns current version number.
*
* @return
*/
VersionNumber getCurrentVersionNumber();
/**
* Deletes all the selected components from the project.
*/
void deleteSelectedComponents();
/**
* Adds a list of components to the project.
*
* @param components
*/
void pasteComponents(List<IDIYComponent<?>> components);
/**
* Sets default value for the specified property name for currently selected
* component types.
*
* @param propertyName
* display name for property
* @param value
* new default value, must not be null
*/
void setSelectionDefaultPropertyValue(String propertyName, Object value);
/**
* Deletes all the selected components from the project.
*/
void deleteSelectedComponents();
/**
* Sets default value for the specified property name for projects.
*
* @param propertyName
* display name for property
* @param value
* new default value, must not be null
*/
void setProjectDefaultPropertyValue(String propertyName, Object value);
/**
* Sets default value for the specified property name for currently selected component types.
*
* @param propertyName display name for property
* @param value new default value, must not be null
*/
void setSelectionDefaultPropertyValue(String propertyName, Object value);
/**
* @return a list of properties that are mutual for all the selected
* components. Resulting list may be empty if selected components do
* not have mutual properties or can be null if the selection is
* empty.
*/
List<PropertyWrapper> getMutualSelectionProperties();
/**
* Sets default value for the specified property name for projects.
*
* @param propertyName display name for property
* @param value new default value, must not be null
*/
void setProjectDefaultPropertyValue(String propertyName, Object value);
void editSelection();
/**
* @return a list of properties that are mutual for all the selected components. Resulting list
* may be empty if selected components do not have mutual properties or can be null if the
* selection is empty.
*/
List<PropertyWrapper> getMutualSelectionProperties();
/**
* @return a list of editable properties of the current project.
*/
List<PropertyWrapper> getProjectProperties();
void editSelection();
/**
* Applies specified properties to the current project.
*
* @param properties
*/
void applyPropertiesToProject(List<PropertyWrapper> properties);
/**
* Gets the current new component slot.
*/
ComponentType getNewComponentTypeSlot();
/**
* @return a list of editable properties of the current project.
*/
List<PropertyWrapper> getProjectProperties();
/**
* Sets the new component slot. Specified component type will be used to
* instantiate new component.
*
* @param componentType
* @param template
*/
void setNewComponentTypeSlot(ComponentType componentType, Template template);
/**
* Applies specified properties to the current project.
*
* @param properties
*/
void applyPropertiesToProject(List<PropertyWrapper> properties);
/**
* Changes default size notation, true for metric, false for imperial.
*
* @param isMetric
*/
void setMetric(boolean isMetric);
/**
* Gets the current new component slot.
*/
ComponentType getNewComponentTypeSlot();
/**
* Groups all selected components.
*/
void groupSelectedComponents();
/**
* Sets the new component slot. Specified component type will be used to instantiate new
* component.
*
* @param componentType
* @param template
*/
void setNewComponentTypeSlot(ComponentType componentType, Template template);
/**
* Ungroups all selected components.
*/
void ungroupSelectedComponents();
/**
* Changes default size notation, true for metric, false for imperial.
*
* @param isMetric
*/
void setMetric(boolean isMetric);
/**
* 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);
/**
* Groups all selected components.
*/
void groupSelectedComponents();
/**
* @return selection size expressed in either inches or centimeters, based
* on the user preference.
*/
Point2D calculateSelectionDimension();
// /**
// * @return the smallest rectangle that encloses the selection
// */
// Rectangle2D getSelectedAreaRect();
/**
* Ungroups all selected components.
*/
void ungroupSelectedComponents();
/**
* Sends each of the selected components one step back.
*/
void sendSelectionToBack();
/**
* 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);
/**
* Brings each of the selected components one step to front.
*/
void bringSelectionToFront();
/**
* @return selection size expressed in either inches or centimeters, based on the user preference.
*/
Point2D calculateSelectionDimension();
/**
* Causes the display to refresh.
*/
void refresh();
// /**
// * @return the smallest rectangle that encloses the selection
// */
// Rectangle2D getSelectedAreaRect();
/**
* @return currently selected theme.
*/
Theme getSelectedTheme();
/**
* Sends each of the selected components one step back.
*/
void sendSelectionToBack();
/**
* Changes the current theme.
*
* @param theme
*/
void setSelectedTheme(Theme theme);
/**
* Brings each of the selected components one step to front.
*/
void bringSelectionToFront();
/**
* Renumbers all the selected components.
*
* @param xAxisFirst
*/
void renumberSelectedComponents(boolean xAxisFirst);
/**
* Causes the display to refresh.
*/
void refresh();
/**
* @return currently selected theme.
*/
Theme getSelectedTheme();
/**
* Changes the current theme.
*
* @param theme
*/
void setSelectedTheme(Theme theme);
/**
* Renumbers all the selected components.
*
* @param xAxisFirst
*/
void renumberSelectedComponents(boolean xAxisFirst);
}
@@ -8,52 +8,49 @@ import org.diylc.core.IDIYComponent;
public interface ISelectionProcessor {
/**
* Returns the current {@link ComponentTransferable}.
*
* @return
*/
List<IDIYComponent<?>> getSelectedComponents();
/**
* Returns the current {@link ComponentTransferable}.
*
* @return
*/
List<IDIYComponent<?>> getSelectedComponents();
/**
* Updates the selection with the specified list of component. Also, updates
* control point map with all components that are stuck to the newly
* selected components.
*
* @param newSelection
*/
void updateSelection(List<IDIYComponent<?>> newSelection);
/**
* Updates the selection with the specified list of component. Also, updates control point map
* with all components that are stuck to the newly selected components.
*
* @param newSelection
*/
void updateSelection(List<IDIYComponent<?>> newSelection);
/**
* Finds all components at the specified location, sorted by z-index from
* top to bottom.
*
* @param point
* @return
*/
List<IDIYComponent<?>> findComponentsAt(Point point);
/**
* Finds all components at the specified location, sorted by z-index from top to bottom.
*
* @param point
* @return
*/
List<IDIYComponent<?>> findComponentsAt(Point point);
/**
* Expands the current selection to include surrounding components. Options
* are controlled with <code>expansionMode</code> flag.
*
* @param expansionMode
*/
void expandSelection(ExpansionMode expansionMode);
/**
* Expands the current selection to include surrounding components. Options are controlled with
* <code>expansionMode</code> flag.
*
* @param expansionMode
*/
void expandSelection(ExpansionMode expansionMode);
/**
* Selects all components in the project.
*
* @param int layer if > 0, designates which layer to select. If <= 0 we
* should select all regardless of layer
*/
void selectAll(int layer);
/**
* Selects all components in the project.
*
* @param int layer if > 0, designates which layer to select. If <= 0 we should select all
* regardless of layer
*/
void selectAll(int layer);
/**
* Rotates selection for 90 degrees.
*
* @param direction
* 1 for clockwise, -1 for counter-clockwise
*/
void rotateSelection(int direction);
/**
* Rotates selection for 90 degrees.
*
* @param direction 1 for clockwise, -1 for counter-clockwise
*/
void rotateSelection(int direction);
}
@@ -9,26 +9,25 @@ package org.diylc.common;
*/
public interface ITask<T> {
/**
* Runs in background thread.
*
* @return
* @throws Exception
*/
T doInBackground() throws Exception;
/**
* 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 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);
/**
* Called if background thread is executed correctly, the result is passed as a parameter.
*
* @param result
*/
void complete(T result);
}
@@ -6,21 +6,21 @@ import org.diylc.core.Template;
public interface ITemplateProcessor {
public static final String TEMPLATES_KEY = "templates";
public static final String TEMPLATES_KEY = "templates";
void saveSelectedComponentAsTemplate(String templateName);
void saveSelectedComponentAsTemplate(String templateName);
List<Template> getTemplatesFor(String categoryName, String componentTypeName);
List<Template> getTemplatesForSelection();
void applyTemplateToSelection(Template template);
void deleteTemplate(String categoryName, String componentTypeName, String templateName);
List<Template> getTemplatesFor(String categoryName, String componentTypeName);
public class TemplateAlreadyExistsException extends Exception {
List<Template> getTemplatesForSelection();
private static final long serialVersionUID = 1L;
void applyTemplateToSelection(Template template);
}
void deleteTemplate(String categoryName, String componentTypeName, String templateName);
public class TemplateAlreadyExistsException extends Exception {
private static final long serialVersionUID = 1L;
}
}
@@ -2,10 +2,10 @@ package org.diylc.common;
public enum LabelPosition {
ABOVE, BELOW;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
ABOVE, BELOW;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -7,33 +7,31 @@ import java.util.HashMap;
import java.util.Map;
/**
* Repository for object that may be reused, such as {@link Stroke} or
* {@link AlphaComposite}.
* Repository for object that may be reused, such as {@link Stroke} or {@link AlphaComposite}.
*
* @author Branislav Stojkovic
*/
public class ObjectCache {
private static ObjectCache instance;
private static ObjectCache instance;
public static ObjectCache getInstance() {
if (instance == null) {
instance = new ObjectCache();
}
return instance;
}
public static ObjectCache getInstance() {
if (instance == null) {
instance = new ObjectCache();
}
return instance;
}
private ObjectCache() {
}
private ObjectCache() {}
private Map<Integer, Stroke> basicStrokeMap = new HashMap<Integer, Stroke>();
private Map<Integer, Stroke> basicStrokeMap = new HashMap<Integer, Stroke>();
public Stroke fetchBasicStroke(int width) {
if (basicStrokeMap.containsKey(width)) {
return basicStrokeMap.get(width);
}
Stroke stroke = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
basicStrokeMap.put(width, stroke);
return stroke;
}
public Stroke fetchBasicStroke(int width) {
if (basicStrokeMap.containsKey(width)) {
return basicStrokeMap.get(width);
}
Stroke stroke = new BasicStroke(width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
basicStrokeMap.put(width, stroke);
return stroke;
}
}
@@ -2,14 +2,14 @@ package org.diylc.common;
public enum Orientation {
DEFAULT, _90, _180, _270;
DEFAULT, _90, _180, _270;
@Override
public String toString() {
if (this == DEFAULT) {
return "Default";
} else {
return name().replace("_", "") + " degrees clockwise";
}
}
@Override
public String toString() {
if (this == DEFAULT) {
return "Default";
} else {
return name().replace("_", "") + " degrees clockwise";
}
}
}
@@ -2,10 +2,10 @@ package org.diylc.common;
public enum OrientationHV {
VERTICAL, HORIZONTAL;
VERTICAL, HORIZONTAL;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -2,9 +2,9 @@ package org.diylc.common;
public enum PCBLayer {
_1, _2, _3, _4, _5;
public String toString() {
return name().substring(1);
};
_1, _2, _3, _4, _5;
public String toString() {
return name().substring(1);
};
}
@@ -5,163 +5,161 @@ import java.lang.reflect.InvocationTargetException;
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.
* Entity class for editable properties extracted from component objects. Represents a single
* editable property together with it's current value.
*
* @author Branislav Stojkovic
*/
public class PropertyWrapper implements Cloneable {
private String name;
private Class<?> type;
private Object value;
private String setter;
private String getter;
private boolean defaultable;
private IPropertyValidator validator;
private boolean unique = true;
private boolean changed = false;
private String name;
private Class<?> type;
private Object value;
private String setter;
private String getter;
private boolean defaultable;
private IPropertyValidator validator;
private boolean unique = true;
private boolean changed = false;
public PropertyWrapper(String name, Class<?> type, String getter,
String setter, boolean defaultable, IPropertyValidator validator) {
super();
this.name = name;
this.type = type;
this.getter = getter;
this.setter = setter;
this.defaultable = defaultable;
this.validator = validator;
}
public PropertyWrapper(String name, Class<?> type, String getter, String setter, boolean defaultable,
IPropertyValidator validator) {
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,
SecurityException, NoSuchMethodException {
this.value = object.getClass().getMethod(getter).invoke(object);
}
public void readFrom(Object object) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException {
this.value = object.getClass().getMethod(getter).invoke(object);
}
// public void readUniqueFrom(IDIYComponent component)
// throws IllegalArgumentException, IllegalAccessException,
// InvocationTargetException {
// Object newValue = getter.invoke(component);
// if (!newValue.equals(value)) {
// this.value = null;
// }
// }
// public void readUniqueFrom(IDIYComponent component)
// throws IllegalArgumentException, IllegalAccessException,
// InvocationTargetException {
// Object newValue = getter.invoke(component);
// if (!newValue.equals(value)) {
// this.value = null;
// }
// }
public void writeTo(Object object) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchMethodException {
object.getClass().getMethod(setter, type).invoke(object, this.value);
}
public void writeTo(Object object) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException {
object.getClass().getMethod(setter, type).invoke(object, this.value);
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public Class<?> getType() {
return type;
}
public Class<?> getType() {
return type;
}
public Object getValue() {
return value;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public void setValue(Object value) {
this.value = value;
}
public boolean isDefaultable() {
return defaultable;
}
public boolean isDefaultable() {
return defaultable;
}
public IPropertyValidator getValidator() {
return validator;
}
public IPropertyValidator getValidator() {
return validator;
}
public boolean isUnique() {
return unique;
}
public boolean isUnique() {
return unique;
}
public void setUnique(boolean unique) {
this.unique = unique;
}
public void setUnique(boolean unique) {
this.unique = unique;
}
public boolean isChanged() {
return changed;
}
public boolean isChanged() {
return changed;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
public void setChanged(boolean changed) {
this.changed = changed;
}
// @Override
// public Object clone() throws CloneNotSupportedException {
// // Try to invoke clone method on value if possible.
// try {
// Method cloneMethod = value.getClass().getMethod("clone");
// return new Property(name, type, cloneMethod.invoke(value));
// } catch (Exception e) {
// }
// return new Property(name, type, value);
// }
@Override
public Object clone() throws CloneNotSupportedException {
PropertyWrapper clone = new PropertyWrapper(this.name, this.type, this.getter,
this.setter, this.defaultable, this.validator);
clone.value = this.value;
clone.changed = this.changed;
clone.unique = this.unique;
return clone;
}
// @Override
// public Object clone() throws CloneNotSupportedException {
// // Try to invoke clone method on value if possible.
// try {
// Method cloneMethod = value.getClass().getMethod("clone");
// return new Property(name, type, cloneMethod.invoke(value));
// } catch (Exception e) {
// }
// return new Property(name, type, value);
// }
@Override
public Object clone() throws CloneNotSupportedException {
PropertyWrapper clone =
new PropertyWrapper(this.name, this.type, this.getter, this.setter, this.defaultable, this.validator);
clone.value = this.value;
clone.changed = this.changed;
clone.unique = this.unique;
return clone;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (defaultable ? 1231 : 1237);
result = prime * result + ((getter == null) ? 0 : getter.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (defaultable ? 1231 : 1237);
result = prime * result + ((getter == null) ? 0 : getter.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PropertyWrapper other = (PropertyWrapper) obj;
if (defaultable != other.defaultable)
return false;
if (getter == null) {
if (other.getter != null)
return false;
} else if (!getter.equals(other.getter))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (setter == null) {
if (other.setter != null)
return false;
} else if (!setter.equals(other.setter))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PropertyWrapper other = (PropertyWrapper) obj;
if (defaultable != other.defaultable)
return false;
if (getter == null) {
if (other.getter != null)
return false;
} else if (!getter.equals(other.getter))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (setter == null) {
if (other.setter != null)
return false;
} else if (!setter.equals(other.setter))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
@Override
public String toString() {
return name + " = " + value;
}
@Override
public String toString() {
return name + " = " + value;
}
}
@@ -2,13 +2,13 @@ package org.diylc.common;
public enum ResistorColorCode {
NONE, _4_BAND, _5_BAND;
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();
}
@Override
public String toString() {
if (name().startsWith("_")) {
return name().substring(1).replace("_", " ").toLowerCase();
}
return name().substring(0, 1).toUpperCase() + name().substring(1).toLowerCase();
}
}
@@ -1,9 +1,9 @@
package org.diylc.common;
public enum VerticalAlignment {
TOP, CENTER, BOTTOM;
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
TOP, CENTER, BOTTOM;
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@@ -21,12 +21,11 @@ import org.diylc.core.IDIYComponent;
import org.diylc.core.annotations.EditableProperty;
/**
* Abstract implementation of {@link IDIYComponent} that contains component name
* and toString.
* Abstract implementation of {@link IDIYComponent} that contains component name and toString.
*
* IMPORTANT: to improve performance, all fields except for <code>Point</code>
* and <code>Point</code> arrays should be immutable. Failing to comply with
* this can result in annoying and hard to trace bugs.
* IMPORTANT: to improve performance, all fields except for <code>Point</code> and
* <code>Point</code> arrays should be immutable. Failing to comply with this can result in annoying
* and hard to trace bugs.
*
* @author Branislav Stojkovic
*
@@ -34,215 +33,207 @@ import org.diylc.core.annotations.EditableProperty;
*/
public abstract class AbstractComponent<T> implements IDIYComponent<T> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
protected String name = "";
protected String name = "";
public static Color SELECTION_COLOR = Color.red;
public static Color LABEL_COLOR = Color.black;
public static Color LABEL_COLOR_SELECTED = Color.red;
public static Font LABEL_FONT = new Font("Tahoma", Font.PLAIN, 14);
public static Color METAL_COLOR = Color.decode("#236B8E");
public static Color SELECTION_COLOR = Color.red;
public static Color LABEL_COLOR = Color.black;
public static Color LABEL_COLOR_SELECTED = Color.red;
public static Font LABEL_FONT = new Font("Tahoma", Font.PLAIN, 14);
public static Color METAL_COLOR = Color.decode("#236B8E");
@EditableProperty(defaultable = false)
@Override
public String getName() {
return name;
}
@EditableProperty(defaultable = false)
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
}
@Override
public String toString() {
return name;
}
@Override
public String getValueForDisplay() {
return getValue() == null ? "" : getValue().toString();
}
@Override
public String toString() {
return name;
}
/**
* Returns the closest odd number, i.e. x when x is odd, or x + 1 when x is
* even.
*
* @param x
* @return
*/
protected int getClosestOdd(double x) {
return ((int) x / 2) * 2 + 1;
}
@Override
public String getValueForDisplay() {
return getValue() == null ? "" : getValue().toString();
}
/**
* @param clip
* @return true if none of the control points lie in the clip rectangle.
*/
protected boolean checkPointsClipped(Shape clip) {
for (int i = 0; i < getControlPointCount(); i++) {
if (clip.contains(getControlPoint(i))) {
return false;
}
}
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
for (int i = 0; i < getControlPointCount(); i++) {
Point p = getControlPoint(i);
if (minX > p.x) {
minX = p.x;
}
if (maxX < p.x) {
maxX = p.x;
}
if (minY > p.y) {
minY = p.y;
}
if (maxY < p.y) {
maxY = p.y;
}
}
Rectangle2D rect = new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
return !clip.intersects(rect);
}
/**
* Returns the closest odd number, i.e. x when x is odd, or x + 1 when x is even.
*
* @param x
* @return
*/
protected int getClosestOdd(double x) {
return ((int) x / 2) * 2 + 1;
}
protected void drawCenteredText(Graphics2D g2d, String text, int x, int y,
HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle stringBounds = fontMetrics.getStringBounds(text, g2d).getBounds();
/**
* @param clip
* @return true if none of the control points lie in the clip rectangle.
*/
protected boolean checkPointsClipped(Shape clip) {
for (int i = 0; i < getControlPointCount(); i++) {
if (clip.contains(getControlPoint(i))) {
return false;
}
}
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxY = Integer.MIN_VALUE;
for (int i = 0; i < getControlPointCount(); i++) {
Point p = getControlPoint(i);
if (minX > p.x) {
minX = p.x;
}
if (maxX < p.x) {
maxX = p.x;
}
if (minY > p.y) {
minY = p.y;
}
if (maxY < p.y) {
maxY = p.y;
}
}
Rectangle2D rect = new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
return !clip.intersects(rect);
}
Font font = g2d.getFont();
FontRenderContext renderContext = g2d.getFontRenderContext();
GlyphVector glyphVector = font.createGlyphVector(renderContext, text);
Rectangle visualBounds = glyphVector.getVisualBounds().getBounds();
protected void drawCenteredText(Graphics2D g2d, String text, int x, int y, HorizontalAlignment horizontalAlignment,
VerticalAlignment verticalAlignment) {
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle stringBounds = fontMetrics.getStringBounds(text, g2d).getBounds();
int textX = 0;
switch (horizontalAlignment) {
case CENTER:
textX = x - stringBounds.width / 2;
break;
case LEFT:
textX = x;
break;
case RIGHT:
textX = x - stringBounds.width;
break;
}
Font font = g2d.getFont();
FontRenderContext renderContext = g2d.getFontRenderContext();
GlyphVector glyphVector = font.createGlyphVector(renderContext, text);
Rectangle visualBounds = glyphVector.getVisualBounds().getBounds();
int textY = 0;
switch (verticalAlignment) {
case TOP:
textY = y + stringBounds.height;
break;
case CENTER:
textY = y - visualBounds.height / 2 - visualBounds.y;
break;
case BOTTOM:
textY = y - visualBounds.y;
break;
}
int textX = 0;
switch (horizontalAlignment) {
case CENTER:
textX = x - stringBounds.width / 2;
break;
case LEFT:
textX = x;
break;
case RIGHT:
textX = x - stringBounds.width;
break;
}
g2d.drawString(text, textX, textY);
}
int textY = 0;
switch (verticalAlignment) {
case TOP:
textY = y + stringBounds.height;
break;
case CENTER:
textY = y - visualBounds.height / 2 - visualBounds.y;
break;
case BOTTOM:
textY = y - visualBounds.y;
break;
}
@SuppressWarnings("unchecked")
public IDIYComponent<T> clone() throws CloneNotSupportedException {
try {
// Instantiate object of the same type
AbstractComponent<T> newInstance = (AbstractComponent<T>) this.getClass()
.getConstructors()[0].newInstance();
Class<?> clazz = this.getClass();
while (AbstractComponent.class.isAssignableFrom(clazz)) {
Field[] fields = clazz.getDeclaredFields();
clazz = clazz.getSuperclass();
// fields = this.getClass().getDeclaredFields();
// Copy over all non-static, non-final fields that are declared
// in AbstractComponent or one of it's child classes
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())
&& !Modifier.isFinal(field.getModifiers())) {
field.setAccessible(true);
Object value = field.get(this);
g2d.drawString(text, textX, textY);
}
// Deep copy point arrays.
// TODO: something nicer
if (value != null
&& value.getClass().isArray()
&& value.getClass().getComponentType()
.isAssignableFrom(Point.class)) {
Object newArray = Array.newInstance(
value.getClass().getComponentType(), Array.getLength(value));
for (int i = 0; i < Array.getLength(value); i++) {
Point p = (Point) Array.get(value, i);
Array.set(newArray, i, new Point(p));
}
value = newArray;
}
// Deep copy points.
// TODO: something nicer
if (value != null && value instanceof Point) {
value = new Point((Point) value);
}
@SuppressWarnings("unchecked")
public IDIYComponent<T> clone() throws CloneNotSupportedException {
try {
// Instantiate object of the same type
AbstractComponent<T> newInstance = (AbstractComponent<T>) this.getClass().getConstructors()[0].newInstance();
Class<?> clazz = this.getClass();
while (AbstractComponent.class.isAssignableFrom(clazz)) {
Field[] fields = clazz.getDeclaredFields();
clazz = clazz.getSuperclass();
// fields = this.getClass().getDeclaredFields();
// Copy over all non-static, non-final fields that are declared
// in AbstractComponent or one of it's child classes
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
field.setAccessible(true);
Object value = field.get(this);
field.set(newInstance, value);
}
}
}
return newInstance;
} catch (Exception e) {
throw new CloneNotSupportedException("Could not clone the component. Reason: "
+ e.getMessage());
}
}
// Deep copy point arrays.
// TODO: something nicer
if (value != null && value.getClass().isArray()
&& value.getClass().getComponentType().isAssignableFrom(Point.class)) {
Object newArray = Array.newInstance(value.getClass().getComponentType(), Array.getLength(value));
for (int i = 0; i < Array.getLength(value); i++) {
Point p = (Point) Array.get(value, i);
Array.set(newArray, i, new Point(p));
}
value = newArray;
}
// Deep copy points.
// TODO: something nicer
if (value != null && value instanceof Point) {
value = new Point((Point) value);
}
@Override
public boolean equalsTo(IDIYComponent<?> other) {
if (other == null)
return false;
if (!other.getClass().equals(this.getClass()))
return false;
Class<?> clazz = this.getClass();
while (AbstractComponent.class.isAssignableFrom(clazz)) {
Field[] fields = clazz.getDeclaredFields();
clazz = clazz.getSuperclass();
// fields = this.getClass().getDeclaredFields();
// Copy over all non-static, non-final fields that are declared
// in
// AbstractComponent or one of it's child classes
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())
&& !Modifier.isFinal(field.getModifiers())) {
field.setAccessible(true);
try {
Object value = field.get(this);
Object otherValue = field.get(other);
if (!compareObjects(value, otherValue))
return false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
return true;
}
field.set(newInstance, value);
}
}
}
return newInstance;
} catch (Exception e) {
throw new CloneNotSupportedException("Could not clone the component. Reason: " + e.getMessage());
}
}
private boolean compareObjects(Object o1, Object o2) {
if (o1 == null && o2 == null)
return true;
if (o1 == null || o2 == null)
return false;
if (o1.getClass().isArray()) {
return Arrays.equals((Object[])o1, (Object[])o2);
}
return o1.equals(o2);
}
@Override
public boolean equalsTo(IDIYComponent<?> other) {
if (other == null)
return false;
if (!other.getClass().equals(this.getClass()))
return false;
Class<?> clazz = this.getClass();
while (AbstractComponent.class.isAssignableFrom(clazz)) {
Field[] fields = clazz.getDeclaredFields();
clazz = clazz.getSuperclass();
// fields = this.getClass().getDeclaredFields();
// Copy over all non-static, non-final fields that are declared
// in
// AbstractComponent or one of it's child classes
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
field.setAccessible(true);
try {
Object value = field.get(this);
Object otherValue = field.get(other);
if (!compareObjects(value, otherValue))
return false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
return true;
}
private boolean compareObjects(Object o1, Object o2) {
if (o1 == null && o2 == null)
return true;
if (o1 == null || o2 == null)
return false;
if (o1.getClass().isArray()) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
}
return o1.equals(o2);
}
}
@@ -19,231 +19,223 @@ import org.diylc.utils.Constants;
public abstract class AbstractCurvedComponent<T> extends AbstractTransparentComponent<T> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public static Color GUIDELINE_COLOR = Color.blue;
public static Size DEFAULT_SIZE = new Size(1d, SizeUnit.in);
public static Color GUIDELINE_COLOR = Color.blue;
public static Size DEFAULT_SIZE = new Size(1d, SizeUnit.in);
protected Point[] controlPoints = new Point[] {
new Point(0, 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), (int) (DEFAULT_SIZE
.convertToPixels())),
new Point((int) DEFAULT_SIZE.convertToPixels(), (int) DEFAULT_SIZE.convertToPixels()) };
protected Point[] controlPoints = new Point[] {new Point(0, 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), (int) (DEFAULT_SIZE.convertToPixels())),
new Point((int) DEFAULT_SIZE.convertToPixels(), (int) DEFAULT_SIZE.convertToPixels())};
protected Color color = getDefaultColor();
protected PointCount pointCount = PointCount.FOUR;
protected Color color = getDefaultColor();
protected PointCount pointCount = PointCount.FOUR;
/**
* Draws the specified curve onto graphics.
*
* @param curve
* @param g2d
* @param componentState
* @param theme
*/
protected abstract void drawCurve(CubicCurve2D curve, Graphics2D g2d,
ComponentState componentState);
/**
* Draws the specified curve onto graphics.
*
* @param curve
* @param g2d
* @param componentState
* @param theme
*/
protected abstract void drawCurve(CubicCurve2D curve, Graphics2D g2d, ComponentState componentState);
/**
* @return default color.
*/
protected abstract Color getDefaultColor();
/**
* @return default color.
*/
protected abstract Color getDefaultColor();
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(getDefaultColor().darker());
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(3));
CubicCurve2D curve = new CubicCurve2D.Double(1, height - 1, width / 4, height / 3,
3 * width / 4, 2 * height / 3, width - 1, 1);
g2d.draw(curve);
g2d.setColor(getDefaultColor());
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
g2d.draw(curve);
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.setColor(getDefaultColor().darker());
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(3));
CubicCurve2D curve =
new CubicCurve2D.Double(1, height - 1, width / 4, height / 3, 3 * width / 4, 2 * height / 3, width - 1, 1);
g2d.draw(curve);
g2d.setColor(getDefaultColor());
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
g2d.draw(curve);
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
if (checkPointsClipped(g2d.getClip())) {
return;
}
if (componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING) {
// Do not track guidelines.
drawingObserver.stopTracking();
g2d.setStroke(Constants.DASHED_STROKE);
g2d.setColor(GUIDELINE_COLOR);
g2d.drawLine(controlPoints[0].x, controlPoints[0].y, controlPoints[1].x,
controlPoints[1].y);
g2d.drawLine(controlPoints[1].x, controlPoints[1].y, controlPoints[2].x,
controlPoints[2].y);
g2d.drawLine(controlPoints[2].x, controlPoints[2].y, controlPoints[3].x,
controlPoints[3].y);
drawingObserver.startTracking();
}
CubicCurve2D curve = new CubicCurve2D.Double(controlPoints[0].x, controlPoints[0].y,
controlPoints[1].x, controlPoints[1].y, controlPoints[2].x, controlPoints[2].y,
controlPoints[3].x, controlPoints[3].y);
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode, Project project,
IDrawingObserver drawingObserver) {
if (checkPointsClipped(g2d.getClip())) {
return;
}
if (componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING) {
// Do not track guidelines.
drawingObserver.stopTracking();
g2d.setStroke(Constants.DASHED_STROKE);
g2d.setColor(GUIDELINE_COLOR);
g2d.drawLine(controlPoints[0].x, controlPoints[0].y, controlPoints[1].x, controlPoints[1].y);
g2d.drawLine(controlPoints[1].x, controlPoints[1].y, controlPoints[2].x, controlPoints[2].y);
g2d.drawLine(controlPoints[2].x, controlPoints[2].y, controlPoints[3].x, controlPoints[3].y);
drawingObserver.startTracking();
}
CubicCurve2D curve =
new CubicCurve2D.Double(controlPoints[0].x, controlPoints[0].y, controlPoints[1].x, controlPoints[1].y,
controlPoints[2].x, controlPoints[2].y, controlPoints[3].x, controlPoints[3].y);
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha
/ MAX_ALPHA));
}
// g2d.setColor(color.darker());
// g2d.setStroke(new BasicStroke(thickness));
// g2d.draw(path);
// g2d.setColor(color);
// g2d.setStroke(new BasicStroke(thickness - 2));
// g2d.draw(path);
drawCurve(curve, g2d, componentState);
g2d.setComposite(oldComposite);
}
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha / MAX_ALPHA));
}
// g2d.setColor(color.darker());
// g2d.setStroke(new BasicStroke(thickness));
// g2d.draw(path);
// g2d.setColor(color);
// g2d.setStroke(new BasicStroke(thickness - 2));
// g2d.draw(path);
drawCurve(curve, g2d, componentState);
g2d.setComposite(oldComposite);
}
@EditableProperty(name = "Point Count")
public PointCount getPointCount() {
if (pointCount == null) {
pointCount = PointCount.FOUR;
}
return pointCount;
}
@EditableProperty(name = "Point Count")
public PointCount getPointCount() {
if (pointCount == null) {
pointCount = PointCount.FOUR;
}
return pointCount;
}
public void setPointCount(PointCount pointCount) {
this.pointCount = pointCount;
// Reset control points.
for (int i = 0; i < getControlPointCount(); i++) {
setControlPoint(getControlPoint(i), i);
}
}
public void setPointCount(PointCount pointCount) {
this.pointCount = pointCount;
// Reset control points.
for (int i = 0; i < getControlPointCount(); i++) {
setControlPoint(getControlPoint(i), i);
}
}
@Override
public int getControlPointCount() {
switch (getPointCount()) {
case TWO:
return 2;
case THREE:
return 3;
case FOUR:
return 4;
}
return 0;
}
@Override
public int getControlPointCount() {
switch (getPointCount()) {
case TWO:
return 2;
case THREE:
return 3;
case FOUR:
return 4;
}
return 0;
}
@Override
public boolean isControlPointSticky(int index) {
return index == 0 || index == getControlPointCount() - 1;
}
@Override
public boolean isControlPointSticky(int index) {
return index == 0 || index == getControlPointCount() - 1;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public boolean canControlPointOverlap(int index) {
// Only shape control points may overlap.
switch (getPointCount()) {
case TWO:
return false;
case THREE:
return index == 1;
case FOUR:
return index == 1 || index == 2;
}
return false;
}
@Override
public boolean canControlPointOverlap(int index) {
// Only shape control points may overlap.
switch (getPointCount()) {
case TWO:
return false;
case THREE:
return index == 1;
case FOUR:
return index == 1 || index == 2;
}
return false;
}
@Override
public Point getControlPoint(int index) {
if (index == 0) {
return controlPoints[0];
}
switch (getPointCount()) {
case TWO:
switch (index) {
case 1:
return controlPoints[3];
}
case THREE:
switch (index) {
case 1:
return controlPoints[1];
case 2:
return controlPoints[3];
}
case FOUR:
switch (index) {
case 1:
return controlPoints[1];
case 2:
return controlPoints[2];
case 3:
return controlPoints[3];
}
}
return controlPoints[index];
}
@Override
public Point getControlPoint(int index) {
if (index == 0) {
return controlPoints[0];
}
switch (getPointCount()) {
case TWO:
switch (index) {
case 1:
return controlPoints[3];
}
case THREE:
switch (index) {
case 1:
return controlPoints[1];
case 2:
return controlPoints[3];
}
case FOUR:
switch (index) {
case 1:
return controlPoints[1];
case 2:
return controlPoints[2];
case 3:
return controlPoints[3];
}
}
return controlPoints[index];
}
@Override
public void setControlPoint(Point point, int index) {
if (index == 0) {
controlPoints[0].setLocation(point);
} else {
switch (getPointCount()) {
case TWO:
switch (index) {
case 1:
Point center = new Point((point.x + controlPoints[0].x) / 2,
(point.y + controlPoints[0].y) / 2);
controlPoints[1].setLocation(center);
controlPoints[2].setLocation(center);
controlPoints[3].setLocation(point);
break;
}
break;
case THREE:
switch (index) {
case 1:
controlPoints[1].setLocation(point);
controlPoints[2].setLocation(point);
break;
case 2:
controlPoints[3].setLocation(point);
break;
}
break;
case FOUR:
switch (index) {
case 1:
controlPoints[1].setLocation(point);
break;
case 2:
controlPoints[2].setLocation(point);
break;
case 3:
controlPoints[3].setLocation(point);
break;
}
break;
}
}
}
@Override
public void setControlPoint(Point point, int index) {
if (index == 0) {
controlPoints[0].setLocation(point);
} else {
switch (getPointCount()) {
case TWO:
switch (index) {
case 1:
Point center = new Point((point.x + controlPoints[0].x) / 2, (point.y + controlPoints[0].y) / 2);
controlPoints[1].setLocation(center);
controlPoints[2].setLocation(center);
controlPoints[3].setLocation(point);
break;
}
break;
case THREE:
switch (index) {
case 1:
controlPoints[1].setLocation(point);
controlPoints[2].setLocation(point);
break;
case 2:
controlPoints[3].setLocation(point);
break;
}
break;
case FOUR:
switch (index) {
case 1:
controlPoints[1].setLocation(point);
break;
case 2:
controlPoints[2].setLocation(point);
break;
case 3:
controlPoints[3].setLocation(point);
break;
}
break;
}
}
}
@EditableProperty
public Color getColor() {
return color;
}
@EditableProperty
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void setColor(Color color) {
this.color = color;
}
enum PointCount {
TWO, THREE, FOUR;
enum PointCount {
TWO, THREE, FOUR;
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
@Override
public String toString() {
return name().substring(0, 1) + name().substring(1).toLowerCase();
}
}
}
@@ -27,430 +27,436 @@ import org.diylc.core.measures.SizeUnit;
import org.diylc.utils.Constants;
/**
* Base class for all leaded components such as resistors or capacitors. Has two
* control points and draws leads between them. Also, it positions and draws the
* shape of the component as specified by a child class.
* Base class for all leaded components such as resistors or capacitors. Has two control points and
* draws leads between them. Also, it positions and draws the shape of the component as specified by
* a child class.
*
* @author Branislav Stojkovic
*/
public abstract class AbstractLeadedComponent<T> extends AbstractTransparentComponent<T> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public static Color LEAD_COLOR = Color.decode("#CCCCCC");
public static Color LEAD_COLOR_ICON = LEAD_COLOR.darker().darker();
public static Size LEAD_THICKNESS = new Size(0.6d, SizeUnit.mm);
public static Size DEFAULT_SIZE = new Size(1d, SizeUnit.in);
public static Color LEAD_COLOR = Color.decode("#CCCCCC");
public static Color LEAD_COLOR_ICON = LEAD_COLOR.darker().darker();
public static Size LEAD_THICKNESS = new Size(0.6d, SizeUnit.mm);
public static Size DEFAULT_SIZE = new Size(1d, SizeUnit.in);
protected Size length;
protected Size width;
protected Point[] points = new Point[] { new Point((int) (-DEFAULT_SIZE.convertToPixels() / 2), 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), 0) };
protected Color bodyColor = Color.white;
protected Color borderColor = Color.black;
protected Color labelColor = LABEL_COLOR;
protected Color leadColor = LEAD_COLOR;
protected Display display = Display.NAME;
private boolean flipStanding = false;
protected Size length;
protected Size width;
protected Point[] points = new Point[] {new Point((int) (-DEFAULT_SIZE.convertToPixels() / 2), 0),
new Point((int) (DEFAULT_SIZE.convertToPixels() / 2), 0)};
protected Color bodyColor = Color.white;
protected Color borderColor = Color.black;
protected Color labelColor = LABEL_COLOR;
protected Color leadColor = LEAD_COLOR;
protected Display display = Display.NAME;
private boolean flipStanding = false;
protected AbstractLeadedComponent() {
super();
try {
this.length = getDefaultLength().clone();
this.width = getDefaultWidth().clone();
} catch (CloneNotSupportedException e) {
// This should never happen because Size supports cloning.
} catch (NullPointerException e) {
// This will happen if components do not have any shape.
}
}
protected AbstractLeadedComponent() {
super();
try {
this.length = getDefaultLength().clone();
this.width = getDefaultWidth().clone();
} catch (CloneNotSupportedException e) {
// This should never happen because Size supports cloning.
} catch (NullPointerException e) {
// This will happen if components do not have any shape.
}
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode, Project project,
IDrawingObserver drawingObserver) {
double distance = points[0].distance(points[1]);
Shape shape = getBodyShape();
// If there's no body, just draw the line connecting the ending points.
if (shape == null) {
drawLead(g2d, componentState);
} else if (supportsStandingMode() && length.convertToPixels() > points[0].distance(points[1])) {
// When ending points are too close draw the component in standing
// mode.
int width = getClosestOdd(this.width.convertToPixels());
Shape body = new Ellipse2D.Double((getFlipStanding() ? points[1] : points[0]).x - width / 2,
(getFlipStanding() ? points[1] : points[0]).y - width / 2, width, width);
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha / MAX_ALPHA));
}
g2d.setColor(outlineMode ? Constants.TRANSPARENT_COLOR : getStandingBodyColor());
g2d.fill(body);
g2d.setComposite(oldComposite);
Color finalBorderColor;
if (outlineMode) {
Theme theme = (Theme) ConfigurationManager.getInstance().readObject(IPlugInPort.THEME_KEY,
Constants.DEFAULT_THEME);
finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : theme.getOutlineColor();
} else {
finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : borderColor;
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode, Project project,
IDrawingObserver drawingObserver) {
double distance = points[0].distance(points[1]);
Shape shape = getBodyShape();
// If there's no body, just draw the line connecting the ending points.
if (shape == null) {
drawLead(g2d, componentState);
} else if (supportsStandingMode() && length.convertToPixels() > points[0].distance(points[1])) {
// When ending points are too close draw the component in standing
// mode.
int width = getClosestOdd(this.width.convertToPixels());
Shape body =
new Ellipse2D.Double((getFlipStanding() ? points[1] : points[0]).x - width / 2,
(getFlipStanding() ? points[1] : points[0]).y - width / 2, width, width);
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha / MAX_ALPHA));
}
g2d.setColor(outlineMode ? Constants.TRANSPARENT_COLOR : getStandingBodyColor());
g2d.fill(body);
g2d.setComposite(oldComposite);
Color finalBorderColor;
if (outlineMode) {
Theme theme =
(Theme) ConfigurationManager.getInstance().readObject(IPlugInPort.THEME_KEY, Constants.DEFAULT_THEME);
finalBorderColor =
componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: theme.getOutlineColor();
} else {
finalBorderColor =
componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: borderColor;
}
g2d.setColor(finalBorderColor);
g2d.draw(body);
if (!outlineMode) {
drawLead(g2d, componentState);
}
} else {
// Normal mode with component body in the center and two lead parts.
Rectangle shapeRect = shape.getBounds();
Double theta = Math.atan2(points[1].y - points[0].y, points[1].x - points[0].x);
// Go back to the original transformation to draw leads.
if (!outlineMode) {
AffineTransform textTransform = g2d.getTransform();
// if (length.convertToPixels() > points[0].distance(points[1]))
// {
// g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
// 0.5f));
// }
int leadThickness = getClosestOdd(getLeadThickness());
double leadLength = (distance - calculatePinSpacing(shapeRect)) / 2 - leadThickness / 2;
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness));
Color leadColor = shouldShadeLeads() ? getLeadColorForPainting(componentState).darker()
: getLeadColorForPainting(componentState);
g2d.setColor(leadColor);
int endX = (int) (points[0].x + Math.cos(theta) * leadLength);
int endY = (int) Math.round(points[0].y + Math.sin(theta) * leadLength);
g2d.drawLine(points[0].x, points[0].y, endX, endY);
endX = (int) (points[1].x + Math.cos(theta - Math.PI) * leadLength);
endY = (int) Math.round(points[1].y + Math.sin(theta - Math.PI) * leadLength);
g2d.drawLine(points[1].x, points[1].y, endX, endY);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness - 2));
leadColor = getLeadColorForPainting(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, (int) (points[0].x + Math.cos(theta) * leadLength),
(int) (points[0].y + Math.sin(theta) * leadLength));
g2d.drawLine(points[1].x, points[1].y, (int) (points[1].x + Math.cos(theta - Math.PI) * leadLength),
(int) (points[1].y + Math.sin(theta - Math.PI) * leadLength));
}
g2d.setTransform(textTransform);
}
// Transform graphics to draw the body in the right place and at the
// right angle.
AffineTransform oldTransform = null;
double width;
double length;
if (useShapeRectAsPosition()) {
width = shapeRect.getHeight();
length = shapeRect.getWidth();
} else {
width = getWidth().convertToPixels();
length = getLength().convertToPixels();
}
oldTransform = g2d.getTransform();
g2d.translate((points[0].x + points[1].x - length) / 2, (points[0].y + points[1].y - width) / 2);
g2d.rotate(theta, length / 2, width / 2);
// Draw body.
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha / MAX_ALPHA));
}
if (bodyColor != null) {
if (bodyColor != null) {
g2d.setColor(outlineMode ? Constants.TRANSPARENT_COLOR : bodyColor);
g2d.fill(shape);
}
}
decorateComponentBody(g2d, outlineMode);
g2d.setComposite(oldComposite);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
Color finalBorderColor;
if (outlineMode) {
Theme theme = (Theme) ConfigurationManager.getInstance().readObject(IPlugInPort.THEME_KEY,
Constants.DEFAULT_THEME);
finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : theme.getOutlineColor();
} else {
finalBorderColor = componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : borderColor;
}
g2d.setColor(finalBorderColor);
g2d.draw(shape);
g2d.setColor(finalBorderColor);
g2d.draw(body);
if (!outlineMode) {
drawLead(g2d, componentState);
}
} else {
// Normal mode with component body in the center and two lead parts.
Rectangle shapeRect = shape.getBounds();
Double theta = Math.atan2(points[1].y - points[0].y, points[1].x - points[0].x);
// Go back to the original transformation to draw leads.
if (!outlineMode) {
AffineTransform textTransform = g2d.getTransform();
// if (length.convertToPixels() > points[0].distance(points[1]))
// {
// g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
// 0.5f));
// }
int leadThickness = getClosestOdd(getLeadThickness());
double leadLength = (distance - calculatePinSpacing(shapeRect)) / 2 - leadThickness / 2;
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness));
Color leadColor =
shouldShadeLeads() ? getLeadColorForPainting(componentState).darker()
: getLeadColorForPainting(componentState);
g2d.setColor(leadColor);
int endX = (int) (points[0].x + Math.cos(theta) * leadLength);
int endY = (int) Math.round(points[0].y + Math.sin(theta) * leadLength);
g2d.drawLine(points[0].x, points[0].y, endX, endY);
endX = (int) (points[1].x + Math.cos(theta - Math.PI) * leadLength);
endY = (int) Math.round(points[1].y + Math.sin(theta - Math.PI) * leadLength);
g2d.drawLine(points[1].x, points[1].y, endX, endY);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness - 2));
leadColor = getLeadColorForPainting(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, (int) (points[0].x + Math.cos(theta) * leadLength),
(int) (points[0].y + Math.sin(theta) * leadLength));
g2d.drawLine(points[1].x, points[1].y, (int) (points[1].x + Math.cos(theta - Math.PI) * leadLength),
(int) (points[1].y + Math.sin(theta - Math.PI) * leadLength));
}
g2d.setTransform(textTransform);
}
// Transform graphics to draw the body in the right place and at the
// right angle.
AffineTransform oldTransform = null;
double width;
double length;
if (useShapeRectAsPosition()) {
width = shapeRect.getHeight();
length = shapeRect.getWidth();
} else {
width = getWidth().convertToPixels();
length = getLength().convertToPixels();
}
oldTransform = g2d.getTransform();
g2d.translate((points[0].x + points[1].x - length) / 2, (points[0].y + points[1].y - width) / 2);
g2d.rotate(theta, length / 2, width / 2);
// Draw body.
Composite oldComposite = g2d.getComposite();
if (alpha < MAX_ALPHA) {
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f * alpha / MAX_ALPHA));
}
if (bodyColor != null) {
if (bodyColor != null) {
g2d.setColor(outlineMode ? Constants.TRANSPARENT_COLOR : bodyColor);
g2d.fill(shape);
}
}
decorateComponentBody(g2d, outlineMode);
g2d.setComposite(oldComposite);
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
Color finalBorderColor;
if (outlineMode) {
Theme theme =
(Theme) ConfigurationManager.getInstance().readObject(IPlugInPort.THEME_KEY, Constants.DEFAULT_THEME);
finalBorderColor =
componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: theme.getOutlineColor();
} else {
finalBorderColor =
componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: borderColor;
}
g2d.setColor(finalBorderColor);
g2d.draw(shape);
// // Go back to the original transformation to draw leads.
// if (!outlineMode) {
// AffineTransform textTransform = g2d.getTransform();
// g2d.setTransform(oldTransform);
// if (length.convertToPixels() > points[0].distance(points[1])) {
// g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
// 0.5f));
// }
// int leadThickness = getClosestOdd(getLeadThickness());
// double leadLength = (distance - calculatePinSpacing(shapeRect)) /
// 2 - leadThickness / 2;
// g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness));
// Color leadColor = shouldShadeLeads() ?
// getLeadColor(componentState).darker()
// : getLeadColor(componentState);
// g2d.setColor(leadColor);
// int endX = (int) (points[0].x + Math.cos(theta) * leadLength);
// int endY = (int) Math.round(points[0].y + Math.sin(theta) *
// leadLength);
// g2d.drawLine(points[0].x, points[0].y, endX, endY);
// endX = (int) (points[1].x + Math.cos(theta - Math.PI) *
// leadLength);
// endY = (int) Math.round(points[1].y + Math.sin(theta - Math.PI) *
// leadLength);
// g2d.drawLine(points[1].x, points[1].y, endX, endY);
// if (shouldShadeLeads()) {
// g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness
// - 2));
// leadColor = getLeadColor(componentState);
// g2d.setColor(leadColor);
// g2d.drawLine(points[0].x, points[0].y, (int) (points[0].x +
// Math.cos(theta)
// * leadLength), (int) (points[0].y + Math.sin(theta) *
// leadLength));
// g2d.drawLine(points[1].x, points[1].y, (int) (points[1].x +
// Math.cos(theta
// - Math.PI)
// * leadLength), (int) (points[1].y + Math.sin(theta - Math.PI)
// * leadLength));
// }
// g2d.setComposite(oldComposite);
// g2d.setTransform(textTransform);
// }
// // Go back to the original transformation to draw leads.
// if (!outlineMode) {
// AffineTransform textTransform = g2d.getTransform();
// g2d.setTransform(oldTransform);
// if (length.convertToPixels() > points[0].distance(points[1])) {
// g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
// 0.5f));
// }
// int leadThickness = getClosestOdd(getLeadThickness());
// double leadLength = (distance - calculatePinSpacing(shapeRect)) /
// 2 - leadThickness / 2;
// g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness));
// Color leadColor = shouldShadeLeads() ?
// getLeadColor(componentState).darker()
// : getLeadColor(componentState);
// g2d.setColor(leadColor);
// int endX = (int) (points[0].x + Math.cos(theta) * leadLength);
// int endY = (int) Math.round(points[0].y + Math.sin(theta) *
// leadLength);
// g2d.drawLine(points[0].x, points[0].y, endX, endY);
// endX = (int) (points[1].x + Math.cos(theta - Math.PI) *
// leadLength);
// endY = (int) Math.round(points[1].y + Math.sin(theta - Math.PI) *
// leadLength);
// g2d.drawLine(points[1].x, points[1].y, endX, endY);
// if (shouldShadeLeads()) {
// g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(leadThickness
// - 2));
// leadColor = getLeadColor(componentState);
// g2d.setColor(leadColor);
// g2d.drawLine(points[0].x, points[0].y, (int) (points[0].x +
// Math.cos(theta)
// * leadLength), (int) (points[0].y + Math.sin(theta) *
// leadLength));
// g2d.drawLine(points[1].x, points[1].y, (int) (points[1].x +
// Math.cos(theta
// - Math.PI)
// * leadLength), (int) (points[1].y + Math.sin(theta - Math.PI)
// * leadLength));
// }
// g2d.setComposite(oldComposite);
// g2d.setTransform(textTransform);
// }
// Draw label.
g2d.setFont(LABEL_FONT);
if (useShapeRectAsPosition()) {
g2d.translate(shapeRect.x, shapeRect.y);
}
Color finalLabelColor;
if (outlineMode) {
Theme theme = (Theme) ConfigurationManager.getInstance().readObject(IPlugInPort.THEME_KEY,
Constants.DEFAULT_THEME);
finalLabelColor = componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING
? LABEL_COLOR_SELECTED : theme.getOutlineColor();
} else {
finalLabelColor = componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING
? LABEL_COLOR_SELECTED : labelColor;
}
g2d.setColor(finalLabelColor);
FontMetrics fontMetrics = g2d.getFontMetrics();
String label = "";
label = display == Display.NAME ? getName() : (getValue() == null ? "" : getValue().toString());
if (display == Display.NONE) {
label = "";
}
if (display == Display.BOTH) {
label = getName() + " " + (getValue() == null ? "" : getValue().toString());
}
Rectangle2D textRect = fontMetrics.getStringBounds(label, g2d);
// Don't offset in outline mode.
int offset = outlineMode ? 0 : getLabelOffset((int) length, (int) width);
// Adjust label angle if needed to make sure that it's readable.
if ((theta >= Math.PI / 2 && theta <= Math.PI) || (theta < -Math.PI / 2 && theta > -Math.PI)) {
g2d.rotate(Math.PI, length / 2, width / 2);
offset = -offset;
}
g2d.drawString(label, (int) (length - textRect.getWidth()) / 2 + offset,
calculateLabelYCoordinate(shapeRect, textRect, fontMetrics));
g2d.setTransform(oldTransform);
}
}
// Draw label.
g2d.setFont(LABEL_FONT);
if (useShapeRectAsPosition()) {
g2d.translate(shapeRect.x, shapeRect.y);
}
Color finalLabelColor;
if (outlineMode) {
Theme theme =
(Theme) ConfigurationManager.getInstance().readObject(IPlugInPort.THEME_KEY, Constants.DEFAULT_THEME);
finalLabelColor =
componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? LABEL_COLOR_SELECTED
: theme.getOutlineColor();
} else {
finalLabelColor =
componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? LABEL_COLOR_SELECTED
: labelColor;
}
g2d.setColor(finalLabelColor);
FontMetrics fontMetrics = g2d.getFontMetrics();
String label = "";
label = display == Display.NAME ? getName() : (getValue() == null ? "" : getValue().toString());
if (display == Display.NONE) {
label = "";
}
if (display == Display.BOTH) {
label = getName() + " " + (getValue() == null ? "" : getValue().toString());
}
Rectangle2D textRect = fontMetrics.getStringBounds(label, g2d);
// Don't offset in outline mode.
int offset = outlineMode ? 0 : getLabelOffset((int) length, (int) width);
// Adjust label angle if needed to make sure that it's readable.
if ((theta >= Math.PI / 2 && theta <= Math.PI) || (theta < -Math.PI / 2 && theta > -Math.PI)) {
g2d.rotate(Math.PI, length / 2, width / 2);
offset = -offset;
}
g2d.drawString(label, (int) (length - textRect.getWidth()) / 2 + offset,
calculateLabelYCoordinate(shapeRect, textRect, fontMetrics));
g2d.setTransform(oldTransform);
}
}
private void drawLead(Graphics2D g2d, ComponentState componentState) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(getLeadThickness()));
Color leadColor = shouldShadeLeads() ? getLeadColorForPainting(componentState).darker()
: getLeadColorForPainting(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(getLeadThickness() - 2));
leadColor = getLeadColorForPainting(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
}
}
private void drawLead(Graphics2D g2d, ComponentState componentState) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(getLeadThickness()));
Color leadColor =
shouldShadeLeads() ? getLeadColorForPainting(componentState).darker() : getLeadColorForPainting(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
if (shouldShadeLeads()) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(getLeadThickness() - 2));
leadColor = getLeadColorForPainting(componentState);
g2d.setColor(leadColor);
g2d.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
}
}
protected void decorateComponentBody(Graphics2D g2d, boolean outlineMode) {
// Do nothing.
}
protected void decorateComponentBody(Graphics2D g2d, boolean outlineMode) {
// Do nothing.
}
protected int calculateLabelYCoordinate(Rectangle2D shapeRect, Rectangle2D textRect, FontMetrics fontMetrics) {
return (int) (shapeRect.getHeight() - textRect.getHeight()) / 2 + fontMetrics.getAscent();
}
protected int calculateLabelYCoordinate(Rectangle2D shapeRect, Rectangle2D textRect, FontMetrics fontMetrics) {
return (int) (shapeRect.getHeight() - textRect.getHeight()) / 2 + fontMetrics.getAscent();
}
protected boolean shouldShadeLeads() {
return true;
}
protected boolean shouldShadeLeads() {
return true;
}
protected boolean supportsStandingMode() {
return false;
}
protected boolean supportsStandingMode() {
return false;
}
protected int getLabelOffset(int bodyWidth, int labelWidth) {
return 0;
}
protected int getLabelOffset(int bodyWidth, int labelWidth) {
return 0;
}
/**
* @return default component length.
*/
protected abstract Size getDefaultLength();
/**
* @return default component length.
*/
protected abstract Size getDefaultLength();
/**
* Returns default component width.
*
* @return
*/
protected abstract Size getDefaultWidth();
/**
* Returns default component width.
*
* @return
*/
protected abstract Size getDefaultWidth();
/**
* @return shape that represents component body. Shape should not be
* transformed and should be referenced to (0, 0).
*/
protected abstract Shape getBodyShape();
/**
* @return shape that represents component body. Shape should not be transformed and should be
* referenced to (0, 0).
*/
protected abstract Shape getBodyShape();
/**
* Controls how component shape should be placed relative to start and end
* point.
*
* @return <code>true<code> if shape rect should be used to center the component or <code>false</code>
* to place the component relative to <code>length</code> and
* <code>width</code> values.
*/
protected boolean useShapeRectAsPosition() {
return true;
}
/**
* Controls how component shape should be placed relative to start and end point.
*
* @return <code>true<code> if shape rect should be used to center the component or <code>false</code>
* to place the component relative to <code>length</code> and <code>width</code> values.
*/
protected boolean useShapeRectAsPosition() {
return true;
}
/**
* @return default lead thickness. Override this method to change it.
*/
protected int getLeadThickness() {
return (int) LEAD_THICKNESS.convertToPixels();
}
/**
* @return default lead thickness. Override this method to change it.
*/
protected int getLeadThickness() {
return (int) LEAD_THICKNESS.convertToPixels();
}
/**
* @return default lead color. Override this method to change it.
*/
protected Color getLeadColorForPainting(ComponentState componentState) {
return componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: getLeadColor();
}
/**
* @return default lead color. Override this method to change it.
*/
protected Color getLeadColorForPainting(ComponentState componentState) {
return componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: getLeadColor();
}
@EditableProperty(name = "Lead color")
public Color getLeadColor() {
if (leadColor == null) {
leadColor = LEAD_COLOR_ICON;
}
return leadColor;
}
@EditableProperty(name = "Lead color")
public Color getLeadColor() {
if (leadColor == null) {
leadColor = LEAD_COLOR_ICON;
}
return leadColor;
}
public void setLeadColor(Color leadColor) {
this.leadColor = leadColor;
}
public void setLeadColor(Color leadColor) {
this.leadColor = leadColor;
}
protected int calculatePinSpacing(Rectangle shapeRect) {
return shapeRect.width;
}
protected int calculatePinSpacing(Rectangle shapeRect) {
return shapeRect.width;
}
@Override
public int getControlPointCount() {
return points.length;
}
@Override
public int getControlPointCount() {
return points.length;
}
@Override
public Point getControlPoint(int index) {
return (Point) points[index];
}
@Override
public Point getControlPoint(int index) {
return (Point) points[index];
}
@Override
public boolean isControlPointSticky(int index) {
return true;
}
@Override
public boolean isControlPointSticky(int index) {
return true;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.ALWAYS;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.ALWAYS;
}
@Override
public void setControlPoint(Point point, int index) {
points[index].setLocation(point);
}
@Override
public void setControlPoint(Point point, int index) {
points[index].setLocation(point);
}
@EditableProperty(name = "Color")
public Color getBodyColor() {
return bodyColor;
}
@EditableProperty(name = "Color")
public Color getBodyColor() {
return bodyColor;
}
public void setBodyColor(Color bodyColor) {
this.bodyColor = bodyColor;
}
public void setBodyColor(Color bodyColor) {
this.bodyColor = bodyColor;
}
public Color getStandingBodyColor() {
return bodyColor;
}
public Color getStandingBodyColor() {
return bodyColor;
}
@EditableProperty(name = "Border")
public Color getBorderColor() {
return borderColor;
}
@EditableProperty(name = "Border")
public Color getBorderColor() {
return borderColor;
}
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
}
@EditableProperty(name = "Length", defaultable = true)
public Size getLength() {
return length;
}
@EditableProperty(name = "Length", defaultable = true)
public Size getLength() {
return length;
}
public void setLength(Size length) {
this.length = length;
}
public void setLength(Size length) {
this.length = length;
}
@EditableProperty(name = "Width", defaultable = true)
public Size getWidth() {
return width;
}
@EditableProperty(name = "Width", defaultable = true)
public Size getWidth() {
return width;
}
public void setWidth(Size width) {
this.width = width;
}
public void setWidth(Size width) {
this.width = width;
}
@EditableProperty
public Display getDisplay() {
return display;
}
@EditableProperty
public Display getDisplay() {
return display;
}
public void setDisplay(Display display) {
this.display = display;
}
public void setDisplay(Display display) {
this.display = display;
}
@EditableProperty(name = "Label color")
public Color getLabelColor() {
return labelColor;
}
@EditableProperty(name = "Label color")
public Color getLabelColor() {
return labelColor;
}
public void setLabelColor(Color labelColor) {
this.labelColor = labelColor;
}
public void setLabelColor(Color labelColor) {
this.labelColor = labelColor;
}
/**
* Override this method with @EditableProperty annotation in child classes
* where standing mode is supported
*
* @return
*/
public boolean getFlipStanding() {
return flipStanding;
}
/**
* Override this method with @EditableProperty annotation in child classes where standing mode is
* supported
*
* @return
*/
public boolean getFlipStanding() {
return flipStanding;
}
public void setFlipStanding(boolean flipStanding) {
this.flipStanding = flipStanding;
}
public void setFlipStanding(boolean flipStanding) {
this.flipStanding = flipStanding;
}
}
@@ -7,37 +7,36 @@ import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
/**
* Base class for radial components. The same as {@link AbstractRadialComponent}
* but with added pin spacing.
* Base class for radial components. The same as {@link AbstractRadialComponent} but with added pin
* spacing.
*
* @author bancika
*
* @param <T>
*/
public abstract class AbstractRadialComponent<T> extends
AbstractLeadedComponent<T> {
public abstract class AbstractRadialComponent<T> extends AbstractLeadedComponent<T> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public static Size PIN_SPACING = new Size(0.1d, SizeUnit.in);
public static Size PIN_SPACING = new Size(0.1d, SizeUnit.in);
private Size pinSpacing = PIN_SPACING;
private Size pinSpacing = PIN_SPACING;
@Override
protected int calculatePinSpacing(Rectangle shapeRect) {
return getClosestOdd(getPinSpacing().convertToPixels());
}
@Override
protected int calculatePinSpacing(Rectangle shapeRect) {
return getClosestOdd(getPinSpacing().convertToPixels());
}
@EditableProperty(name = "Pin spacing")
public Size getPinSpacing() {
if (pinSpacing == null) {
pinSpacing = PIN_SPACING;
}
return pinSpacing;
}
@EditableProperty(name = "Pin spacing")
public Size getPinSpacing() {
if (pinSpacing == null) {
pinSpacing = PIN_SPACING;
}
return pinSpacing;
}
public void setPinSpacing(Size pinSpacing) {
this.pinSpacing = pinSpacing;
}
public void setPinSpacing(Size pinSpacing) {
this.pinSpacing = pinSpacing;
}
}
@@ -10,64 +10,63 @@ import org.diylc.core.annotations.EditableProperty;
public abstract class AbstractSchematicLeadedSymbol<T> extends AbstractLeadedComponent<T> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public static Color COLOR = Color.blue;
public static Color LEAD_COLOR = Color.black;
public static Color COLOR = Color.blue;
public static Color LEAD_COLOR = Color.black;
protected LabelPosition labelPosition = LabelPosition.ABOVE;
protected LabelPosition labelPosition = LabelPosition.ABOVE;
public AbstractSchematicLeadedSymbol() {
super();
// We don't want to fill the body, so use null.
this.bodyColor = null;
this.leadColor = LEAD_COLOR;
this.borderColor = COLOR;
}
public AbstractSchematicLeadedSymbol() {
super();
// We don't want to fill the body, so use null.
this.bodyColor = null;
this.leadColor = LEAD_COLOR;
this.borderColor = COLOR;
}
@Override
public Color getBodyColor() {
return super.getBodyColor();
}
@Override
public Color getBodyColor() {
return super.getBodyColor();
}
@Override
protected boolean shouldShadeLeads() {
return false;
}
@Override
protected boolean shouldShadeLeads() {
return false;
}
@Override
protected int getLeadThickness() {
return 1;
}
@Override
protected int getLeadThickness() {
return 1;
}
@Override
protected int calculateLabelYCoordinate(Rectangle2D shapeRect, Rectangle2D textRect,
FontMetrics fontMetrics) {
if (labelPosition == LabelPosition.ABOVE) {
return -1;
} else {
return (int) (shapeRect.getHeight() + textRect.getHeight() - 1);
}
}
@Override
protected int calculateLabelYCoordinate(Rectangle2D shapeRect, Rectangle2D textRect, FontMetrics fontMetrics) {
if (labelPosition == LabelPosition.ABOVE) {
return -1;
} else {
return (int) (shapeRect.getHeight() + textRect.getHeight() - 1);
}
}
@EditableProperty(name = "Label position")
public LabelPosition getLabelPosition() {
return labelPosition;
}
@EditableProperty(name = "Label position")
public LabelPosition getLabelPosition() {
return labelPosition;
}
@Override
@EditableProperty(name = "Color")
public Color getBorderColor() {
return super.getBorderColor();
}
@Override
@EditableProperty(name = "Color")
public Color getBorderColor() {
return super.getBorderColor();
}
public void setLabelPosition(LabelPosition labelPosition) {
this.labelPosition = labelPosition;
}
public void setLabelPosition(LabelPosition labelPosition) {
this.labelPosition = labelPosition;
}
@Override
protected Color getLeadColorForPainting(ComponentState componentState) {
return componentState == ComponentState.SELECTED
|| componentState == ComponentState.DRAGGING ? SELECTION_COLOR : getLeadColor();
}
@Override
protected Color getLeadColorForPainting(ComponentState componentState) {
return componentState == ComponentState.SELECTED || componentState == ComponentState.DRAGGING ? SELECTION_COLOR
: getLeadColor();
}
}
@@ -4,18 +4,18 @@ import org.diylc.core.annotations.EditableProperty;
public abstract class AbstractTransparentComponent<T> extends AbstractComponent<T> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public static byte MAX_ALPHA = 127;
public static byte MAX_ALPHA = 127;
protected byte alpha = MAX_ALPHA;
protected byte alpha = MAX_ALPHA;
@EditableProperty
public Byte getAlpha() {
return alpha;
}
@EditableProperty
public Byte getAlpha() {
return alpha;
}
public void setAlpha(Byte alpha) {
this.alpha = alpha;
}
public void setAlpha(Byte alpha) {
this.alpha = alpha;
}
}
@@ -7,7 +7,6 @@ package org.diylc.core;
*/
public class AllowAllValidator implements IPropertyValidator {
@Override
public void validate(Object value) throws ValidationException {
}
@Override
public void validate(Object value) throws ValidationException {}
}
@@ -7,5 +7,5 @@ package org.diylc.core;
*/
public enum ComponentState {
NORMAL, SELECTED, LOCKED, DRAGGING
NORMAL, SELECTED, LOCKED, DRAGGING
}
@@ -2,5 +2,5 @@ package org.diylc.core;
public enum CreationMethod {
SINGLE_CLICK, POINT_BY_POINT;
SINGLE_CLICK, POINT_BY_POINT;
}
@@ -2,7 +2,5 @@ package org.diylc.core;
public enum ExpansionMode {
ALL,
SAME_TYPE,
IMMEDIATE,
ALL, SAME_TYPE, IMMEDIATE,
}
@@ -8,136 +8,129 @@ import org.diylc.core.annotations.ComponentDescriptor;
import org.diylc.core.annotations.EditableProperty;
/**
* Interface for component instance. Implementation classes of this interface
* will be instantiated by the application when component is added to the
* canvas. <br>
* Interface for component instance. Implementation classes of this interface will be instantiated
* by the application when component is added to the canvas. <br>
* <br>
* <b>Implementing classes should meet the following: </b>
* <ul>
* <li>Must have an empty constructor.</li>
* <li>Class should be annotated with {@link ComponentDescriptor}.</li>
* <li>Getters for properties editable by users should be annotated with
* {@link EditableProperty}.</li>
* <li>Component configuration should be stored int <code>public static</code>
* fields so they can be set through config file.</li>
* <li>Getters for properties editable by users should be annotated with {@link EditableProperty}.</li>
* <li>Component configuration should be stored int <code>public static</code> fields so they can be
* set through config file.</li>
* </ul>
*
* @author Branislav Stojkovic
*
* @param <T>
* type of component values, e.g. Resistance for resistors or String
* for transistors.
* @param <T> type of component values, e.g. Resistance for resistors or String for transistors.
*/
public interface IDIYComponent<T> extends Serializable {
public static final int CHASSIS = 1;
public static final int BOARD = 2;
public static final int TRACE = 3;
public static final int COMPONENT = 4;
public static final int TEXT = 5;
public static final int CHASSIS = 1;
public static final int BOARD = 2;
public static final int TRACE = 3;
public static final int COMPONENT = 4;
public static final int TEXT = 5;
/**
* @return component instance name.
*/
String getName();
/**
* @return component instance name.
*/
String getName();
/**
* Updates component instance name.
*
* @param name
*/
void setName(String name);
/**
* Updates component instance name.
*
* @param name
*/
void setName(String name);
/**
* @return component value.
*/
T getValue();
/**
* @return component value.
*/
T getValue();
/**
* Updates component value.
*
* @param value
*/
void setValue(T value);
/**
* Updates component value.
*
* @param value
*/
void setValue(T value);
/**
* @return number of control points for this component instance. May vary
* between two instances of the same type, e.g. DIL IC with 8 and 16
* pins will have 8 or 16 pins although they are of the same type.
*/
int getControlPointCount();
/**
* @return number of control points for this component instance. May vary between two instances of
* the same type, e.g. DIL IC with 8 and 16 pins will have 8 or 16 pins although they are
* of the same type.
*/
int getControlPointCount();
/**
* @param index
* @return control point at the specified index.
*/
Point getControlPoint(int index);
/**
* @param index
* @return control point at the specified index.
*/
Point getControlPoint(int index);
/**
* Updates the control point at the specified index.
*
* @param point
* @param index
*/
void setControlPoint(Point point, int index);
/**
* Updates the control point at the specified index.
*
* @param point
* @param index
*/
void setControlPoint(Point point, int index);
/**
* @param index
* @return true, if the specified control point may stick to control points
* of other components.
*/
boolean isControlPointSticky(int index);
/**
* @param index
* @return true, if the specified control point may 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);
/**
* @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);
VisibilityPolicy getControlPointVisibilityPolicy(int index);
/**
* Draws the component onto the {@link Graphics2D}.
*
* @param g2d
* @param componentState
* @param outlineMode
* @param project
* @param drawingObserver
*/
void draw(Graphics2D g2d, ComponentState componentState,
boolean outlineMode, Project project,
IDrawingObserver drawingObserver);
/**
* Draws the component onto the {@link Graphics2D}.
*
* @param g2d
* @param componentState
* @param outlineMode
* @param project
* @param drawingObserver
*/
void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode, Project project,
IDrawingObserver drawingObserver);
/**
* Draws icon representation of the component. This should not depend on
* component state, i.e. it should be treated as a static method.
*
* @param g2d
* @param width
* @param height
*/
void drawIcon(Graphics2D g2d, int width, int height);
/**
* Draws icon representation of the component. This should not depend on component state, i.e. it
* should be treated as a static method.
*
* @param g2d
* @param width
* @param height
*/
void drawIcon(Graphics2D g2d, int width, int height);
/**
* Clones the component.
*
* @return
*/
IDIYComponent<T> clone() throws CloneNotSupportedException;
/**
* Clones the component.
*
* @return
*/
IDIYComponent<T> clone() throws CloneNotSupportedException;
/**
* @return full value for BOM.
*/
String getValueForDisplay();
/**
* @return full value for BOM.
*/
String getValueForDisplay();
/**
* Checks if two components are equal.
*
* @param other
* @return
*/
boolean equalsTo(IDIYComponent<?> other);
/**
* Checks if two components are equal.
*
* @param other
* @return
*/
boolean equalsTo(IDIYComponent<?> other);
}
@@ -1,15 +1,14 @@
package org.diylc.core;
/**
* Interface for tracking component drawing process. Components may use it to
* stop or restart tracking. Anything drawn while tracking is stopped will not
* be added to the mouse hot-spot area.
* Interface for tracking component drawing process. Components may use it to stop or restart
* tracking. Anything drawn while tracking is stopped will not be added to the mouse hot-spot area.
*
* @author Branislav Stojkovic
*/
public interface IDrawingObserver {
void stopTracking();
void stopTracking();
void startTracking();
void startTracking();
}
@@ -7,10 +7,9 @@ package org.diylc.core;
*/
public interface IPropertyValidator {
/**
* @param value
* @throws ValidationException
* if validation fails. Message will contain the reason.
*/
void validate(Object value) throws ValidationException;
/**
* @param value
* @throws ValidationException if validation fails. Message will contain the reason.
*/
void validate(Object value) throws ValidationException;
}
@@ -14,28 +14,28 @@ import org.diylc.common.PropertyWrapper;
*/
public interface IView {
public static final int ERROR_MESSAGE = 0;
public static final int INFORMATION_MESSAGE = 1;
public static final int WARNING_MESSAGE = 2;
public static final int QUESTION_MESSAGE = 3;
public static final int PLAIN_MESSAGE = -1;
public static final int DEFAULT_OPTION = -1;
public static final int YES_NO_OPTION = 0;
public static final int YES_NO_CANCEL_OPTION = 1;
public static final int OK_CANCEL_OPTION = 2;
public static final int YES_OPTION = 0;
public static final int NO_OPTION = 1;
public static final int CANCEL_OPTION = 2;
public static final int OK_OPTION = 0;
public static final String CHECK_BOX_MENU_ITEM = "org.diylc.checkBoxMenuItem";
public static final String RADIO_BUTTON_GROUP_KEY = "org.diylc.radioButtonGroup";
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);
public static final String CHECK_BOX_MENU_ITEM = "org.diylc.checkBoxMenuItem";
public static final String RADIO_BUTTON_GROUP_KEY = "org.diylc.radioButtonGroup";
int showConfirmDialog(String message, String title, int optionType, int messageType);
boolean editProperties(List<PropertyWrapper> properties, Set<PropertyWrapper> defaultedProperties);
File promptFileSave();
void showMessage(String message, String title, int messageType);
int showConfirmDialog(String message, String title, int optionType, int messageType);
boolean editProperties(List<PropertyWrapper> properties, Set<PropertyWrapper> defaultedProperties);
File promptFileSave();
}
@@ -16,244 +16,244 @@ import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
/**
* Entity class that defines a project. Contains project properties and a
* collection of components.This class is serialized to file. Some filed getters
* are tagged with {@link EditableProperty} to enable for user to edit them.
* Entity class that defines a project. Contains project properties and a collection of
* components.This class is serialized to file. Some filed getters are tagged with
* {@link EditableProperty} to enable for user to edit them.
*
* @author Branislav Stojkovic
*/
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public static String DEFAULT_TITLE = "New Project";
public static Size DEFAULT_WIDTH = new Size(29d, SizeUnit.cm);
public static Size DEFAULT_HEIGHT = new Size(21d, SizeUnit.cm);
public static Size DEFAULT_GRID_SPACING = new Size(0.1d, SizeUnit.in);
public static String DEFAULT_TITLE = "New Project";
public static Size DEFAULT_WIDTH = new Size(29d, SizeUnit.cm);
public static Size DEFAULT_HEIGHT = new Size(21d, SizeUnit.cm);
public static Size DEFAULT_GRID_SPACING = new Size(0.1d, SizeUnit.in);
private VersionNumber fileVersion;
private VersionNumber fileVersion;
private String title;
private String author;
private String description;
private Size width;
private Size height;
private Size gridSpacing;
private List<IDIYComponent<?>> components;
private Set<Set<IDIYComponent<?>>> groups;
private Set<Integer> lockedLayers;
private String title;
private String author;
private String description;
private Size width;
private Size height;
private Size gridSpacing;
private List<IDIYComponent<?>> components;
private Set<Set<IDIYComponent<?>>> groups;
private Set<Integer> lockedLayers;
public Project() {
components = new ArrayList<IDIYComponent<?>>();
groups = new HashSet<Set<IDIYComponent<?>>>();
lockedLayers = new HashSet<Integer>();
title = DEFAULT_TITLE;
author = System.getProperty("user.name");
width = DEFAULT_WIDTH;
height = DEFAULT_HEIGHT;
gridSpacing = DEFAULT_GRID_SPACING;
}
public Project() {
components = new ArrayList<IDIYComponent<?>>();
groups = new HashSet<Set<IDIYComponent<?>>>();
lockedLayers = new HashSet<Integer>();
title = DEFAULT_TITLE;
author = System.getProperty("user.name");
width = DEFAULT_WIDTH;
height = DEFAULT_HEIGHT;
gridSpacing = DEFAULT_GRID_SPACING;
}
@EditableProperty(defaultable = false)
public String getTitle() {
return title;
}
@EditableProperty(defaultable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setTitle(String title) {
this.title = title;
}
@EditableProperty
public String getAuthor() {
return author;
}
@EditableProperty
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public void setAuthor(String author) {
this.author = author;
}
@EditableProperty(defaultable = false)
public String getDescription() {
return description;
}
@EditableProperty(defaultable = false)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDescription(String description) {
this.description = description;
}
@EditableProperty
public Size getWidth() {
return width;
}
@EditableProperty
public Size getWidth() {
return width;
}
public void setWidth(Size width) {
this.width = width;
}
public void setWidth(Size width) {
this.width = width;
}
@EditableProperty
public Size getHeight() {
return height;
}
@EditableProperty
public Size getHeight() {
return height;
}
public void setHeight(Size height) {
this.height = height;
}
public void setHeight(Size height) {
this.height = height;
}
@EditableProperty(name = "Grid spacing", validatorClass = SpacingValidator.class)
public Size getGridSpacing() {
return gridSpacing;
}
@EditableProperty(name = "Grid spacing", validatorClass = SpacingValidator.class)
public Size getGridSpacing() {
return gridSpacing;
}
public void setGridSpacing(Size gridSpacing) {
this.gridSpacing = gridSpacing;
}
public void setGridSpacing(Size gridSpacing) {
this.gridSpacing = gridSpacing;
}
/**
* List of components sorted by z-order ascending.
*
* @return
*/
public List<IDIYComponent<?>> getComponents() {
return components;
}
/**
* List of components sorted by z-order ascending.
*
* @return
*/
public List<IDIYComponent<?>> getComponents() {
return components;
}
/**
* Set of grouped components.
*
* @return
*/
public Set<Set<IDIYComponent<?>>> getGroups() {
return groups;
}
/**
* Set of grouped components.
*
* @return
*/
public Set<Set<IDIYComponent<?>>> getGroups() {
return groups;
}
public Set<Integer> getLockedLayers() {
return lockedLayers;
}
public Set<Integer> getLockedLayers() {
return lockedLayers;
}
public VersionNumber getFileVersion() {
return fileVersion;
}
public VersionNumber getFileVersion() {
return fileVersion;
}
public void setFileVersion(VersionNumber fileVersion) {
this.fileVersion = fileVersion;
}
public void setFileVersion(VersionNumber fileVersion) {
this.fileVersion = fileVersion;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + ((components == null) ? 0 : components.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((height == null) ? 0 : height.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + ((width == null) ? 0 : width.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + ((components == null) ? 0 : components.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((height == null) ? 0 : height.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + ((width == null) ? 0 : width.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Project other = (Project) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (components == null) {
if (other.components != null)
return false;
} else if (components.size() != other.components.size()) {
return false;
} else {
Iterator<IDIYComponent<?>> i1 = components.iterator();
Iterator<IDIYComponent<?>> i2 = other.components.iterator();
while (i1.hasNext()) {
IDIYComponent<?> c1 = i1.next();
IDIYComponent<?> c2 = i2.next();
if (!c1.equalsTo(c2))
return false;
}
}
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (height == null) {
if (other.height != null)
return false;
} else if (!height.equals(other.height))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (width == null) {
if (other.width != null)
return false;
} else if (!width.equals(other.width))
return false;
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Project other = (Project) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (components == null) {
if (other.components != null)
return false;
} else if (components.size() != other.components.size()) {
return false;
} else {
Iterator<IDIYComponent<?>> i1 = components.iterator();
Iterator<IDIYComponent<?>> i2 = other.components.iterator();
while (i1.hasNext()) {
IDIYComponent<?> c1 = i1.next();
IDIYComponent<?> c2 = i2.next();
if (!c1.equalsTo(c2))
return false;
}
}
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (height == null) {
if (other.height != null)
return false;
} else if (!height.equals(other.height))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (width == null) {
if (other.width != null)
return false;
} else if (!width.equals(other.width))
return false;
return true;
}
@Override
public String toString() {
return title;
}
@Override
public String toString() {
return title;
}
public static class SpacingValidator extends PositiveMeasureValidator {
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(0.1d, SizeUnit.mm)) < 0) {
throw new ValidationException("must be at least 0.1mm");
}
if (size.compareTo(new Size(1d, SizeUnit.in)) > 0) {
throw new ValidationException("must be less than 1in");
}
}
}
@Override
public void validate(Object value) throws ValidationException {
super.validate(value);
Size size = (Size) value;
if (size.compareTo(new Size(0.1d, SizeUnit.mm)) < 0) {
throw new ValidationException("must be at least 0.1mm");
}
if (size.compareTo(new Size(1d, SizeUnit.in)) > 0) {
throw new ValidationException("must be less than 1in");
}
}
}
@Override
public Project clone() {
Project project = new Project();
project.setTitle(this.getTitle());
project.setAuthor(this.getAuthor());
project.setDescription(this.getDescription());
project.setFileVersion(this.getFileVersion());
project.setGridSpacing(this.getGridSpacing());
project.setHeight(this.getHeight());
project.setWidth(this.getWidth());
project.getLockedLayers().addAll(this.getLockedLayers());
@Override
public Project clone() {
Project project = new Project();
project.setTitle(this.getTitle());
project.setAuthor(this.getAuthor());
project.setDescription(this.getDescription());
project.setFileVersion(this.getFileVersion());
project.setGridSpacing(this.getGridSpacing());
project.setHeight(this.getHeight());
project.setWidth(this.getWidth());
project.getLockedLayers().addAll(this.getLockedLayers());
Map<IDIYComponent<?>, IDIYComponent<?>> cloneMap = new HashMap<IDIYComponent<?>, IDIYComponent<?>>();
Map<IDIYComponent<?>, IDIYComponent<?>> cloneMap = new HashMap<IDIYComponent<?>, IDIYComponent<?>>();
for (IDIYComponent<?> component : this.components) {
try {
IDIYComponent<?> clone = component.clone();
project.getComponents().add(clone);
cloneMap.put(component, clone);
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
for (IDIYComponent<?> component : this.components) {
try {
IDIYComponent<?> clone = component.clone();
project.getComponents().add(clone);
cloneMap.put(component, clone);
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
for (Set<IDIYComponent<?>> group : this.groups) {
Set<IDIYComponent<?>> cloneGroup = new HashSet<IDIYComponent<?>>();
for (IDIYComponent<?> component : group) {
cloneGroup.add(cloneMap.get(component));
}
project.groups.add(cloneGroup);
}
return project;
}
for (Set<IDIYComponent<?>> group : this.groups) {
Set<IDIYComponent<?>> cloneGroup = new HashSet<IDIYComponent<?>>();
for (IDIYComponent<?> component : group) {
cloneGroup.add(cloneMap.get(component));
}
project.groups.add(cloneGroup);
}
return project;
}
}
@@ -6,75 +6,75 @@ import java.util.Map;
public class Template {
private String name;
private Map<String, Object> values;
private List<Point> points;
private String name;
private Map<String, Object> values;
private List<Point> points;
public Template(String name, Map<String, Object> values, List<Point> points) {
super();
this.name = name;
this.values = values;
this.points = points;
}
public Template(String name, Map<String, Object> values, List<Point> points) {
super();
this.name = name;
this.values = values;
this.points = points;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getValues() {
return values;
}
public Map<String, Object> getValues() {
return values;
}
public void setValues(Map<String, Object> values) {
this.values = values;
}
public List<Point> getPoints() {
return points;
}
public void setPoints(List<Point> points) {
this.points = points;
}
public void setValues(Map<String, Object> values) {
this.values = values;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((points == null) ? 0 : points.hashCode());
result = prime * result + ((values == null) ? 0 : values.hashCode());
return result;
}
public List<Point> getPoints() {
return points;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Template other = (Template) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (points == null) {
if (other.points != null)
return false;
} else if (!points.equals(other.points))
return false;
if (values == null) {
if (other.values != null)
return false;
} else if (!values.equals(other.values))
return false;
return true;
}
public void setPoints(List<Point> points) {
this.points = points;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((points == null) ? 0 : points.hashCode());
result = prime * result + ((values == null) ? 0 : values.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Template other = (Template) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (points == null) {
if (other.points != null)
return false;
} else if (!points.equals(other.points))
return false;
if (values == null) {
if (other.values != null)
return false;
} else if (!values.equals(other.values))
return false;
return true;
}
}
@@ -5,82 +5,82 @@ import java.io.Serializable;
public class Theme implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private String name;
private Color bgColor;
private Color gridColor;
private Color outlineColor;
private String name;
private Color bgColor;
private Color gridColor;
private Color outlineColor;
public Theme(String name, Color bgColor, Color gridColor, Color outlineColor) {
super();
this.name = name;
this.bgColor = bgColor;
this.gridColor = gridColor;
this.outlineColor = outlineColor;
}
public Theme(String name, Color bgColor, Color gridColor, Color outlineColor) {
super();
this.name = name;
this.bgColor = bgColor;
this.gridColor = gridColor;
this.outlineColor = outlineColor;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public Color getBgColor() {
return bgColor;
}
public Color getBgColor() {
return bgColor;
}
public Color getGridColor() {
return gridColor;
}
public Color getGridColor() {
return gridColor;
}
public Color getOutlineColor() {
return outlineColor;
}
public Color getOutlineColor() {
return outlineColor;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bgColor == null) ? 0 : bgColor.hashCode());
result = prime * result + ((gridColor == null) ? 0 : gridColor.hashCode());
result = prime * result + ((outlineColor == null) ? 0 : outlineColor.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bgColor == null) ? 0 : bgColor.hashCode());
result = prime * result + ((gridColor == null) ? 0 : gridColor.hashCode());
result = prime * result + ((outlineColor == null) ? 0 : outlineColor.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Theme other = (Theme) obj;
if (bgColor == null) {
if (other.bgColor != null)
return false;
} else if (!bgColor.equals(other.bgColor))
return false;
if (gridColor == null) {
if (other.gridColor != null)
return false;
} else if (!gridColor.equals(other.gridColor))
return false;
if (outlineColor == null) {
if (other.outlineColor != null)
return false;
} else if (!outlineColor.equals(other.outlineColor))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Theme other = (Theme) obj;
if (bgColor == null) {
if (other.bgColor != null)
return false;
} else if (!bgColor.equals(other.bgColor))
return false;
if (gridColor == null) {
if (other.gridColor != null)
return false;
} else if (!gridColor.equals(other.gridColor))
return false;
if (outlineColor == null) {
if (other.outlineColor != null)
return false;
} else if (!outlineColor.equals(other.outlineColor))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return name;
}
@Override
public String toString() {
return name;
}
}
@@ -1,11 +1,10 @@
package org.diylc.core;
public class ValidationException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public ValidationException(String message) {
super(message);
}
public ValidationException(String message) {
super(message);
}
}
@@ -7,16 +7,16 @@ package org.diylc.core;
*/
public enum VisibilityPolicy {
/**
* Control point should be rendered all the time.
*/
ALWAYS,
/**
* Control point should be rendered only when the component is selected.
*/
WHEN_SELECTED,
/**
* Control point should not be rendered regardless of component selection.
*/
NEVER;
/**
* Control point should be rendered all the time.
*/
ALWAYS,
/**
* Control point should be rendered only when the component is selected.
*/
WHEN_SELECTED,
/**
* Control point should not be rendered regardless of component selection.
*/
NEVER;
}
@@ -1,7 +1,5 @@
package org.diylc.core.annotations;
public enum BomPolicy {
SHOW_ALL_NAMES,
SHOW_ONLY_TYPE_NAME,
NEVER_SHOW,
SHOW_ALL_NAMES, SHOW_ONLY_TYPE_NAME, NEVER_SHOW,
}
@@ -7,80 +7,77 @@ import org.diylc.core.CreationMethod;
import org.diylc.core.IDIYComponent;
/**
* Annotation for {@link IDIYComponent} implementation. Describes component
* properties.
* Annotation for {@link IDIYComponent} implementation. Describes component properties.
*
* @author Branislav Stojkovic
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface ComponentDescriptor {
/**
* @return component type name.
*/
String name();
/**
* @return component type name.
*/
String name();
/**
* @return component type description.
*/
String description();
/**
* @return component type description.
*/
String description();
/**
* @return method that should be used to create a component. If
* <code>CreationMethod.POINT_BY_POINT</code> is used, user will
* have to select ending points before the component is created.
*/
CreationMethod creationMethod() default CreationMethod.SINGLE_CLICK;
/**
* @return method that should be used to create a component. If
* <code>CreationMethod.POINT_BY_POINT</code> is used, user will have to select ending
* points before the component is created.
*/
CreationMethod creationMethod() default CreationMethod.SINGLE_CLICK;
/**
* @return component category, e.g. "Passive", "Semiconductors", etc.
*/
String category();
/**
* @return component category, e.g. "Passive", "Semiconductors", etc.
*/
String category();
/**
* @return component author name.
*/
String author();
/**
* @return component author name.
*/
String author();
/**
* @return prefix that will be used to generate component instance names,
* e.g. "R" for resistors or "Q" for transistors.
*/
String instanceNamePrefix();
/**
* @return prefix that will be used to generate component instance names, e.g. "R" for resistors
* or "Q" for transistors.
*/
String instanceNamePrefix();
/**
* @return Z-order of the component.
*/
double zOrder();
/**
* @return Z-order of the component.
*/
double zOrder();
/**
* @return true if the component may go beyond it's predefined layer. In
* that case, <code>zOrder</code> is used as initial z order of the
* component.
*/
boolean flexibleZOrder() default false;
/**
* @return true if the component may go beyond it's predefined layer. In that case,
* <code>zOrder</code> is used as initial z order of the component.
*/
boolean flexibleZOrder() default false;
/**
* @return when false, moving one control point will cause all the others to
* move together with it.
*/
boolean stretchable() default true;
/**
* @return when false, moving one control point will cause all the others to move together with
* it.
*/
boolean stretchable() default true;
/**
* @return controls what should be shown the BOM
*/
BomPolicy bomPolicy() default BomPolicy.SHOW_ALL_NAMES;
/**
* @return controls what should be shown the BOM
*/
BomPolicy bomPolicy() default BomPolicy.SHOW_ALL_NAMES;
/**
* @return when true, component editor dialog should be shown in Auto-Edit
* mode.
*/
boolean autoEdit() default true;
/**
* @return true if component may be rotated, false otherwise
* @return
*/
boolean rotatable() default true;
/**
* @return when true, component editor dialog should be shown in Auto-Edit mode.
*/
boolean autoEdit() default true;
/**
* @return true if component may be rotated, false otherwise
* @return
*/
boolean rotatable() default true;
}
@@ -7,36 +7,36 @@ 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>
* respectively and this annotation must be placed on the getter method.
* Used to annotate editable component property. Editable property XYZ must have both getter and
* setter named <code>getXYZ</code> and <code>setXYZ</code> respectively and this annotation must be
* placed on the getter method.
*
* @author Branislav Stojkovic
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface EditableProperty {
/**
* Returns property name. If left blank property name will be extracted from
* the getter name, e.g. getter <code>getXYZ</code> will induce property
* name <code>XYZ</code>. <br>
* Default value is blank.
*
* @return
*/
String name() default "";
/**
* Returns property name. If left blank property name will be extracted from the getter name, e.g.
* getter <code>getXYZ</code> will induce property name <code>XYZ</code>. <br>
* Default value is blank.
*
* @return
*/
String name() default "";
/**
* If true, application may set default value for this property. <br>
* Default value is true.
*
* @return
*/
boolean defaultable() default true;
/**
* Class of validator to use to
* @return
*/
Class<? extends IPropertyValidator> validatorClass() default AllowAllValidator.class;
/**
* If true, application may set default value for this property. <br>
* Default value is true.
*
* @return
*/
boolean defaultable() default true;
/**
* Class of validator to use to
*
* @return
*/
Class<? extends IPropertyValidator> validatorClass() default AllowAllValidator.class;
}
@@ -6,17 +6,17 @@ import org.diylc.core.measures.AbstractMeasure;
public class PositiveMeasureValidator implements IPropertyValidator {
@Override
public void validate(Object value) throws ValidationException {
if (value == null)
return;
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.");
}
}
@Override
public void validate(Object value) throws ValidationException {
if (value == null)
return;
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.");
}
}
}
@@ -13,76 +13,76 @@ import java.text.Format;
*/
public class AbstractMeasure<T extends Enum<? extends Unit>> implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
protected static final Format format = new DecimalFormat("0.####");
protected static final Format format = new DecimalFormat("0.####");
protected Double value;
protected T unit;
protected Double value;
protected T unit;
// public AbstractMeasure() {
// }
// public AbstractMeasure() {
// }
public AbstractMeasure(Double value, T unit) {
super();
this.value = value;
this.unit = unit;
}
public AbstractMeasure(Double value, T unit) {
super();
this.value = value;
this.unit = unit;
}
public Double getValue() {
return value;
}
public Double getValue() {
return value;
}
// public void setValue(Double value) {
// this.value = value;
// }
// public void setValue(Double value) {
// this.value = value;
// }
public T getUnit() {
return unit;
}
public T getUnit() {
return unit;
}
// public void setUnit(T multiplier) {
// this.unit = multiplier;
// }
// @Override
// public Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
// public void setUnit(T multiplier) {
// this.unit = multiplier;
// }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((unit == null) ? 0 : unit.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
// @Override
// public Object clone() throws CloneNotSupportedException {
// return super.clone();
// }
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractMeasure<?> other = (AbstractMeasure<?>) obj;
if (unit == null) {
if (other.unit != null)
return false;
} else if (!unit.equals(other.unit))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((unit == null) ? 0 : unit.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public String toString() {
return format.format(value) + unit;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractMeasure<?> other = (AbstractMeasure<?>) obj;
if (unit == null) {
if (other.unit != null)
return false;
} else if (!unit.equals(other.unit))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public String toString() {
return format.format(value) + unit;
}
}
@@ -2,30 +2,30 @@ package org.diylc.core.measures;
public class Capacitance extends AbstractMeasure<CapacitanceUnit> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
// public Capacitance() {
// super();
// // TODO Auto-generated constructor stub
// }
// public Capacitance() {
// super();
// // TODO Auto-generated constructor stub
// }
public Capacitance(Double value, CapacitanceUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
public Capacitance(Double value, CapacitanceUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Capacitance clone() throws CloneNotSupportedException {
return new Capacitance(value, unit);
}
public static Capacitance parseCapacitance(String value) {
for (CapacitanceUnit unit : CapacitanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Capacitance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse capacitance: " + value);
}
@Override
public Capacitance clone() throws CloneNotSupportedException {
return new Capacitance(value, unit);
}
public static Capacitance parseCapacitance(String value) {
for (CapacitanceUnit unit : CapacitanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Capacitance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse capacitance: " + value);
}
}
@@ -2,23 +2,23 @@ package org.diylc.core.measures;
public enum CapacitanceUnit implements Unit {
pF(1, "pF"), nF(1e3, "nF"), uF(1e6, "uF"), mF(1e9, "mF"), F(1e12, "F");
pF(1, "pF"), nF(1e3, "nF"), uF(1e6, "uF"), mF(1e9, "mF"), F(1e12, "F");
double factor;
String display;
double factor;
String display;
private CapacitanceUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
private CapacitanceUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
@Override
public double getFactor() {
return factor;
}
@Override
public double getFactor() {
return factor;
}
@Override
public String toString() {
return display;
}
@Override
public String toString() {
return display;
}
}
@@ -2,15 +2,15 @@ package org.diylc.core.measures;
public class Current extends AbstractMeasure<CurrentUnit> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public Current(Double value, CurrentUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
public Current(Double value, CurrentUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Current clone() throws CloneNotSupportedException {
return new Current(value, unit);
}
@Override
public Current clone() throws CloneNotSupportedException {
return new Current(value, unit);
}
}
@@ -2,23 +2,23 @@ package org.diylc.core.measures;
public enum CurrentUnit implements Unit {
uA(1e-6, "uA"), mA(1e-3, "mA"), A(1, "A");
uA(1e-6, "uA"), mA(1e-3, "mA"), A(1, "A");
double factor;
String display;
double factor;
String display;
private CurrentUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
private CurrentUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
@Override
public double getFactor() {
return factor;
}
@Override
public double getFactor() {
return factor;
}
@Override
public String toString() {
return display;
}
@Override
public String toString() {
return display;
}
}
@@ -2,30 +2,30 @@ package org.diylc.core.measures;
public class Inductance extends AbstractMeasure<InductanceUnit> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
// public Inductance() {
// super();
// // TODO Auto-generated constructor stub
// }
// public Inductance() {
// super();
// // TODO Auto-generated constructor stub
// }
public Inductance(Double value, InductanceUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
public Inductance(Double value, InductanceUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Inductance clone() throws CloneNotSupportedException {
return new Inductance(value, unit);
}
@Override
public Inductance clone() throws CloneNotSupportedException {
return new Inductance(value, unit);
}
public static Inductance parseCapacitance(String value) {
for (InductanceUnit unit : InductanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Inductance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse inductance: " + value);
}
public static Inductance parseCapacitance(String value) {
for (InductanceUnit unit : InductanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Inductance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse inductance: " + value);
}
}
@@ -2,23 +2,23 @@ package org.diylc.core.measures;
public enum InductanceUnit implements Unit {
pH(1, "pH"), nH(1e3, "nH"), uH(1e6, "uH"), mH(1e9, "mH"), H(1e12, "H");
pH(1, "pH"), nH(1e3, "nH"), uH(1e6, "uH"), mH(1e9, "mH"), H(1e12, "H");
double factor;
String display;
double factor;
String display;
private InductanceUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
private InductanceUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
@Override
public double getFactor() {
return factor;
}
@Override
public double getFactor() {
return factor;
}
@Override
public String toString() {
return display;
}
@Override
public String toString() {
return display;
}
}
@@ -2,30 +2,30 @@ package org.diylc.core.measures;
public class Power extends AbstractMeasure<PowerUnit> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
// public Power() {
// super();
// // TODO Auto-generated constructor stub
// }
// public Power() {
// super();
// // TODO Auto-generated constructor stub
// }
public Power(Double value, PowerUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
public Power(Double value, PowerUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Power clone() throws CloneNotSupportedException {
return new Power(value, unit);
}
@Override
public Power clone() throws CloneNotSupportedException {
return new Power(value, unit);
}
public static Power parseCapacitance(String value) {
for (PowerUnit unit : PowerUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Power(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse power: " + value);
}
public static Power parseCapacitance(String value) {
for (PowerUnit unit : PowerUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Power(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse power: " + value);
}
}
@@ -2,23 +2,23 @@ package org.diylc.core.measures;
public enum PowerUnit implements Unit {
MW(1e-1, "mW"), W(1, "W"), KW(1e3, "KW");
MW(1e-1, "mW"), W(1, "W"), KW(1e3, "KW");
double factor;
String display;
double factor;
String display;
private PowerUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
private PowerUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
@Override
public double getFactor() {
return factor;
}
@Override
public double getFactor() {
return factor;
}
@Override
public String toString() {
return display;
}
@Override
public String toString() {
return display;
}
}
@@ -6,93 +6,92 @@ import org.diylc.common.ResistorColorCode;
public class Resistance extends AbstractMeasure<ResistanceUnit> {
private static final long serialVersionUID = 1L;
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 };
private static final Color[] COLOR_DIGITS = new Color[] {Color.black, Color.decode("#8B4513"), Color.red,
Color.orange, Color.yellow, Color.decode("#76EE00"), Color.blue, Color.decode("#91219E"), Color.lightGray,
Color.white};
private static final Color[] COLOR_MULTIPLIER = new Color[] {Color.lightGray.brighter(), Color.decode("#FFB90F"),
Color.black, Color.decode("#8B4513"), Color.red, Color.orange, Color.yellow, Color.decode("#76EE00"), Color.blue};
// public Resistance() {
// super();
// // TODO Auto-generated constructor stub
// }
// public Resistance() {
// super();
// // TODO Auto-generated constructor stub
// }
public Resistance(Double value, ResistanceUnit multiplier) {
super(value, multiplier);
// TODO Auto-generated constructor stub
}
public Resistance(Double value, ResistanceUnit multiplier) {
super(value, multiplier);
// TODO Auto-generated constructor stub
}
@Override
public Resistance clone() throws CloneNotSupportedException {
return new Resistance(value, unit);
}
@Override
public Resistance clone() throws CloneNotSupportedException {
return new Resistance(value, unit);
}
public Color[] getColorCode(ResistorColorCode resistorColorCode) {
Color[] bands;
if (getValue() == 0) {
switch (resistorColorCode) {
case _4_BAND:
bands = new Color[3];
bands[0] = COLOR_DIGITS[0];
bands[1] = COLOR_DIGITS[0];
bands[2] = COLOR_MULTIPLIER[2];
break;
case _5_BAND:
bands = new Color[4];
bands[0] = COLOR_DIGITS[0];
bands[1] = COLOR_DIGITS[0];
bands[2] = COLOR_DIGITS[0];
bands[3] = COLOR_MULTIPLIER[2];
break;
default:
bands = new Color[] {};
}
} else {
double base = getValue() * getUnit().getFactor();
int multiplier = 0;
while (base > (resistorColorCode == ResistorColorCode._4_BAND ? 99 : 999)) {
multiplier += 1;
base /= 10;
}
while (base < (resistorColorCode == ResistorColorCode._4_BAND ? 10 : 100)) {
multiplier -= 1;
base *= 10;
}
if (multiplier > 6 || multiplier < -2) {
// Out of range.
return new Color[] {};
}
switch (resistorColorCode) {
case _4_BAND:
bands = new Color[3];
bands[0] = COLOR_DIGITS[(int) (base / 10)];
bands[1] = COLOR_DIGITS[(int) (base % 10)];
bands[2] = COLOR_MULTIPLIER[multiplier + 2];
break;
case _5_BAND:
bands = new Color[4];
bands[0] = COLOR_DIGITS[(int) (base / 100)];
bands[1] = COLOR_DIGITS[(int) (base / 10 % 10)];
bands[2] = COLOR_DIGITS[(int) (base % 10)];
bands[3] = COLOR_MULTIPLIER[multiplier + 2];
break;
default:
bands = new Color[] {};
}
}
return bands;
}
public Color[] getColorCode(ResistorColorCode resistorColorCode) {
Color[] bands;
if (getValue() == 0) {
switch (resistorColorCode) {
case _4_BAND:
bands = new Color[3];
bands[0] = COLOR_DIGITS[0];
bands[1] = COLOR_DIGITS[0];
bands[2] = COLOR_MULTIPLIER[2];
break;
case _5_BAND:
bands = new Color[4];
bands[0] = COLOR_DIGITS[0];
bands[1] = COLOR_DIGITS[0];
bands[2] = COLOR_DIGITS[0];
bands[3] = COLOR_MULTIPLIER[2];
break;
default:
bands = new Color[] {};
}
} else {
double base = getValue() * getUnit().getFactor();
int multiplier = 0;
while (base > (resistorColorCode == ResistorColorCode._4_BAND ? 99 : 999)) {
multiplier += 1;
base /= 10;
}
while (base < (resistorColorCode == ResistorColorCode._4_BAND ? 10 : 100)) {
multiplier -= 1;
base *= 10;
}
if (multiplier > 6 || multiplier < -2) {
// Out of range.
return new Color[] {};
}
switch (resistorColorCode) {
case _4_BAND:
bands = new Color[3];
bands[0] = COLOR_DIGITS[(int) (base / 10)];
bands[1] = COLOR_DIGITS[(int) (base % 10)];
bands[2] = COLOR_MULTIPLIER[multiplier + 2];
break;
case _5_BAND:
bands = new Color[4];
bands[0] = COLOR_DIGITS[(int) (base / 100)];
bands[1] = COLOR_DIGITS[(int) (base / 10 % 10)];
bands[2] = COLOR_DIGITS[(int) (base % 10)];
bands[3] = COLOR_MULTIPLIER[multiplier + 2];
break;
default:
bands = new Color[] {};
}
}
return bands;
}
public static Resistance parseResistance(String value) {
for (ResistanceUnit unit : ResistanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length()).trim();
return new Resistance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse resistance: " + value);
}
public static Resistance parseResistance(String value) {
for (ResistanceUnit unit : ResistanceUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length()).trim();
return new Resistance(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse resistance: " + value);
}
}
@@ -2,23 +2,23 @@ package org.diylc.core.measures;
public enum ResistanceUnit implements Unit {
R(1, "\u2126"), K(1e3, "K"), M(1e6, "M");
R(1, "\u2126"), K(1e3, "K"), M(1e6, "M");
double factor;
String display;
double factor;
String display;
private ResistanceUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
private ResistanceUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
@Override
public double getFactor() {
return factor;
}
@Override
public double getFactor() {
return factor;
}
@Override
public String toString() {
return display;
}
@Override
public String toString() {
return display;
}
}
@@ -4,44 +4,44 @@ import org.diylc.utils.Constants;
public class Size extends AbstractMeasure<SizeUnit> implements Comparable<Size> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
// public Size() {
// super();
// // TODO Auto-generated constructor stub
// }
// public Size() {
// super();
// // TODO Auto-generated constructor stub
// }
public Size(Double value, SizeUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
public Size(Double value, SizeUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
public double convertToPixels() {
// double factor = getUnit().getFactor() / SizeUnit.in.getFactor();
// int grids = (int) (factor * getValue() * Constants.GRIDS_PER_INCH);
// double remainder = (factor * getValue() * Constants.GRIDS_PER_INCH) - grids;
// return (int) Math.round(Constants.PIXELS_PER_INCH / Constants.GRIDS_PER_INCH
// * (grids + remainder));
return getValue() * getUnit().getFactor() / SizeUnit.in.getFactor() * Constants.PIXELS_PER_INCH;
}
public double convertToPixels() {
// double factor = getUnit().getFactor() / SizeUnit.in.getFactor();
// int grids = (int) (factor * getValue() * Constants.GRIDS_PER_INCH);
// double remainder = (factor * getValue() * Constants.GRIDS_PER_INCH) - grids;
// return (int) Math.round(Constants.PIXELS_PER_INCH / Constants.GRIDS_PER_INCH
// * (grids + remainder));
return getValue() * getUnit().getFactor() / SizeUnit.in.getFactor() * Constants.PIXELS_PER_INCH;
}
@Override
public Size clone() throws CloneNotSupportedException {
return new Size(value, unit);
}
public static Size parseSize(String value) {
for (SizeUnit unit : SizeUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Size(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse size: " + value);
}
@Override
public Size clone() throws CloneNotSupportedException {
return new Size(value, unit);
}
@Override
public int compareTo(Size o) {
return new Double(value * unit.getFactor()).compareTo(o.getValue() * o.getUnit().getFactor());
}
public static Size parseSize(String value) {
for (SizeUnit unit : SizeUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Size(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse size: " + value);
}
@Override
public int compareTo(Size o) {
return new Double(value * unit.getFactor()).compareTo(o.getValue() * o.getUnit().getFactor());
}
}
@@ -2,16 +2,16 @@ package org.diylc.core.measures;
public enum SizeUnit implements Unit {
mm(1d), cm(10d), m(1e4d), in(25.4d), ft(25.4d * 12), yd(9144d);
mm(1d), cm(10d), m(1e4d), in(25.4d), ft(25.4d * 12), yd(9144d);
double factor;
double factor;
private SizeUnit(double factor) {
this.factor = factor;
}
private SizeUnit(double factor) {
this.factor = factor;
}
@Override
public double getFactor() {
return factor;
}
@Override
public double getFactor() {
return factor;
}
}
@@ -2,5 +2,5 @@ package org.diylc.core.measures;
public interface Unit {
double getFactor();
double getFactor();
}
@@ -2,30 +2,30 @@ package org.diylc.core.measures;
public class Voltage extends AbstractMeasure<VoltageUnit> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
// public Voltage() {
// super();
// // TODO Auto-generated constructor stub
// }
// public Voltage() {
// super();
// // TODO Auto-generated constructor stub
// }
public Voltage(Double value, VoltageUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
public Voltage(Double value, VoltageUnit unit) {
super(value, unit);
// TODO Auto-generated constructor stub
}
@Override
public Voltage clone() throws CloneNotSupportedException {
return new Voltage(value, unit);
}
@Override
public Voltage clone() throws CloneNotSupportedException {
return new Voltage(value, unit);
}
public static Voltage parseCapacitance(String value) {
for (VoltageUnit unit : VoltageUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Voltage(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse voltage: " + value);
}
public static Voltage parseCapacitance(String value) {
for (VoltageUnit unit : VoltageUnit.values()) {
if (value.toLowerCase().endsWith(unit.toString().toLowerCase())) {
value = value.substring(0, value.length() - unit.toString().length() - 1).trim();
return new Voltage(Double.parseDouble(value), unit);
}
}
throw new IllegalArgumentException("Could not parse voltage: " + value);
}
}
@@ -2,23 +2,23 @@ package org.diylc.core.measures;
public enum VoltageUnit implements Unit {
MV(1e-3, "mV"), V(1, "V"), KV(1e3, "KV");
MV(1e-3, "mV"), V(1, "V"), KV(1e3, "KV");
double factor;
String display;
double factor;
String display;
private VoltageUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
private VoltageUnit(double factor, String display) {
this.factor = factor;
this.display = display;
}
@Override
public double getFactor() {
return factor;
}
@Override
public double getFactor() {
return factor;
}
@Override
public String toString() {
return display;
}
@Override
public String toString() {
return display;
}
}
@@ -15,47 +15,44 @@ import javax.swing.ImageIcon;
*/
public enum IconLoader {
Delete("delete.png"), Add("add.png"), FolderOut("folder_out.png"), Garbage("garbage.png"), DiskBlue(
"disk_blue.png"), SaveAs("save_as.png"), Exit("exit.png"), DocumentPlainYellow(
"document_plain_yellow.png"), PhotoScenery("photo_scenery.png"), LightBulbOn(
"lightbulb_on.png"), LightBulbOff("lightbulb_off.png"), NotebookAdd("notebook_add.png"), FormGreen(
"form_green.png"), Gears("gears.png"), About("about.png"), WindowColors(
"window_colors.png"), WindowGear("window_gear.png"), NavigateCheck("navigate_check.png"), Undo(
"undo.png"), Error("error.png"), Warning("warning.png"), ZoomSmall("zoom_small.png"), MoveSmall(
"move_small.png"), Print("print.png"), PDF("pdf.png"), Excel("excel.png"), CSV(
"csv.png"), HTML("html.png"), Image("image.png"), Cut("cut.png"), Copy("copy.png"), Paste(
"paste.png"), Selection("selection.png"), BOM("bom.png"), BlackBoard("blackboard.png"), IdCard(
"id_card.png"), IdCardAdd("id_card_add.png"), Chest("chest.png"), Upload("upload.png"), Wrench(
"wrench.png"), Group("group.png"), Ungroup("ungroup.png"), TraceMask("trace_mask.png"), Faq(
"faq.png"), Component("component.png"), Plugin("plugin.png"), Manual("manual.png"), Donate(
"donate.png"), Bug("bug.png"), IconLarge("icon_large.png"), IconMedium(
"icon_medium.png"), IconSmall("icon_small.png"), DocumentEdit("document_edit.png"), EditComponent(
"edit_component.png"), Size("size.png"), Front("front.png"), Back("back.png"), Pens(
"pens.png"), Sort("sort.png"), ElementsSelection("elements_selection.png");
Delete("delete.png"), Add("add.png"), FolderOut("folder_out.png"), Garbage("garbage.png"), DiskBlue("disk_blue.png"), SaveAs(
"save_as.png"), Exit("exit.png"), DocumentPlainYellow("document_plain_yellow.png"), PhotoScenery(
"photo_scenery.png"), LightBulbOn("lightbulb_on.png"), LightBulbOff("lightbulb_off.png"), NotebookAdd(
"notebook_add.png"), FormGreen("form_green.png"), Gears("gears.png"), About("about.png"), WindowColors(
"window_colors.png"), WindowGear("window_gear.png"), NavigateCheck("navigate_check.png"), Undo("undo.png"), Error(
"error.png"), Warning("warning.png"), ZoomSmall("zoom_small.png"), MoveSmall("move_small.png"), Print("print.png"), PDF(
"pdf.png"), Excel("excel.png"), CSV("csv.png"), HTML("html.png"), Image("image.png"), Cut("cut.png"), Copy(
"copy.png"), Paste("paste.png"), Selection("selection.png"), BOM("bom.png"), BlackBoard("blackboard.png"), IdCard(
"id_card.png"), IdCardAdd("id_card_add.png"), Chest("chest.png"), Upload("upload.png"), Wrench("wrench.png"), Group(
"group.png"), Ungroup("ungroup.png"), TraceMask("trace_mask.png"), Faq("faq.png"), Component("component.png"), Plugin(
"plugin.png"), Manual("manual.png"), Donate("donate.png"), Bug("bug.png"), IconLarge("icon_large.png"), IconMedium(
"icon_medium.png"), IconSmall("icon_small.png"), DocumentEdit("document_edit.png"), EditComponent(
"edit_component.png"), Size("size.png"), Front("front.png"), Back("back.png"), Pens("pens.png"), Sort("sort.png"), ElementsSelection(
"elements_selection.png");
protected String name;
protected String name;
private IconLoader(String name) {
this.name = name;
}
private IconLoader(String name) {
this.name = name;
}
public Icon getIcon() {
java.net.URL imgURL = getClass().getResource(name);
if (imgURL != null) {
return new ImageIcon(imgURL, name);
} else {
System.err.println("Couldn't find file: " + name);
return null;
}
}
public Icon getIcon() {
java.net.URL imgURL = getClass().getResource(name);
if (imgURL != null) {
return new ImageIcon(imgURL, name);
} else {
System.err.println("Couldn't find file: " + name);
return null;
}
}
public Image getImage() {
BufferedImage img = null;
try {
img = ImageIO.read(getClass().getResourceAsStream(name));
} catch (IOException e) {
System.err.println("Couldn't find file: " + name);
}
return img;
}
public Image getImage() {
BufferedImage img = null;
try {
img = ImageIO.read(getClass().getResourceAsStream(name));
} catch (IOException e) {
System.err.println("Couldn't find file: " + name);
}
return img;
}
}
@@ -4,182 +4,177 @@ import java.io.Serializable;
public class ProjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String description;
private String owner;
private String category;
private String updated;
private String thumbnailUrl;
private String downloadUrl;
private int id;
private String name;
private String description;
private String owner;
private String category;
private String updated;
private String thumbnailUrl;
private String downloadUrl;
public ProjectEntity() {
super();
}
public ProjectEntity() {
super();
}
public ProjectEntity(int id, String name, String description, String owner,
String category, String updated, String thumbnailUrl,
String downloadUrl) {
super();
this.id = id;
this.name = name;
this.description = description;
this.owner = owner;
this.category = category;
this.updated = updated;
this.thumbnailUrl = thumbnailUrl;
this.downloadUrl = downloadUrl;
}
public ProjectEntity(int id, String name, String description, String owner, String category, String updated,
String thumbnailUrl, String downloadUrl) {
super();
this.id = id;
this.name = name;
this.description = description;
this.owner = owner;
this.category = category;
this.updated = updated;
this.thumbnailUrl = thumbnailUrl;
this.downloadUrl = downloadUrl;
}
public int getId() {
return id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOwner() {
return owner;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getCategory() {
return category;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setCategory(String category) {
this.category = category;
}
public String getUpdated() {
return updated;
}
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getDownloadUrl() {
return downloadUrl;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
// public Action getDownload() {
//
// Action a = new AbstractAction() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// JOptionPane.showMessageDialog(null, name);
// }
// };
// a.putValue(AbstractAction.NAME, "Download");
// return a;
// }
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((category == null) ? 0 : category.hashCode());
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result
+ ((downloadUrl == null) ? 0 : downloadUrl.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((owner == null) ? 0 : owner.hashCode());
result = prime * result
+ ((thumbnailUrl == null) ? 0 : thumbnailUrl.hashCode());
result = prime * result + ((updated == null) ? 0 : updated.hashCode());
return result;
}
// public Action getDownload() {
//
// Action a = new AbstractAction() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// JOptionPane.showMessageDialog(null, name);
// }
// };
// a.putValue(AbstractAction.NAME, "Download");
// return a;
// }
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((category == null) ? 0 : category.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((downloadUrl == null) ? 0 : downloadUrl.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((owner == null) ? 0 : owner.hashCode());
result = prime * result + ((thumbnailUrl == null) ? 0 : thumbnailUrl.hashCode());
result = prime * result + ((updated == null) ? 0 : updated.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProjectEntity other = (ProjectEntity) obj;
if (category == null) {
if (other.category != null)
return false;
} else if (!category.equals(other.category))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (downloadUrl == null) {
if (other.downloadUrl != null)
return false;
} else if (!downloadUrl.equals(other.downloadUrl))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (owner == null) {
if (other.owner != null)
return false;
} else if (!owner.equals(other.owner))
return false;
if (thumbnailUrl == null) {
if (other.thumbnailUrl != null)
return false;
} else if (!thumbnailUrl.equals(other.thumbnailUrl))
return false;
if (updated == null) {
if (other.updated != null)
return false;
} else if (!updated.equals(other.updated))
return false;
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProjectEntity other = (ProjectEntity) obj;
if (category == null) {
if (other.category != null)
return false;
} else if (!category.equals(other.category))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (downloadUrl == null) {
if (other.downloadUrl != null)
return false;
} else if (!downloadUrl.equals(other.downloadUrl))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (owner == null) {
if (other.owner != null)
return false;
} else if (!owner.equals(other.owner))
return false;
if (thumbnailUrl == null) {
if (other.thumbnailUrl != null)
return false;
} else if (!thumbnailUrl.equals(other.thumbnailUrl))
return false;
if (updated == null) {
if (other.updated != null)
return false;
} else if (!updated.equals(other.updated))
return false;
return true;
}
@Override
public String toString() {
return name + " by " + owner + " updated on " + updated;
}
@Override
public String toString() {
return name + " by " + owner + " updated on " + updated;
}
}
@@ -13,150 +13,126 @@ import com.diyfever.httpproxy.ParamName;
*/
public interface ServiceAPI {
public static final String URL_KEY = "serviceUrl";
public static final String URL_KEY = "serviceUrl";
/**
* Creates a user with the specified details.
*
* @param username
* @param password
* @param email
* @param website
* @param bio
* @return "Success" if the operation is successful or error message if it
* failed.
*/
String createUser(@ParamName("username") String username,
@ParamName("password") String password,
@ParamName("email") String email,
@ParamName("website") String website, @ParamName("bio") String bio);
/**
* Creates a user with the specified details.
*
* @param username
* @param password
* @param email
* @param website
* @param bio
* @return "Success" if the operation is successful or error message if it failed.
*/
String createUser(@ParamName("username") String username, @ParamName("password") String password,
@ParamName("email") String email, @ParamName("website") String website, @ParamName("bio") String bio);
/***
* Updates user details using token to authenticate.
*
* @param username
* @param token
* @param machineId
* @param email
* @param website
* @param bio
* @return "Success" if the operation is successful or error message if it
* failed.
*/
String updateUserDetails(@ParamName("username") String username,
@ParamName("token") String token,
@ParamName("machineId") String machineId,
@ParamName("email") String email,
@ParamName("website") String website, @ParamName("bio") String bio);
/***
* Updates user details using token to authenticate.
*
* @param username
* @param token
* @param machineId
* @param email
* @param website
* @param bio
* @return "Success" if the operation is successful or error message if it failed.
*/
String updateUserDetails(@ParamName("username") String username, @ParamName("token") String token,
@ParamName("machineId") String machineId, @ParamName("email") String email, @ParamName("website") String website,
@ParamName("bio") String bio);
/***
* Tries to login with the provided credentials and machineId.
*
* @param username
* @param password
* @param machineId
* @return login token if the login was successful or string literal "Error"
* if it failed.
*/
String login(@ParamName("username") String username,
@ParamName("password") String password,
@ParamName("machineId") String machineId);
/***
* Tries to login with the provided credentials and machineId.
*
* @param username
* @param password
* @param machineId
* @return login token if the login was successful or string literal "Error" if it failed.
*/
String login(@ParamName("username") String username, @ParamName("password") String password,
@ParamName("machineId") String machineId);
/***
* Retrieves current user's details.
*
* @param username
* @param password
* @param machineId
* @return string with an error message if it fails, or an instance of
* {@link UserEntity} if it succeeds.
*/
Object getUserDetails(@ParamName("username") String username,
@ParamName("token") String token,
@ParamName("machineId") String machineId);
/***
* Retrieves current user's details.
*
* @param username
* @param password
* @param machineId
* @return string with an error message if it fails, or an instance of {@link UserEntity} if it
* succeeds.
*/
Object getUserDetails(@ParamName("username") String username, @ParamName("token") String token,
@ParamName("machineId") String machineId);
/***
* Tries to authenticate with the token that was previously created by
* calling login() function.
*
* @param username
* @param password
* @param machineId
* @return "Success" if the login is successful or error message if it
* failed.
*/
String loginWithToken(@ParamName("username") String username,
@ParamName("token") String token,
@ParamName("machineId") String machineId);
/***
* Tries to authenticate with the token that was previously created by calling login() function.
*
* @param username
* @param password
* @param machineId
* @return "Success" if the login is successful or error message if it failed.
*/
String loginWithToken(@ParamName("username") String username, @ParamName("token") String token,
@ParamName("machineId") String machineId);
/***
* Updates password of the current user using token to authenticate.
*
* @param username
* @param token
* @param machineId
* @param password
* @return "Success" if the login is successful or error message if it
* failed.
*/
String updatePassword(@ParamName("username") String username,
@ParamName("oldPassword") String oldPassword,
@ParamName("newPassword") String newPassword);
/***
* Updates password of the current user using token to authenticate.
*
* @param username
* @param token
* @param machineId
* @param password
* @return "Success" if the login is successful or error message if it failed.
*/
String updatePassword(@ParamName("username") String username, @ParamName("oldPassword") String oldPassword,
@ParamName("newPassword") String newPassword);
/***
* Searches for projects that meet the specified search criteria. Supports
* pagination.
*
* @param criteria
* @param category
* @param format
* @param page
* @param itemsPerPage
* @param sort
* @return string with error message if the error occurred or a list of
* {@link ProjectEntity} objects.
*/
Object search(@ParamName("criteria") String criteria,
@ParamName("category") String category,
@ParamName("format") String format,
@ParamName("page") Integer page,
@ParamName("itemsPerPage") Integer itemsPerPage,
@ParamName("sort") String sort);
/***
* Searches for projects that meet the specified search criteria. Supports pagination.
*
* @param criteria
* @param category
* @param format
* @param page
* @param itemsPerPage
* @param sort
* @return string with error message if the error occurred or a list of {@link ProjectEntity}
* objects.
*/
Object search(@ParamName("criteria") String criteria, @ParamName("category") String category,
@ParamName("format") String format, @ParamName("page") Integer page,
@ParamName("itemsPerPage") Integer itemsPerPage, @ParamName("sort") String sort);
/**
* Uploads a project using token to authenticate.
*
* @param username
* @param token
* @param machineId
* @param projectName
* @param category
* @param description
* @param diylcVersion
* @param keywords
* @param thumbnail
* @param project
* @return "Success" if the upload was successful or error message if it
* failed.
*/
String upload(@ParamName("username") String username,
@ParamName("token") String token,
@ParamName("machineId") String machineId,
@ParamName("projectName") String projectName,
@ParamName("category") String category,
@ParamName("description") String description,
@ParamName("diylcVersion") String diylcVersion,
@ParamName("keywords") String keywords,
@ParamName("thumbnail") File thumbnail,
@ParamName("project") File project);
/**
* Uploads a project using token to authenticate.
*
* @param username
* @param token
* @param machineId
* @param projectName
* @param category
* @param description
* @param diylcVersion
* @param keywords
* @param thumbnail
* @param project
* @return "Success" if the upload was successful or error message if it failed.
*/
String upload(@ParamName("username") String username, @ParamName("token") String token,
@ParamName("machineId") String machineId, @ParamName("projectName") String projectName,
@ParamName("category") String category, @ParamName("description") String description,
@ParamName("diylcVersion") String diylcVersion, @ParamName("keywords") String keywords,
@ParamName("thumbnail") File thumbnail, @ParamName("project") File project);
/**
* @return a {@link List} of available categories.
*/
List<String> getCategories();
/**
* @return a {@link List} of available categories.
*/
List<String> getCategories();
/**
* @return a {@link List} of available sortings.
*/
List<String> getSortings();
/**
* @return a {@link List} of available sortings.
*/
List<String> getSortings();
}
@@ -4,100 +4,99 @@ import java.io.Serializable;
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private String username;
private String email;
private String website;
private String bio;
private String username;
private String email;
private String website;
private String bio;
public UserEntity(String userName, String email, String website, String bio) {
super();
this.username = username;
this.email = email;
this.website = website;
this.bio = bio;
}
public UserEntity(String userName, String email, String website, String bio) {
super();
this.username = username;
this.email = email;
this.website = website;
this.bio = bio;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public String getUsername() {
return username;
}
public void setEmail(String email) {
this.email = email;
}
public void setUsername(String username) {
this.username = username;
}
public String getWebsite() {
return website;
}
public String getEmail() {
return email;
}
public void setWebsite(String website) {
this.website = website;
}
public void setEmail(String email) {
this.email = email;
}
public String getBio() {
return bio;
}
public String getWebsite() {
return website;
}
public void setBio(String bio) {
this.bio = bio;
}
public void setWebsite(String website) {
this.website = website;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bio == null) ? 0 : bio.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result
+ ((username == null) ? 0 : username.hashCode());
result = prime * result + ((website == null) ? 0 : website.hashCode());
return result;
}
public String getBio() {
return bio;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserEntity other = (UserEntity) obj;
if (bio == null) {
if (other.bio != null)
return false;
} else if (!bio.equals(other.bio))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
if (website == null) {
if (other.website != null)
return false;
} else if (!website.equals(other.website))
return false;
return true;
}
public void setBio(String bio) {
this.bio = bio;
}
@Override
public String toString() {
return "UserEntity [userName=" + username + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bio == null) ? 0 : bio.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
result = prime * result + ((website == null) ? 0 : website.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserEntity other = (UserEntity) obj;
if (bio == null) {
if (other.bio != null)
return false;
} else if (!bio.equals(other.bio))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
if (website == null) {
if (other.website != null)
return false;
} else if (!website.equals(other.website))
return false;
return true;
}
@Override
public String toString() {
return "UserEntity [userName=" + username + "]";
}
}
@@ -2,14 +2,14 @@ package org.diylc.plugins.cloud.presenter;
public class CloudException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public CloudException(Exception e) {
super(e);
}
public CloudException(Exception e) {
super(e);
}
public CloudException(String string) {
super(string);
}
public CloudException(String string) {
super(string);
}
}
@@ -2,7 +2,7 @@ package org.diylc.plugins.cloud.presenter;
public interface CloudListener {
public void loggedIn();
public void loggedOut();
public void loggedIn();
public void loggedOut();
}
@@ -18,267 +18,241 @@ import com.diyfever.httpproxy.ProxyFactory;
public class CloudPresenter {
private static String USERNAME_KEY = "cloud.Username";
private static String TOKEN_KEY = "cloud.token";
private static String USERNAME_KEY = "cloud.Username";
private static String TOKEN_KEY = "cloud.token";
private static String ERROR = "Error";
private static String ERROR = "Error";
private final static Logger LOG = Logger.getLogger(CloudPresenter.class);
private static final Object SUCCESS = "Success";
private final static Logger LOG = Logger.getLogger(CloudPresenter.class);
private static final Object SUCCESS = "Success";
private ServiceAPI service;
private String serviceUrl;
private String machineId;
private String[] categories;
private ServiceAPI service;
private String serviceUrl;
private String machineId;
private String[] categories;
private CloudListener listener;
private CloudListener listener;
private boolean loggedIn = false;
private boolean loggedIn = false;
public CloudPresenter(CloudListener listener) {
serviceUrl = ConfigurationManager.getInstance().readString(
ServiceAPI.URL_KEY, "http://www.diy-fever.com/diylc/api/v1");
ProxyFactory factory = new ProxyFactory(new PhpFlatProxy());
service = factory.createProxy(ServiceAPI.class, serviceUrl);
if (service == null)
LOG.warn("Service proxy not created!");
this.listener = listener;
}
public CloudPresenter(CloudListener listener) {
serviceUrl =
ConfigurationManager.getInstance().readString(ServiceAPI.URL_KEY, "http://www.diy-fever.com/diylc/api/v1");
ProxyFactory factory = new ProxyFactory(new PhpFlatProxy());
service = factory.createProxy(ServiceAPI.class, serviceUrl);
if (service == null)
LOG.warn("Service proxy not created!");
this.listener = listener;
}
public boolean logIn(String username, String password)
throws CloudException {
if (service == null)
return false;
LOG.info("Trying to login to cloud as " + username);
public boolean logIn(String username, String password) throws CloudException {
if (service == null)
return false;
LOG.info("Trying to login to cloud as " + username);
String res;
try {
res = service.login(username, password, getMachineId());
} catch (Exception e) {
throw new CloudException(e);
}
String res;
try {
res = service.login(username, password, getMachineId());
} catch (Exception e) {
throw new CloudException(e);
}
if (res == null || res.equals(ERROR)) {
LOG.info("Login failed");
return false;
} else {
LOG.info("Login success");
ConfigurationManager.getInstance().writeValue(USERNAME_KEY,
username);
ConfigurationManager.getInstance().writeValue(TOKEN_KEY, res);
listener.loggedIn();
this.loggedIn = true;
return true;
}
}
if (res == null || res.equals(ERROR)) {
LOG.info("Login failed");
return false;
} else {
LOG.info("Login success");
ConfigurationManager.getInstance().writeValue(USERNAME_KEY, username);
ConfigurationManager.getInstance().writeValue(TOKEN_KEY, res);
listener.loggedIn();
this.loggedIn = true;
return true;
}
}
public boolean tryLogInWithToken() throws CloudException {
if (service == null)
return false;
public boolean tryLogInWithToken() throws CloudException {
if (service == null)
return false;
String username = ConfigurationManager.getInstance().readString(
USERNAME_KEY, null);
String token = ConfigurationManager.getInstance().readString(TOKEN_KEY,
null);
String username = ConfigurationManager.getInstance().readString(USERNAME_KEY, null);
String token = ConfigurationManager.getInstance().readString(TOKEN_KEY, null);
if (username != null && token != null) {
LOG.info("Trying to login to cloud using a token as " + username);
String res;
try {
res = service.loginWithToken(username, token, getMachineId());
} catch (Exception e) {
throw new CloudException(e);
}
if (res == null || res.equals(ERROR)) {
LOG.info("Login failed");
return false;
} else {
LOG.info("Login success");
listener.loggedIn();
this.loggedIn = true;
return true;
}
} else
return false;
}
if (username != null && token != null) {
LOG.info("Trying to login to cloud using a token as " + username);
String res;
try {
res = service.loginWithToken(username, token, getMachineId());
} catch (Exception e) {
throw new CloudException(e);
}
if (res == null || res.equals(ERROR)) {
LOG.info("Login failed");
return false;
} else {
LOG.info("Login success");
listener.loggedIn();
this.loggedIn = true;
return true;
}
} else
return false;
}
public void logOut() {
LOG.info("Logged out");
ConfigurationManager.getInstance().writeValue(TOKEN_KEY, null);
this.loggedIn = false;
listener.loggedOut();
}
public void logOut() {
LOG.info("Logged out");
ConfigurationManager.getInstance().writeValue(TOKEN_KEY, null);
this.loggedIn = false;
listener.loggedOut();
}
public boolean isLoggedIn() {
return loggedIn;
}
public boolean isLoggedIn() {
return loggedIn;
}
public String[] getCategories() throws CloudException {
if (categories == null) {
Object res;
try {
res = service.getCategories();
if (res != null && res.equals(ERROR))
throw new CloudException(
"Could not fetch categories from the server.");
if (res instanceof List<?>) {
List<String> cats = (List<String>) res;
cats.add(0, "");
categories = cats.toArray(new String[0]);
} else {
throw new CloudException(
"Unexpected server response received for category list: "
+ res.getClass().getName());
}
} catch (Exception e) {
throw new CloudException(e);
}
}
return categories;
}
public String[] getCategories() throws CloudException {
if (categories == null) {
Object res;
try {
res = service.getCategories();
if (res != null && res.equals(ERROR))
throw new CloudException("Could not fetch categories from the server.");
if (res instanceof List<?>) {
List<String> cats = (List<String>) res;
cats.add(0, "");
categories = cats.toArray(new String[0]);
} else {
throw new CloudException("Unexpected server response received for category list: " + res.getClass().getName());
}
} catch (Exception e) {
throw new CloudException(e);
}
}
return categories;
}
public void upload(String projectName, String category, String description,
String keywords, String diylcVersion, File thumbnail, File project)
throws IOException, CloudException {
String username = ConfigurationManager.getInstance().readString(
USERNAME_KEY, null);
String token = ConfigurationManager.getInstance().readString(TOKEN_KEY,
null);
public void upload(String projectName, String category, String description, String keywords, String diylcVersion,
File thumbnail, File project) throws IOException, CloudException {
String username = ConfigurationManager.getInstance().readString(USERNAME_KEY, null);
String token = ConfigurationManager.getInstance().readString(TOKEN_KEY, null);
if (username == null || token == null)
throw new CloudException("Login failed. Please try to login again.");
if (username == null || token == null)
throw new CloudException("Login failed. Please try to login again.");
try {
String res = service.upload(username, token, getMachineId(),
projectName, category, description, diylcVersion, keywords,
thumbnail, project);
if (!res.equals(SUCCESS))
throw new CloudException(res);
} catch (Exception e) {
throw new CloudException(e);
}
try {
String res =
service.upload(username, token, getMachineId(), projectName, category, description, diylcVersion, keywords,
thumbnail, project);
if (!res.equals(SUCCESS))
throw new CloudException(res);
} catch (Exception e) {
throw new CloudException(e);
}
}
}
public void createUserAccount(String username, String password,
String email, String website, String bio) throws CloudException {
try {
String res = service.createUser(username, password, email, website,
bio);
if (res == null)
throw new CloudException("Could not create user account.");
if (!SUCCESS.equals(res))
throw new CloudException(res);
} catch (Exception e) {
throw new CloudException(e);
}
}
public void createUserAccount(String username, String password, String email, String website, String bio)
throws CloudException {
try {
String res = service.createUser(username, password, email, website, bio);
if (res == null)
throw new CloudException("Could not create user account.");
if (!SUCCESS.equals(res))
throw new CloudException(res);
} catch (Exception e) {
throw new CloudException(e);
}
}
public UserEntity getUserDetails() throws CloudException {
String username = ConfigurationManager.getInstance().readString(
USERNAME_KEY, null);
String token = ConfigurationManager.getInstance().readString(TOKEN_KEY,
null);
public UserEntity getUserDetails() throws CloudException {
String username = ConfigurationManager.getInstance().readString(USERNAME_KEY, null);
String token = ConfigurationManager.getInstance().readString(TOKEN_KEY, null);
Object res;
try {
res = service.getUserDetails(username, token, getMachineId());
} catch (Exception e) {
throw new CloudException(e);
}
if (res instanceof String)
throw new CloudException(res.toString());
if (res instanceof UserEntity)
return (UserEntity) res;
throw new CloudException(
"Unexpected server response received for category list: "
+ res.getClass().getName());
}
Object res;
try {
res = service.getUserDetails(username, token, getMachineId());
} catch (Exception e) {
throw new CloudException(e);
}
if (res instanceof String)
throw new CloudException(res.toString());
if (res instanceof UserEntity)
return (UserEntity) res;
throw new CloudException("Unexpected server response received for category list: " + res.getClass().getName());
}
public void updatePassword(String oldPassword, String newPassword)
throws CloudException {
String username = ConfigurationManager.getInstance().readString(
USERNAME_KEY, null);
public void updatePassword(String oldPassword, String newPassword) throws CloudException {
String username = ConfigurationManager.getInstance().readString(USERNAME_KEY, null);
String res;
try {
res = service.updatePassword(username, oldPassword, newPassword);
} catch (Exception e) {
throw new CloudException(e);
}
if (!res.equals(SUCCESS))
throw new CloudException(res);
}
String res;
try {
res = service.updatePassword(username, oldPassword, newPassword);
} catch (Exception e) {
throw new CloudException(e);
}
if (!res.equals(SUCCESS))
throw new CloudException(res);
}
public void updateUserDetails(String email, String website, String bio)
throws CloudException {
String username = ConfigurationManager.getInstance().readString(
USERNAME_KEY, null);
String token = ConfigurationManager.getInstance().readString(TOKEN_KEY,
null);
public void updateUserDetails(String email, String website, String bio) throws CloudException {
String username = ConfigurationManager.getInstance().readString(USERNAME_KEY, null);
String token = ConfigurationManager.getInstance().readString(TOKEN_KEY, null);
String res;
try {
res = service.updateUserDetails(username, token, getMachineId(),
email, website, bio);
} catch (Exception e) {
throw new CloudException(e);
}
if (!res.equals(SUCCESS))
throw new CloudException(res);
}
String res;
try {
res = service.updateUserDetails(username, token, getMachineId(), email, website, bio);
} catch (Exception e) {
throw new CloudException(e);
}
if (!res.equals(SUCCESS))
throw new CloudException(res);
}
public List<ProjectEntity> search(String criteria, String category,
String sortOrder, int pageNumber, int itemsPerPage)
throws CloudException {
try {
Object res = service.search(criteria, category, "json", pageNumber,
itemsPerPage, sortOrder);
if (res == null)
throw new CloudException("Failed to retreive search results.");
if (res instanceof String)
throw new CloudException(res.toString());
if (res instanceof List<?>)
return (List<ProjectEntity>) res;
throw new CloudException(
"Unexpected server response received for search results: "
+ res.getClass().getName());
} catch (Exception e) {
throw new CloudException(e);
}
}
public String[] getSortings() throws CloudException {
try {
return service.getSortings().toArray(new String[0]);
} catch (Exception e) {
throw new CloudException(e);
}
}
public List<ProjectEntity> search(String criteria, String category, String sortOrder, int pageNumber, int itemsPerPage)
throws CloudException {
try {
Object res = service.search(criteria, category, "json", pageNumber, itemsPerPage, sortOrder);
if (res == null)
throw new CloudException("Failed to retreive search results.");
if (res instanceof String)
throw new CloudException(res.toString());
if (res instanceof List<?>)
return (List<ProjectEntity>) res;
throw new CloudException("Unexpected server response received for search results: " + res.getClass().getName());
} catch (Exception e) {
throw new CloudException(e);
}
}
private String getMachineId() {
if (machineId == null) {
try {
InetAddress ip = InetAddress.getLocalHost();
public String[] getSortings() throws CloudException {
try {
return service.getSortings().toArray(new String[0]);
} catch (Exception e) {
throw new CloudException(e);
}
}
NetworkInterface network = NetworkInterface
.getByInetAddress(ip);
private String getMachineId() {
if (machineId == null) {
try {
InetAddress ip = InetAddress.getLocalHost();
byte[] mac = network.getHardwareAddress();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
StringBuilder sb = new StringBuilder(18);
for (byte b : mac) {
if (sb.length() > 0)
sb.append(':');
sb.append(String.format("%02x", b));
}
byte[] mac = network.getHardwareAddress();
machineId = sb.toString();
} catch (Exception e) {
machineId = "Generic";
}
LOG.info("Local machine id: " + machineId);
}
return machineId;
}
StringBuilder sb = new StringBuilder(18);
for (byte b : mac) {
if (sb.length() > 0)
sb.append(':');
sb.append(String.format("%02x", b));
}
machineId = sb.toString();
} catch (Exception e) {
machineId = "Generic";
}
LOG.info("Local machine id: " + machineId);
}
return machineId;
}
}
@@ -2,6 +2,6 @@ package org.diylc.plugins.cloud.presenter;
public class NotConnectedException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
}
@@ -2,9 +2,9 @@ package org.diylc.plugins.cloud.presenter;
public class NotExistsException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public NotExistsException(String message) {
super(message);
}
public NotExistsException(String message) {
super(message);
}
}
@@ -2,6 +2,6 @@ package org.diylc.plugins.cloud.presenter;
public class NotLoggedInException extends Exception {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
}
@@ -6,20 +6,20 @@ import org.diylc.core.measures.Size;
public class CalcUtils {
/**
* Rounds the number to the closest grid line.
*
* @param x
* @return
*/
public static int roundToGrid(int x, Size gridSpacing) {
double grid = gridSpacing.convertToPixels();
return (int) (Math.round(1f * x / grid) * grid);
}
/**
* Rounds the number to the closest grid line.
*
* @param x
* @return
*/
public static int roundToGrid(int x, Size gridSpacing) {
double grid = gridSpacing.convertToPixels();
return (int) (Math.round(1f * x / grid) * grid);
}
public static void snapPointToGrid(Point point, Size gridSpacing) {
int x = roundToGrid(point.x, gridSpacing);
int y = roundToGrid(point.y, gridSpacing);
point.setLocation(x, y);
}
public static void snapPointToGrid(Point point, Size gridSpacing) {
int x = roundToGrid(point.x, gridSpacing);
int y = roundToGrid(point.y, gridSpacing);
point.setLocation(x, y);
}
}
@@ -8,81 +8,81 @@ import org.diylc.core.IDIYComponent;
public class ComparatorFactory {
private static ComparatorFactory instance;
private static ComparatorFactory instance;
private Comparator<IDIYComponent<?>> componentNameComparator;
private Comparator<ComponentType> componentTypeComparator;
private Comparator<PropertyWrapper> propertyNameComparator;
private Comparator<IDIYComponent<?>> componentZOrderComparator;
private Comparator<IDIYComponent<?>> componentNameComparator;
private Comparator<ComponentType> componentTypeComparator;
private Comparator<PropertyWrapper> propertyNameComparator;
private Comparator<IDIYComponent<?>> componentZOrderComparator;
public static ComparatorFactory getInstance() {
if (instance == null) {
instance = new ComparatorFactory();
}
return instance;
}
public static ComparatorFactory getInstance() {
if (instance == null) {
instance = new ComparatorFactory();
}
return instance;
}
public Comparator<IDIYComponent<?>> getComponentNameComparator() {
if (componentNameComparator == null) {
componentNameComparator = new Comparator<IDIYComponent<?>>() {
public Comparator<IDIYComponent<?>> getComponentNameComparator() {
if (componentNameComparator == null) {
componentNameComparator = new Comparator<IDIYComponent<?>>() {
@Override
public int compare(IDIYComponent<?> o1, IDIYComponent<?> o2) {
String name1 = o1.getName();
String name2 = o2.getName();
if (name1 == null || name2 == null) {
return 0;
}
return name1.compareToIgnoreCase(name2);
}
};
}
return componentNameComparator;
}
@Override
public int compare(IDIYComponent<?> o1, IDIYComponent<?> o2) {
String name1 = o1.getName();
String name2 = o2.getName();
if (name1 == null || name2 == null) {
return 0;
}
return name1.compareToIgnoreCase(name2);
}
};
}
return componentNameComparator;
}
public Comparator<ComponentType> getComponentTypeComparator() {
if (componentTypeComparator == null) {
componentTypeComparator = new Comparator<ComponentType>() {
public Comparator<ComponentType> getComponentTypeComparator() {
if (componentTypeComparator == null) {
componentTypeComparator = new Comparator<ComponentType>() {
@Override
public int compare(ComponentType o1, ComponentType o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
}
return componentTypeComparator;
}
@Override
public int compare(ComponentType o1, ComponentType o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
}
return componentTypeComparator;
}
public Comparator<PropertyWrapper> getPropertyNameComparator() {
if (propertyNameComparator == null) {
propertyNameComparator = new Comparator<PropertyWrapper>() {
public Comparator<PropertyWrapper> getPropertyNameComparator() {
if (propertyNameComparator == null) {
propertyNameComparator = new Comparator<PropertyWrapper>() {
@Override
public int compare(PropertyWrapper o1, PropertyWrapper o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
@Override
public int compare(PropertyWrapper o1, PropertyWrapper o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
}
return propertyNameComparator;
}
};
}
return propertyNameComparator;
}
public Comparator<IDIYComponent<?>> getComponentZOrderComparator() {
if (componentZOrderComparator == null) {
componentZOrderComparator = new Comparator<IDIYComponent<?>>() {
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;
}
@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;
}
}
@@ -31,221 +31,212 @@ import org.diylc.core.annotations.EditableProperty;
*/
public class ComponentProcessor {
private static final Logger LOG = Logger.getLogger(ComponentProcessor.class);
private static final Logger LOG = Logger.getLogger(ComponentProcessor.class);
private static ComponentProcessor instance;
private static ComponentProcessor instance;
private Map<String, List<PropertyWrapper>> propertyCache;
private Map<String, IPropertyValidator> propertyValidatorCache;
private Map<String, ComponentType> componentTypeMap;
private Map<String, List<PropertyWrapper>> propertyCache;
private Map<String, IPropertyValidator> propertyValidatorCache;
private Map<String, ComponentType> componentTypeMap;
public static ComponentProcessor getInstance() {
if (instance == null) {
instance = new ComponentProcessor();
}
return instance;
}
public static ComponentProcessor getInstance() {
if (instance == null) {
instance = new ComponentProcessor();
}
return instance;
}
private ComponentProcessor() {
super();
this.propertyCache = new HashMap<String, List<PropertyWrapper>>();
this.componentTypeMap = new HashMap<String, ComponentType>();
this.propertyValidatorCache = new HashMap<String, IPropertyValidator>();
}
private ComponentProcessor() {
super();
this.propertyCache = new HashMap<String, List<PropertyWrapper>>();
this.componentTypeMap = new HashMap<String, ComponentType>();
this.propertyValidatorCache = new HashMap<String, IPropertyValidator>();
}
public ComponentType extractComponentTypeFrom(Class<? extends IDIYComponent<?>> clazz) {
if (componentTypeMap.containsKey(clazz.getName())) {
return componentTypeMap.get(clazz.getName());
}
String name;
String description;
CreationMethod creationMethod;
String category;
String namePrefix;
String author;
Icon icon;
double zOrder;
boolean flexibleZOrder;
boolean stretchable;
BomPolicy bomPolicy;
boolean autoEdit;
boolean rotatable;
if (clazz.isAnnotationPresent(ComponentDescriptor.class)) {
ComponentDescriptor annotation = clazz.getAnnotation(ComponentDescriptor.class);
name = annotation.name();
description = annotation.description();
creationMethod = annotation.creationMethod();
category = annotation.category();
namePrefix = annotation.instanceNamePrefix();
author = annotation.author();
zOrder = annotation.zOrder();
flexibleZOrder = annotation.flexibleZOrder();
stretchable = annotation.stretchable();
bomPolicy = annotation.bomPolicy();
autoEdit = annotation.autoEdit();
rotatable = annotation.rotatable();
} else {
name = clazz.getSimpleName();
description = "";
creationMethod = CreationMethod.SINGLE_CLICK;
category = "Uncategorized";
namePrefix = "Unknown";
author = "Unknown";
zOrder = IDIYComponent.COMPONENT;
flexibleZOrder = false;
stretchable = true;
bomPolicy = BomPolicy.SHOW_ALL_NAMES;
autoEdit = true;
rotatable = true;
}
icon = null;
// Draw component icon.
try {
IDIYComponent<?> componentInstance = (IDIYComponent<?>) clazz.newInstance();
Image image = new BufferedImage(Presenter.ICON_SIZE, Presenter.ICON_SIZE,
java.awt.image.BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) image.getGraphics();
g2d
.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
// g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
// RenderingHints.VALUE_STROKE_PURE);
componentInstance.drawIcon(g2d, Presenter.ICON_SIZE, Presenter.ICON_SIZE);
icon = new ImageIcon(image);
} catch (Exception e) {
throw new RuntimeException(e);
}
ComponentType componentType = new ComponentType(name, description, creationMethod,
category, namePrefix, author, icon, clazz, zOrder, flexibleZOrder, stretchable,
bomPolicy, autoEdit, rotatable);
componentTypeMap.put(clazz.getName(), componentType);
return componentType;
}
public ComponentType extractComponentTypeFrom(Class<? extends IDIYComponent<?>> clazz) {
if (componentTypeMap.containsKey(clazz.getName())) {
return componentTypeMap.get(clazz.getName());
}
String name;
String description;
CreationMethod creationMethod;
String category;
String namePrefix;
String author;
Icon icon;
double zOrder;
boolean flexibleZOrder;
boolean stretchable;
BomPolicy bomPolicy;
boolean autoEdit;
boolean rotatable;
if (clazz.isAnnotationPresent(ComponentDescriptor.class)) {
ComponentDescriptor annotation = clazz.getAnnotation(ComponentDescriptor.class);
name = annotation.name();
description = annotation.description();
creationMethod = annotation.creationMethod();
category = annotation.category();
namePrefix = annotation.instanceNamePrefix();
author = annotation.author();
zOrder = annotation.zOrder();
flexibleZOrder = annotation.flexibleZOrder();
stretchable = annotation.stretchable();
bomPolicy = annotation.bomPolicy();
autoEdit = annotation.autoEdit();
rotatable = annotation.rotatable();
} else {
name = clazz.getSimpleName();
description = "";
creationMethod = CreationMethod.SINGLE_CLICK;
category = "Uncategorized";
namePrefix = "Unknown";
author = "Unknown";
zOrder = IDIYComponent.COMPONENT;
flexibleZOrder = false;
stretchable = true;
bomPolicy = BomPolicy.SHOW_ALL_NAMES;
autoEdit = true;
rotatable = true;
}
icon = null;
// Draw component icon.
try {
IDIYComponent<?> componentInstance = (IDIYComponent<?>) clazz.newInstance();
Image image =
new BufferedImage(Presenter.ICON_SIZE, Presenter.ICON_SIZE, java.awt.image.BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) image.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
// g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
// RenderingHints.VALUE_STROKE_PURE);
componentInstance.drawIcon(g2d, Presenter.ICON_SIZE, Presenter.ICON_SIZE);
icon = new ImageIcon(image);
} catch (Exception e) {
throw new RuntimeException(e);
}
ComponentType componentType =
new ComponentType(name, description, creationMethod, category, namePrefix, author, icon, clazz, zOrder,
flexibleZOrder, stretchable, bomPolicy, autoEdit, rotatable);
componentTypeMap.put(clazz.getName(), componentType);
return componentType;
}
/**
* Extracts all editable properties from the component class.
*
* @param clazz
* @return
*/
public List<PropertyWrapper> extractProperties(Class<?> clazz) {
if (propertyCache.containsKey(clazz.getName())) {
return cloneProperties(propertyCache.get(clazz.getName()));
}
List<PropertyWrapper> properties = new ArrayList<PropertyWrapper>();
for (Method method : clazz.getMethods()) {
if (method.getName().startsWith("get")) {
try {
if (method.isAnnotationPresent(EditableProperty.class)
&& !method.isAnnotationPresent(Deprecated.class)) {
EditableProperty annotation = method.getAnnotation(EditableProperty.class);
String name;
if (annotation.name().equals("")) {
name = method.getName().substring(3);
} else {
name = annotation.name();
}
IPropertyValidator validator = getPropertyValidator(annotation
.validatorClass());
Method setter = clazz.getMethod("set" + method.getName().substring(3),
method.getReturnType());
PropertyWrapper property = new PropertyWrapper(name,
method.getReturnType(), method.getName(), setter.getName(),
annotation.defaultable(), validator);
properties.add(property);
}
} catch (NoSuchMethodException e) {
LOG.debug("No matching setter found for \"" + method.getName()
+ "\". Skipping...");
}
}
}
/**
* Extracts all editable properties from the component class.
*
* @param clazz
* @return
*/
public List<PropertyWrapper> extractProperties(Class<?> clazz) {
if (propertyCache.containsKey(clazz.getName())) {
return cloneProperties(propertyCache.get(clazz.getName()));
}
List<PropertyWrapper> properties = new ArrayList<PropertyWrapper>();
for (Method method : clazz.getMethods()) {
if (method.getName().startsWith("get")) {
try {
if (method.isAnnotationPresent(EditableProperty.class) && !method.isAnnotationPresent(Deprecated.class)) {
EditableProperty annotation = method.getAnnotation(EditableProperty.class);
String name;
if (annotation.name().equals("")) {
name = method.getName().substring(3);
} else {
name = annotation.name();
}
IPropertyValidator validator = getPropertyValidator(annotation.validatorClass());
Method setter = clazz.getMethod("set" + method.getName().substring(3), method.getReturnType());
PropertyWrapper property =
new PropertyWrapper(name, method.getReturnType(), method.getName(), setter.getName(),
annotation.defaultable(), validator);
properties.add(property);
}
} catch (NoSuchMethodException e) {
LOG.debug("No matching setter found for \"" + method.getName() + "\". Skipping...");
}
}
}
propertyCache.put(clazz.getName(), properties);
return cloneProperties(properties);
}
propertyCache.put(clazz.getName(), properties);
return cloneProperties(properties);
}
private List<PropertyWrapper> cloneProperties(List<PropertyWrapper> properties) {
List<PropertyWrapper> result = new ArrayList<PropertyWrapper>(properties.size());
for (PropertyWrapper propertyWrapper : properties) {
try {
result.add((PropertyWrapper) propertyWrapper.clone());
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
return result;
}
private List<PropertyWrapper> cloneProperties(List<PropertyWrapper> properties) {
List<PropertyWrapper> result = new ArrayList<PropertyWrapper>(properties.size());
for (PropertyWrapper propertyWrapper : properties) {
try {
result.add((PropertyWrapper) propertyWrapper.clone());
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
return result;
}
/**
* Returns properties that have the same value for all the selected
* components.
*
* @param selectedComponents
* @return
*/
public List<PropertyWrapper> getMutualSelectionProperties(
List<IDIYComponent<?>> selectedComponents) throws Exception {
if (selectedComponents.isEmpty()) {
return null;
}
List<PropertyWrapper> properties = new ArrayList<PropertyWrapper>();
IDIYComponent<?> firstComponent = selectedComponents.get(0);
properties.addAll(extractProperties(firstComponent.getClass()));
// Initialize values
for (PropertyWrapper property : properties) {
property.readFrom(firstComponent);
}
for (int i = 1; i < selectedComponents.size(); i++) {
IDIYComponent<?> component = selectedComponents.get(i);
List<PropertyWrapper> newProperties = extractProperties(component.getClass());
for (PropertyWrapper property : newProperties) {
property.readFrom(component);
}
properties.retainAll(newProperties);
// Try to find matching properties in old and new lists and see if
// their values match.
for (PropertyWrapper oldProperty : properties) {
if (newProperties.contains(oldProperty)) {
PropertyWrapper newProperty = newProperties.get(newProperties
.indexOf(oldProperty));
if (newProperty.getValue() != null && newProperty.getValue() != null) {
if (!newProperty.getValue().equals(oldProperty.getValue()))
// Values don't match, so the property is not unique
// valued.
oldProperty.setUnique(false);
} else if ((newProperty.getValue() == null && oldProperty.getValue() != null)
|| (newProperty.getValue() != null && oldProperty.getValue() == null)) {
oldProperty.setUnique(false);
}
}
}
// for (PropertyWrapper property : properties) {
// try {
// property.readUniqueFrom(component);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
Collections.sort(properties, ComparatorFactory.getInstance().getPropertyNameComparator());
return properties;
}
/**
* Returns properties that have the same value for all the selected components.
*
* @param selectedComponents
* @return
*/
public List<PropertyWrapper> getMutualSelectionProperties(List<IDIYComponent<?>> selectedComponents) throws Exception {
if (selectedComponents.isEmpty()) {
return null;
}
List<PropertyWrapper> properties = new ArrayList<PropertyWrapper>();
IDIYComponent<?> firstComponent = selectedComponents.get(0);
properties.addAll(extractProperties(firstComponent.getClass()));
// Initialize values
for (PropertyWrapper property : properties) {
property.readFrom(firstComponent);
}
for (int i = 1; i < selectedComponents.size(); i++) {
IDIYComponent<?> component = selectedComponents.get(i);
List<PropertyWrapper> newProperties = extractProperties(component.getClass());
for (PropertyWrapper property : newProperties) {
property.readFrom(component);
}
properties.retainAll(newProperties);
// Try to find matching properties in old and new lists and see if
// their values match.
for (PropertyWrapper oldProperty : properties) {
if (newProperties.contains(oldProperty)) {
PropertyWrapper newProperty = newProperties.get(newProperties.indexOf(oldProperty));
if (newProperty.getValue() != null && newProperty.getValue() != null) {
if (!newProperty.getValue().equals(oldProperty.getValue()))
// Values don't match, so the property is not unique
// valued.
oldProperty.setUnique(false);
} else if ((newProperty.getValue() == null && oldProperty.getValue() != null)
|| (newProperty.getValue() != null && oldProperty.getValue() == null)) {
oldProperty.setUnique(false);
}
}
}
// for (PropertyWrapper property : properties) {
// try {
// property.readUniqueFrom(component);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
Collections.sort(properties, ComparatorFactory.getInstance().getPropertyNameComparator());
return properties;
}
private IPropertyValidator getPropertyValidator(Class<? extends IPropertyValidator> clazz) {
if (propertyValidatorCache.containsKey(clazz.getName())) {
return propertyValidatorCache.get(clazz.getName());
}
IPropertyValidator validator;
try {
validator = clazz.newInstance();
} catch (Exception e) {
LOG.error("Could not instantiate validator for " + clazz.getName(), e);
return null;
}
propertyValidatorCache.put(clazz.getName(), validator);
return validator;
}
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;
}
}
@@ -33,393 +33,348 @@ import org.diylc.core.VisibilityPolicy;
import org.diylc.utils.Constants;
/**
* Utility that deals with painting {@link Project} on the {@link Graphics2D}
* and keeps areas taken by each drawn component.
* Utility that deals with painting {@link Project} on the {@link Graphics2D} and keeps areas taken
* by each drawn component.
*
* @author Branislav Stojkovic
*/
public class DrawingManager {
private static final Logger LOG = Logger.getLogger(DrawingManager.class);
private static final Logger LOG = Logger.getLogger(DrawingManager.class);
public static int CONTROL_POINT_SIZE = 7;
public static int CONTROL_POINT_SIZE = 7;
public static final String ZOOM_KEY = "zoom";
public static final String ZOOM_KEY = "zoom";
public static String DEBUG_COMPONENT_AREAS = "org.diylc.debugComponentAreas";
public static String DEBUG_COMPONENT_AREAS = "org.diylc.debugComponentAreas";
public static Color CONTROL_POINT_COLOR = Color.blue;
public static Color SELECTED_CONTROL_POINT_COLOR = Color.green;
public static Color CONTROL_POINT_COLOR = Color.blue;
public static Color SELECTED_CONTROL_POINT_COLOR = Color.green;
private Theme theme = (Theme) ConfigurationManager.getInstance()
.readObject(IPlugInPort.THEME_KEY, Constants.DEFAULT_THEME);
private Theme theme = (Theme) ConfigurationManager.getInstance().readObject(IPlugInPort.THEME_KEY,
Constants.DEFAULT_THEME);
// Keeps Area object of each drawn component.
private Map<IDIYComponent<?>, Area> componentAreaMap;
// Maps components to the last state they are drawn in. Also, used to
// determine which components are invalidated when they are not in the map.
private Map<IDIYComponent<?>, ComponentState> lastDrawnStateMap;
// Keeps Area object of each drawn component.
private Map<IDIYComponent<?>, Area> componentAreaMap;
// Maps components to the last state they are drawn in. Also, used to
// determine which components are invalidated when they are not in the map.
private Map<IDIYComponent<?>, ComponentState> lastDrawnStateMap;
private Composite slotComposite = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.3f);
private Composite lockedComposite = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.3f);
private List<IDIYComponent<?>> failedComponents = new ArrayList<IDIYComponent<?>>();
private Composite slotComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
private Composite lockedComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
private List<IDIYComponent<?>> failedComponents = new ArrayList<IDIYComponent<?>>();
private double zoomLevel = 1d;// ConfigurationManager.getInstance().readDouble(ZOOM_KEY,
// 1d);
private double zoomLevel = 1d;// ConfigurationManager.getInstance().readDouble(ZOOM_KEY,
// 1d);
private MessageDispatcher<EventType> messageDispatcher;
private MessageDispatcher<EventType> messageDispatcher;
private boolean debugComponentAreas;
private boolean debugComponentAreas;
public DrawingManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.messageDispatcher = messageDispatcher;
componentAreaMap = new HashMap<IDIYComponent<?>, Area>();
lastDrawnStateMap = new HashMap<IDIYComponent<?>, ComponentState>();
String debugComponentAreasStr = System
.getProperty(DEBUG_COMPONENT_AREAS);
debugComponentAreas = debugComponentAreasStr != null
&& debugComponentAreasStr.equalsIgnoreCase("true");
}
public DrawingManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.messageDispatcher = messageDispatcher;
componentAreaMap = new HashMap<IDIYComponent<?>, Area>();
lastDrawnStateMap = new HashMap<IDIYComponent<?>, ComponentState>();
String debugComponentAreasStr = System.getProperty(DEBUG_COMPONENT_AREAS);
debugComponentAreas = debugComponentAreasStr != null && debugComponentAreasStr.equalsIgnoreCase("true");
}
/**
* Paints the project onto the canvas and returns the list of components
* that failed to draw.
*
* @param g2d
* @param project
* @param drawOptions
* @param filter
* @param selectionRect
* @param selectedComponents
* @param lockedComponents
* @param groupedComponents
* @param controlPointSlot
* @param componentSlot
* @param dragInProgress
* @return
*/
public List<IDIYComponent<?>> drawProject(Graphics2D g2d, Project project,
Set<DrawOption> drawOptions, IComponentFiler filter,
Rectangle selectionRect, List<IDIYComponent<?>> selectedComponents,
Set<IDIYComponent<?>> lockedComponents,
Set<IDIYComponent<?>> groupedComponents,
List<Point> controlPointSlot, List<IDIYComponent<?>> componentSlot,
boolean dragInProgress) {
failedComponents.clear();
if (project == null) {
return failedComponents;
}
G2DWrapper g2dWrapper = new G2DWrapper(g2d);
/**
* 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,
List<IDIYComponent<?>> componentSlot, boolean dragInProgress) {
failedComponents.clear();
if (project == null) {
return failedComponents;
}
G2DWrapper g2dWrapper = new G2DWrapper(g2d);
if (drawOptions.contains(DrawOption.ANTIALIASING)) {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} else {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
if (ConfigurationManager.getInstance().readBoolean(
IPlugInPort.HI_QUALITY_RENDER_KEY, false)) {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
// RenderingHints.VALUE_STROKE_PURE);
} else {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_DISABLE);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
if (drawOptions.contains(DrawOption.ANTIALIASING)) {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
} else {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
if (ConfigurationManager.getInstance().readBoolean(IPlugInPort.HI_QUALITY_RENDER_KEY, false)) {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
// RenderingHints.VALUE_STROKE_PURE);
} else {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
double zoom = 1d;
if (drawOptions.contains(DrawOption.ZOOM)) {
zoom = zoomLevel;
} else {
zoom = 1 / Constants.PIXEL_SIZE;
}
double zoom = 1d;
if (drawOptions.contains(DrawOption.ZOOM)) {
zoom = zoomLevel;
} else {
zoom = 1 / Constants.PIXEL_SIZE;
}
// AffineTransform initialTx = g2d.getTransform();
Dimension d = getCanvasDimensions(project, zoom, true);
// AffineTransform initialTx = g2d.getTransform();
Dimension d = getCanvasDimensions(project, zoom, true);
g2dWrapper.setColor(theme.getBgColor());
g2dWrapper.fillRect(0, 0, d.width, d.height);
g2d.clip(new Rectangle(new Point(0, 0), d));
g2dWrapper.setColor(theme.getBgColor());
g2dWrapper.fillRect(0, 0, d.width, d.height);
g2d.clip(new Rectangle(new Point(0, 0), d));
GridType gridType = GridType.LINES;
if (drawOptions.contains(DrawOption.GRID) && gridType != GridType.NONE) {
double zoomStep = project.getGridSpacing().convertToPixels() * zoom;
if (gridType == GridType.CROSSHAIR) {
g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10f, new float[] {
(float) zoomStep / 2, (float) zoomStep / 2 },
(float) zoomStep / 4));
} else if (gridType == GridType.DOT) {
g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10f, new float[] { 1f,
(float) zoomStep - 1 }, 0f));
}
GridType gridType = GridType.LINES;
if (drawOptions.contains(DrawOption.GRID) && gridType != GridType.NONE) {
double zoomStep = project.getGridSpacing().convertToPixels() * zoom;
if (gridType == GridType.CROSSHAIR) {
g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {
(float) zoomStep / 2, (float) zoomStep / 2}, (float) zoomStep / 4));
} else if (gridType == GridType.DOT) {
g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {1f,
(float) zoomStep - 1}, 0f));
}
g2dWrapper.setColor(theme.getGridColor());
for (double i = zoomStep; i < d.width; i += zoomStep) {
g2dWrapper.drawLine((int) i, 0, (int) i, d.height - 1);
}
for (double j = zoomStep; j < d.height; j += zoomStep) {
g2dWrapper.drawLine(0, (int) j, d.width - 1, (int) j);
}
}
g2dWrapper.setColor(theme.getGridColor());
for (double i = zoomStep; i < d.width; i += zoomStep) {
g2dWrapper.drawLine((int) i, 0, (int) i, d.height - 1);
}
for (double j = zoomStep; j < d.height; j += zoomStep) {
g2dWrapper.drawLine(0, (int) j, d.width - 1, (int) j);
}
}
if (Math.abs(1.0 - zoom) > 1e-4) {
g2dWrapper.scale(zoom, zoom);
}
if (Math.abs(1.0 - zoom) > 1e-4) {
g2dWrapper.scale(zoom, zoom);
}
// Composite mainComposite = g2d.getComposite();
// Composite alphaComposite =
// AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
// Composite mainComposite = g2d.getComposite();
// Composite alphaComposite =
// AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
// g2dWrapper.resetTx();
// g2dWrapper.resetTx();
// componentAreaMap.clear();
for (IDIYComponent<?> component : project.getComponents()) {
// Do not draw the component if it's filtered out.
if (filter != null && !filter.testComponent(component)) {
continue;
}
ComponentState state = ComponentState.NORMAL;
if (drawOptions.contains(DrawOption.SELECTION)
&& selectedComponents.contains(component)) {
if (dragInProgress) {
state = ComponentState.DRAGGING;
} else {
state = ComponentState.SELECTED;
}
}
// Do not track the area if component is not invalidated and was
// drawn in the same state.
boolean trackArea = lastDrawnStateMap.get(component) != state;
// componentAreaMap.clear();
for (IDIYComponent<?> component : project.getComponents()) {
// Do not draw the component if it's filtered out.
if (filter != null && !filter.testComponent(component)) {
continue;
}
ComponentState state = ComponentState.NORMAL;
if (drawOptions.contains(DrawOption.SELECTION) && selectedComponents.contains(component)) {
if (dragInProgress) {
state = ComponentState.DRAGGING;
} else {
state = ComponentState.SELECTED;
}
}
// Do not track the area if component is not invalidated and was
// drawn in the same state.
boolean trackArea = lastDrawnStateMap.get(component) != state;
synchronized (g2d) {
g2dWrapper.startedDrawingComponent();
if (!trackArea) {
g2dWrapper.stopTracking();
}
// Draw locked components in a new composite.
if (lockedComponents.contains(component)) {
g2d.setComposite(lockedComposite);
}
// Draw the component through the g2dWrapper.
try {
component.draw(g2dWrapper, state, drawOptions
.contains(DrawOption.OUTLINE_MODE), project,
g2dWrapper);
} catch (Exception e) {
LOG.error("Error drawing " + component.getName(), e);
failedComponents.add(component);
}
Area area = g2dWrapper.finishedDrawingComponent();
if (trackArea && area != null && !area.isEmpty()) {
componentAreaMap.put(component, area);
lastDrawnStateMap.put(component, state);
}
}
}
synchronized (g2d) {
g2dWrapper.startedDrawingComponent();
if (!trackArea) {
g2dWrapper.stopTracking();
}
// Draw locked components in a new composite.
if (lockedComponents.contains(component)) {
g2d.setComposite(lockedComposite);
}
// Draw the component through the g2dWrapper.
try {
component.draw(g2dWrapper, state, drawOptions.contains(DrawOption.OUTLINE_MODE), project, g2dWrapper);
} catch (Exception e) {
LOG.error("Error drawing " + component.getName(), e);
failedComponents.add(component);
}
Area area = g2dWrapper.finishedDrawingComponent();
if (trackArea && area != null && !area.isEmpty()) {
componentAreaMap.put(component, area);
lastDrawnStateMap.put(component, state);
}
}
}
// Draw control points.
if (drawOptions.contains(DrawOption.CONTROL_POINTS)) {
// Draw unselected points first to make sure they are below.
if (dragInProgress || drawOptions.contains(DrawOption.OUTLINE_MODE)) {
for (IDIYComponent<?> component : project.getComponents()) {
for (int i = 0; i < component.getControlPointCount(); i++) {
VisibilityPolicy visibilityPolicy = component
.getControlPointVisibilityPolicy(i);
if ((groupedComponents.contains(component)
&& (visibilityPolicy == VisibilityPolicy.ALWAYS || (selectedComponents
.contains(component) && visibilityPolicy == VisibilityPolicy.WHEN_SELECTED)) || (!groupedComponents
.contains(component)
&& !selectedComponents.contains(component) && component
.getControlPointVisibilityPolicy(i) == VisibilityPolicy.ALWAYS))) {
g2dWrapper.setColor(CONTROL_POINT_COLOR);
Point controlPoint = component.getControlPoint(i);
int pointSize = CONTROL_POINT_SIZE - 2;
g2dWrapper.fillOval(controlPoint.x - pointSize / 2,
controlPoint.y - pointSize / 2, pointSize,
pointSize);
}
}
}
}
// Then draw the selected ones.
for (IDIYComponent<?> component : selectedComponents) {
for (int i = 0; i < component.getControlPointCount(); i++) {
if (!groupedComponents.contains(component)
&& (component.getControlPointVisibilityPolicy(i) == VisibilityPolicy.WHEN_SELECTED || component
.getControlPointVisibilityPolicy(i) == VisibilityPolicy.ALWAYS)) {
// Draw control points.
if (drawOptions.contains(DrawOption.CONTROL_POINTS)) {
// Draw unselected points first to make sure they are below.
if (dragInProgress || drawOptions.contains(DrawOption.OUTLINE_MODE)) {
for (IDIYComponent<?> component : project.getComponents()) {
for (int i = 0; i < component.getControlPointCount(); i++) {
VisibilityPolicy visibilityPolicy = component.getControlPointVisibilityPolicy(i);
if ((groupedComponents.contains(component)
&& (visibilityPolicy == VisibilityPolicy.ALWAYS || (selectedComponents.contains(component) && visibilityPolicy == VisibilityPolicy.WHEN_SELECTED)) || (!groupedComponents
.contains(component) && !selectedComponents.contains(component) && component
.getControlPointVisibilityPolicy(i) == VisibilityPolicy.ALWAYS))) {
g2dWrapper.setColor(CONTROL_POINT_COLOR);
Point controlPoint = component.getControlPoint(i);
int pointSize = CONTROL_POINT_SIZE - 2;
g2dWrapper.fillOval(controlPoint.x - pointSize / 2, controlPoint.y - pointSize / 2, pointSize, pointSize);
}
}
}
}
// Then draw the selected ones.
for (IDIYComponent<?> component : selectedComponents) {
for (int i = 0; i < component.getControlPointCount(); i++) {
if (!groupedComponents.contains(component)
&& (component.getControlPointVisibilityPolicy(i) == VisibilityPolicy.WHEN_SELECTED || component
.getControlPointVisibilityPolicy(i) == VisibilityPolicy.ALWAYS)) {
Point controlPoint = component.getControlPoint(i);
int pointSize = CONTROL_POINT_SIZE;
Point controlPoint = component.getControlPoint(i);
int pointSize = CONTROL_POINT_SIZE;
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR
.darker());
g2dWrapper.fillOval(controlPoint.x - pointSize / 2,
controlPoint.y - pointSize / 2, pointSize,
pointSize);
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR);
g2dWrapper.fillOval(controlPoint.x - CONTROL_POINT_SIZE
/ 2 + 1, controlPoint.y - CONTROL_POINT_SIZE
/ 2 + 1, CONTROL_POINT_SIZE - 2,
CONTROL_POINT_SIZE - 2);
}
}
}
}
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR.darker());
g2dWrapper.fillOval(controlPoint.x - pointSize / 2, controlPoint.y - pointSize / 2, pointSize, pointSize);
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR);
g2dWrapper.fillOval(controlPoint.x - CONTROL_POINT_SIZE / 2 + 1, controlPoint.y - CONTROL_POINT_SIZE / 2
+ 1, CONTROL_POINT_SIZE - 2, CONTROL_POINT_SIZE - 2);
}
}
}
}
// Draw component slot in a separate composite.
if (componentSlot != null) {
g2dWrapper.startedDrawingComponent();
g2dWrapper.setComposite(slotComposite);
for (IDIYComponent<?> component : componentSlot) {
try {
// Draw component slot in a separate composite.
if (componentSlot != null) {
g2dWrapper.startedDrawingComponent();
g2dWrapper.setComposite(slotComposite);
for (IDIYComponent<?> component : componentSlot) {
try {
component.draw(g2dWrapper, ComponentState.NORMAL,
drawOptions.contains(DrawOption.OUTLINE_MODE),
project, g2dWrapper);
component.draw(g2dWrapper, ComponentState.NORMAL, drawOptions.contains(DrawOption.OUTLINE_MODE), project,
g2dWrapper);
} catch (Exception e) {
LOG.error("Error drawing " + component.getName(), e);
failedComponents.add(component);
}
}
g2dWrapper.finishedDrawingComponent();
}
} catch (Exception e) {
LOG.error("Error drawing " + component.getName(), e);
failedComponents.add(component);
}
}
g2dWrapper.finishedDrawingComponent();
}
// Draw control points of the component in the slot.
if (controlPointSlot != null) {
for (Point point : controlPointSlot) {
if (point != null) {
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR.darker());
g2dWrapper.fillOval(point.x - CONTROL_POINT_SIZE / 2,
point.y - CONTROL_POINT_SIZE / 2,
CONTROL_POINT_SIZE, CONTROL_POINT_SIZE);
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR);
g2dWrapper.fillOval(point.x - CONTROL_POINT_SIZE / 2 + 1,
point.y - CONTROL_POINT_SIZE / 2 + 1,
CONTROL_POINT_SIZE - 2, CONTROL_POINT_SIZE - 2);
}
}
}
// Draw control points of the component in the slot.
if (controlPointSlot != null) {
for (Point point : controlPointSlot) {
if (point != null) {
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR.darker());
g2dWrapper.fillOval(point.x - CONTROL_POINT_SIZE / 2, point.y - CONTROL_POINT_SIZE / 2, CONTROL_POINT_SIZE,
CONTROL_POINT_SIZE);
g2dWrapper.setColor(SELECTED_CONTROL_POINT_COLOR);
g2dWrapper.fillOval(point.x - CONTROL_POINT_SIZE / 2 + 1, point.y - CONTROL_POINT_SIZE / 2 + 1,
CONTROL_POINT_SIZE - 2, CONTROL_POINT_SIZE - 2);
}
}
}
// Go back to the original transformation and zoom in to draw the
// selection rectangle and other similar elements.
// g2d.setTransform(initialTx);
// if ((drawOptions.contains(DrawOption.ZOOM)) && (Math.abs(1.0 -
// zoomLevel) > 1e-4)) {
// g2d.scale(zoomLevel, zoomLevel);
// }
// Go back to the original transformation and zoom in to draw the
// selection rectangle and other similar elements.
// g2d.setTransform(initialTx);
// if ((drawOptions.contains(DrawOption.ZOOM)) && (Math.abs(1.0 -
// zoomLevel) > 1e-4)) {
// g2d.scale(zoomLevel, zoomLevel);
// }
// At the end draw selection rectangle if needed.
if (drawOptions.contains(DrawOption.SELECTION)
&& (selectionRect != null)) {
g2d.setColor(Color.white);
g2d.draw(selectionRect);
g2d.setColor(Color.black);
g2d.setStroke(Constants.DASHED_STROKE);
g2d.draw(selectionRect);
}
// At the end draw selection rectangle if needed.
if (drawOptions.contains(DrawOption.SELECTION) && (selectionRect != null)) {
g2d.setColor(Color.white);
g2d.draw(selectionRect);
g2d.setColor(Color.black);
g2d.setStroke(Constants.DASHED_STROKE);
g2d.draw(selectionRect);
}
// Draw component area for test
if (debugComponentAreas) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
g2d.setColor(Color.red);
for (Area area : componentAreaMap.values()) {
g2d.draw(area);
}
}
// Draw component area for test
if (debugComponentAreas) {
g2d.setStroke(ObjectCache.getInstance().fetchBasicStroke(1));
g2d.setColor(Color.red);
for (Area area : componentAreaMap.values()) {
g2d.draw(area);
}
}
return failedComponents;
}
return failedComponents;
}
public double getZoomLevel() {
return zoomLevel;
}
public double getZoomLevel() {
return zoomLevel;
}
public void setZoomLevel(double zoomLevel) {
this.zoomLevel = zoomLevel;
fireZoomChanged();
// ConfigurationManager.getInstance().writeValue(ZOOM_KEY, zoomLevel);
}
public void setZoomLevel(double zoomLevel) {
this.zoomLevel = zoomLevel;
fireZoomChanged();
// ConfigurationManager.getInstance().writeValue(ZOOM_KEY, zoomLevel);
}
public void invalidateComponent(IDIYComponent<?> component) {
componentAreaMap.remove(component);
lastDrawnStateMap.remove(component);
}
public void invalidateComponent(IDIYComponent<?> component) {
componentAreaMap.remove(component);
lastDrawnStateMap.remove(component);
}
public Area getComponentArea(IDIYComponent<?> component) {
return componentAreaMap.get(component);
}
public Area getComponentArea(IDIYComponent<?> component) {
return componentAreaMap.get(component);
}
public void clearComponentAreaMap() {
componentAreaMap.clear();
lastDrawnStateMap.clear();
}
public void clearComponentAreaMap() {
componentAreaMap.clear();
lastDrawnStateMap.clear();
}
public List<IDIYComponent<?>> findComponentsAt(Point point, Project project) {
List<IDIYComponent<?>> components = new ArrayList<IDIYComponent<?>>();
for (int i = 0; i < project.getComponents().size(); i++) {
Area area = componentAreaMap.get(project.getComponents().get(i));
if (area != null && area.contains(point)) {
components.add(0, project.getComponents().get(i));
}
}
return components;
}
public List<IDIYComponent<?>> findComponentsAt(Point point, Project project) {
List<IDIYComponent<?>> components = new ArrayList<IDIYComponent<?>>();
for (int i = 0; i < project.getComponents().size(); i++) {
Area area = componentAreaMap.get(project.getComponents().get(i));
if (area != null && area.contains(point)) {
components.add(0, project.getComponents().get(i));
}
}
return components;
}
public Dimension getCanvasDimensions(Project project, Double zoomLevel,
boolean useZoom) {
double width = project.getWidth().convertToPixels();
double height = project.getHeight().convertToPixels();
if (useZoom) {
width *= zoomLevel;
height *= zoomLevel;
} else {
width /= Constants.PIXEL_SIZE;
height /= Constants.PIXEL_SIZE;
}
return new Dimension((int) width, (int) height);
}
public Dimension getCanvasDimensions(Project project, Double zoomLevel, boolean useZoom) {
double width = project.getWidth().convertToPixels();
double height = project.getHeight().convertToPixels();
if (useZoom) {
width *= zoomLevel;
height *= zoomLevel;
} else {
width /= Constants.PIXEL_SIZE;
height /= Constants.PIXEL_SIZE;
}
return new Dimension((int) width, (int) height);
}
public void fireZoomChanged() {
messageDispatcher.dispatchMessage(EventType.ZOOM_CHANGED, zoomLevel);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
public void fireZoomChanged() {
messageDispatcher.dispatchMessage(EventType.ZOOM_CHANGED, zoomLevel);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
public Theme getTheme() {
return theme;
}
public Theme getTheme() {
return theme;
}
public void setTheme(Theme theme) {
this.theme = theme;
ConfigurationManager.getInstance().writeValue(IPlugInPort.THEME_KEY,
theme);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
public void setTheme(Theme theme) {
this.theme = theme;
ConfigurationManager.getInstance().writeValue(IPlugInPort.THEME_KEY, theme);
messageDispatcher.dispatchMessage(EventType.REPAINT);
}
}
@@ -28,372 +28,340 @@ import org.diylc.core.measures.Size;
*/
public class InstantiationManager {
private static final Logger LOG = Logger
.getLogger(InstantiationManager.class);
private static final Logger LOG = Logger.getLogger(InstantiationManager.class);
public static int MAX_RECENT_COMPONENTS = 16;
public static int MAX_RECENT_COMPONENTS = 16;
private ComponentType componentTypeSlot;
private Template template;
private List<IDIYComponent<?>> componentSlot;
private Point firstControlPoint;
private Point potentialControlPoint;
private ComponentType componentTypeSlot;
private Template template;
private List<IDIYComponent<?>> componentSlot;
private Point firstControlPoint;
private Point potentialControlPoint;
private static final ComponentType clipboardType = new ComponentType(
"Clipboard contents", "Components from the clipboard",
CreationMethod.SINGLE_CLICK, "Multi", "", "", null, null, 0, false,
false, null, false, true);
private static final ComponentType clipboardType = new ComponentType("Clipboard contents",
"Components from the clipboard", CreationMethod.SINGLE_CLICK, "Multi", "", "", null, null, 0, false, false, null,
false, true);
public InstantiationManager() {
}
public InstantiationManager() {}
public ComponentType getComponentTypeSlot() {
return componentTypeSlot;
}
public ComponentType getComponentTypeSlot() {
return componentTypeSlot;
}
public Template getTemplate() {
return template;
}
public Template getTemplate() {
return template;
}
public List<IDIYComponent<?>> getComponentSlot() {
return componentSlot;
}
public List<IDIYComponent<?>> getComponentSlot() {
return componentSlot;
}
public Point getFirstControlPoint() {
return firstControlPoint;
}
public Point getFirstControlPoint() {
return firstControlPoint;
}
public Point getPotentialControlPoint() {
return potentialControlPoint;
}
public Point getPotentialControlPoint() {
return potentialControlPoint;
}
public void setComponentTypeSlot(ComponentType componentTypeSlot,
Template template, Project currentProject) throws Exception {
this.componentTypeSlot = componentTypeSlot;
this.template = template;
if (componentTypeSlot == null) {
this.componentSlot = null;
} else {
switch (componentTypeSlot.getCreationMethod()) {
case POINT_BY_POINT:
this.componentSlot = null;
break;
case SINGLE_CLICK:
this.componentSlot = instantiateComponent(componentTypeSlot,
template, new Point(0, 0), currentProject);
break;
}
}
this.firstControlPoint = null;
this.potentialControlPoint = null;
}
public void setComponentTypeSlot(ComponentType componentTypeSlot, Template template, Project currentProject)
throws Exception {
this.componentTypeSlot = componentTypeSlot;
this.template = template;
if (componentTypeSlot == null) {
this.componentSlot = null;
} else {
switch (componentTypeSlot.getCreationMethod()) {
case POINT_BY_POINT:
this.componentSlot = null;
break;
case SINGLE_CLICK:
this.componentSlot = instantiateComponent(componentTypeSlot, template, new Point(0, 0), currentProject);
break;
}
}
this.firstControlPoint = null;
this.potentialControlPoint = null;
}
public void instatiatePointByPoint(Point scaledPoint, Project currentProject)
throws Exception {
firstControlPoint = scaledPoint;
componentSlot = instantiateComponent(componentTypeSlot, template,
firstControlPoint, currentProject);
public void instatiatePointByPoint(Point scaledPoint, Project currentProject) throws Exception {
firstControlPoint = scaledPoint;
componentSlot = instantiateComponent(componentTypeSlot, template, firstControlPoint, currentProject);
// Set the other control point to the same location, we'll
// move it later when mouse moves.
componentSlot.get(0).setControlPoint(firstControlPoint, 0);
componentSlot.get(0).setControlPoint(firstControlPoint, 1);
}
// Set the other control point to the same location, we'll
// move it later when mouse moves.
componentSlot.get(0).setControlPoint(firstControlPoint, 0);
componentSlot.get(0).setControlPoint(firstControlPoint, 1);
}
/**
* Updates component in the slot with the new second control point.
*
* @param scaledPoint
* @return true, if any change is made
*/
public boolean updatePointByPoint(Point scaledPoint) {
boolean changeMade = !scaledPoint.equals(potentialControlPoint);
potentialControlPoint = scaledPoint;
if (componentSlot != null && !componentSlot.isEmpty()) {
componentSlot.get(0).setControlPoint(scaledPoint, 1);
}
return changeMade;
}
/**
* Updates component in the slot with the new second control point.
*
* @param scaledPoint
* @return true, if any change is made
*/
public boolean updatePointByPoint(Point scaledPoint) {
boolean changeMade = !scaledPoint.equals(potentialControlPoint);
potentialControlPoint = scaledPoint;
if (componentSlot != null && !componentSlot.isEmpty()) {
componentSlot.get(0).setControlPoint(scaledPoint, 1);
}
return changeMade;
}
public void pasteComponents(List<IDIYComponent<?>> components,
Point scaledPoint, boolean snapToGrid, Size gridSpacing) {
// Adjust location of components so they are centered under the mouse
// cursor
int minX = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for (IDIYComponent<?> component : components) {
for (int i = 0; i < component.getControlPointCount(); i++) {
Point p = component.getControlPoint(i);
if (p.x > maxX) {
maxX = p.x;
}
if (p.x < minX) {
minX = p.x;
}
if (p.y > maxY) {
maxY = p.y;
}
if (p.y < minY) {
minY = p.y;
}
}
}
int x = minX;
int y = minY;
if (snapToGrid) {
x = CalcUtils.roundToGrid(x, gridSpacing);
x = CalcUtils.roundToGrid(x, gridSpacing);
}
for (IDIYComponent<?> component : components) {
for (int i = 0; i < component.getControlPointCount(); i++) {
Point p = component.getControlPoint(i);
p.translate(-x, -y);
component.setControlPoint(p, i);
}
}
public void pasteComponents(List<IDIYComponent<?>> components, Point scaledPoint, boolean snapToGrid, Size gridSpacing) {
// Adjust location of components so they are centered under the mouse
// cursor
int minX = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for (IDIYComponent<?> component : components) {
for (int i = 0; i < component.getControlPointCount(); i++) {
Point p = component.getControlPoint(i);
if (p.x > maxX) {
maxX = p.x;
}
if (p.x < minX) {
minX = p.x;
}
if (p.y > maxY) {
maxY = p.y;
}
if (p.y < minY) {
minY = p.y;
}
}
}
int x = minX;
int y = minY;
if (snapToGrid) {
x = CalcUtils.roundToGrid(x, gridSpacing);
x = CalcUtils.roundToGrid(x, gridSpacing);
}
for (IDIYComponent<?> component : components) {
for (int i = 0; i < component.getControlPointCount(); i++) {
Point p = component.getControlPoint(i);
p.translate(-x, -y);
component.setControlPoint(p, i);
}
}
// Update component slot
this.componentSlot = new ArrayList<IDIYComponent<?>>(components);
// Update component slot
this.componentSlot = new ArrayList<IDIYComponent<?>>(components);
// Update the component type slot so the app knows that something's
// being instantiated.
this.componentTypeSlot = clipboardType;
// Update the component type slot so the app knows that something's
// being instantiated.
this.componentTypeSlot = clipboardType;
if (snapToGrid) {
scaledPoint = new Point(scaledPoint);
CalcUtils.snapPointToGrid(scaledPoint, gridSpacing);
}
// Update the location according to mouse location
updateSingleClick(scaledPoint, snapToGrid, gridSpacing);
}
if (snapToGrid) {
scaledPoint = new Point(scaledPoint);
CalcUtils.snapPointToGrid(scaledPoint, gridSpacing);
}
// Update the location according to mouse location
updateSingleClick(scaledPoint, snapToGrid, gridSpacing);
}
/**
* Updates location of component slot based on the new mouse location.
*
* @param scaledPoint
* @param snapToGrid
* @param gridSpacing
* @return true if we need to refresh the canvas
*/
public boolean updateSingleClick(Point scaledPoint, boolean snapToGrid,
Size gridSpacing) {
if (potentialControlPoint == null) {
potentialControlPoint = new Point(0, 0);
}
if (scaledPoint == null) {
scaledPoint = new Point(0, 0);
}
int dx = scaledPoint.x - potentialControlPoint.x;
int dy = scaledPoint.y - potentialControlPoint.y;
if (snapToGrid) {
dx = CalcUtils.roundToGrid(dx, gridSpacing);
dy = CalcUtils.roundToGrid(dy, gridSpacing);
}
// Only repaint if there's an actual change.
if (dx == 0 && dy == 0) {
return false;
}
potentialControlPoint.translate(dx, dy);
if (componentSlot == null) {
LOG.error("Component slot should not be null!");
} else {
Point p = new Point();
for (IDIYComponent<?> component : componentSlot) {
for (int i = 0; i < component.getControlPointCount(); i++) {
p.setLocation(component.getControlPoint(i));
p.translate(dx, dy);
component.setControlPoint(p, i);
}
}
}
return true;
}
/**
* Updates location of component slot based on the new mouse location.
*
* @param scaledPoint
* @param snapToGrid
* @param gridSpacing
* @return true if we need to refresh the canvas
*/
public boolean updateSingleClick(Point scaledPoint, boolean snapToGrid, Size gridSpacing) {
if (potentialControlPoint == null) {
potentialControlPoint = new Point(0, 0);
}
if (scaledPoint == null) {
scaledPoint = new Point(0, 0);
}
int dx = scaledPoint.x - potentialControlPoint.x;
int dy = scaledPoint.y - potentialControlPoint.y;
if (snapToGrid) {
dx = CalcUtils.roundToGrid(dx, gridSpacing);
dy = CalcUtils.roundToGrid(dy, gridSpacing);
}
// Only repaint if there's an actual change.
if (dx == 0 && dy == 0) {
return false;
}
potentialControlPoint.translate(dx, dy);
if (componentSlot == null) {
LOG.error("Component slot should not be null!");
} else {
Point p = new Point();
for (IDIYComponent<?> component : componentSlot) {
for (int i = 0; i < component.getControlPointCount(); i++) {
p.setLocation(component.getControlPoint(i));
p.translate(dx, dy);
component.setControlPoint(p, i);
}
}
}
return true;
}
@SuppressWarnings("unchecked")
public List<IDIYComponent<?>> instantiateComponent(
ComponentType componentType, Template template, Point point,
Project currentProject) throws Exception {
LOG.info("Instatiating component of type: "
+ componentType.getInstanceClass().getName());
@SuppressWarnings("unchecked")
public List<IDIYComponent<?>> instantiateComponent(ComponentType componentType, Template template, Point point,
Project currentProject) throws Exception {
LOG.info("Instatiating component of type: " + componentType.getInstanceClass().getName());
// Instantiate the component.
IDIYComponent<?> component = componentType.getInstanceClass()
.newInstance();
// Instantiate the component.
IDIYComponent<?> component = componentType.getInstanceClass().newInstance();
component.setName(createUniqueName(componentType, currentProject));
component.setName(createUniqueName(componentType, currentProject));
// Translate them to the desired location.
if (point != null) {
for (int j = 0; j < component.getControlPointCount(); j++) {
Point controlPoint = new Point(component.getControlPoint(j));
controlPoint.translate(point.x, point.y);
// snapPointToGrid(controlPoint);
component.setControlPoint(controlPoint, j);
}
}
// Translate them to the desired location.
if (point != null) {
for (int j = 0; j < component.getControlPointCount(); j++) {
Point controlPoint = new Point(component.getControlPoint(j));
controlPoint.translate(point.x, point.y);
// snapPointToGrid(controlPoint);
component.setControlPoint(controlPoint, j);
}
}
loadComponentShapeFromTemplate(component, template);
loadComponentShapeFromTemplate(component, template);
fillWithDefaultProperties(component, template);
fillWithDefaultProperties(component, template);
// Write to recent components
List<String> recentComponentTypes = (List<String>) ConfigurationManager
.getInstance().readObject(IPlugInPort.RECENT_COMPONENTS_KEY,
new ArrayList<ComponentType>());
String className = componentType.getInstanceClass().getName();
if (recentComponentTypes.size() == 0
|| !recentComponentTypes.get(0).equals(className)) {
// Remove if it's already somewhere in the list.
recentComponentTypes.remove(className);
// Add to the end of the list.
recentComponentTypes.add(0, className);
// Trim the list if necessary.
if (recentComponentTypes.size() > MAX_RECENT_COMPONENTS) {
recentComponentTypes.remove(recentComponentTypes.size() - 1);
}
ConfigurationManager.getInstance().writeValue(
IPlugInPort.RECENT_COMPONENTS_KEY, recentComponentTypes);
}
// Write to recent components
List<String> recentComponentTypes =
(List<String>) ConfigurationManager.getInstance().readObject(IPlugInPort.RECENT_COMPONENTS_KEY,
new ArrayList<ComponentType>());
String className = componentType.getInstanceClass().getName();
if (recentComponentTypes.size() == 0 || !recentComponentTypes.get(0).equals(className)) {
// Remove if it's already somewhere in the list.
recentComponentTypes.remove(className);
// Add to the end of the list.
recentComponentTypes.add(0, className);
// Trim the list if necessary.
if (recentComponentTypes.size() > MAX_RECENT_COMPONENTS) {
recentComponentTypes.remove(recentComponentTypes.size() - 1);
}
ConfigurationManager.getInstance().writeValue(IPlugInPort.RECENT_COMPONENTS_KEY, recentComponentTypes);
}
List<IDIYComponent<?>> list = new ArrayList<IDIYComponent<?>>();
list.add(component);
return list;
}
List<IDIYComponent<?>> list = new ArrayList<IDIYComponent<?>>();
list.add(component);
return list;
}
public String createUniqueName(ComponentType componentType,
Project currentProject) {
boolean exists = true;
List<IDIYComponent<?>> components = currentProject.getComponents();
String[] takenNames = new String[components.size()];
for (int j = 0; j < currentProject.getComponents().size(); j++) {
takenNames[j] = components.get(j).getName();
}
Arrays.sort(takenNames);
int i = 0;
while (exists) {
i++;
String name = componentType.getNamePrefix() + i;
exists = false;
if (Arrays.binarySearch(takenNames, name) >= 0) {
exists = true;
}
}
return componentType.getNamePrefix() + i;
}
public String createUniqueName(ComponentType componentType, Project currentProject) {
boolean exists = true;
List<IDIYComponent<?>> components = currentProject.getComponents();
String[] takenNames = new String[components.size()];
for (int j = 0; j < currentProject.getComponents().size(); j++) {
takenNames[j] = components.get(j).getName();
}
Arrays.sort(takenNames);
int i = 0;
while (exists) {
i++;
String name = componentType.getNamePrefix() + i;
exists = false;
if (Arrays.binarySearch(takenNames, name) >= 0) {
exists = true;
}
}
return componentType.getNamePrefix() + i;
}
/**
* Finds any properties that have default values and injects default values.
* Typically it should be used for {@link IDIYComponent} and {@link Project}
* objects.
*
* @param object
* @param template
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws SecurityException
*/
public void fillWithDefaultProperties(Object object, Template template)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException {
// Extract properties.
List<PropertyWrapper> properties = ComponentProcessor.getInstance()
.extractProperties(object.getClass());
Map<String, PropertyWrapper> propertyCache = new HashMap<String, PropertyWrapper>();
// Override with default values if available.
for (PropertyWrapper property : properties) {
propertyCache.put(property.getName(), property);
Object defaultValue = ConfigurationManager.getInstance()
.readObject(
Presenter.DEFAULTS_KEY_PREFIX
+ object.getClass().getName() + ":"
+ property.getName(), null);
if (defaultValue != null) {
property.setValue(defaultValue);
property.writeTo(object);
}
}
if (template != null) {
for (Map.Entry<String, Object> pair : template.getValues()
.entrySet()) {
PropertyWrapper property = propertyCache.get(pair.getKey());
if (property == null) {
LOG.warn("Cannot find property " + pair.getKey());
} else {
LOG.debug("Filling value from template for "
+ pair.getKey());
property.setValue(pair.getValue());
property.writeTo(object);
}
}
}
}
/**
* Finds any properties that have default values and injects default values. Typically it should
* be used for {@link IDIYComponent} and {@link Project} objects.
*
* @param object
* @param template
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws SecurityException
*/
public void fillWithDefaultProperties(Object object, Template template) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
// Extract properties.
List<PropertyWrapper> properties = ComponentProcessor.getInstance().extractProperties(object.getClass());
Map<String, PropertyWrapper> propertyCache = new HashMap<String, PropertyWrapper>();
// Override with default values if available.
for (PropertyWrapper property : properties) {
propertyCache.put(property.getName(), property);
Object defaultValue =
ConfigurationManager.getInstance().readObject(
Presenter.DEFAULTS_KEY_PREFIX + object.getClass().getName() + ":" + property.getName(), null);
if (defaultValue != null) {
property.setValue(defaultValue);
property.writeTo(object);
}
}
if (template != null) {
for (Map.Entry<String, Object> pair : template.getValues().entrySet()) {
PropertyWrapper property = propertyCache.get(pair.getKey());
if (property == null) {
LOG.warn("Cannot find property " + pair.getKey());
} else {
LOG.debug("Filling value from template for " + pair.getKey());
property.setValue(pair.getValue());
property.writeTo(object);
}
}
}
}
/**
* Uses stored control points from the template to shape component.
*
* @param component
* @param template
*/
public void loadComponentShapeFromTemplate(IDIYComponent<?> component,
Template template) {
if (template != null
&& template.getPoints() != null
&& template.getPoints().size() >= component
.getControlPointCount()) {
for (int i = 0; i < component.getControlPointCount(); i++) {
Point p = new Point(component.getControlPoint(0));
p.translate(template.getPoints().get(i).x, template.getPoints()
.get(i).y);
component.setControlPoint(p, i);
}
}
}
/**
* Uses stored control points from the template to shape component.
*
* @param component
* @param template
*/
public void loadComponentShapeFromTemplate(IDIYComponent<?> component, Template template) {
if (template != null && template.getPoints() != null
&& template.getPoints().size() >= component.getControlPointCount()) {
for (int i = 0; i < component.getControlPointCount(); i++) {
Point p = new Point(component.getControlPoint(0));
p.translate(template.getPoints().get(i).x, template.getPoints().get(i).y);
component.setControlPoint(p, i);
}
}
}
public void tryToRotateComponentSlot() {
if (this.componentSlot == null) {
LOG.debug("Component slot is empty, cannot rotate");
return;
}
List<PropertyWrapper> properties = ComponentProcessor.getInstance()
.extractProperties(this.componentTypeSlot.getInstanceClass());
PropertyWrapper angleProperty = null;
for (PropertyWrapper propertyWrapper : properties) {
if (propertyWrapper.getType().getName().equals(
Orientation.class.getName())
|| propertyWrapper.getType().getName().equals(
OrientationHV.class.getName())) {
angleProperty = propertyWrapper;
break;
}
}
if (angleProperty == null) {
LOG
.debug("Component in the slot does not have a property of type Orientation, cannot rotate");
return;
}
try {
for (IDIYComponent<?> component : this.componentSlot) {
angleProperty.readFrom(component);
Object value = angleProperty.getValue();
if (value instanceof Orientation) {
angleProperty
.setValue(Orientation.values()[(((Orientation) value)
.ordinal() + 1)
% Orientation.values().length]);
} else if (value instanceof OrientationHV) {
angleProperty
.setValue(OrientationHV.values()[(((OrientationHV) value)
.ordinal() + 1)
% OrientationHV.values().length]);
}
angleProperty.writeTo(component);
}
} catch (Exception e) {
LOG.warn("Error trying to rotate the component", e);
}
}
public void tryToRotateComponentSlot() {
if (this.componentSlot == null) {
LOG.debug("Component slot is empty, cannot rotate");
return;
}
List<PropertyWrapper> properties =
ComponentProcessor.getInstance().extractProperties(this.componentTypeSlot.getInstanceClass());
PropertyWrapper angleProperty = null;
for (PropertyWrapper propertyWrapper : properties) {
if (propertyWrapper.getType().getName().equals(Orientation.class.getName())
|| propertyWrapper.getType().getName().equals(OrientationHV.class.getName())) {
angleProperty = propertyWrapper;
break;
}
}
if (angleProperty == null) {
LOG.debug("Component in the slot does not have a property of type Orientation, cannot rotate");
return;
}
try {
for (IDIYComponent<?> component : this.componentSlot) {
angleProperty.readFrom(component);
Object value = angleProperty.getValue();
if (value instanceof Orientation) {
angleProperty.setValue(Orientation.values()[(((Orientation) value).ordinal() + 1)
% Orientation.values().length]);
} else if (value instanceof OrientationHV) {
angleProperty.setValue(OrientationHV.values()[(((OrientationHV) value).ordinal() + 1)
% OrientationHV.values().length]);
}
angleProperty.writeTo(component);
}
} catch (Exception e) {
LOG.warn("Error trying to rotate the component", e);
}
}
}
@@ -8,22 +8,22 @@ import org.diylc.core.IDIYComponent;
public class PCBLayerFiler implements IComponentFiler {
private PCBLayer layer;
private PCBLayer layer;
public PCBLayerFiler(PCBLayer layer) {
super();
this.layer = layer;
}
public PCBLayerFiler(PCBLayer layer) {
super();
this.layer = layer;
}
@Override
public boolean testComponent(IDIYComponent<?> component) {
Class<?> clazz = component.getClass();
try {
Method m = clazz.getMethod("getLayer");
PCBLayer l = (PCBLayer) m.invoke(component);
return layer == l;
} catch (Exception e) {
return false;
}
}
@Override
public boolean testComponent(IDIYComponent<?> component) {
Class<?> clazz = component.getClass();
try {
Method m = clazz.getMethod("getLayer");
PCBLayer l = (PCBLayer) m.invoke(component);
return layer == l;
} catch (Exception e) {
return false;
}
}
}
@@ -11,31 +11,30 @@ import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* Serializes {@link Point} objects by converting coordinates from pixels to
* inches, thus avoiding the resolution to affect point placement.
* Serializes {@link Point} objects by converting coordinates from pixels to inches, thus avoiding
* the resolution to affect point placement.
*
* @author Branislav Stojkovic
*/
public class PointConverter implements Converter {
@Override
public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) {
Point point = (Point) object;
writer.addAttribute("x", Double.toString(1d * point.x / Constants.PIXELS_PER_INCH));
writer.addAttribute("y", Double.toString(1d * point.y / Constants.PIXELS_PER_INCH));
}
@Override
public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) {
Point point = (Point) object;
writer.addAttribute("x", Double.toString(1d * point.x / Constants.PIXELS_PER_INCH));
writer.addAttribute("y", Double.toString(1d * point.y / Constants.PIXELS_PER_INCH));
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
double x = Double.parseDouble(reader.getAttribute("x"));
double y = Double.parseDouble(reader.getAttribute("y"));
return new Point((int) Math.round(x * Constants.PIXELS_PER_INCH), (int) Math.round(y
* Constants.PIXELS_PER_INCH));
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
double x = Double.parseDouble(reader.getAttribute("x"));
double y = Double.parseDouble(reader.getAttribute("y"));
return new Point((int) Math.round(x * Constants.PIXELS_PER_INCH), (int) Math.round(y * Constants.PIXELS_PER_INCH));
}
@SuppressWarnings("unchecked")
@Override
public boolean canConvert(Class clazz) {
return Point.class.isAssignableFrom(clazz);
}
@SuppressWarnings("unchecked")
@Override
public boolean canConvert(Class clazz) {
return Point.class.isAssignableFrom(clazz);
}
}
@@ -66,494 +66,484 @@ import com.thoughtworks.xstream.io.xml.DomDriver;
public class ProjectFileManager {
private static final Logger LOG = Logger.getLogger(ProjectFileManager.class);
private static final Logger LOG = Logger.getLogger(ProjectFileManager.class);
// private static final int V1_PIXELS_PER_INCH = 200;
private static final Size V1_GRID_SPACING = new Size(0.1d, SizeUnit.in);
private static final Map<String, Color> V1_COLOR_MAP = new HashMap<String, Color>();
static {
V1_COLOR_MAP.put("red", Color.red);
V1_COLOR_MAP.put("blue", Color.blue);
V1_COLOR_MAP.put("white", Color.white);
V1_COLOR_MAP.put("green", Color.green.darker());
V1_COLOR_MAP.put("black", Color.black);
V1_COLOR_MAP.put("yellow", Color.yellow);
}
// private static final int V1_PIXELS_PER_INCH = 200;
private static final Size V1_GRID_SPACING = new Size(0.1d, SizeUnit.in);
private static final Map<String, Color> V1_COLOR_MAP = new HashMap<String, Color>();
static {
V1_COLOR_MAP.put("red", Color.red);
V1_COLOR_MAP.put("blue", Color.blue);
V1_COLOR_MAP.put("white", Color.white);
V1_COLOR_MAP.put("green", Color.green.darker());
V1_COLOR_MAP.put("black", Color.black);
V1_COLOR_MAP.put("yellow", Color.yellow);
}
private XStream xStream;
// Legacy deserializer for 3.0.1 through 3.0.7, loads Points referenced in
// pixels.
private XStream xStreamOld;
private XStream xStream;
// Legacy deserializer for 3.0.1 through 3.0.7, loads Points referenced in
// pixels.
private XStream xStreamOld;
private String currentFileName = null;
private boolean modified = false;
private String currentFileName = null;
private boolean modified = false;
private MessageDispatcher<EventType> messageDispatcher;
private MessageDispatcher<EventType> messageDispatcher;
public ProjectFileManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.xStream = new XStream(new DomDriver("UTF-8"));
xStream.autodetectAnnotations(true);
xStream.registerConverter(new PointConverter());
this.xStreamOld = new XStream(new DomDriver());
xStreamOld.autodetectAnnotations(true);
this.messageDispatcher = messageDispatcher;
}
public ProjectFileManager(MessageDispatcher<EventType> messageDispatcher) {
super();
this.xStream = new XStream(new DomDriver("UTF-8"));
xStream.autodetectAnnotations(true);
xStream.registerConverter(new PointConverter());
this.xStreamOld = new XStream(new DomDriver());
xStreamOld.autodetectAnnotations(true);
this.messageDispatcher = messageDispatcher;
}
public void startNewFile() {
currentFileName = null;
modified = false;
fireFileStatusChanged();
}
public void startNewFile() {
currentFileName = null;
modified = false;
fireFileStatusChanged();
}
public synchronized void serializeProjectToFile(Project project, String fileName, boolean isBackup)
throws IOException {
if (!isBackup) {
LOG.info(String.format("saveProjectToFile(%s)", fileName));
}
FileOutputStream fos;
fos = new FileOutputStream(fileName);
Writer writer = new OutputStreamWriter(fos, "UTF-8");
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
xStream.toXML(project, writer);
fos.close();
if (!isBackup) {
this.currentFileName = fileName;
this.modified = false;
fireFileStatusChanged();
}
}
public synchronized void serializeProjectToFile(Project project, String fileName, boolean isBackup)
throws IOException {
if (!isBackup) {
LOG.info(String.format("saveProjectToFile(%s)", fileName));
}
FileOutputStream fos;
fos = new FileOutputStream(fileName);
Writer writer = new OutputStreamWriter(fos, "UTF-8");
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
xStream.toXML(project, writer);
fos.close();
if (!isBackup) {
this.currentFileName = fileName;
this.modified = false;
fireFileStatusChanged();
}
}
public Project deserializeProjectFromFile(String fileName, List<String> warnings)
throws SAXException, IOException, ParserConfigurationException {
LOG.info(String.format("loadProjectFromFile(%s)", fileName));
Project project;
File file = new File(fileName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new InputStreamReader(new FileInputStream(file))));
doc.getDocumentElement().normalize();
if (doc.getDocumentElement().getNodeName().equalsIgnoreCase(Project.class.getName())) {
project = parseV3File(fileName);
} else {
if (!doc.getDocumentElement().getNodeName().equalsIgnoreCase("layout")) {
throw new IllegalArgumentException(
"Could not open DIY file. Root node is not named 'Layout'.");
}
String formatVersion = doc.getDocumentElement().getAttribute("formatVersion");
if (formatVersion == null || formatVersion.trim().isEmpty()) {
LOG.debug("Detected v1 file.");
project = parseV1File(doc.getDocumentElement(), warnings);
} else if (formatVersion.equals("2.0")) {
LOG.debug("Detected v2 file.");
project = parseV2File(doc.getDocumentElement());
} else {
throw new IllegalArgumentException("Unknown file format version: " + formatVersion);
}
}
Collections.sort(warnings);
this.currentFileName = fileName;
this.modified = false;
return project;
}
public Project deserializeProjectFromFile(String fileName, List<String> warnings) throws SAXException, IOException,
ParserConfigurationException {
LOG.info(String.format("loadProjectFromFile(%s)", fileName));
Project project;
File file = new File(fileName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new InputStreamReader(new FileInputStream(file))));
doc.getDocumentElement().normalize();
if (doc.getDocumentElement().getNodeName().equalsIgnoreCase(Project.class.getName())) {
project = parseV3File(fileName);
} else {
if (!doc.getDocumentElement().getNodeName().equalsIgnoreCase("layout")) {
throw new IllegalArgumentException("Could not open DIY file. Root node is not named 'Layout'.");
}
String formatVersion = doc.getDocumentElement().getAttribute("formatVersion");
if (formatVersion == null || formatVersion.trim().isEmpty()) {
LOG.debug("Detected v1 file.");
project = parseV1File(doc.getDocumentElement(), warnings);
} else if (formatVersion.equals("2.0")) {
LOG.debug("Detected v2 file.");
project = parseV2File(doc.getDocumentElement());
} else {
throw new IllegalArgumentException("Unknown file format version: " + formatVersion);
}
}
Collections.sort(warnings);
this.currentFileName = fileName;
this.modified = false;
return project;
}
public void notifyFileChange() {
this.modified = true;
fireFileStatusChanged();
}
public void notifyFileChange() {
this.modified = true;
fireFileStatusChanged();
}
public String getCurrentFileName() {
return currentFileName;
}
public String getCurrentFileName() {
return currentFileName;
}
public boolean isModified() {
return modified;
}
public boolean isModified() {
return modified;
}
public void fireFileStatusChanged() {
messageDispatcher.dispatchMessage(EventType.FILE_STATUS_CHANGED, getCurrentFileName(),
isModified());
}
public void fireFileStatusChanged() {
messageDispatcher.dispatchMessage(EventType.FILE_STATUS_CHANGED, getCurrentFileName(), isModified());
}
private Project parseV1File(Element root, List<String> warnings) {
Project project = new Project();
project.setTitle(root.getAttribute("Project"));
project.setAuthor(root.getAttribute("Credits"));
project.setGridSpacing(V1_GRID_SPACING);
String type = root.getAttribute("Type");
private Project parseV1File(Element root, List<String> warnings) {
Project project = new Project();
project.setTitle(root.getAttribute("Project"));
project.setAuthor(root.getAttribute("Credits"));
project.setGridSpacing(V1_GRID_SPACING);
String type = root.getAttribute("Type");
// Create the board.
int width = Integer.parseInt(root.getAttribute("Width")) + 1;
int height = Integer.parseInt(root.getAttribute("Height")) + 1;
int boardWidth = (int) (width * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue());
int boardHeight = (int) (height * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue());
int projectWidth = (int) project.getWidth().convertToPixels();
int projectHeight = (int) project.getHeight().convertToPixels();
int x = (projectWidth - boardWidth) / 2;
int y = (projectHeight - boardHeight) / 2;
AbstractBoard board;
if (type.equalsIgnoreCase("pcb")) {
board = new BlankBoard();
board.setBoardColor(Color.white);
board.setBorderColor(Color.black);
} else if (type.equalsIgnoreCase("perfboard")) {
board = new PerfBoard();
} else if (type.equalsIgnoreCase("stripboard")) {
board = new VeroBoard();
} else {
throw new IllegalArgumentException("Unrecognized board type: " + type);
}
board.setName("Main board");
Point referencePoint = new Point(CalcUtils.roundToGrid(x, V1_GRID_SPACING), CalcUtils
.roundToGrid(y, V1_GRID_SPACING));
board.setControlPoint(referencePoint, 0);
board.setControlPoint(new Point(CalcUtils.roundToGrid(x + boardWidth, V1_GRID_SPACING),
CalcUtils.roundToGrid(y + boardHeight, V1_GRID_SPACING)), 1);
project.getComponents().add(board);
// Create the board.
int width = Integer.parseInt(root.getAttribute("Width")) + 1;
int height = Integer.parseInt(root.getAttribute("Height")) + 1;
int boardWidth = (int) (width * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue());
int boardHeight = (int) (height * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue());
int projectWidth = (int) project.getWidth().convertToPixels();
int projectHeight = (int) project.getHeight().convertToPixels();
int x = (projectWidth - boardWidth) / 2;
int y = (projectHeight - boardHeight) / 2;
AbstractBoard board;
if (type.equalsIgnoreCase("pcb")) {
board = new BlankBoard();
board.setBoardColor(Color.white);
board.setBorderColor(Color.black);
} else if (type.equalsIgnoreCase("perfboard")) {
board = new PerfBoard();
} else if (type.equalsIgnoreCase("stripboard")) {
board = new VeroBoard();
} else {
throw new IllegalArgumentException("Unrecognized board type: " + type);
}
board.setName("Main board");
Point referencePoint =
new Point(CalcUtils.roundToGrid(x, V1_GRID_SPACING), CalcUtils.roundToGrid(y, V1_GRID_SPACING));
board.setControlPoint(referencePoint, 0);
board.setControlPoint(
new Point(CalcUtils.roundToGrid(x + boardWidth, V1_GRID_SPACING), CalcUtils.roundToGrid(y + boardHeight,
V1_GRID_SPACING)), 1);
project.getComponents().add(board);
NodeList childNodes = root.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String nodeName = node.getNodeName();
String nameAttr = node.getAttributes().getNamedItem("Name").getNodeValue();
Node valueNode = node.getAttributes().getNamedItem("Value");
String valueAttr = valueNode == null ? null : valueNode.getNodeValue();
int x1Attr = Integer.parseInt(node.getAttributes().getNamedItem("X1")
.getNodeValue());
int y1Attr = Integer.parseInt(node.getAttributes().getNamedItem("Y1")
.getNodeValue());
Point point1 = convertV1CoordinatesToV3Point(referencePoint, x1Attr, y1Attr);
Point point2 = null;
Integer x2Attr = null;
Integer y2Attr = null;
Color color = null;
if (node.getAttributes().getNamedItem("Color") != null) {
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
color = V1_COLOR_MAP.get(colorAttr.toLowerCase());
}
if (node.getAttributes().getNamedItem("X2") != null
&& node.getAttributes().getNamedItem("Y2") != null) {
x2Attr = Integer.parseInt(node.getAttributes().getNamedItem("X2")
.getNodeValue());
y2Attr = Integer.parseInt(node.getAttributes().getNamedItem("Y2")
.getNodeValue());
point2 = convertV1CoordinatesToV3Point(referencePoint, x2Attr, y2Attr);
}
IDIYComponent<?> component = null;
if (nodeName.equalsIgnoreCase("text")) {
LOG.debug("Recognized " + nodeName);
Label label = new Label();
label.setName(nameAttr);
if (color != null) {
label.setColor(color);
}
label.setText(valueAttr);
label.setHorizontalAlignment(HorizontalAlignment.LEFT);
label.setVerticalAlignment(VerticalAlignment.CENTER);
label.setControlPoint(convertV1CoordinatesToV3Point(referencePoint, x1Attr,
y1Attr), 0);
component = label;
} else if (nodeName.equalsIgnoreCase("pad")) {
LOG.debug("Recognized " + nodeName);
SolderPad pad = new SolderPad();
pad.setName(nameAttr);
if (color != null) {
pad.setColor(color);
}
pad.setControlPoint(convertV1CoordinatesToV3Point(referencePoint, x1Attr,
y1Attr), 0);
component = pad;
} else if (nodeName.equalsIgnoreCase("trace")) {
LOG.debug("Recognized " + nodeName);
CopperTrace trace = new CopperTrace();
trace.setName(nameAttr);
if (color != null) {
trace.setLeadColor(color);
}
trace.setControlPoint(point1, 0);
trace.setControlPoint(point2, 1);
component = trace;
} else if (nodeName.equalsIgnoreCase("jumper")) {
LOG.debug("Recognized " + nodeName);
Jumper jumper = new Jumper();
jumper.setName(nameAttr);
jumper.setControlPoint(point1, 0);
jumper.setControlPoint(point2, 1);
component = jumper;
} else if (nodeName.equalsIgnoreCase("wire")) {
LOG.debug("Recognized " + nodeName);
HookupWire wire = new HookupWire();
Point midPoint = new Point((point1.x + point2.x) / 2, (point1.y + point2.y) / 2);
wire.setName(nameAttr);
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
wire.setColor(parseV1Color(colorAttr));
wire.setControlPoint(point1, 0);
wire.setControlPoint(midPoint, 1);
wire.setControlPoint(midPoint, 2);
wire.setControlPoint(point2, 3);
component = wire;
} else if (nodeName.equalsIgnoreCase("resistor")) {
LOG.debug("Recognized " + nodeName);
Resistor resistor = new Resistor();
resistor.setName(nameAttr);
try {
resistor.setValue(Resistance.parseResistance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
resistor.setLength(new Size(6.35d, SizeUnit.mm));
resistor.setWidth(new Size(2.2d, SizeUnit.mm));
resistor.setControlPoint(point1, 0);
resistor.setControlPoint(point2, 1);
component = resistor;
} else if (nodeName.equalsIgnoreCase("capacitor")) {
LOG.debug("Recognized " + nodeName);
RadialFilmCapacitor capacitor = new RadialFilmCapacitor();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
capacitor.setLength(new Size(6d, SizeUnit.mm));
capacitor.setWidth(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("electrolyte")) {
LOG.debug("Recognized " + nodeName);
RadialElectrolytic capacitor = new RadialElectrolytic();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
try {
String sizeAttr = node.getAttributes().getNamedItem("Size").getNodeValue();
if (sizeAttr.equalsIgnoreCase("small")) {
capacitor.setLength(new Size(3.5d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("medium")) {
capacitor.setLength(new Size(5d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("large")) {
capacitor.setLength(new Size(7d, SizeUnit.mm));
} else {
capacitor.setLength(new Size(4d, SizeUnit.mm));
}
} catch (Exception e) {
capacitor.setLength(new Size(5d, SizeUnit.mm));
LOG.debug("Could not set size of " + nameAttr);
}
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("diode")) {
LOG.debug("Recognized " + nodeName);
DiodePlastic capacitor = new DiodePlastic();
capacitor.setName(nameAttr);
try {
capacitor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
capacitor.setLength(new Size(6d, SizeUnit.mm));
capacitor.setWidth(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("led")) {
LOG.debug("Recognized " + nodeName);
LED led = new LED();
led.setName(nameAttr);
led.setValue(valueAttr);
led.setBodyColor(Color.red);
led.setBorderColor(Color.red.darker());
led.setLength(new Size(3d, SizeUnit.mm));
led.setControlPoint(point1, 0);
led.setControlPoint(point2, 1);
component = led;
} else if (nodeName.equalsIgnoreCase("transistor")) {
LOG.debug("Recognized " + nodeName);
TransistorTO92 transistor = new TransistorTO92();
transistor.setName(nameAttr);
try {
transistor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
transistor.setControlPoint(point1, 0);
if (point1.y > point2.y) {
transistor.setOrientation(Orientation._180);
} else if (point1.y < point2.y) {
transistor.setOrientation(Orientation.DEFAULT);
} else if (point1.x < point2.x) {
transistor.setOrientation(Orientation._270);
} else if (point1.x > point2.x) {
transistor.setOrientation(Orientation._90);
}
// capacitor.setControlPoint(point2, 1);
component = transistor;
} else if (nodeName.equalsIgnoreCase("ic")) {
LOG.debug("Recognized " + nodeName);
DIL_IC ic = new DIL_IC();
int pinCount = 8;
int rowSpace = 3;
if (x1Attr < x2Attr && y1Attr < y2Attr) {
pinCount = (y2Attr - y1Attr + 1) * 2;
rowSpace = x2Attr - x1Attr;
ic.setOrientation(Orientation.DEFAULT);
} else if (x1Attr > x2Attr && y1Attr < y2Attr) {
pinCount = (x1Attr - x2Attr + 1) * 2;
rowSpace = y2Attr - y1Attr;
ic.setOrientation(Orientation._90);
} else if (x1Attr > x2Attr && y1Attr > y2Attr) {
rowSpace = x1Attr - x2Attr;
pinCount = (y1Attr - y2Attr + 1) * 2;
ic.setOrientation(Orientation._180);
} else if (x1Attr < x2Attr && y1Attr > y2Attr) {
rowSpace = y1Attr - y2Attr;
pinCount = (x2Attr - x1Attr + 1) * 2;
ic.setOrientation(Orientation._270);
}
ic.setRowSpacing(new Size(0.1 * rowSpace, SizeUnit.in));
ic.setPinCount(DIL_IC.PinCount.valueOf("_" + pinCount));
ic.setName(nameAttr);
// Translate control points.
for (int j = 0; j < ic.getControlPointCount(); j++) {
Point p = new Point(ic.getControlPoint(j));
p.translate(point1.x, point1.y);
ic.setControlPoint(p, j);
}
ic.setValue(valueAttr);
component = ic;
} else if (nodeName.equalsIgnoreCase("pot")) {
LOG.debug("Recognized " + nodeName);
PotentiometerPanel pot = new PotentiometerPanel();
pot.setBodyDiameter(new Size(14d, SizeUnit.mm));
pot.setSpacing(new Size(0.2, SizeUnit.in));
pot.setName(nameAttr);
try {
pot.setValue(Resistance.parseResistance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
String taperAttr = node.getAttributes().getNamedItem("Taper").getNodeValue();
if ("Linear".equals(taperAttr)) {
pot.setTaper(Taper.LIN);
} else if ("Audio".equals(taperAttr)) {
pot.setTaper(Taper.LOG);
} else if ("Reverse Audio".equals(taperAttr)) {
pot.setTaper(Taper.REV_LOG);
}
// Pin spacing, we'll need to move pot around a bit.
int delta = Constants.PIXELS_PER_INCH / 5;
if (x1Attr < x2Attr) {
pot.setOrientation(Orientation.DEFAULT);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x - delta, point1.y);
pot.setControlPoint(p, j);
}
} else if (x1Attr > x2Attr) {
pot.setOrientation(Orientation._180);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x + delta, point1.y);
pot.setControlPoint(p, j);
}
} else if (y1Attr < y2Attr) {
pot.setOrientation(Orientation._90);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x, point1.y - delta);
pot.setControlPoint(p, j);
}
} else if (y1Attr > y2Attr) {
pot.setOrientation(Orientation._270);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x, point1.y + delta);
pot.setControlPoint(p, j);
}
;
}
component = pot;
} else {
String message = "Could not recognize component type " + nodeName;
LOG.debug(message);
if (!warnings.contains(message)) {
warnings.add(message);
}
}
if (component != null) {
if (component instanceof AbstractLeadedComponent<?>) {
((AbstractLeadedComponent<?>) component).setDisplay(Display.NAME);
}
if (component instanceof AbstractTransparentComponent<?>) {
((AbstractTransparentComponent<?>) component).setAlpha((byte) 100);
}
project.getComponents().add(component);
}
}
}
Collections.sort(project.getComponents(), ComparatorFactory.getInstance()
.getComponentZOrderComparator());
return project;
}
NodeList childNodes = root.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String nodeName = node.getNodeName();
String nameAttr = node.getAttributes().getNamedItem("Name").getNodeValue();
Node valueNode = node.getAttributes().getNamedItem("Value");
String valueAttr = valueNode == null ? null : valueNode.getNodeValue();
int x1Attr = Integer.parseInt(node.getAttributes().getNamedItem("X1").getNodeValue());
int y1Attr = Integer.parseInt(node.getAttributes().getNamedItem("Y1").getNodeValue());
Point point1 = convertV1CoordinatesToV3Point(referencePoint, x1Attr, y1Attr);
Point point2 = null;
Integer x2Attr = null;
Integer y2Attr = null;
Color color = null;
if (node.getAttributes().getNamedItem("Color") != null) {
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
color = V1_COLOR_MAP.get(colorAttr.toLowerCase());
}
if (node.getAttributes().getNamedItem("X2") != null && node.getAttributes().getNamedItem("Y2") != null) {
x2Attr = Integer.parseInt(node.getAttributes().getNamedItem("X2").getNodeValue());
y2Attr = Integer.parseInt(node.getAttributes().getNamedItem("Y2").getNodeValue());
point2 = convertV1CoordinatesToV3Point(referencePoint, x2Attr, y2Attr);
}
IDIYComponent<?> component = null;
if (nodeName.equalsIgnoreCase("text")) {
LOG.debug("Recognized " + nodeName);
Label label = new Label();
label.setName(nameAttr);
if (color != null) {
label.setColor(color);
}
label.setText(valueAttr);
label.setHorizontalAlignment(HorizontalAlignment.LEFT);
label.setVerticalAlignment(VerticalAlignment.CENTER);
label.setControlPoint(convertV1CoordinatesToV3Point(referencePoint, x1Attr, y1Attr), 0);
component = label;
} else if (nodeName.equalsIgnoreCase("pad")) {
LOG.debug("Recognized " + nodeName);
SolderPad pad = new SolderPad();
pad.setName(nameAttr);
if (color != null) {
pad.setColor(color);
}
pad.setControlPoint(convertV1CoordinatesToV3Point(referencePoint, x1Attr, y1Attr), 0);
component = pad;
} else if (nodeName.equalsIgnoreCase("trace")) {
LOG.debug("Recognized " + nodeName);
CopperTrace trace = new CopperTrace();
trace.setName(nameAttr);
if (color != null) {
trace.setLeadColor(color);
}
trace.setControlPoint(point1, 0);
trace.setControlPoint(point2, 1);
component = trace;
} else if (nodeName.equalsIgnoreCase("jumper")) {
LOG.debug("Recognized " + nodeName);
Jumper jumper = new Jumper();
jumper.setName(nameAttr);
jumper.setControlPoint(point1, 0);
jumper.setControlPoint(point2, 1);
component = jumper;
} else if (nodeName.equalsIgnoreCase("wire")) {
LOG.debug("Recognized " + nodeName);
HookupWire wire = new HookupWire();
Point midPoint = new Point((point1.x + point2.x) / 2, (point1.y + point2.y) / 2);
wire.setName(nameAttr);
String colorAttr = node.getAttributes().getNamedItem("Color").getNodeValue();
wire.setColor(parseV1Color(colorAttr));
wire.setControlPoint(point1, 0);
wire.setControlPoint(midPoint, 1);
wire.setControlPoint(midPoint, 2);
wire.setControlPoint(point2, 3);
component = wire;
} else if (nodeName.equalsIgnoreCase("resistor")) {
LOG.debug("Recognized " + nodeName);
Resistor resistor = new Resistor();
resistor.setName(nameAttr);
try {
resistor.setValue(Resistance.parseResistance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
resistor.setLength(new Size(6.35d, SizeUnit.mm));
resistor.setWidth(new Size(2.2d, SizeUnit.mm));
resistor.setControlPoint(point1, 0);
resistor.setControlPoint(point2, 1);
component = resistor;
} else if (nodeName.equalsIgnoreCase("capacitor")) {
LOG.debug("Recognized " + nodeName);
RadialFilmCapacitor capacitor = new RadialFilmCapacitor();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
capacitor.setLength(new Size(6d, SizeUnit.mm));
capacitor.setWidth(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("electrolyte")) {
LOG.debug("Recognized " + nodeName);
RadialElectrolytic capacitor = new RadialElectrolytic();
capacitor.setName(nameAttr);
try {
capacitor.setValue(Capacitance.parseCapacitance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
try {
String sizeAttr = node.getAttributes().getNamedItem("Size").getNodeValue();
if (sizeAttr.equalsIgnoreCase("small")) {
capacitor.setLength(new Size(3.5d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("medium")) {
capacitor.setLength(new Size(5d, SizeUnit.mm));
} else if (sizeAttr.equalsIgnoreCase("large")) {
capacitor.setLength(new Size(7d, SizeUnit.mm));
} else {
capacitor.setLength(new Size(4d, SizeUnit.mm));
}
} catch (Exception e) {
capacitor.setLength(new Size(5d, SizeUnit.mm));
LOG.debug("Could not set size of " + nameAttr);
}
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("diode")) {
LOG.debug("Recognized " + nodeName);
DiodePlastic capacitor = new DiodePlastic();
capacitor.setName(nameAttr);
try {
capacitor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
capacitor.setLength(new Size(6d, SizeUnit.mm));
capacitor.setWidth(new Size(2d, SizeUnit.mm));
capacitor.setControlPoint(point1, 0);
capacitor.setControlPoint(point2, 1);
component = capacitor;
} else if (nodeName.equalsIgnoreCase("led")) {
LOG.debug("Recognized " + nodeName);
LED led = new LED();
led.setName(nameAttr);
led.setValue(valueAttr);
led.setBodyColor(Color.red);
led.setBorderColor(Color.red.darker());
led.setLength(new Size(3d, SizeUnit.mm));
led.setControlPoint(point1, 0);
led.setControlPoint(point2, 1);
component = led;
} else if (nodeName.equalsIgnoreCase("transistor")) {
LOG.debug("Recognized " + nodeName);
TransistorTO92 transistor = new TransistorTO92();
transistor.setName(nameAttr);
try {
transistor.setValue(valueAttr);
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
transistor.setControlPoint(point1, 0);
if (point1.y > point2.y) {
transistor.setOrientation(Orientation._180);
} else if (point1.y < point2.y) {
transistor.setOrientation(Orientation.DEFAULT);
} else if (point1.x < point2.x) {
transistor.setOrientation(Orientation._270);
} else if (point1.x > point2.x) {
transistor.setOrientation(Orientation._90);
}
// capacitor.setControlPoint(point2, 1);
component = transistor;
} else if (nodeName.equalsIgnoreCase("ic")) {
LOG.debug("Recognized " + nodeName);
DIL_IC ic = new DIL_IC();
int pinCount = 8;
int rowSpace = 3;
if (x1Attr < x2Attr && y1Attr < y2Attr) {
pinCount = (y2Attr - y1Attr + 1) * 2;
rowSpace = x2Attr - x1Attr;
ic.setOrientation(Orientation.DEFAULT);
} else if (x1Attr > x2Attr && y1Attr < y2Attr) {
pinCount = (x1Attr - x2Attr + 1) * 2;
rowSpace = y2Attr - y1Attr;
ic.setOrientation(Orientation._90);
} else if (x1Attr > x2Attr && y1Attr > y2Attr) {
rowSpace = x1Attr - x2Attr;
pinCount = (y1Attr - y2Attr + 1) * 2;
ic.setOrientation(Orientation._180);
} else if (x1Attr < x2Attr && y1Attr > y2Attr) {
rowSpace = y1Attr - y2Attr;
pinCount = (x2Attr - x1Attr + 1) * 2;
ic.setOrientation(Orientation._270);
}
ic.setRowSpacing(new Size(0.1 * rowSpace, SizeUnit.in));
ic.setPinCount(DIL_IC.PinCount.valueOf("_" + pinCount));
ic.setName(nameAttr);
// Translate control points.
for (int j = 0; j < ic.getControlPointCount(); j++) {
Point p = new Point(ic.getControlPoint(j));
p.translate(point1.x, point1.y);
ic.setControlPoint(p, j);
}
ic.setValue(valueAttr);
component = ic;
} else if (nodeName.equalsIgnoreCase("pot")) {
LOG.debug("Recognized " + nodeName);
PotentiometerPanel pot = new PotentiometerPanel();
pot.setBodyDiameter(new Size(14d, SizeUnit.mm));
pot.setSpacing(new Size(0.2, SizeUnit.in));
pot.setName(nameAttr);
try {
pot.setValue(Resistance.parseResistance(valueAttr));
} catch (Exception e) {
LOG.debug("Could not set value of " + nameAttr);
}
String taperAttr = node.getAttributes().getNamedItem("Taper").getNodeValue();
if ("Linear".equals(taperAttr)) {
pot.setTaper(Taper.LIN);
} else if ("Audio".equals(taperAttr)) {
pot.setTaper(Taper.LOG);
} else if ("Reverse Audio".equals(taperAttr)) {
pot.setTaper(Taper.REV_LOG);
}
// Pin spacing, we'll need to move pot around a bit.
int delta = Constants.PIXELS_PER_INCH / 5;
if (x1Attr < x2Attr) {
pot.setOrientation(Orientation.DEFAULT);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x - delta, point1.y);
pot.setControlPoint(p, j);
}
} else if (x1Attr > x2Attr) {
pot.setOrientation(Orientation._180);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x + delta, point1.y);
pot.setControlPoint(p, j);
}
} else if (y1Attr < y2Attr) {
pot.setOrientation(Orientation._90);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x, point1.y - delta);
pot.setControlPoint(p, j);
}
} else if (y1Attr > y2Attr) {
pot.setOrientation(Orientation._270);
for (int j = 0; j < pot.getControlPointCount(); j++) {
Point p = new Point(pot.getControlPoint(j));
p.translate(point1.x, point1.y + delta);
pot.setControlPoint(p, j);
};
}
component = pot;
} else {
String message = "Could not recognize component type " + nodeName;
LOG.debug(message);
if (!warnings.contains(message)) {
warnings.add(message);
}
}
if (component != null) {
if (component instanceof AbstractLeadedComponent<?>) {
((AbstractLeadedComponent<?>) component).setDisplay(Display.NAME);
}
if (component instanceof AbstractTransparentComponent<?>) {
((AbstractTransparentComponent<?>) component).setAlpha((byte) 100);
}
project.getComponents().add(component);
}
}
}
Collections.sort(project.getComponents(), ComparatorFactory.getInstance().getComponentZOrderComparator());
return project;
}
private Point convertV1CoordinatesToV3Point(Point reference, int x, int y) {
Point point = new Point(reference);
point.translate((int) (x * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue()),
(int) (y * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue()));
return point;
}
private Point convertV1CoordinatesToV3Point(Point reference, int x, int y) {
Point point = new Point(reference);
point.translate((int) (x * Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue()), (int) (y
* Constants.PIXELS_PER_INCH * V1_GRID_SPACING.getValue()));
return point;
}
private Color parseV1Color(String color) {
if ("brown".equals(color.toLowerCase()))
return new Color(139, 69, 19);
try {
Field field = Color.class.getDeclaredField(color.toLowerCase());
return (Color) field.get(null);
} catch (Exception e) {
LOG.error("Could not parse color \"" + color + "\"", e);
return Color.black;
}
}
private Color parseV1Color(String color) {
if ("brown".equals(color.toLowerCase()))
return new Color(139, 69, 19);
try {
Field field = Color.class.getDeclaredField(color.toLowerCase());
return (Color) field.get(null);
} catch (Exception e) {
LOG.error("Could not parse color \"" + color + "\"", e);
return Color.black;
}
}
private Project parseV2File(Element root) {
Project project = new Project();
String projectName = root.getAttribute("projectName");
String credits = root.getAttribute("credits");
String width = root.getAttribute("width");
String height = root.getAttribute("height");
NodeList childNodes = root.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getNodeName().equalsIgnoreCase("component")) {
LOG.debug(node.getAttributes().getNamedItem("name").getNodeValue());
} else {
LOG.debug("Unrecognized node name found: " + node.getNodeName());
}
}
}
return project;
}
private Project parseV2File(Element root) {
Project project = new Project();
String projectName = root.getAttribute("projectName");
String credits = root.getAttribute("credits");
String width = root.getAttribute("width");
String height = root.getAttribute("height");
NodeList childNodes = root.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getNodeName().equalsIgnoreCase("component")) {
LOG.debug(node.getAttributes().getNamedItem("name").getNodeValue());
} else {
LOG.debug("Unrecognized node name found: " + node.getNodeName());
}
}
}
return project;
}
private Project parseV3File(String fileName) throws IOException {
Project project;
FileInputStream fis = new FileInputStream(fileName);
try {
Reader reader = new InputStreamReader(fis, "UTF-8");
project = (Project) xStream.fromXML(reader);
} catch (Exception e) {
LOG.warn("Could not open with the new xStream, trying the old one");
fis.close();
fis = new FileInputStream(fileName);
project = (Project) xStreamOld.fromXML(fis);
}
fis.close();
return project;
}
}
private Project parseV3File(String fileName) throws IOException {
Project project;
FileInputStream fis = new FileInputStream(fileName);
try {
Reader reader = new InputStreamReader(fis, "UTF-8");
project = (Project) xStream.fromXML(reader);
} catch (Exception e) {
LOG.warn("Could not open with the new xStream, trying the old one");
fis.close();
fis = new FileInputStream(fileName);
project = (Project) xStreamOld.fromXML(fis);
}
fis.close();
return project;
}
}
@@ -2,100 +2,100 @@ package org.diylc.utils;
public class BomEntry {
private String type;
private String name;
private String value;
private Integer quantity;
private String notes;
private String type;
private String name;
private String value;
private Integer quantity;
private String notes;
public BomEntry(String type, String name, String value, int quantity) {
super();
this.type = type;
this.name = name;
this.value = value;
this.quantity = quantity;
}
public String getType() {
return type;
}
public BomEntry(String type, String name, String value, int quantity) {
super();
this.type = type;
this.name = name;
this.value = value;
this.quantity = quantity;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public void setName(String name) {
this.name = name;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public Integer getQuantity() {
return quantity;
}
public void setValue(String value) {
this.value = value;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Integer getQuantity() {
return quantity;
}
public String getNotes() {
return notes;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getNotes() {
return notes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((notes == null) ? 0 : notes.hashCode());
result = prime * result + quantity;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
public void setNotes(String notes) {
this.notes = notes;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BomEntry other = (BomEntry) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (notes == null) {
if (other.notes != null)
return false;
} else if (!notes.equals(other.notes))
return false;
if (quantity != other.quantity)
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((notes == null) ? 0 : notes.hashCode());
result = prime * result + quantity;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BomEntry other = (BomEntry) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (notes == null) {
if (other.notes != null)
return false;
} else if (!notes.equals(other.notes))
return false;
if (quantity != other.quantity)
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
@@ -16,75 +16,72 @@ import org.diylc.presenter.ComponentProcessor;
public class BomMaker {
private static BomMaker instance;
private static BomMaker instance;
public static BomMaker getInstance() {
if (instance == null) {
instance = new BomMaker();
}
return instance;
}
public static BomMaker getInstance() {
if (instance == null) {
instance = new BomMaker();
}
return instance;
}
private BomMaker() {
}
private BomMaker() {}
public List<BomEntry> createBom(List<IDIYComponent<?>> components) {
Map<String, BomEntry> entryMap = new LinkedHashMap<String, BomEntry>();
List<IDIYComponent<?>> sortedComponents = new ArrayList<IDIYComponent<?>>(
components);
Collections.sort(sortedComponents, new Comparator<IDIYComponent<?>>() {
public List<BomEntry> createBom(List<IDIYComponent<?>> components) {
Map<String, BomEntry> entryMap = new LinkedHashMap<String, BomEntry>();
List<IDIYComponent<?>> sortedComponents = new ArrayList<IDIYComponent<?>>(components);
Collections.sort(sortedComponents, new Comparator<IDIYComponent<?>>() {
@Override
public int compare(IDIYComponent<?> o1, IDIYComponent<?> o2) {
String name1 = o1.getName();
String name2 = o2.getName();
Pattern p = Pattern.compile("(\\D+)(\\d+)");
Matcher m1 = p.matcher(name1);
Matcher m2 = p.matcher(name2);
if (m1.matches() && m2.matches()) {
String prefix1 = m1.group(1);
int value1 = Integer.parseInt(m1.group(2));
String prefix2 = m2.group(1);
int value2 = Integer.parseInt(m2.group(2));
int compare = prefix1.compareToIgnoreCase(prefix2);
if (compare != 0) {
return compare;
}
return new Integer(value1).compareTo(value2);
}
return name1.compareToIgnoreCase(name2);
}
});
for (IDIYComponent<?> component : sortedComponents) {
ComponentType type = ComponentProcessor.getInstance()
.extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component
.getClass());
if (type.getBomPolicy() == BomPolicy.NEVER_SHOW)
continue;
String name = component.getName();
String value;
try {
value = component.getValueForDisplay();
} catch (Exception e){
value = "<undefined>";
}
if ((name != null) && (value != null)) {
String key = type.getName() + "|" + value;
if (entryMap.containsKey(key)) {
BomEntry entry = entryMap.get(key);
entry.setQuantity(entry.getQuantity() + 1);
if (type.getBomPolicy() == BomPolicy.SHOW_ALL_NAMES) {
entry.setName(entry.getName() + ", " + name);
}
} else {
entryMap.put(key, new BomEntry(type.getName(), type
.getBomPolicy() == BomPolicy.SHOW_ALL_NAMES ? name
: type.getName(), value, 1));
}
}
}
List<BomEntry> bom = new ArrayList<BomEntry>(entryMap.values());
return bom;
}
@Override
public int compare(IDIYComponent<?> o1, IDIYComponent<?> o2) {
String name1 = o1.getName();
String name2 = o2.getName();
Pattern p = Pattern.compile("(\\D+)(\\d+)");
Matcher m1 = p.matcher(name1);
Matcher m2 = p.matcher(name2);
if (m1.matches() && m2.matches()) {
String prefix1 = m1.group(1);
int value1 = Integer.parseInt(m1.group(2));
String prefix2 = m2.group(1);
int value2 = Integer.parseInt(m2.group(2));
int compare = prefix1.compareToIgnoreCase(prefix2);
if (compare != 0) {
return compare;
}
return new Integer(value1).compareTo(value2);
}
return name1.compareToIgnoreCase(name2);
}
});
for (IDIYComponent<?> component : sortedComponents) {
ComponentType type =
ComponentProcessor.getInstance().extractComponentTypeFrom(
(Class<? extends IDIYComponent<?>>) component.getClass());
if (type.getBomPolicy() == BomPolicy.NEVER_SHOW)
continue;
String name = component.getName();
String value;
try {
value = component.getValueForDisplay();
} catch (Exception e) {
value = "<undefined>";
}
if ((name != null) && (value != null)) {
String key = type.getName() + "|" + value;
if (entryMap.containsKey(key)) {
BomEntry entry = entryMap.get(key);
entry.setQuantity(entry.getQuantity() + 1);
if (type.getBomPolicy() == BomPolicy.SHOW_ALL_NAMES) {
entry.setName(entry.getName() + ", " + name);
}
} else {
entryMap.put(key,
new BomEntry(type.getName(), type.getBomPolicy() == BomPolicy.SHOW_ALL_NAMES ? name : type.getName(),
value, 1));
}
}
}
List<BomEntry> bom = new ArrayList<BomEntry>(entryMap.values());
return bom;
}
}
@@ -9,19 +9,18 @@ import org.diylc.core.Theme;
public class Constants {
public static final int PIXELS_PER_INCH = 200;
public static final double PIXEL_SIZE = 1d * PIXELS_PER_INCH
/ Toolkit.getDefaultToolkit().getScreenResolution();
public static final int PIXELS_PER_INCH = 200;
public static final double PIXEL_SIZE = 1d * PIXELS_PER_INCH / Toolkit.getDefaultToolkit().getScreenResolution();
public static Color CANVAS_COLOR = Color.white;
public static Color CANVAS_COLOR = Color.white;
public static final Stroke DASHED_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10f, new float[] { 2.0f }, 0.0f);
public static final Stroke DASHED_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f,
new float[] {2.0f}, 0.0f);
public static final Theme DEFAULT_THEME = new Theme("Light", Constants.CANVAS_COLOR, new Color(
240, 240, 240), Color.black);
public static final Theme DEFAULT_THEME = new Theme("Light", Constants.CANVAS_COLOR, new Color(240, 240, 240),
Color.black);
public static final Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0);
public static final Color MULTI_VALUE_COLOR = Color.yellow;
public static final Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0);
public static final Color MULTI_VALUE_COLOR = Color.yellow;
}
@@ -9,35 +9,35 @@ import org.apache.log4j.Logger;
public class MemoryCleaner {
private static final Logger LOG = Logger.getLogger(MemoryCleaner.class);
private static final Logger LOG = Logger.getLogger(MemoryCleaner.class);
public static void clean(Object obj) {
Class<?> clazz = obj.getClass();
LOG.debug("Cleaning up object of type: " + clazz.getName());
try {
Method disposeMethod = clazz.getMethod("dispose");
disposeMethod.invoke(obj);
} catch (Exception e) {
LOG.error(e);
}
// If it's a collection loop over and dispose elements.
if (Collection.class.isAssignableFrom(clazz)) {
LOG.info("Cleaning up collection elements");
for (Object childObj : (Collection<?>) obj) {
clean(childObj);
}
}
for (Field field : clazz.getFields()) {
if (!Modifier.isFinal(field.getModifiers())) {
try {
LOG.info("Cleaning up field: " + field.getName());
Object childObj = field.get(obj);
field.set(obj, null);
clean(childObj);
} catch (Exception e) {
LOG.error(e);
}
}
}
}
public static void clean(Object obj) {
Class<?> clazz = obj.getClass();
LOG.debug("Cleaning up object of type: " + clazz.getName());
try {
Method disposeMethod = clazz.getMethod("dispose");
disposeMethod.invoke(obj);
} catch (Exception e) {
LOG.error(e);
}
// If it's a collection loop over and dispose elements.
if (Collection.class.isAssignableFrom(clazz)) {
LOG.info("Cleaning up collection elements");
for (Object childObj : (Collection<?>) obj) {
clean(childObj);
}
}
for (Field field : clazz.getFields()) {
if (!Modifier.isFinal(field.getModifiers())) {
try {
LOG.info("Cleaning up field: " + field.getName());
Object childObj = field.get(obj);
field.set(obj, null);
clean(childObj);
} catch (Exception e) {
LOG.error(e);
}
}
}
}
}
@@ -8,7 +8,7 @@ import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses( { BomMakerTest.class, ClassProcessorTest.class })
@SuiteClasses({BomMakerTest.class, ClassProcessorTest.class})
public class AllTests {
}
@@ -16,22 +16,22 @@ import org.junit.Test;
public class BomMakerTest {
@Test
public void testCreateBom() {
List<IDIYComponent<?>> components = new ArrayList<IDIYComponent<?>>();
MockDIYComponent c1 = new MockDIYComponent();
c1.setValue(new Capacitance(3d, CapacitanceUnit.pF));
components.add(c1);
components.add(new MockDIYComponent());
components.add(new MockDIYComponent());
List<BomEntry> bom = BomMaker.getInstance().createBom(components);
assertNotNull(bom);
assertEquals(2, bom.size());
BomEntry entry1 = bom.get(0);
assertEquals("something", entry1.getName());
assertEquals(2, (int) entry1.getQuantity());
BomEntry entry2 = bom.get(1);
assertEquals("something", entry2.getName());
assertEquals(1, (int) entry2.getQuantity());
}
@Test
public void testCreateBom() {
List<IDIYComponent<?>> components = new ArrayList<IDIYComponent<?>>();
MockDIYComponent c1 = new MockDIYComponent();
c1.setValue(new Capacitance(3d, CapacitanceUnit.pF));
components.add(c1);
components.add(new MockDIYComponent());
components.add(new MockDIYComponent());
List<BomEntry> bom = BomMaker.getInstance().createBom(components);
assertNotNull(bom);
assertEquals(2, bom.size());
BomEntry entry1 = bom.get(0);
assertEquals("something", entry1.getName());
assertEquals(2, (int) entry1.getQuantity());
BomEntry entry2 = bom.get(1);
assertEquals("something", entry2.getName());
assertEquals(1, (int) entry2.getQuantity());
}
}
@@ -12,11 +12,10 @@ import org.junit.Test;
public class ClassProcessorTest {
@Test
public void testExtractProperties() {
List<PropertyWrapper> properties = ComponentProcessor.getInstance().extractProperties(
MockDIYComponent.class);
assertNotNull(properties);
assertEquals(4, properties.size());
};
@Test
public void testExtractProperties() {
List<PropertyWrapper> properties = ComponentProcessor.getInstance().extractProperties(MockDIYComponent.class);
assertNotNull(properties);
assertEquals(4, properties.size());
};
}
@@ -19,128 +19,128 @@ import org.diylc.core.measures.ResistanceUnit;
import org.diylc.core.measures.Size;
import org.diylc.core.measures.SizeUnit;
@ComponentDescriptor(name = "Mock", author = "bancika", category = "Sample", instanceNamePrefix = "M", description = "test", zOrder = IDIYComponent.COMPONENT)
@ComponentDescriptor(name = "Mock", author = "bancika", category = "Sample", instanceNamePrefix = "M",
description = "test", zOrder = IDIYComponent.COMPONENT)
public class MockDIYComponent extends AbstractComponent<Capacitance> {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private String testField = "Hello World";
private Capacitance c = new Capacitance(100d, CapacitanceUnit.uF);
private Resistance r = new Resistance(123d, ResistanceUnit.K);
private Size s = new Size(1d, SizeUnit.cm);
private Color color = Color.green;
private Point leftTopCorner = new Point(0, 0);
private String name = "something";
private String testField = "Hello World";
private Capacitance c = new Capacitance(100d, CapacitanceUnit.uF);
private Resistance r = new Resistance(123d, ResistanceUnit.K);
private Size s = new Size(1d, SizeUnit.cm);
private Color color = Color.green;
private Point leftTopCorner = new Point(0, 0);
private String name = "something";
public MockDIYComponent(String testField, Capacitance c, Resistance r, Size s, Color color,
Point leftTopCorner) {
super();
this.testField = testField;
this.c = c;
this.r = r;
this.s = s;
this.color = color;
this.leftTopCorner = leftTopCorner;
}
public MockDIYComponent(String testField, Capacitance c, Resistance r, Size s, Color color, Point leftTopCorner) {
super();
this.testField = testField;
this.c = c;
this.r = r;
this.s = s;
this.color = color;
this.leftTopCorner = leftTopCorner;
}
public MockDIYComponent() {
super();
}
public MockDIYComponent() {
super();
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
}
@Override
public boolean canControlPointOverlap(int index) {
return false;
}
@EditableProperty
public String getName() {
return name;
}
@EditableProperty
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int getControlPointCount() {
return 1;
}
@Override
public int getControlPointCount() {
return 1;
}
@Override
public boolean isControlPointSticky(int index) {
return false;
}
@Override
public boolean isControlPointSticky(int index) {
return false;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public VisibilityPolicy getControlPointVisibilityPolicy(int index) {
return VisibilityPolicy.WHEN_SELECTED;
}
@Override
public Point getControlPoint(int index) {
return leftTopCorner;
}
@Override
public Point getControlPoint(int index) {
return leftTopCorner;
}
@Override
public void setControlPoint(Point point, int index) {
leftTopCorner.setLocation(point);
}
@Override
public void setControlPoint(Point point, int index) {
leftTopCorner.setLocation(point);
}
@EditableProperty(name = "Test Field")
public String getTestField() {
return testField;
}
@EditableProperty(name = "Test Field")
public String getTestField() {
return testField;
}
public void setTestField(String testField) {
this.testField = testField;
}
public void setTestField(String testField) {
this.testField = testField;
}
@EditableProperty(defaultable = true)
public Capacitance getValue() {
return c;
}
@EditableProperty(defaultable = true)
public Capacitance getValue() {
return c;
}
public void setValue(Capacitance c) {
this.c = c;
}
public void setValue(Capacitance c) {
this.c = c;
}
@EditableProperty(defaultable = true)
public Color getColor() {
return color;
}
@EditableProperty(defaultable = true)
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public void setColor(Color color) {
this.color = color;
}
@EditableProperty
public Resistance getR() {
return r;
}
@EditableProperty
public Resistance getR() {
return r;
}
// Setter is commented out, ClassProcessor should ignore this property.
// public void setR(Resistance r) {
// this.r = r;
// }
// Setter is commented out, ClassProcessor should ignore this property.
// public void setR(Resistance r) {
// this.r = r;
// }
// No annotation, so this property should be ignored.
public Size getS() {
return s;
}
// No annotation, so this property should be ignored.
public Size getS() {
return s;
}
public void setS(Size s) {
this.s = s;
}
public void setS(Size s) {
this.s = s;
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode,
Project project, IDrawingObserver drawingObserver) {
g2d.setColor(componentState.equals(ComponentState.SELECTED) ? color : color.darker());
g2d.fillRect(leftTopCorner.x, leftTopCorner.y, 200, 50);
}
@Override
public void draw(Graphics2D g2d, ComponentState componentState, boolean outlineMode, Project project,
IDrawingObserver drawingObserver) {
g2d.setColor(componentState.equals(ComponentState.SELECTED) ? color : color.darker());
g2d.fillRect(leftTopCorner.x, leftTopCorner.y, 200, 50);
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.drawString("X", 10, 10);
}
@Override
public void drawIcon(Graphics2D g2d, int width, int height) {
g2d.drawString("X", 10, 10);
}
}