]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram/src/org/simantics/diagram/participant/ConnectTool2.java
Performance and resource consumption optimization for G2D picking
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / participant / ConnectTool2.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in 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.diagram.participant;
13
14 import java.awt.AlphaComposite;
15 import java.awt.BasicStroke;
16 import java.awt.Color;
17 import java.awt.Composite;
18 import java.awt.geom.AffineTransform;
19 import java.awt.geom.Path2D;
20 import java.awt.geom.Point2D;
21 import java.awt.geom.Rectangle2D;
22 import java.util.ArrayDeque;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Deque;
28 import java.util.Iterator;
29 import java.util.List;
30
31 import org.simantics.Simantics;
32 import org.simantics.db.ReadGraph;
33 import org.simantics.db.Resource;
34 import org.simantics.db.WriteGraph;
35 import org.simantics.db.common.request.UniqueRead;
36 import org.simantics.db.common.request.WriteRequest;
37 import org.simantics.db.common.utils.NameUtils;
38 import org.simantics.db.exception.DatabaseException;
39 import org.simantics.diagram.connection.RouteGraph;
40 import org.simantics.diagram.connection.RouteGraphConnectionClass;
41 import org.simantics.diagram.connection.RouteLine;
42 import org.simantics.diagram.connection.RouteTerminal;
43 import org.simantics.diagram.connection.delta.RouteGraphDelta;
44 import org.simantics.diagram.connection.rendering.arrows.PlainLineEndStyle;
45 import org.simantics.diagram.content.ResourceTerminal;
46 import org.simantics.diagram.stubs.DiagramResource;
47 import org.simantics.diagram.synchronization.ISynchronizationContext;
48 import org.simantics.diagram.synchronization.SynchronizationHints;
49 import org.simantics.diagram.synchronization.graph.RouteGraphConnection;
50 import org.simantics.g2d.canvas.ICanvasContext;
51 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
52 import org.simantics.g2d.canvas.impl.DependencyReflection.Reference;
53 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGCleanup;
54 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
55 import org.simantics.g2d.connection.IConnectionAdvisor;
56 import org.simantics.g2d.diagram.DiagramHints;
57 import org.simantics.g2d.diagram.DiagramUtils;
58 import org.simantics.g2d.diagram.IDiagram;
59 import org.simantics.g2d.diagram.handler.PickContext;
60 import org.simantics.g2d.diagram.handler.Topology.Terminal;
61 import org.simantics.g2d.diagram.participant.ElementPainter;
62 import org.simantics.g2d.diagram.participant.TerminalPainter;
63 import org.simantics.g2d.diagram.participant.TerminalPainter.TerminalHoverStrategy;
64 import org.simantics.g2d.diagram.participant.pointertool.AbstractMode;
65 import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;
66 import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil;
67 import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;
68 import org.simantics.g2d.element.ElementClass;
69 import org.simantics.g2d.element.ElementClasses;
70 import org.simantics.g2d.element.ElementUtils;
71 import org.simantics.g2d.element.IElement;
72 import org.simantics.g2d.element.IElementClassProvider;
73 import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
74 import org.simantics.g2d.element.handler.SceneGraph;
75 import org.simantics.g2d.element.handler.TerminalTopology;
76 import org.simantics.g2d.element.handler.impl.BranchPointTerminal;
77 import org.simantics.g2d.element.impl.Element;
78 import org.simantics.g2d.elementclass.BranchPoint;
79 import org.simantics.g2d.elementclass.BranchPoint.Direction;
80 import org.simantics.g2d.elementclass.FlagClass;
81 import org.simantics.g2d.elementclass.FlagHandler;
82 import org.simantics.g2d.participant.RenderingQualityInteractor;
83 import org.simantics.g2d.participant.TransformUtil;
84 import org.simantics.g2d.utils.geom.DirectionSet;
85 import org.simantics.modeling.ModelingResources;
86 import org.simantics.scenegraph.g2d.G2DParentNode;
87 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
88 import org.simantics.scenegraph.g2d.events.KeyEvent;
89 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;
90 import org.simantics.scenegraph.g2d.events.MouseEvent;
91 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonEvent;
92 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;
93 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonReleasedEvent;
94 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;
95 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
96 import org.simantics.scenegraph.g2d.events.command.Commands;
97 import org.simantics.scenegraph.g2d.nodes.BranchPointNode;
98 import org.simantics.scenegraph.g2d.nodes.ShapeNode;
99 import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;
100 import org.simantics.scenegraph.utils.GeometryUtils;
101 import org.simantics.scenegraph.utils.Quality;
102 import org.simantics.structural2.modelingRules.ConnectionJudgement;
103 import org.simantics.utils.datastructures.Pair;
104 import org.simantics.utils.logging.TimeLogger;
105 import org.simantics.utils.ui.ErrorLogger;
106 import org.simantics.utils.ui.ExceptionUtils;
107
108 import gnu.trove.map.hash.THashMap;
109
110 /**
111  * A basic tool for making connection on diagrams.
112  * 
113  * This version defines the starting, ending and route points of a connection.
114  * The routing itself is left up to the diagram router employed by
115  * {@link DiagramUtils#validateAndFix(IDiagram, ICanvasContext)}.
116  * 
117  * Manual:
118  * 
119  * This tool is added to the diagram when a connection sequence is initiated by
120  * another participant. PointerInteractor is one such participant which adds the
121  * tool when a terminal or non-terminal-occupied canvas space is ALT+clicked
122  * (see {@link PointerInteractor#checkInitiateConnectTool(MouseEvent, Point2D)}
123  * ). The connection will be finished when another allowed terminal is clicked
124  * upon or empty canvas space is ALT+clicked. Route points for the connection
125  * can be created by clicking around on non-terminal-occupied canvas space while
126  * connecting.
127  * 
128  * <p>
129  * Connections can be started from and ended in flags by pressing ALT while
130  * left-clicking.
131  * 
132  * @author Tuukka Lehtonen
133  */
134 public class ConnectTool2 extends AbstractMode {
135
136     public static final int          PAINT_PRIORITY        = ElementPainter.ELEMENT_PAINT_PRIORITY + 5;
137
138     @Reference
139     protected RenderingQualityInteractor quality;
140
141     @Dependency
142     protected TransformUtil          util;
143
144     @Dependency
145     protected ElementPainter         diagramPainter;
146
147     @Dependency
148     protected PointerInteractor      pi;
149
150     @Dependency
151     protected PickContext            pickContext;
152
153     /**
154      * Start element terminal of the connection. <code>null</code> if connection
155      * was started from a flag or a branch point.
156      * 
157      * The value is received by the constructor.
158      */
159     protected List<TerminalInfo>     startTerminals;
160
161     /**
162      * Refers to any of the possible overlapping start terminals. The value is
163      * taken from the first index of {@link #startTerminals} assuming that the
164      * first one is the nearest. It is <code>null</code> if
165      * {@link #startTerminals} is empty.
166      */
167     protected TerminalInfo           startTerminal;
168
169     protected TerminalInfo           startFlag;
170
171     /**
172      * Starting position of the connection, received as an external argument.
173      */
174     protected final Point2D          startPos;
175
176     /**
177      * <code>true</code> if this tool should create connection continuation
178      * flags, <code>false</code> otherwise.
179      */
180     protected boolean                createFlags;
181
182     /**
183      * 
184      */
185     protected IElementClassProvider  elementClassProvider;
186
187     /**
188      * 
189      */
190     protected Deque<ControlPoint>    controlPoints         = new ArrayDeque<ControlPoint>();
191
192     /**
193      * Contains <code>null</code> when a connection is started from a new flag
194      * or one of the terminals in {@link #startTerminals} when a connection is
195      * being created starting from a terminal or possibly a set of terminals.
196      * 
197      * <p>
198      * Note that this is different from {@link #startTerminal} which simply
199      * represents the first element of {@link #startTerminals}.
200      * 
201      * <p>
202      * Only when this value and {@link #endTerminal} is properly set will a
203      * connection be created between two element terminals.
204      */
205     protected TerminalInfo           selectedStartTerminal;
206
207     /**
208      * Element terminal of connection end element. <code>null</code> if
209      * connection cannot be ended where it is currently being attempted to end.
210      */
211     protected TerminalInfo           endTerminal;
212
213     /**
214      * The latest connectability judgment from the active
215      * {@link IConnectionAdvisor} should the connection happen between
216      * {@link #selectedStartTerminal} and {@link #endTerminal}.
217      */
218     protected ConnectionJudgement    connectionJudgment;
219
220     /**
221      * The latest connectability judgment from the active
222      * {@link IConnectionAdvisor} should the connection happen between
223      * {@link #selectedStartTerminal} and {@link #lastRouteGraphTarget}.
224      */
225     protected ConnectionJudgement    attachToConnectionJudgement;
226
227     /**
228      * If non-null during connection drawing this field tells the direction
229      * forced for the current branch point by the user through the UI commands
230      * {@link Commands#ROTATE_ELEMENT_CCW} and
231      * {@link Commands#ROTATE_ELEMENT_CW}.
232      */
233     private Direction                forcedBranchPointDirection;
234
235     /**
236      * A temporary variable for use with
237      * {@link TerminalTopology#getTerminals(IElement, Collection)}.
238      */
239     protected Collection<Terminal>   terminals             = new ArrayList<Terminal>();
240
241     /**
242      * Previous mouse canvas position recorded by
243      * {@link #processMouseMove(MouseMovedEvent)}.
244      */
245     protected Point2D                lastMouseCanvasPos    = new Point2D.Double();
246
247     /**
248      * Set to true once {@link #processMouseMove(MouseMovedEvent)} has been
249      * invoked at least once. This is used to tell whether to allow creation of
250      * branch points or finising the connection in thin air. It will not be
251      * allowed if the mouse has not moved at all since starting the connection.
252      */
253     protected boolean                mouseHasMoved         = false;
254
255     protected TerminalHoverStrategy  originalStrategy      = null;
256
257     protected TerminalHoverStrategy  terminalHoverStrategy = new TerminalHoverStrategy() {
258         @Override
259         public boolean highlightEnabled() {
260             return !isEndingInFlag();
261         }
262
263         @Override
264         public boolean highlight(TerminalInfo ti) {
265             boolean reflexive = isStartTerminal(ti.e, ti.t);
266             if (reflexive && !allowReflexiveConnections())
267                 return false;
268
269             return canConnect(ti.e, ti.t) != null;
270         }
271     };
272
273     protected final static Composite ALPHA_COMPOSITE       = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.75f);
274
275     /**
276      * Root scene graph node for all visualization performed by this tool.
277      */
278     protected G2DParentNode          ghostNode;
279
280     /**
281      * Indicates whether the connection is about to be ended into a new
282      * flag/branchpoint or not.
283      */
284     protected TerminalInfo           endFlag;
285
286     protected G2DParentNode          endFlagNode;
287
288     private RouteGraphTarget         lastRouteGraphTarget;
289
290     /**
291      * @param startTerminal
292      * @param mouseId
293      * @param startCanvasPos
294      */
295     public ConnectTool2(TerminalInfo startTerminal, int mouseId, Point2D startCanvasPos) {
296         this(startTerminal == null ? Collections.<TerminalInfo> emptyList()
297                 : Collections.singletonList(startTerminal),
298                 mouseId,
299                 startCanvasPos);
300     }
301
302     /**
303      * @param startTerminals
304      * @param mouseId
305      * @param startCanvasPos
306      */
307     public ConnectTool2(List<TerminalInfo> startTerminals, int mouseId, Point2D startCanvasPos) {
308         super(mouseId);
309
310         if (startCanvasPos == null)
311             throw new NullPointerException("null start position");
312         if (startTerminals == null)
313             throw new NullPointerException("null start terminals");
314
315         this.startPos = startCanvasPos;
316         this.lastMouseCanvasPos.setLocation(startPos);
317
318         this.startTerminals = startTerminals;
319         this.startTerminal = startTerminals.isEmpty() ? null : startTerminals.get(0);
320     }
321
322     @Override
323     public void addedToContext(ICanvasContext ctx) {
324         super.addedToContext(ctx);
325
326         if (quality != null)
327             quality.setStaticQuality(Quality.LOW);
328
329         // Force terminals to always be highlighted without pressing certain
330         // keys or key combinations.
331         originalStrategy = getHint(TerminalPainter.TERMINAL_HOVER_STRATEGY);
332         setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
333     }
334
335     @Override
336     protected void onDiagramSet(IDiagram newDiagram, IDiagram oldDiagram) {
337         if (newDiagram != null) {
338             // Get IElementClassProvider
339             ISynchronizationContext ctx = newDiagram.getHint(SynchronizationHints.CONTEXT);
340             if (ctx != null) {
341                 this.elementClassProvider = ctx.get(SynchronizationHints.ELEMENT_CLASS_PROVIDER);
342             }
343
344             // See if flags should be created or not.
345             this.createFlags = Boolean.TRUE.equals(newDiagram.getHint(DiagramHints.KEY_USE_CONNECTION_FLAGS));
346             startConnection();
347         }
348     }
349
350     @Override
351     public void removedFromContext(ICanvasContext ctx) {
352         if (getHint(TerminalPainter.TERMINAL_HOVER_STRATEGY) == terminalHoverStrategy) {
353             if (originalStrategy != null)
354                 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, originalStrategy);
355             else
356                 removeHint(TerminalPainter.TERMINAL_HOVER_STRATEGY);
357         }
358
359         if (quality != null)
360             quality.setStaticQuality(null);
361
362         super.removedFromContext(ctx);
363     }
364
365     protected void startConnection() {
366         Point2D startPos = (Point2D) this.startPos.clone();
367         ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
368         if (snapAdvisor != null)
369             snapAdvisor.snap(startPos);
370
371         // Resolve the first element and terminal of the connection.
372         ControlPoint start = new ControlPoint(startPos);
373
374         if (startTerminal != null) {
375             assert ElementUtils.peekDiagram(startTerminal.e) == diagram;
376             Point2D terminalPos = new Point2D.Double(startTerminal.posDia.getTranslateX(),
377                     startTerminal.posDia.getTranslateY());
378             start.setPosition(terminalPos).setAttachedToTerminal(startTerminal);
379         } else {
380             // Create TerminalInfo describing the flag to be created.
381             if (createFlags) {
382                 // This prevents connection creation from creating a branch
383                 // point in place of this flag.
384                 startFlag = createFlag(EdgeEnd.Begin);
385                 start.setAttachedToTerminal(startFlag);
386                 showElement(ghostNode, "startFlag", startFlag.e, startPos);
387             }
388         }
389         controlPoints.add(start);
390         controlPoints.add(new ControlPoint(startPos));
391
392         // Make sure that we are ending with a flag if ALT is pressed.
393         // This makes the tool always start with a flag which can be quite
394         // cumbersome and is therefore disabled. The current version will not
395         // end the connection if the mouse has not moved at all.
396         //if (keyUtil.isKeyPressed(java.awt.event.KeyEvent.VK_ALT)) {
397         //    endWithoutTerminal(lastMouseCanvasPos, true);
398         //}
399     }
400
401     @SGInit
402     public void initSG(G2DParentNode parent) {
403         ghostNode = parent.addNode(G2DParentNode.class);
404         ghostNode.setZIndex(PAINT_PRIORITY);
405
406         ShapeNode pathNode = ghostNode.getOrCreateNode("path", ShapeNode.class);
407         pathNode.setColor(new Color(160, 0, 0));
408         pathNode.setStroke(new BasicStroke(0.1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10,
409                 new float[] { 0.5f, 0.2f }, 0));
410         pathNode.setScaleStroke(false);
411         pathNode.setZIndex(0);
412
413         G2DParentNode points = ghostNode.getOrCreateNode("points", G2DParentNode.class);
414         points.setZIndex(1);
415
416         updateSG();
417     }
418
419     private RouteTerminal addControlPoint(RouteGraph routeGraph, ControlPoint cp) {
420         TerminalInfo ti = cp.getAttachedTerminal();
421         if(ti != null && ti != startFlag && ti != endFlag) {
422             Rectangle2D bounds = ElementUtils.getElementBoundsOnDiagram(ti.e, new Rectangle2D.Double());
423             GeometryUtils.expandRectangle(bounds, 2);
424             int allowedDirections = RouteGraphConnectionClass.shortestDirectionOutOfBounds(
425                     ti.posDia.getTranslateX(), ti.posDia.getTranslateY(), bounds);
426             return routeGraph.addTerminal(ti.posDia.getTranslateX(), ti.posDia.getTranslateY(),
427                     bounds, allowedDirections, PlainLineEndStyle.INSTANCE);
428         }
429         else {
430             double x = cp.getPosition().getX();
431             double y = cp.getPosition().getY();
432             int allowedDirections = 0xf;
433             switch(cp.getDirection()) {
434             case Horizontal: allowedDirections = 5; break;
435             case Vertical: allowedDirections = 10; break;
436             case Any: allowedDirections = 15; break;
437             }
438             return routeGraph.addTerminal(x, y, x, y, x, y, allowedDirections);
439         }
440     }
441     
442     protected void updateSG() {
443         if (controlPoints.size() != 2)
444             return;
445
446         ControlPoint begin = controlPoints.getFirst();
447         ControlPoint end = controlPoints.getLast();
448
449         RouteGraph routeGraph = new RouteGraph();
450         RouteTerminal a = addControlPoint(routeGraph, begin);
451         RouteTerminal b = addControlPoint(routeGraph, end);
452         routeGraph.link(a, b);
453
454         Path2D path = routeGraph.getPath2D();
455
456         // Create scene graph to visualize the connection.
457         ShapeNode pathNode = ghostNode.getOrCreateNode("path", ShapeNode.class);
458         pathNode.setShape(path);
459
460         setDirty();
461     }
462
463     private G2DParentNode showElement(G2DParentNode parent, String nodeId, IElement element, Point2D pos) {
464         return showElement(parent, nodeId, element, AffineTransform.getTranslateInstance(pos.getX(), pos.getY()));
465     }
466
467     private G2DParentNode showElement(G2DParentNode parent, String nodeId, IElement element, AffineTransform tr) {
468         G2DParentNode elementParent = parent.getOrCreateNode(nodeId, G2DParentNode.class);
469         elementParent.setTransform(tr);
470         elementParent.removeNodes();
471         for (SceneGraph sg : element.getElementClass().getItemsByClass(SceneGraph.class))
472             sg.init(element, elementParent);
473         return elementParent;
474     }
475
476     @SGCleanup
477     public void cleanupSG() {
478         ghostNode.remove();
479         ghostNode = null;
480     }
481
482     @EventHandler(priority = 200)
483     public boolean handleCommandEvents(CommandEvent ce) {
484         if (ce.command.equals(Commands.CANCEL)) {
485             setDirty();
486             remove();
487             return true;
488         } else if (ce.command.equals(Commands.ROTATE_ELEMENT_CCW) || ce.command.equals(Commands.ROTATE_ELEMENT_CW)) {
489             return rotateLastBranchPoint(ce.command.equals(Commands.ROTATE_ELEMENT_CW));
490         }
491         return false;
492     }
493
494     @EventHandler(priority = PointerInteractor.TOOL_PRIORITY + 20)
495     public boolean handleKeyEvents(KeyEvent ke) {
496         if (ke instanceof KeyPressedEvent) {
497             // Back-space, cancel prev bend
498             if (ke.keyCode == java.awt.event.KeyEvent.VK_BACK_SPACE)
499                 return cancelPreviousBend();
500         }
501
502         if (ke.keyCode == java.awt.event.KeyEvent.VK_ALT) {
503             if (createFlags) {
504                 endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(ke instanceof KeyPressedEvent));
505                 return true;
506             }
507         }
508
509         return false;
510     }
511
512     @EventHandler(priority = PointerInteractor.TOOL_PRIORITY + 20)
513     public boolean handleEvent(MouseEvent me) {
514         // Only handle events for the connection-initiating mouse
515         if (me.mouseId != mouseId)
516             return false;
517
518         if (me instanceof MouseMovedEvent)
519             return processMouseMove((MouseMovedEvent) me);
520
521         if (me instanceof MouseButtonPressedEvent)
522             return processMouseButtonPress((MouseButtonPressedEvent) me);
523
524         // #7653: Support creating connections between terminals without lifting mouse button in between.
525         if (me instanceof MouseButtonReleasedEvent)
526             return processMouseButtonRelease((MouseButtonReleasedEvent) me);
527
528         return false;
529     }
530
531     protected boolean processMouseMove(MouseMovedEvent me) {
532         mouseHasMoved = true;
533
534         Point2D mouseControlPos = me.controlPosition;
535         Point2D mouseCanvasPos = util.controlToCanvas(mouseControlPos, new Point2D.Double());
536
537         ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
538         if (snapAdvisor != null)
539             snapAdvisor.snap(mouseCanvasPos);
540
541         // Record last snapped canvas position of mouse.
542         this.lastMouseCanvasPos.setLocation(mouseCanvasPos);
543
544         if (isEndingInFlag()) {
545             endFlagNode.setTransform(AffineTransform.getTranslateInstance(mouseCanvasPos.getX(), mouseCanvasPos.getY()));
546         }
547
548         List<TerminalInfo> tis = pi.pickTerminals(me.controlPosition);
549         tis = TerminalUtil.findNearestOverlappingTerminals(tis);
550         if (!tis.isEmpty() && !containsStartTerminal(tis)) {
551             //System.out.println("end terminals (" + tis.size() + "):\n" + EString.implode(tis));
552             for (TerminalInfo ti : tis) {
553                 Pair<ConnectionJudgement, TerminalInfo> canConnect = canConnect(ti.e, ti.t);
554                 if (canConnect != null) {
555                     connectionJudgment = canConnect.first;
556
557                     if (!isEndingInFlag() || !TerminalUtil.isSameTerminal(ti, endTerminal)) {
558                         if (canConnect.second != null) {
559                             controlPoints.getFirst()
560                             .setPosition(canConnect.second.posDia)
561                             .setAttachedToTerminal(canConnect.second);
562                         }
563                         controlPoints.getLast()
564                         .setPosition(ti.posDia)
565                         .setAttachedToTerminal(ti);
566
567                         selectedStartTerminal = canConnect.second;
568                         endTerminal = ti;
569                     }
570
571                     // Make sure that we are ending with a flag if ALT is pressed
572                     // and no end terminal is defined.
573                     if (!endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me)))
574                         updateSG();
575                     return false;
576                 }
577             }
578         } else {
579             RouteGraphTarget cp = RouteGraphConnectTool.pickRouteGraphConnection(
580                     getContext(),
581                     diagram,
582                     pi.getCanvasPickShape(me.controlPosition),
583                     pi.getPickDistance());
584             if (cp != null) {
585                 // Remove branch point highlight from previously picked route graph.
586                 if (lastRouteGraphTarget != null && cp.getNode() != lastRouteGraphTarget.getNode())
587                     cp.getNode().showBranchPoint(null);
588                 lastRouteGraphTarget = cp;
589
590                 // Validate connection before visualizing connectability
591                 Point2D isectPos = cp.getIntersectionPosition();
592                 TerminalInfo ti = TerminalInfo.create(
593                         isectPos,
594                         cp.getElement(),
595                         BranchPointTerminal.existingTerminal(
596                                 isectPos,
597                                 DirectionSet.ANY,
598                                 BranchPointNode.SHAPE),
599                         BranchPointNode.SHAPE);
600                 Pair<ConnectionJudgement, TerminalInfo> canConnect = canConnect(ti.e, ti.t);
601                 if (canConnect != null) {
602                     attachToConnectionJudgement = canConnect.first;
603                     controlPoints.getLast().setPosition(ti.posDia).setAttachedToTerminal(ti);
604                     endTerminal = ti;
605                     cp.getNode().showBranchPoint(isectPos);
606                     if (!endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me)))
607                         updateSG();
608                     return false;
609                 }
610             } else {
611                 if (lastRouteGraphTarget != null) {
612                     lastRouteGraphTarget.getNode().showBranchPoint(null);
613                     lastRouteGraphTarget = null;
614                 }
615             }
616         }
617
618         connectionJudgment = null;
619         attachToConnectionJudgement = null;
620         if (isEndTerminalDefined()) {
621             // CASE: Mouse was previously on top of a valid terminal to end
622             // the connection. Now the mouse has been moved where there is
623             // no longer a terminal to connect to.
624             //
625             // => Disconnect the last edge segment from the previous
626             // terminal, mark endElement/endTerminal non-existent
627             // and connect the disconnected edge to a new branch point.
628
629             controlPoints.getLast()
630             .setPosition(mouseCanvasPos)
631             .setDirection(calculateCurrentBranchPointDirection())
632             .setAttachedToTerminal(null);
633
634             endTerminal = null;
635         } else {
636             // CASE: Mouse was not previously on top of a valid ending
637             // element terminal.
638             //
639             // => Move and re-orient last branch point.
640
641             controlPoints.getLast()
642             .setPosition(mouseCanvasPos)
643             .setDirection(calculateCurrentBranchPointDirection());
644         }
645
646         // Make sure that we are ending with a flag if ALT is pressed and no end
647         // terminal is defined.
648         if (!endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me)))
649             updateSG();
650
651         return false;
652     }
653
654     protected boolean processMouseButtonPress(MouseButtonPressedEvent e) {
655         MouseButtonEvent me = e;
656
657         // Do nothing before the mouse has moved at least a little.
658         // This prevents the user from ending the connection right where
659         // it started.
660         if (!mouseHasMoved)
661             return true;
662
663         if (me.button == MouseEvent.LEFT_BUTTON) {
664             Point2D mouseControlPos = me.controlPosition;
665             Point2D mouseCanvasPos = util.getInverseTransform().transform(mouseControlPos, new Point2D.Double());
666
667             ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
668             if (snapAdvisor != null)
669                 snapAdvisor.snap(mouseCanvasPos);
670
671             if (tryEndConnection()) {
672                 return true;
673             } else {
674                 // Finish connection in thin air only if the
675                 // connection was started from a valid terminal.
676                 if (me.hasAnyModifier(MouseEvent.ALT_MASK | MouseEvent.ALT_GRAPH_MASK) && !startTerminals.isEmpty()) {
677                     Pair<ConnectionJudgement, TerminalInfo> pair = canConnect(null, null);
678                     if (pair != null) {
679                         connectionJudgment = (ConnectionJudgement) pair.first;
680                         selectedStartTerminal = pair.second;
681 //                        endFlag = createFlag(EdgeEnd.End);
682 //                        controlPoints.getLast().setAttachedToTerminal(endFlag);
683                         createConnection();
684                         setDirty();
685                         remove();
686                     } else {
687                         // Inform the user why connection couldn't be created.
688                         String tmsg = terminalsToString(startTerminals);
689                         ErrorLogger.defaultLogWarning("Can't resolve connection type for new connection when starting from one of the following terminals:\n" + tmsg, null);
690                     }
691                     return true;
692                 } else if (routePointsAllowed()
693                         && (me.stateMask & (MouseEvent.ALT_MASK | MouseEvent.SHIFT_MASK | MouseEvent.CTRL_MASK)) == 0) {
694                     // Add new connection control point.
695                     controlPoints.add(newControlPointWithCalculatedDirection(mouseCanvasPos));
696                     resetForcedBranchPointDirection();
697                     updateSG();
698                 }
699             }
700
701             // Eat the event to prevent other participants from doing
702             // incompatible things while in this connection mode.
703             return true;
704         } else if (me.button == MouseEvent.RIGHT_BUTTON) {
705             return cancelPreviousBend();
706         }
707
708         return false;
709     }
710
711     private int mouseLeftReleaseCount = 0;
712
713     protected boolean processMouseButtonRelease(MouseButtonReleasedEvent me) {
714         if (me.button == MouseEvent.LEFT_BUTTON
715                 && ++mouseLeftReleaseCount == 1) {
716             return tryEndConnection();
717         }
718         return false;
719     }
720
721     /**
722      * @return <code>true</code> if connection was successfully ended
723      */
724     private boolean tryEndConnection() {
725         if (isEndTerminalDefined() && connectionJudgment != null) {
726             createConnection();
727             remove();
728             return true;
729         } else if (lastRouteGraphTarget != null && attachToConnectionJudgement != null) {
730             lastRouteGraphTarget.getNode().showBranchPoint(null);
731             attachToConnection();
732             remove();
733             return true;
734         }
735         return false;
736     }
737
738     private void attachToConnection() {
739         ConnectionJudgement judgment = this.attachToConnectionJudgement;
740         if (judgment == null) {
741             ErrorLogger.defaultLogError("Cannot attach to connection, no judgment available on connection validity", null);
742             return;
743         }
744
745         ConnectionBuilder builder = new ConnectionBuilder(this.diagram);
746         RouteGraph before = lastRouteGraphTarget.getNode().getRouteGraph();
747         THashMap<Object, Object> copyMap = new THashMap<>();
748         RouteGraph after = before.copy(copyMap);
749
750         RouteLine attachTo = (RouteLine) copyMap.get(lastRouteGraphTarget.getLine());
751         after.makePersistent(attachTo);
752         for (RouteLine line : after.getAllLines()) {
753             if (!line.isTransient() && line.isHorizontal() == attachTo.isHorizontal()
754                     && line.getPosition() == attachTo.getPosition()) {
755                 attachTo = line;
756                 break;
757             }
758         }
759         RouteLine attachToLine = attachTo;
760         RouteGraphDelta delta = new RouteGraphDelta(before, after);
761
762         Simantics.getSession().asyncRequest(new WriteRequest() {
763             @Override
764             public void perform(WriteGraph graph) throws DatabaseException {
765                 graph.markUndoPoint();
766                 Resource connection = ElementUtils.getObject(endTerminal.e);
767                 if (!delta.isEmpty()) {
768                     new RouteGraphConnection(graph, connection).synchronize(graph, before, after, delta);
769                 }
770                 Resource line = RouteGraphConnection.deserialize(graph, attachToLine.getData());
771                 Deque<ControlPoint> cps = new ArrayDeque<>();
772                 for (Iterator<ControlPoint> iterator = controlPoints.descendingIterator(); iterator.hasNext();)
773                     cps.add(iterator.next());
774                 builder.attachToRouteGraph(graph, judgment, connection, line, cps, startTerminal, FlagClass.Type.In);
775             }
776         }, parameter -> {
777             if (parameter != null)
778                 ExceptionUtils.logAndShowError(parameter);
779         });
780     }
781
782     protected boolean cancelPreviousBend() {
783         if (!routePointsAllowed())
784             return false;
785
786         // Just to make this code more comprehensible, prevent an editing
787         // case that requires ugly code to work.
788         if (isEndingInFlag())
789             return true;
790
791         // If there are no real route points, cancel whole connection.
792         if (controlPoints.size() <= 2) {
793             setDirty();
794             remove();
795             return true;
796         }
797
798         // Cancel last bend
799         controlPoints.removeLast();
800         controlPoints.getLast().setPosition(lastMouseCanvasPos);
801         resetForcedBranchPointDirection();
802
803         updateSG();
804         return true;
805     }
806
807     /**
808      * Rotates the last branch point in the created connection in either
809      * clockwise or counter-clockwise direction as a response to a user
810      * interaction.
811      * 
812      * <p>
813      * At the same time it use {@link #forcedBranchPointDirection} to mark the
814      * current last branch point to be forcefully oriented according to the
815      * users wishes instead of calculating a default value for the orientation
816      * from the routed connection path. See
817      * {@link #calculateCurrentBranchPointDirection()} for more information on
818      * this.
819      * 
820      * <p>
821      * The logic of this method goes as follows:
822      * <ul>
823      * <li>Calculate the current branch point direction</li>
824      * <li>If the branch point direction is currently user selected (
825      * {@link #forcedBranchPointDirection}</li>
826      * <li></li>
827      * <li></li>
828      * </ul>
829      * 
830      * @param clockwise
831      * @return <code>true</code> if the rotation was successful
832      */
833     protected boolean rotateLastBranchPoint(boolean clockwise) {
834         Direction oldDir = calculateCurrentBranchPointDirection();
835
836         if (forcedBranchPointDirection == null) {
837             forcedBranchPointDirection = oldDir.toggleDetermined();
838         } else {
839             forcedBranchPointDirection = clockwise ? oldDir.cycleNext() : oldDir.cyclePrevious();
840         }
841
842         controlPoints.getLast().setDirection(forcedBranchPointDirection);
843
844         updateSG();
845
846         return true;
847     }
848
849     /**
850      * Set preferred direction for a branch/route point element.
851      * 
852      * @param branchPoint the element to set the direction for
853      * @param direction the direction to set
854      * @return
855      */
856     protected void setDirection(IElement branchPoint, Direction direction) {
857         branchPoint.getElementClass().getSingleItem(BranchPoint.class).setDirectionPreference(branchPoint, direction);
858     }
859
860     protected Direction forcedBranchPointDirection() {
861         return forcedBranchPointDirection;
862     }
863
864     protected void resetForcedBranchPointDirection() {
865         forcedBranchPointDirection = null;
866     }
867
868     protected void forceBranchPointDirection(Direction direction) {
869         forcedBranchPointDirection = direction;
870     }
871
872     /**
873      * @return
874      */
875     protected Direction calculateCurrentBranchPointDirection() {
876         // If this is not the first branch point, toggle direction compared to
877         // last.
878         if (forcedBranchPointDirection != null)
879             return forcedBranchPointDirection;
880
881         if (controlPoints.size() > 2) {
882             // This is not the first edge segment, toggle route point
883             // directions.
884             Iterator<ControlPoint> it = controlPoints.descendingIterator();
885             it.next();
886             ControlPoint secondLastCp = it.next();
887
888             Direction dir = secondLastCp.getDirection();
889             switch (dir) {
890                 case Horizontal:
891                     return Direction.Vertical;
892                 case Vertical:
893                     return Direction.Horizontal;
894                 case Any:
895             }
896         }
897
898         // If this is the first branch point, calculate based on edge segment
899         // angle.
900         if (controlPoints.size() > 1) {
901             Iterator<ControlPoint> it = controlPoints.descendingIterator();
902             ControlPoint last = it.next();
903             ControlPoint secondLast = it.next();
904
905             double angle = Math.atan2(Math.abs(last.getPosition().getY() - secondLast.getPosition().getY()),
906                     Math.abs(last.getPosition().getX() - secondLast.getPosition().getX()));
907
908             if (angle >= 0 && angle < Math.PI / 4) {
909                 return Direction.Horizontal;
910             } else if (angle > Math.PI / 4 && angle <= Math.PI / 2) {
911                 return Direction.Vertical;
912             }
913         }
914
915         return Direction.Any;
916     }
917
918     protected boolean isEndingInFlag() {
919         return endFlag != null;
920     }
921
922     /**
923      * @param mousePos
924      * @param altDown
925      * @return <code>true</code> if updateSG was executed, <code>false</code>
926      *         otherwise
927      */
928     protected boolean endWithoutTerminal(Point2D mousePos, boolean altDown) {
929         // Just go with branch points if flags are not allowed.
930         if (!createFlags)
931             return false;
932
933         boolean endTerminalDefined = isEndTerminalDefined();
934
935         if (altDown) {
936             if (!isEndingInFlag()) {
937                 endFlag = createFlag(EdgeEnd.End);
938                 endFlagNode = showElement(ghostNode, "endFlag", endFlag.e, mousePos);
939                 controlPoints.getLast()
940                 .setDirection(calculateCurrentBranchPointDirection())
941                 .setAttachedToTerminal(endFlag);
942
943                 // TerminalPainter must refresh
944                 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
945
946                 updateSG();
947                 return true;
948             }
949         } else {
950             if (isEndingInFlag()) {
951                 // Currently ending with flag but ALT is no longer down
952                 // so that flag must be removed.
953                 endFlag = null;
954                 endFlagNode.remove();
955                 endFlagNode = null;
956
957                 ControlPoint cp = controlPoints.getLast();
958                 cp.setDirection(calculateCurrentBranchPointDirection())
959                 .setAttachedToTerminal(endTerminal);
960
961                 if (endTerminalDefined) {
962                     cp.setPosition(endTerminal.posDia);
963                 } else {
964                     cp.setPosition(mousePos);
965                 }
966
967                 // Force TerminalPainter refresh
968                 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
969
970                 updateSG();
971                 return true;
972             }
973         }
974         return false;
975     }
976
977     protected void createConnection() {
978         createConnection(
979                 this.selectedStartTerminal,
980                 this.endTerminal,
981                 this.connectionJudgment,
982                 this.controlPoints);
983     }
984
985     protected void createConnection(
986             final TerminalInfo startTerminal,
987             final TerminalInfo endTerminal,
988             final ConnectionJudgement judgement,
989             final Deque<ControlPoint> controlPoints)
990     {
991         TimeLogger.resetTimeAndLog(getClass(), "createConnection");
992         if (judgement == null) {
993             // Inform the user why connection couldn't be created.
994             String tmsg = terminalsToString(Arrays.asList(startTerminal, endTerminal));
995             ErrorLogger.defaultLogError("Cannot create connection, no judgment available on connection validity when connecting the terminals:\n" + tmsg, null);
996             return;
997         }
998
999         final ConnectionBuilder builder = new ConnectionBuilder(this.diagram);
1000
1001         Simantics.getSession().asyncRequest(new WriteRequest() {
1002             @Override
1003             public void perform(WriteGraph graph) throws DatabaseException {
1004                 builder.create(graph, judgement, controlPoints, startTerminal, endTerminal);
1005             }
1006         }, parameter -> {
1007             if (parameter != null)
1008                 ExceptionUtils.logAndShowError(parameter);
1009         });
1010     }
1011
1012     /**
1013      * @param canvasPos
1014      * @return
1015      */
1016     protected ControlPoint newControlPointWithCalculatedDirection(Point2D canvasPos) {
1017         return new ControlPoint(canvasPos, calculateCurrentBranchPointDirection());
1018     }
1019
1020     /**
1021      * @param e
1022      * @param t
1023      * @return <code>true</code> if the specified element terminal matches any
1024      *         TerminalInfo in {@link #startTerminals}
1025      */
1026     protected boolean isStartTerminal(IElement e, Terminal t) {
1027         if (startTerminal == null)
1028             return false;
1029         for (TerminalInfo st : startTerminals) {
1030             if (st.e == e && st.t == t) {
1031                 return true;
1032             }
1033         }
1034         return false;
1035     }
1036
1037     /**
1038      * @param e
1039      * @param t
1040      * @return <code>true</code> if the specified element terminal matches any
1041      *         TerminalInfo in {@link #startTerminals}
1042      */
1043     protected boolean containsStartTerminal(List<TerminalInfo> tis) {
1044         if (startTerminal == null)
1045             return false;
1046         for (TerminalInfo st : startTerminals) {
1047             for (TerminalInfo et : tis) {
1048                 if (st.e == et.e && st.t == et.t) {
1049                     return true;
1050                 }
1051             }
1052         }
1053         return false;
1054     }
1055
1056     protected static FlagClass.Type endToFlagType(EdgeEnd end) {
1057         switch (end) {
1058             case Begin:
1059                 return FlagClass.Type.In;
1060             case End:
1061                 return FlagClass.Type.Out;
1062             default:
1063                 throw new IllegalArgumentException("unrecognized edge end: " + end);
1064         }
1065     }
1066
1067     protected TerminalInfo createFlag(EdgeEnd connectionEnd) {
1068         ElementClass flagClass = elementClassProvider.get(ElementClasses.FLAG);
1069         IElement e = Element.spawnNew(flagClass);
1070
1071         e.setHint(FlagClass.KEY_FLAG_TYPE, endToFlagType(connectionEnd));
1072         e.setHint(FlagClass.KEY_FLAG_MODE, FlagClass.Mode.Internal);
1073
1074         TerminalInfo ti = new TerminalInfo();
1075         ti.e = e;
1076         ti.t = ElementUtils.getSingleTerminal(e);
1077         ti.posElem = TerminalUtil.getTerminalPosOnElement(e, ti.t);
1078         ti.posDia = TerminalUtil.getTerminalPosOnDiagram(e, ti.t);
1079
1080         return ti;
1081     }
1082
1083     protected boolean shouldEndWithFlag(MouseEvent me) {
1084         return shouldEndWithFlag( me.hasAnyModifier(MouseEvent.ALT_MASK | MouseEvent.ALT_GRAPH_MASK) );
1085     }
1086
1087     protected boolean shouldEndWithFlag(boolean altPressed) {
1088         return altPressed && !isEndTerminalDefined() && createFlags && startFlag == null;
1089     }
1090
1091     protected boolean isEndTerminalDefined() {
1092         return endTerminal != null;
1093     }
1094
1095     protected boolean isFlagTerminal(TerminalInfo ti) {
1096         return ti.e.getElementClass().containsClass(FlagHandler.class);
1097     }
1098
1099     protected boolean allowReflexiveConnections() {
1100         return false;
1101     }
1102
1103     protected boolean routePointsAllowed() {
1104         return Boolean.TRUE.equals(diagram.getHint(DiagramHints.KEY_ALLOW_ROUTE_POINTS));
1105     }
1106
1107     /**
1108      * @param endElement
1109      * @param endTerminal
1110      * @return
1111      */
1112     @SuppressWarnings("unchecked")
1113     protected final Pair<ConnectionJudgement, TerminalInfo> canConnect(IElement endElement, Terminal endTerminal) {
1114         IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);
1115         Object judgement = canConnect(advisor, endElement, endTerminal);
1116         if (judgement == null)
1117             return null;
1118         if (judgement instanceof Pair<?, ?>)
1119             return (Pair<ConnectionJudgement, TerminalInfo>) judgement;
1120         return Pair.<ConnectionJudgement, TerminalInfo>make((ConnectionJudgement) judgement, startTerminal);
1121     }
1122
1123     protected Object canConnect(IConnectionAdvisor advisor, IElement endElement, Terminal endTerminal) {
1124         if (advisor == null)
1125             return Pair.make(ConnectionJudgement.CANBEMADELEGAL, startTerminal);
1126         if (startTerminals.isEmpty()) {
1127             ConnectionJudgement obj = (ConnectionJudgement) advisor.canBeConnected(null, null, null, endElement, endTerminal);
1128             return obj != null ? Pair.<ConnectionJudgement, TerminalInfo>make(obj, null) : null;
1129         }
1130         for (TerminalInfo st : startTerminals) {
1131             ConnectionJudgement obj = (ConnectionJudgement) advisor.canBeConnected(null, st.e, st.t, endElement, endTerminal);
1132             if (obj != null) {
1133                 return Pair.make(obj, st);
1134             }
1135         }
1136         return null;
1137     }
1138
1139     /**
1140      * For generating debugging information of what was attempted by the user
1141      * when a connection couldn't be created.
1142      * 
1143      * @param ts
1144      * @return
1145      */
1146     private String terminalsToString(final Iterable<TerminalInfo> ts) {
1147         try {
1148             return Simantics.sync(new UniqueRead<String>() {
1149                 @Override
1150                 public String perform(ReadGraph graph) throws DatabaseException {
1151                     DiagramResource DIA = DiagramResource.getInstance(graph);
1152                     ModelingResources MOD = ModelingResources.getInstance(graph);
1153                     StringBuilder sb = new StringBuilder();
1154                     boolean first = true;
1155                     for (TerminalInfo ti : ts) {
1156                         if (!first)
1157                             sb.append("\n");
1158                         first = false;
1159                         sb.append("element ");
1160                         Object o = ElementUtils.getObject(ti.e);
1161                         if (o instanceof Resource) {
1162                             Resource er = (Resource) o;
1163                             Resource cer = graph.getPossibleObject(er, MOD.ElementToComponent);
1164                             Resource r = cer != null ? cer : er;
1165                             sb.append(NameUtils.getSafeName(graph, r)).append(" : ");
1166                             for (Resource type : graph.getPrincipalTypes(r)) {
1167                                 sb.append(NameUtils.getSafeName(graph, type, true));
1168                             }
1169                         } else {
1170                             sb.append(ti.e.toString());
1171                         }
1172                         sb.append(", terminal ");
1173                         if (ti.t instanceof ResourceTerminal) {
1174                             Resource tr = ((ResourceTerminal) ti.t).getResource();
1175                             Resource cp = graph.getPossibleObject(tr, DIA.HasConnectionPoint);
1176                             Resource r = cp != null ? cp : tr;
1177                             sb.append(NameUtils.getSafeName(graph, r, true));
1178                         } else {
1179                             sb.append(ti.t.toString());
1180                         }
1181                     }
1182                     return sb.toString();
1183                 }
1184             });
1185         } catch (DatabaseException e) {
1186             return e.getMessage();
1187         }
1188     }
1189
1190 }