]> gerrit.simantics Code Review - simantics/platform.git/blob
b0e9147f63134e5c2af5dee0c2436efbdbc016e3
[simantics/platform.git] /
1 /*******************************************************************************
2  * Copyright (c) 2011 Association for Decentralized Information Management in
3  * Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.scenegraph.g2d.nodes.connection;
13
14 import java.awt.BasicStroke;
15 import java.awt.Color;
16 import java.awt.Graphics2D;
17 import java.awt.RenderingHints;
18 import java.awt.Shape;
19 import java.awt.Stroke;
20 import java.awt.event.KeyEvent;
21 import java.awt.geom.AffineTransform;
22 import java.awt.geom.Path2D;
23 import java.awt.geom.Point2D;
24 import java.awt.geom.Rectangle2D;
25 import java.lang.reflect.Constructor;
26 import java.util.Collection;
27 import java.util.List;
28 import java.util.Map;
29
30 import org.simantics.diagram.connection.RouteGraph;
31 import org.simantics.diagram.connection.RouteLine;
32 import org.simantics.diagram.connection.RouteLink;
33 import org.simantics.diagram.connection.RouteTerminal;
34 import org.simantics.diagram.connection.actions.IAction;
35 import org.simantics.diagram.connection.actions.IReconnectAction;
36 import org.simantics.diagram.connection.actions.MoveAction;
37 import org.simantics.diagram.connection.actions.ReconnectLineAction;
38 import org.simantics.diagram.connection.delta.RouteGraphDelta;
39 import org.simantics.diagram.connection.rendering.BasicConnectionStyle;
40 import org.simantics.diagram.connection.rendering.ConnectionStyle;
41 import org.simantics.diagram.connection.rendering.IRouteGraphRenderer;
42 import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;
43 import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;
44 import org.simantics.diagram.connection.splitting.SplittedRouteGraph;
45 import org.simantics.scenegraph.INode;
46 import org.simantics.scenegraph.ISelectionPainterNode;
47 import org.simantics.scenegraph.g2d.G2DNode;
48 import org.simantics.scenegraph.g2d.G2DParentNode;
49 import org.simantics.scenegraph.g2d.G2DSceneGraph;
50 import org.simantics.scenegraph.g2d.IG2DNode;
51 import org.simantics.scenegraph.g2d.events.EventTypes;
52 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;
53 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyReleasedEvent;
54 import org.simantics.scenegraph.g2d.events.MouseEvent;
55 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;
56 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonReleasedEvent;
57 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseClickEvent;
58 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseDragBegin;
59 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;
60 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
61 import org.simantics.scenegraph.g2d.events.command.Commands;
62 import org.simantics.scenegraph.g2d.nodes.GridNode;
63 import org.simantics.scenegraph.g2d.nodes.LinkNode;
64 import org.simantics.scenegraph.g2d.nodes.NavigationNode;
65 import org.simantics.scenegraph.g2d.nodes.SVGNodeAssignment;
66 import org.simantics.scenegraph.g2d.nodes.connection.HighlightActionPointsAction.Action;
67 import org.simantics.scenegraph.g2d.nodes.connection.HighlightActionPointsAction.Pick;
68 import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;
69 import org.simantics.scenegraph.utils.ColorUtil;
70 import org.simantics.scenegraph.utils.GeometryUtils;
71 import org.simantics.scenegraph.utils.InitValueSupport;
72 import org.simantics.scenegraph.utils.NodeUtil;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 import gnu.trove.map.hash.THashMap;
77
78 /**
79  * @author Tuukka Lehtonen
80  */
81 public class RouteGraphNode extends G2DNode implements ISelectionPainterNode, InitValueSupport  {
82
83     private static final Logger LOGGER = LoggerFactory.getLogger(RouteGraphNode.class);
84
85         private static final long       serialVersionUID = -917194130412280965L;
86
87     private static final double     TOLERANCE        = IAction.TOLERANCE;
88     private static final Stroke     SELECTION_STROKE = new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
89     private static final Color      SELECTION_COLOR  = new Color(255, 0, 255, 96);
90
91     private static final HighlightActionPointsAction highlightActions = new HighlightActionPointsAction(null);
92
93     protected RouteGraph            rg;
94     protected IRouteGraphRenderer   baseRenderer;
95     protected IRouteGraphRenderer   renderer;
96     protected double                pickTolerance    = TOLERANCE;
97     protected boolean               editable         = true;
98     private boolean                 branchable       = true;
99
100     protected IRouteGraphListener   rgListener;
101     protected RouteGraphDelta       rgDelta;
102
103     protected transient double      mouseX;
104     protected transient double      mouseY;
105     protected transient Point2D     pt               = new Point2D.Double();
106
107     protected transient MoveAction  dragAction;
108     protected transient IAction     currentAction;
109     protected transient Rectangle2D bounds;
110
111     /**
112      * Dynamic color for connection rendering.
113      */
114     protected transient Color       dynamicColor;
115
116     /**
117      * Dynamic stroke for connection rendering.
118      */
119     protected transient Stroke      dynamicStroke;
120
121     protected transient Path2D      selectionPath    = new Path2D.Double();
122     protected transient Stroke      selectionStroke  = null;
123
124     protected transient boolean     highlightActionsEnabled = false;
125     protected transient AffineTransform lastViewTransform = null;
126
127     /**
128      * x = NaN is used to indicate that possible branch point should not be
129      * rendered but interaction has not ended yet.
130      */
131     protected transient Point2D     newBranchPointPosition = null;
132
133
134     protected transient Map<Object,ILineEndStyle> dynamicStyles = null;
135
136     private transient boolean ignoreSelection = false;
137     
138     @Override
139     public void initValues() {
140         dynamicColor = null;
141         wrapRenderer();
142     }
143
144     private static float tryParseFloat(String s, float def) {
145         try {
146                 return Float.parseFloat(s);
147         } catch (NumberFormatException e) {
148                 LOGGER.error("Could not parse '" + s + "' into float.");
149                 return def;
150         }
151     }
152     
153     /*
154      * 1.0 BUTT MITER 1.0 0.0
155      */
156     private static Stroke parseStroke(String definition) {
157         
158         float width = 1.0f;
159         int cap = BasicStroke.CAP_BUTT;
160         int join = BasicStroke.JOIN_MITER;
161         float miterLimit = 1.0f;
162         float[] dash = { 1, 0};
163         float dash_phase = 0;
164
165         String[] parts = definition.split(" ");
166         
167         if(parts.length > 0) {
168                 width = tryParseFloat(parts[0], width);
169         }
170         if(parts.length > 1) { 
171                 if("BUTT".equals(parts[1])) cap = BasicStroke.CAP_BUTT;
172                 else if("ROUND".equals(parts[1])) cap = BasicStroke.CAP_ROUND;
173                 else if("SQUARE".equals(parts[1])) cap = BasicStroke.CAP_SQUARE;
174         }
175         if(parts.length > 2) { 
176                 if("BEVEL".equals(parts[2])) cap = BasicStroke.JOIN_BEVEL;
177                 else if("MITER".equals(parts[2])) cap = BasicStroke.JOIN_MITER;
178                 else if("ROUND".equals(parts[2])) cap = BasicStroke.JOIN_ROUND;
179         }
180         if(parts.length > 3) {
181                 miterLimit = tryParseFloat(parts[3], miterLimit);
182         } 
183         if(parts.length > 4) {
184                 dash_phase = tryParseFloat(parts[4], dash_phase);
185         }
186         if(parts.length > 6) {
187                 dash = new float[parts.length - 5];
188                 for(int i=5;i<parts.length;i++) {
189                         dash[i-5] = tryParseFloat(parts[i], 1.0f);
190                 }
191         }
192                         
193         
194         try {
195                 return new BasicStroke(width, cap, join, miterLimit, dash, dash_phase);
196         } catch (IllegalArgumentException e) {
197                 return new BasicStroke();
198         }
199         
200     }
201     
202     public void setAssignments(List<SVGNodeAssignment> assignments) {
203         for(SVGNodeAssignment ass : assignments) {
204                 if("dynamicColor".equals(ass.elementId)) {
205                         setDynamicColor(ColorUtil.hexColor(ass.value));
206                 } else if("dynamicStroke".equals(ass.elementId)) {
207                         setDynamicStroke(parseStroke(ass.value));
208                 }
209         }
210     }
211
212     public void setIgnoreSelection(boolean value) {
213         ignoreSelection = value;
214     }
215     
216     public boolean getIgnoreSelection() {
217         return ignoreSelection;
218     }  
219   
220     @PropertySetter("color")
221     @SyncField(value = {"dynamicColor"})
222     public void setDynamicColor(Color color) {
223         this.dynamicColor = color;
224         wrapRenderer();
225     }
226
227     @PropertySetter("width")
228     @SyncField("dynamicStroke")
229     public void setDynamicStroke(Stroke stroke) {
230         this.dynamicStroke = stroke;
231         wrapRenderer();
232         createSelectionStroke();
233     }
234     
235     @SyncField(value = {"dynamicStyles"})
236     public void setDynamicLineEnd(RouteTerminal terminal, ILineEndStyle style) {
237         if (dynamicStyles == null)
238                 dynamicStyles = new THashMap<Object, ILineEndStyle>();
239         terminal.setDynamicStyle(style);
240         if (terminal.getData() != null) {
241                 if (style != null)
242                         dynamicStyles.put(terminal.getData(),style);
243                 else
244                         dynamicStyles.remove(terminal.getData());
245         }
246     }
247     
248     private void updateLineEnds() {
249         if (dynamicStyles == null)
250                 return;
251         for (RouteTerminal t : rg.getTerminals()) {
252                 if (t.getData() == null)
253                         continue;
254                 ILineEndStyle dynamicStyle = dynamicStyles.get(t.getData());
255                 if (dynamicStyle != null)
256                         t.setDynamicStyle(dynamicStyle);
257         }
258     }
259
260     @SyncField(value = {"rg"})
261     public void setRouteGraph(RouteGraph graph) {
262         this.rg = graph;
263         updateLineEnds();
264         updateBounds();
265     }
266
267     @SyncField(value = {"rgDelta"})
268     public void setRouteGraphDelta(RouteGraphDelta delta) {
269         this.rgDelta = delta;
270     }
271
272     @SyncField(value = {"renderer"})
273     public void setRenderer(IRouteGraphRenderer renderer) {
274
275         this.baseRenderer = renderer;
276         wrapRenderer();
277
278         createSelectionStroke();      
279     }
280     
281     private void createSelectionStroke() {
282          BasicConnectionStyle style = tryGetStyle();
283          selectionStroke = null;
284          if (style != null) {
285              BasicStroke stroke = (BasicStroke) style.getLineStroke();
286              if (stroke != null) {
287                  float width = Math.max(stroke.getLineWidth() + 0.75f, stroke.getLineWidth()*1.3f);
288                  selectionStroke = new BasicStroke(width, BasicStroke.CAP_BUTT, stroke.getLineJoin());
289              }
290          } else {
291              selectionStroke = SELECTION_STROKE;
292          }
293     }
294     
295     private void wrapRenderer() {
296         
297         if(baseRenderer == null) {
298             renderer = null;
299             return;
300         }
301         
302         if(dynamicColor != null || dynamicStroke != null) {
303             BasicConnectionStyle baseStyle = (BasicConnectionStyle)tryGetStyle(baseRenderer);
304             try {
305                 Constructor<? extends BasicConnectionStyle> c = baseStyle.getClass().getConstructor(Color.class, Color.class, double.class, Stroke.class, Stroke.class, double.class, double.class);
306                 renderer = new StyledRouteGraphRenderer(c.newInstance(
307                         dynamicColor != null ? dynamicColor : baseStyle.getLineColor(),
308                                 baseStyle.getBranchPointColor(), baseStyle.getBranchPointRadius(),
309                                     dynamicStroke != null ? dynamicStroke : baseStyle.getLineStroke(), 
310                                             dynamicStroke != null ? dynamicStroke : baseStyle.getRouteLineStroke(),
311                                                     baseStyle.getDegeneratedLineLength(), baseStyle.getRounding()));
312             } catch (Exception e) {
313                 renderer = new StyledRouteGraphRenderer(new BasicConnectionStyle(
314                         dynamicColor != null ? dynamicColor : baseStyle.getLineColor(),
315                                 baseStyle.getBranchPointColor(), baseStyle.getBranchPointRadius(),
316                                     dynamicStroke != null ? dynamicStroke : baseStyle.getLineStroke(), 
317                                             dynamicStroke != null ? dynamicStroke : baseStyle.getRouteLineStroke(),
318                                                     baseStyle.getDegeneratedLineLength(), baseStyle.getRounding()));
319             }
320             
321             
322         } else {
323             renderer = baseRenderer;
324         }
325         
326     }
327
328     @SyncField(value = {"pickTolerance"})
329     public void setPickTolerance(double tolerance) {
330         this.pickTolerance = tolerance;
331     }
332
333     @SyncField(value = {"editable"})
334     public void setEditable(boolean editable) {
335         this.editable = editable;
336     }
337
338     @SyncField(value = {"branchable"})
339     public void setBranchable(boolean branchable) {
340         this.branchable = branchable;
341     }
342
343     public RouteGraph getRouteGraph() {
344         return rg;
345     }
346
347     public RouteGraphDelta getRouteGraphDelta() {
348         return rgDelta;
349     }
350
351     public IRouteGraphRenderer getRenderer() {
352         return renderer;
353     }
354
355     public boolean isEditable() {
356         return editable;
357     }
358
359     public boolean isBranchable() {
360         return branchable;
361     }
362     
363     public double getPickTolerance() {
364                 return pickTolerance;
365         }
366
367     /**
368      * When in client-server mode, listener is only set on the server side and
369      * fireRouteGraphChanged will tell it when rg has changed.
370      * 
371      * @param listener
372      */
373     public void setRouteGraphListener(IRouteGraphListener listener) {
374         this.rgListener = listener;
375     }
376
377     /**
378      * @param before
379      * @param after
380      * @return <code>true</code> if changes were fired
381      */
382     public boolean setRouteGraphAndFireChanges(RouteGraph before, RouteGraph after) {
383         RouteGraphDelta delta = new RouteGraphDelta(before, after);
384         if (!delta.isEmpty()) {
385             setRouteGraph(after);
386             setRouteGraphDelta(delta);
387             fireRouteGraphChanged(before, after, delta);
388             return true;
389         }
390         return false;
391     }
392
393     @ServerSide
394     protected void fireRouteGraphChanged(RouteGraph before, RouteGraph after, RouteGraphDelta delta) {
395         if (rgListener != null) {
396             RouteGraphChangeEvent event = new RouteGraphChangeEvent(this, before, after, delta);
397             rgListener.routeGraphChanged(event);
398         }
399     }
400
401     public void showBranchPoint(Point2D p) {
402         newBranchPointPosition = p;
403     }
404
405     @Override
406     public void init() {
407         super.init();
408         addEventHandler(this);
409     }
410
411     @Override
412     public void cleanup() {
413         rgListener = null;
414         removeEventHandler(this);
415         super.cleanup();
416     }
417
418     protected boolean isSelected() {
419         return NodeUtil.isSelected(this, 1);
420     }
421
422     @Override
423     public void render(Graphics2D g) {
424         if (renderer == null)
425             return;
426
427         AffineTransform ot = null;
428         AffineTransform t = getTransform();
429         if (t != null && !t.isIdentity()) {
430             ot = g.getTransform();
431             g.transform(getTransform());
432         }
433
434         Object aaHint = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
435         g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
436
437         boolean selected = ignoreSelection ? false : NodeUtil.isSelected(this, 1);
438
439         rg.updateTerminals();
440
441         if (currentAction != null) {
442             currentAction.render(g, renderer, mouseX, mouseY);
443         } else {
444             if (selected && selectionStroke != null) {
445                 selectionPath.reset();
446                 rg.getPath2D(selectionPath);
447                 Shape selectionShape = selectionStroke.createStrokedShape(selectionPath);
448                 g.setColor(SELECTION_COLOR);
449                 g.fill(selectionShape);
450             }
451
452             renderer.render(g, rg);
453             if(selected)
454                 renderer.renderGuides(g, rg);
455
456             if (selected && highlightActionsEnabled) {
457                 // Needed for performing actions in #mouseClicked
458                 this.lastViewTransform = g.getTransform();
459                 highlightActions.setRouteGraph(rg);
460                 highlightActions.render(g, renderer, mouseX, mouseY);
461                 highlightActions.setRouteGraph(null);
462             }
463         }
464
465         g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, aaHint);
466
467         if (editable && branchable && newBranchPointPosition != null && !Double.isNaN(newBranchPointPosition.getX())) {
468             ConnectionStyle style = tryGetStyle();
469             if(style != null)
470                 style.drawBranchPoint(g, newBranchPointPosition.getX(), newBranchPointPosition.getY());
471         }
472
473         if (ot != null)
474             g.setTransform(ot);
475     }
476     
477     private BasicConnectionStyle tryGetStyle() {
478         return tryGetStyle(renderer);
479     }
480
481     private BasicConnectionStyle tryGetStyle(IRouteGraphRenderer renderer) {
482         if (renderer instanceof StyledRouteGraphRenderer) {
483             ConnectionStyle cs = ((StyledRouteGraphRenderer) renderer).getStyle();
484             if (cs instanceof BasicConnectionStyle)
485                 return (BasicConnectionStyle) cs;
486         }
487         return null;
488     }
489
490     public double getSelectionStrokeWidth() {
491         if (selectionStroke instanceof BasicStroke) {
492             BasicStroke bs = (BasicStroke) selectionStroke;
493             return bs.getLineWidth();
494         }
495         return 1.0;
496     }
497
498     @Override
499     public Rectangle2D getBoundsInLocal() {
500         return bounds;
501     }
502
503     protected void updateBounds() {
504         Rectangle2D r = this.bounds;
505         if (r == null)
506             r = new Rectangle2D.Double();
507         this.bounds = calculateBounds(r);
508
509         // Need to expand to take stroke width into account.
510         double sw = getSelectionStrokeWidth() / 2;
511         GeometryUtils.expandRectangle(this.bounds, sw, sw);
512     }
513
514     protected Rectangle2D calculateBounds(Rectangle2D rect) {
515         RouteGraph rg = this.rg;
516         if (currentAction instanceof MoveAction)
517             rg = ((MoveAction) currentAction).getRouteGraph();
518         rg.getBounds(rect);
519         return rect;
520     }
521
522     protected void getMouseLocalPos(MouseEvent e) {
523         //System.out.println("m: " + e.controlPosition);
524         pt.setLocation(e.controlPosition);
525         //System.out.println("parent: " + pt);
526         pt = NodeUtil.worldToLocal(this, pt, pt);
527         //System.out.println("local: " + pt);
528         mouseX = pt.getX();
529         mouseY = pt.getY();
530     }
531
532     @Override
533     protected boolean mouseDragged(MouseDragBegin e) {
534         // Consume event if drag is possible. 
535         // PointerInteractor will call handleDrag with the MouseDragBegin event for the route line that is closest to the cursor.
536         return currentAction != null;
537     }
538
539     public boolean handleDrag(MouseDragBegin e) {
540         if (dragAction != null && !e.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK) && e.button == MouseEvent.LEFT_BUTTON) {
541             currentAction = dragAction;
542             dragAction = null;
543         }
544         return updateCurrentAction(e, true);
545     }
546
547     @Override
548     protected boolean mouseMoved(MouseMovedEvent e) {
549         //System.out.println("mouse moved: " + e);
550
551         // Handle connection branching visualization.
552         getMouseLocalPos(e);
553         if (newBranchPointPosition == null && e.hasAnyModifier(MouseEvent.ALT_MASK | MouseEvent.ALT_GRAPH_MASK)) {
554             if (bounds.contains(mouseX, mouseY)) {
555                 newBranchPointPosition = new Point2D.Double(Double.NaN, Double.NaN);
556             }
557         }
558         if (newBranchPointPosition != null) {
559             RouteLine line = rg.pickLine(mouseX, mouseY, scaledPickTolerance());
560             if (line != null) {
561                 newBranchPointPosition.setLocation(mouseX, mouseY);
562                 SplittedRouteGraph.snapToLine(newBranchPointPosition, line);
563                 repaint();
564             } else if (!Double.isNaN(newBranchPointPosition.getX())) {
565                 newBranchPointPosition.setLocation(Double.NaN, Double.NaN);
566                 repaint();
567             }
568         }
569
570         // Make sure that highlight action rendering is according to mouse hover.
571         if (highlightActionsEnabled) {
572             if (NodeUtil.isSelected(this, 1)) {
573                 repaint();
574             }
575         }
576
577         return updateCurrentAction(e, false);
578     }
579
580     protected boolean updateCurrentAction(MouseEvent e, boolean updateMousePos) {
581         boolean oldHighlight = highlightActionsEnabled;
582         highlightActionsEnabled = e.hasAllModifiers(MouseEvent.CTRL_MASK);
583         if (oldHighlight != highlightActionsEnabled)
584             repaint();
585
586         if (currentAction != null) {
587             if (updateMousePos)
588                 getMouseLocalPos(e);
589             updateBounds();
590
591             // Repaint, but only if absolutely necessary.
592             if (currentAction instanceof MoveAction || bounds.contains(mouseX, mouseY))
593                 repaint();
594
595             return true;
596         }
597         return false;
598     }
599
600     @Override
601     protected boolean mouseClicked(MouseClickEvent e) {
602         if (!editable)
603             return false;
604
605         if (e.button == MouseEvent.LEFT_BUTTON) {
606             if (isSelected() && highlightActionsEnabled) {
607                 // Reconnection / segment deletion only available for branched connections. 
608                 if (rg.getTerminals().size() > 2) {
609                     Pick pick = highlightActions.pickAction(rg, lastViewTransform, mouseX, mouseY);
610                     if (pick.hasAction(Action.REMOVE)) {
611                         RemoveLineAction remove = RemoveLineAction.perform(rg, pick.line.getLine(), mouseX, mouseY);
612                         if (remove != null) {
613                             setRouteGraphAndFireChanges(remove.getOriginalRouteGraph(), remove.getRouteGraph());
614                             repaint();
615                             return true;
616                         }
617                     }
618                     if (pick.hasAction(Action.RECONNECT)) {
619                         currentAction = ReconnectLineAction.create(rg, mouseX, mouseY);
620                         if (currentAction != null) {
621                             repaint();
622                         }
623                     }
624                 }
625             }
626         }
627
628         return false;
629     }
630
631     @Override
632     protected boolean mouseButtonPressed(MouseButtonPressedEvent e) {
633         if (!editable)
634             return false;
635
636         if (e.button == MouseEvent.LEFT_BUTTON) {
637             // Visualize new branch point no longer.
638             newBranchPointPosition = null;
639
640             getMouseLocalPos(e);
641             dragAction = null;
642 //          if(currentAction instanceof HighlightActionPointsAction) {
643 //              RemoveLineAction remove = RemoveLineAction.perform(rg, mouseX, mouseY);
644 //              if (remove != null) {
645 //                  setRouteGraphAndFireChanges(remove.getOriginalRouteGraph(), remove.getRouteGraph());
646 //                  repaint();
647 //              } else {
648 //                  currentAction = ReconnectLineAction.create(rg, mouseX, mouseY);
649 //                  if (currentAction != null)
650 //                      repaint();
651 //              }
652 //          }
653 //          else
654             if(currentAction instanceof IReconnectAction) {
655                 RouteGraph originalRg = rg.copy();
656                 ((IReconnectAction)currentAction).finish(mouseX, mouseY);
657                 currentAction = null;
658
659                 setRouteGraphAndFireChanges(originalRg, rg);
660
661                 currentAction = null;
662                 repaint();
663                 return true;
664             }
665             else {
666                 if (!allowConnectionRerouting()) {
667                     return false;
668                 }
669                 //System.out.println("move action");
670                 dragAction = SnappingMoveAction.create(rg, mouseX, mouseY, scaledPickTolerance(), moveFilter, getSnapAdvisor());
671                 //System.out.println("DRAG ACTION: " + dragAction);
672             }
673
674             //System.out.println(this + " NEW action: " + currentAction);
675             if (currentAction != null)
676                 return true;
677         }
678         return false;
679     }
680
681     private double scaledPickTolerance() {
682         NavigationNode nn = NodeUtil.findNearestParentNode(this, NavigationNode.class);
683         double scale = 1.0;
684         if (nn != null) {
685             scale = GeometryUtils.getScale(nn.getTransform());
686         }
687         double pickDistance = 0;
688         G2DSceneGraph sg = NodeUtil.getRootNode(nn != null ? nn : this);
689         if (sg != null) {
690             pickDistance = sg.getGlobalProperty(G2DSceneGraph.PICK_DISTANCE, pickDistance);
691         }
692         return Math.max(getSelectionStrokeWidth() / 2.0, pickDistance / scale);
693     }
694     
695     /**
696      * Checks the selections data node in the scene graph for any links 
697      * @return
698      */
699     private boolean allowConnectionRerouting() {
700         final int maxOtherNodesSelected = 1;
701
702         INode selections = NodeUtil.tryLookup(this, "selections");
703         if (!(selections instanceof G2DParentNode))
704             return true;
705         G2DParentNode p = (G2DParentNode) selections;
706         for (IG2DNode selection : p.getNodes()) {
707             if (!(selection instanceof G2DParentNode))
708                 continue;
709
710             G2DParentNode sp = (G2DParentNode) selection;
711             Collection<IG2DNode> links = sp.getNodes();
712             if (links.isEmpty())
713                 return true;
714             int othersSelected = 0;
715             for (IG2DNode link : links) {
716                 if (link instanceof LinkNode) {
717                     INode node = ((LinkNode) link).getDelegate();
718                     if (!NodeUtil.isParentOf(node, this)) {
719                         othersSelected++;
720                         if (othersSelected > maxOtherNodesSelected)
721                             return false;
722                     }
723                 }
724             }
725             if (othersSelected > maxOtherNodesSelected)
726                 return false;
727         }
728         return true;
729     }
730
731     protected ISnapAdvisor getSnapAdvisor() {
732         GridNode grid = lookupNode(GridNode.GRID_NODE_ID, GridNode.class);
733         return grid != null ? grid.getSnapAdvisor() : null;
734     }
735
736     MoveAction.TargetFilter moveFilter = new MoveAction.TargetFilter() {
737         @Override
738         public boolean accept(Object target) {
739             return (target instanceof RouteLine) || (target instanceof RouteLink);
740         }
741     };
742
743     @Override
744     protected boolean handleCommand(CommandEvent e) {
745         /*if (Commands.DELETE.equals(e.command)) {
746             Object target = rg.pick(mouseX, mouseY, pickTolerance);
747             return deleteTarget(target);
748         } else if (Commands.SPLIT_CONNECTION.equals(e.command)) {
749             Object target = rg.pick(mouseX, mouseY, pickTolerance);
750             return splitTarget(target);
751         } else */
752         if (Commands.CANCEL.equals(e.command)) {
753             return cancelCurrentAction();
754         }
755         return false;
756     }
757
758     protected boolean mouseButtonReleased(MouseButtonReleasedEvent e) {
759         if (currentAction instanceof MoveAction) {
760             MoveAction move = (MoveAction) currentAction;
761             RouteGraph originalRg = rg.copy();
762             move.finish(mouseX, mouseY);
763
764             setRouteGraphAndFireChanges(originalRg, rg);
765
766             currentAction = null;
767             repaint();
768             return true;
769         }
770         return false;
771     }
772
773     @Override
774     protected boolean keyPressed(KeyPressedEvent e) {
775         if (!editable)
776             return false;
777
778         if (!e.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK) && e.keyCode == KeyEvent.VK_S) {
779             Object target = rg.pick(mouseX, mouseY, scaledPickTolerance(), RouteGraph.PICK_PERSISTENT_LINES | RouteGraph.PICK_TRANSIENT_LINES);
780             return splitTarget(target);
781         }
782         else if (!e.hasAnyModifier(MouseEvent.ALT_MASK | MouseEvent.ALT_GRAPH_MASK | MouseEvent.CTRL_MASK) && (e.keyCode == KeyEvent.VK_R || e.keyCode == KeyEvent.VK_D)) {
783             Object target = rg.pick(mouseX, mouseY, scaledPickTolerance(), RouteGraph.PICK_PERSISTENT_LINES);
784             return deleteTarget(target);
785         }
786         else if (e.keyCode == KeyEvent.VK_ESCAPE) {
787             return cancelCurrentAction();
788         }
789 //        else if (e.keyCode == KeyEvent.VK_D) {
790 //            if (target instanceof RouteTerminal) {
791 //                RouteTerminal terminal = (RouteTerminal) target;
792 //                RouteGraph before = rg.copy();
793 //                rg.toggleDirectLines(terminal);
794 //                setRouteGraphAndFireChanges(before, rg);
795 //                repaint();
796 //            }
797 //        }
798 //        else if (target != null && e.getKeyCode() == KeyEvent.VK_P) {
799 //            rg.print();
800 //        }
801         else if (e.keyCode == KeyEvent.VK_CONTROL) {
802             highlightActionsEnabled = true;
803             repaint();
804         }
805         else if (e.keyCode == KeyEvent.VK_ALT) {
806             // Begin connection branching visualization.
807             RouteLine line = rg.pickLine(mouseX, mouseY, scaledPickTolerance());
808             if (branchable && line != null) {
809                 newBranchPointPosition = new Point2D.Double(mouseX, mouseY);
810                 SplittedRouteGraph.snapToLine(newBranchPointPosition, line);
811                 repaint();
812             }
813         }
814
815         return false;
816     }
817
818     @Override
819     protected boolean keyReleased(KeyReleasedEvent e) {
820         if (e.keyCode == KeyEvent.VK_ALT) {
821             // End connection branching visualization.
822             if (newBranchPointPosition != null) {
823                 newBranchPointPosition = null;
824                 repaint();
825             }
826         }
827         if (e.keyCode == KeyEvent.VK_CONTROL) {
828             highlightActionsEnabled = false;
829             repaint();
830         }
831         return false;
832     }
833
834
835     private boolean cancelCurrentAction() {
836         if (currentAction != null) {
837             currentAction = null;
838             repaint();
839             return true;
840         }
841         return false;
842     }
843
844     private boolean splitTarget(Object target) {
845         if (target instanceof RouteLine) {
846             RouteLine rLine = (RouteLine)target;
847             RouteGraph before = rg.copy();
848             rg.split(rLine, rLine.isHorizontal() ? mouseX : mouseY);
849             setRouteGraphAndFireChanges(before, rg);
850             repaint();
851             return true;
852         }
853         return false;
854     }
855
856     private boolean deleteTarget(Object target) {
857         boolean changed = false;
858         if (target instanceof RouteLine) {
859             RouteLine line = (RouteLine) target;
860             RouteGraph before = rg.copy();
861             rg.merge(line);
862             changed = setRouteGraphAndFireChanges(before, rg);
863         }
864         else if (target instanceof RouteLink) {
865             RouteGraph before = rg.copy();
866             rg.deleteCorner((RouteLink) target);
867             changed = setRouteGraphAndFireChanges(before, rg);
868         }
869 //        else if (target instanceof RouteTerminal) {
870 //            RouteGraph before = rg.copy();
871 //            rg.remove((RouteTerminal) target);
872 //            changed = setRouteGraphAndFireChanges(before, rg);
873 //        }
874         if (changed)
875             repaint();
876         return changed;
877     }
878
879     /**
880      * A version of MoveAction that snaps movements using the specified
881      * ISnapAdvisor.
882      */
883     static class SnappingMoveAction extends MoveAction {
884
885         private ISnapAdvisor snapAdvisor;
886         private Point2D      point = new Point2D.Double();
887
888         public SnappingMoveAction(RouteGraph rg, Object target, ISnapAdvisor snapAdvisor) {
889             super(rg, target);
890             this.snapAdvisor = snapAdvisor;
891         }
892
893         protected void move(RouteGraph rg, Object target, double x, double y) {
894             point.setLocation(x, y);
895             snapAdvisor.snap(point);
896             super.move(rg, target, point.getX(), point.getY());
897         }
898
899         public static MoveAction create(RouteGraph rg, double x, double y, double tolerance, TargetFilter filter, ISnapAdvisor snapAdvisor) {
900             Object target = rg.pick(x, y, tolerance, RouteGraph.PICK_LINES | RouteGraph.PICK_INTERIOR_POINTS);
901             if (target != null && (filter == null || filter.accept(target))) {
902                 if (snapAdvisor != null)
903                     return new SnappingMoveAction(rg, target, snapAdvisor);
904                 return new MoveAction(rg, target);
905             }
906             return null;
907         }
908
909     }
910
911     @Override
912     public int getEventMask() {
913         return EventTypes.CommandMask | EventTypes.KeyMask | EventTypes.MouseMask;
914     }
915
916 }