1 /*******************************************************************************
2 * Copyright (c) 2007, 2016 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 * Semantum Oy - Fixed bug #6364
12 *******************************************************************************/
13 package org.simantics.diagram.participant;
15 import java.awt.AlphaComposite;
16 import java.awt.Composite;
17 import java.awt.Shape;
18 import java.awt.geom.AffineTransform;
19 import java.awt.geom.Point2D;
20 import java.awt.geom.Rectangle2D;
21 import java.util.ArrayDeque;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Deque;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
30 import org.simantics.Simantics;
31 import org.simantics.db.Resource;
32 import org.simantics.db.WriteGraph;
33 import org.simantics.db.common.request.WriteRequest;
34 import org.simantics.db.exception.DatabaseException;
35 import org.simantics.diagram.connection.RouteGraph;
36 import org.simantics.diagram.connection.RouteGraphConnectionClass;
37 import org.simantics.diagram.connection.RouteLine;
38 import org.simantics.diagram.connection.RoutePoint;
39 import org.simantics.diagram.connection.RouteTerminal;
40 import org.simantics.diagram.connection.delta.RouteGraphDelta;
41 import org.simantics.diagram.connection.rendering.IRouteGraphRenderer;
42 import org.simantics.diagram.connection.rendering.arrows.ArrowLineEndStyle;
43 import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;
44 import org.simantics.diagram.connection.rendering.arrows.PlainLineEndStyle;
45 import org.simantics.diagram.synchronization.ISynchronizationContext;
46 import org.simantics.diagram.synchronization.SynchronizationHints;
47 import org.simantics.diagram.synchronization.graph.RouteGraphConnection;
48 import org.simantics.g2d.canvas.ICanvasContext;
49 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
50 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGCleanup;
51 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
52 import org.simantics.g2d.connection.ConnectionEntity;
53 import org.simantics.g2d.connection.IConnectionAdvisor;
54 import org.simantics.g2d.diagram.DiagramHints;
55 import org.simantics.g2d.diagram.DiagramUtils;
56 import org.simantics.g2d.diagram.IDiagram;
57 import org.simantics.g2d.diagram.handler.PickRequest;
58 import org.simantics.g2d.diagram.handler.Topology.Connection;
59 import org.simantics.g2d.diagram.handler.Topology.Terminal;
60 import org.simantics.g2d.diagram.participant.ElementPainter;
61 import org.simantics.g2d.diagram.participant.TerminalPainter;
62 import org.simantics.g2d.diagram.participant.TerminalPainter.TerminalHoverStrategy;
63 import org.simantics.g2d.diagram.participant.pointertool.AbstractMode;
64 import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;
65 import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil;
66 import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;
67 import org.simantics.g2d.element.ElementClass;
68 import org.simantics.g2d.element.ElementClasses;
69 import org.simantics.g2d.element.ElementHints;
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.FlagClass;
79 import org.simantics.g2d.elementclass.FlagHandler;
80 import org.simantics.g2d.participant.TransformUtil;
81 import org.simantics.g2d.utils.geom.DirectionSet;
82 import org.simantics.scenegraph.g2d.G2DParentNode;
83 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
84 import org.simantics.scenegraph.g2d.events.KeyEvent;
85 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;
86 import org.simantics.scenegraph.g2d.events.MouseEvent;
87 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonEvent;
88 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;
89 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonReleasedEvent;
90 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;
91 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
92 import org.simantics.scenegraph.g2d.events.command.Commands;
93 import org.simantics.scenegraph.g2d.nodes.BranchPointNode;
94 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
95 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
96 import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;
97 import org.simantics.scenegraph.utils.GeometryUtils;
98 import org.simantics.structural2.modelingRules.ConnectionJudgement;
99 import org.simantics.utils.datastructures.Pair;
100 import org.simantics.utils.datastructures.Triple;
101 import org.simantics.utils.logging.TimeLogger;
102 import org.simantics.utils.ui.ErrorLogger;
103 import org.simantics.utils.ui.ExceptionUtils;
105 import gnu.trove.map.hash.THashMap;
108 * A basic tool for making connection on diagrams.
110 * This version defines the starting, ending and route points of a connection.
111 * The routing itself is left up to the diagram router employed by
112 * {@link DiagramUtils#validateAndFix(IDiagram, ICanvasContext)}.
116 * This tool is added to the diagram when a connection sequence is initiated by
117 * another participant. PointerInteractor is one such participant which adds the
118 * tool when a terminal or non-terminal-occupied canvas space is ALT+clicked
119 * (see {@link PointerInteractor#checkInitiateConnectTool(MouseEvent, Point2D)}
120 * ). The connection will be finished when another allowed terminal is clicked
121 * upon or empty canvas space is ALT+clicked. Route points for the connection
122 * can be created by clicking around on non-terminal-occupied canvas space while
126 * Connections can be started from and ended in flags by pressing ALT while
129 * @author Tuukka Lehtonen
131 public class RouteGraphConnectTool extends AbstractMode {
133 private static final String END_TERMINAL_DATA = "END";
135 public static final int PAINT_PRIORITY = ElementPainter.ELEMENT_PAINT_PRIORITY + 5;
138 protected TransformUtil util;
141 protected ElementPainter diagramPainter;
144 protected PointerInteractor pi;
147 * Starting point designation.
149 * The value is received by the constructor.
151 protected RouteGraphTarget startingPoint;
153 protected TerminalInfo startTerminal = new TerminalInfo();
156 * <code>true</code> if this tool should create connection continuation
157 * flags, <code>false</code> otherwise.
159 protected boolean createFlags;
164 protected IElementClassProvider elementClassProvider;
169 protected Deque<ControlPoint> controlPoints = new ArrayDeque<ControlPoint>();
172 * Element terminal of connection end element. <code>null</code> if
173 * connection cannot be ended where it is currently being attempted to end.
175 protected TerminalInfo endTerminal;
178 * The latest connectability judgment from the active
179 * {@link IConnectionAdvisor} should the connection happen between
180 * {@link #startTerminal} and {@link #endTerminal}.
182 protected ConnectionJudgement connectionJudgment;
185 * A temporary variable for use with
186 * {@link TerminalTopology#getTerminals(IElement, Collection)}.
188 protected Collection<Terminal> terminals = new ArrayList<Terminal>();
191 * Previous mouse canvas position recorded by
192 * {@link #processMouseMove(MouseMovedEvent)}.
194 protected Point2D lastMouseCanvasPos = new Point2D.Double();
197 * Set to true once {@link #processMouseMove(MouseMovedEvent)} has been
198 * invoked at least once. This is used to tell whether to allow creation of
199 * branch points or finising the connection in thin air. It will not be
200 * allowed if the mouse has not moved at all since starting the connection.
202 protected boolean mouseHasMoved = false;
204 protected TerminalHoverStrategy originalStrategy = null;
206 protected TerminalHoverStrategy terminalHoverStrategy = new TerminalHoverStrategy() {
208 public boolean highlightEnabled() {
209 return !isEndingInFlag();
213 public boolean highlight(TerminalInfo ti) {
214 return canConnect(ti.e, ti.t) != null;
218 protected final static Composite ALPHA_COMPOSITE = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.75f);
221 * Root scene graph node for all visualization performed by this tool.
223 protected ConnectionNode ghostNode;
225 protected RouteGraphNode rgNode;
227 protected RouteGraph routeGraph;
228 protected RouteTerminal endRouteTerminal;
229 private ILineEndStyle endTerminalStyle;
232 * Indicates whether the connection is about to be ended into a new
233 * flag/branchpoint or not.
235 protected TerminalInfo endFlag;
237 protected G2DParentNode endFlagNode;
239 private RouteLine attachedToRouteLine;
241 protected RouteGraph beforeRouteGraph;
243 private IRouteGraphRenderer beforeRenderer;
245 private boolean beforeEditable;
247 protected RouteGraphDelta routeGraphDelta;
249 private Set<Pair<IElement, Terminal>> alreadyConnected;
252 * @param startElement
253 * @param routeGraphConnection
255 * @param startCanvasPos
257 public RouteGraphConnectTool(RouteGraphTarget startingPoint, int mouseId) {
260 Point2D intersection = startingPoint.getIntersectionPosition();
262 this.startingPoint = startingPoint;
263 this.lastMouseCanvasPos.setLocation(intersection);
265 BranchPointTerminal t = BranchPointTerminal.existingTerminal(
266 AffineTransform.getTranslateInstance(intersection.getX(), intersection.getY()),
268 BranchPointNode.SHAPE);
270 Point2D p = startingPoint.getIntersectionPosition();
271 AffineTransform at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
273 startTerminal.e = startingPoint.getElement();
275 startTerminal.posElem = at;
276 startTerminal.posDia = at;
277 startTerminal.shape = t.getShape();
279 controlPoints.add( newControlPoint( startingPoint.getIntersectionPosition() ) );
280 controlPoints.add( newControlPoint( startingPoint.getCanvasPosition() ) );
282 alreadyConnected = new HashSet<Pair<IElement,Terminal>>();
283 IElement connection = startingPoint.getElement();
284 ConnectionEntity ce = connection.getHint(ElementHints.KEY_CONNECTION_ENTITY);
285 Collection<Connection> tcs = ce.getTerminalConnections(null);
286 for (Connection tc : tcs)
287 alreadyConnected.add(Pair.make(tc.node, tc.terminal));
291 public void addedToContext(ICanvasContext ctx) {
292 super.addedToContext(ctx);
294 // Force terminals to always be highlighted without pressing certain
295 // keys or key combinations.
296 originalStrategy = getHint(TerminalPainter.TERMINAL_HOVER_STRATEGY);
297 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
301 protected void onDiagramSet(IDiagram newDiagram, IDiagram oldDiagram) {
302 if (newDiagram != null) {
303 // Get IElementClassProvider
304 ISynchronizationContext ctx = newDiagram.getHint(SynchronizationHints.CONTEXT);
306 this.elementClassProvider = ctx.get(SynchronizationHints.ELEMENT_CLASS_PROVIDER);
309 // See if flags should be created or not.
310 this.createFlags = Boolean.TRUE.equals(newDiagram.getHint(DiagramHints.KEY_USE_CONNECTION_FLAGS));
315 public void removedFromContext(ICanvasContext ctx) {
316 if (getHint(TerminalPainter.TERMINAL_HOVER_STRATEGY) == terminalHoverStrategy) {
317 if (originalStrategy != null)
318 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, originalStrategy);
320 removeHint(TerminalPainter.TERMINAL_HOVER_STRATEGY);
323 super.removedFromContext(ctx);
326 int straightDirections(RouteLine line) {
327 return line.isHorizontal()
328 ? (RouteTerminal.DIR_DOWN | RouteTerminal.DIR_UP)
329 : (RouteTerminal.DIR_LEFT | RouteTerminal.DIR_RIGHT);
332 private static RouteTerminal addTerminal(Object data, RouteGraph rg, double x, double y, Rectangle2D bounds, int allowedDirections, ILineEndStyle style) {
335 rt = rg.addTerminal(x, y, bounds.getMinX(), bounds.getMinY(), bounds.getMaxX(), bounds.getMaxY(), allowedDirections, style);
337 rt = rg.addTerminal(x, y, x, y, x, y, allowedDirections, style);
342 private RouteTerminal setEndTerminal(double x, double y, Rectangle2D bounds, int allowedDirections) {
344 // First add then remove to prevent deletion of route lines in case there are 2 only terminals
346 RouteTerminal toRemove = endRouteTerminal;
348 endRouteTerminal = addTerminal( END_TERMINAL_DATA, routeGraph, x, y, bounds, allowedDirections, endTerminalStyle );
349 routeGraph.link( attachedToRouteLine, endRouteTerminal );
351 if (toRemove != null)
352 routeGraph.remove(toRemove);
354 return endRouteTerminal;
358 protected void setEndTerminal(TerminalInfo ti) {
359 Rectangle2D bounds = ElementUtils.getElementBoundsOnDiagram(ti.e, new Rectangle2D.Double());
360 GeometryUtils.expandRectangle(bounds, 2);
361 int dir = RouteGraphConnectionClass.shortestDirectionOutOfBounds(
362 ti.posDia.getTranslateX(), ti.posDia.getTranslateY(), bounds);
363 setEndTerminal(ti.posDia.getTranslateX(), ti.posDia.getTranslateY(), bounds, dir);
367 public void initSG(G2DParentNode parent) {
368 ghostNode = parent.addNode("branched connection", ConnectionNode.class);
369 //ghostNode.setComposite(AlphaComposite.SrcOver.derive(0.5f));
370 ghostNode.setZIndex(PAINT_PRIORITY);
372 rgNode = ghostNode.addNode("branch", RouteGraphNode.class);
374 double ex = startingPoint.getCanvasPosition().getX();
375 double ey = startingPoint.getCanvasPosition().getY();
377 beforeRouteGraph = startingPoint.getNode().getRouteGraph();
378 beforeEditable = startingPoint.getNode().isEditable();
380 RouteGraphNode beforeRgNode = startingPoint.getNode();
381 beforeRenderer = beforeRgNode.getRenderer();
383 rgNode.setRenderer(beforeRenderer);
384 rgNode.setEditable(false);
386 beforeRgNode.setEditable(beforeEditable);
387 beforeRgNode.setRenderer(null);
393 public void initRG(double ex, double ey) {
395 THashMap<Object, Object> map = new THashMap<Object, Object>();
396 routeGraph = beforeRouteGraph.copy(map);
398 endTerminalStyle = PlainLineEndStyle.INSTANCE;
399 for (RouteTerminal t : routeGraph.getTerminals()) {
400 if (t.getRenderStyle() instanceof ArrowLineEndStyle) {
401 endTerminalStyle = t.getRenderStyle();
406 attachedToRouteLine = (RouteLine) map.get(startingPoint.getLine());
407 routeGraph.makePersistent(attachedToRouteLine);
408 for (RouteLine line : routeGraph.getAllLines()) {
409 if (!line.isTransient() && line.isHorizontal() == attachedToRouteLine.isHorizontal()
410 && line.getPosition() == attachedToRouteLine.getPosition()) {
411 attachedToRouteLine = line;
415 routeGraphDelta = new RouteGraphDelta(beforeRouteGraph, routeGraph);
417 // beforeRouteGraph.print();
418 // routeGraph.print();
419 // routeGraphDelta.print();
421 setEndTerminal(ex, ey, null, 0xf);
423 rgNode.setRouteGraph(routeGraph);
428 public void cleanupSG() {
429 RouteGraphNode beforeRgNode = startingPoint.getNode();
430 beforeRgNode.setRouteGraph(beforeRouteGraph);
431 beforeRgNode.setRenderer(beforeRenderer);
432 beforeRgNode.setEditable(beforeEditable);
440 @EventHandler(priority = 200)
441 public boolean handleCommandEvents(CommandEvent ce) {
442 if (ce.command.equals(Commands.CANCEL)) {
446 } else if (ce.command.equals(Commands.ROTATE_ELEMENT_CCW) || ce.command.equals(Commands.ROTATE_ELEMENT_CW)) {
447 // TODO: rotate flag?
452 @EventHandler(priority = PointerInteractor.TOOL_PRIORITY + 20)
453 public boolean handleKeyEvents(KeyEvent ke) {
454 if (ke instanceof KeyPressedEvent) {
455 // Back-space, cancel prev bend
456 if (ke.keyCode == java.awt.event.KeyEvent.VK_BACK_SPACE)
457 return cancelPreviousBend();
460 if (ke.keyCode == java.awt.event.KeyEvent.VK_ALT) {
462 endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(ke instanceof KeyPressedEvent));
470 @EventHandler(priority = PointerInteractor.TOOL_PRIORITY + 20)
471 public boolean handleEvent(MouseEvent me) {
472 // Only handle events for the connection-initiating mouse
473 if (me.mouseId != mouseId)
476 if (me instanceof MouseMovedEvent)
477 return processMouseMove((MouseMovedEvent) me);
479 if (me instanceof MouseButtonPressedEvent)
480 return processMouseButtonPress((MouseButtonPressedEvent) me);
482 // #7653: Support creating connections between terminals without lifting mouse button in between.
483 if (me instanceof MouseButtonReleasedEvent)
484 return processMouseButtonRelease((MouseButtonReleasedEvent) me);
489 protected boolean processMouseMove(MouseMovedEvent me) {
490 mouseHasMoved = true;
492 Point2D mouseControlPos = me.controlPosition;
493 Point2D mouseCanvasPos = util.controlToCanvas(mouseControlPos, new Point2D.Double());
495 ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
496 if (snapAdvisor != null)
497 snapAdvisor.snap(mouseCanvasPos);
499 // Record last snapped canvas position of mouse.
500 this.lastMouseCanvasPos.setLocation(mouseCanvasPos);
502 if (isEndingInFlag()) {
503 endFlagNode.setTransform(AffineTransform.getTranslateInstance(mouseCanvasPos.getX(), mouseCanvasPos.getY()));
506 List<TerminalInfo> tis = pi.pickTerminals(me.controlPosition);
507 tis = TerminalUtil.findNearestOverlappingTerminals(tis);
508 if (!tis.isEmpty()) {
509 for (TerminalInfo ti : tis) {
510 Object canConnect = canConnect(ti.e, ti.t);
512 if (canConnect != null) {
513 connectionJudgment = (ConnectionJudgement) canConnect;
515 if (!isEndingInFlag() || !TerminalUtil.isSameTerminal(ti, endTerminal)) {
516 controlPoints.getLast().setPosition(ti.posDia).setAttachedToTerminal(ti);
524 // Make sure that we are ending with a flag if ALT is pressed
525 // and no end terminal is defined.
526 endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));
528 updateSG(new Point2D.Double(ti.posDia.getTranslateX(), ti.posDia.getTranslateY()));
534 connectionJudgment = null;
535 if (isEndTerminalDefined()) {
536 // CASE: Mouse was previously on top of a valid terminal to end
537 // the connection. Now the mouse has been moved where there is
538 // no longer a terminal to connect to.
540 // => Disconnect the last edge segment from the previous
541 // terminal, mark endElement/endTerminal non-existent
542 // and connect the disconnected edge to a new branch point.
544 disconnect(mouseCanvasPos);
546 controlPoints.getLast()
547 .setPosition(mouseCanvasPos)
548 .setAttachedToTerminal(null);
552 // CASE: Mouse was not previously on top of a valid ending
555 // => Move and re-orient last branch point.
557 controlPoints.getLast()
558 .setPosition(mouseCanvasPos);
561 // Make sure that we are ending with a flag if ALT is pressed and no end
562 // terminal is defined.
563 endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));
565 updateSG(lastMouseCanvasPos);
570 protected void connect(TerminalInfo ti) {
574 protected void disconnect(Point2D mouseCanvasPos) {
575 setEndTerminal(mouseCanvasPos.getX(), mouseCanvasPos.getY(), null, 0xf);
578 protected boolean processMouseButtonPress(MouseButtonEvent me) {
579 // Do nothing before the mouse has moved at least a little.
580 // This prevents the user from ending the connection right where
585 if (me.button == MouseEvent.LEFT_BUTTON) {
586 Point2D mouseControlPos = me.controlPosition;
587 Point2D mouseCanvasPos = util.getInverseTransform().transform(mouseControlPos, new Point2D.Double());
589 ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
590 if (snapAdvisor != null)
591 snapAdvisor.snap(mouseCanvasPos);
593 // Clicked on an allowed end terminal. End connection & end mode.
594 if (tryEndConnection()) {
597 // Finish connection in thin air only if the
598 // connection was started from a valid terminal.
599 if ((me.stateMask & MouseEvent.ALT_MASK) != 0 && startTerminal != null) {
600 connectionJudgment = (ConnectionJudgement) canConnect(null, null);
601 if (connectionJudgment == null)
606 } else if (routePointsAllowed()
607 && (me.stateMask & (MouseEvent.ALT_MASK | MouseEvent.SHIFT_MASK | MouseEvent.CTRL_MASK)) == 0) {
608 // Add new connection control point.
609 controlPoints.add(newControlPoint(mouseCanvasPos));
610 updateSG(mouseCanvasPos);
614 // Eat the event to prevent other participants from doing
615 // incompatible things while in this connection mode.
617 } else if (me.button == MouseEvent.RIGHT_BUTTON) {
618 return cancelPreviousBend();
624 private int mouseLeftReleaseCount = 0;
626 protected boolean processMouseButtonRelease(MouseButtonReleasedEvent me) {
627 if (me.button == MouseEvent.LEFT_BUTTON
628 && ++mouseLeftReleaseCount == 1) {
629 return tryEndConnection();
635 * @return <code>true</code> if connection was successfully ended
637 private boolean tryEndConnection() {
638 if (isEndTerminalDefined()) {
646 protected boolean cancelPreviousBend() {
647 if (!routePointsAllowed())
650 // Just to make this code more comprehensible, prevent an editing
651 // case that requires ugly code to work.
652 if (isEndingInFlag())
655 // If there are no real route points, cancel whole connection.
656 if (controlPoints.size() <= 2) {
663 controlPoints.removeLast();
664 controlPoints.getLast().setPosition(lastMouseCanvasPos);
666 updateSG(lastMouseCanvasPos);
670 protected void updateSG(Point2D mousePos) {
671 routeGraph.setLocation(endRouteTerminal, mousePos.getX(), mousePos.getY());
672 //routeGraph.print(System.err);
676 protected boolean shouldEndWithFlag(MouseEvent me) {
677 return shouldEndWithFlag((me.stateMask & MouseEvent.ALT_MASK) != 0);
680 protected boolean shouldEndWithFlag(boolean altPressed) {
681 return altPressed && !isEndTerminalDefined() && createFlags;
684 protected boolean isEndTerminalDefined() {
685 return endTerminal != null;
688 protected boolean isFlagTerminal(TerminalInfo ti) {
689 return ti.e.getElementClass().containsClass(FlagHandler.class);
693 protected boolean isEndingInFlag() {
694 return endFlag != null;
697 protected void endWithoutTerminal(Point2D mousePos, boolean altDown) {
698 // Just go with branch points if flags are not allowed.
702 boolean endTerminalDefined = isEndTerminalDefined();
705 if (!isEndingInFlag()) {
706 endFlag = createFlag(EdgeEnd.End);
707 endFlagNode = showElement(ghostNode, "endFlag", endFlag.e, mousePos);
708 controlPoints.getLast()
709 .setAttachedToTerminal(endFlag);
711 // TerminalPainter must refresh
712 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
717 if (isEndingInFlag()) {
718 // Currently ending with flag but ALT is no longer down
719 // so that flag must be removed.
721 endFlagNode.remove();
724 ControlPoint cp = controlPoints.getLast();
725 cp.setAttachedToTerminal(endTerminal);
727 if (endTerminalDefined) {
728 cp.setPosition(endTerminal.posDia);
730 cp.setPosition(mousePos);
733 // Force Terminalpainter refresh
734 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
741 private G2DParentNode showElement(G2DParentNode parent, String nodeId, IElement element, Point2D pos) {
742 return showElement(parent, nodeId, element, AffineTransform.getTranslateInstance(pos.getX(), pos.getY()));
745 private G2DParentNode showElement(G2DParentNode parent, String nodeId, IElement element, AffineTransform tr) {
746 G2DParentNode elementParent = parent.getOrCreateNode(nodeId, G2DParentNode.class);
747 elementParent.setTransform(tr);
748 elementParent.removeNodes();
749 for (SceneGraph sg : element.getElementClass().getItemsByClass(SceneGraph.class))
750 sg.init(element, elementParent);
751 return elementParent;
758 protected ControlPoint newControlPoint(Point2D canvasPos) {
759 return new ControlPoint(canvasPos);
762 protected Triple<RouteGraph,RouteGraph,RouteGraphDelta> prepareRouteGraphDelta() {
763 // Prevent route graph connection synchronization from crashing on the
764 // transient route terminal that doesn't exist yet. It is created after
765 // persisting the route line, which is the only purpose of this route
766 // graph synchronization.
767 routeGraph.remove(endRouteTerminal);
768 return Triple.make(beforeRouteGraph, routeGraph, routeGraphDelta);
771 protected void createConnection() {
772 TimeLogger.resetTimeAndLog(getClass(), "createConnection");
773 final ConnectionJudgement judgment = this.connectionJudgment;
774 if (judgment == null) {
775 ErrorLogger.defaultLogError("Cannot create connection, no judgment available on connection validity", null);
779 final ConnectionBuilder builder = new ConnectionBuilder(this.diagram);
780 final Triple<RouteGraph,RouteGraph,RouteGraphDelta> rgs = prepareRouteGraphDelta();
782 Simantics.getSession().asyncRequest(new WriteRequest() {
784 public void perform(WriteGraph graph) throws DatabaseException {
785 graph.markUndoPoint();
786 Resource connection = ElementUtils.getObject(startTerminal.e);
787 if (!rgs.third.isEmpty()) {
788 new RouteGraphConnection(graph, connection).synchronize(graph, rgs.first, rgs.second, rgs.third);
790 Resource attachToLine = RouteGraphConnection.deserialize(graph, attachedToRouteLine.getData());
791 builder.attachToRouteGraph(graph, judgment, connection, attachToLine, controlPoints, endTerminal, FlagClass.Type.Out);
795 ExceptionUtils.logAndShowError(e);
799 protected boolean routePointsAllowed() {
800 return Boolean.TRUE.equals(diagram.getHint(DiagramHints.KEY_ALLOW_ROUTE_POINTS));
803 protected Object canConnect(IElement endElement, Terminal endTerminal) {
804 IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);
805 return canConnect(advisor, endElement, endTerminal);
808 protected Object canConnect(IConnectionAdvisor advisor, IElement endElement, Terminal endTerminal) {
810 return ConnectionJudgement.CANBEMADELEGAL;
811 if (alreadyConnected.contains(Pair.make(endElement, endTerminal)))
813 return advisor.canBeConnected(null, startTerminal.e, startTerminal.t, endElement, endTerminal);
816 protected static FlagClass.Type endToFlagType(EdgeEnd end) {
819 return FlagClass.Type.In;
821 return FlagClass.Type.Out;
823 throw new IllegalArgumentException("unrecognized edge end: " + end);
827 protected TerminalInfo createFlag(EdgeEnd connectionEnd) {
828 ElementClass flagClass = elementClassProvider.get(ElementClasses.FLAG);
829 IElement e = Element.spawnNew(flagClass);
831 e.setHint(FlagClass.KEY_FLAG_TYPE, endToFlagType(connectionEnd));
832 e.setHint(FlagClass.KEY_FLAG_MODE, FlagClass.Mode.Internal);
834 TerminalInfo ti = new TerminalInfo();
836 ti.t = ElementUtils.getSingleTerminal(e);
837 ti.posElem = TerminalUtil.getTerminalPosOnElement(e, ti.t);
838 ti.posDia = TerminalUtil.getTerminalPosOnDiagram(e, ti.t);
843 // ------------------------------------------------------------------------
845 static RouteGraphTarget pickRouteGraphConnection(ICanvasContext ctx, IDiagram diagram, Shape pickShape, double pickDistance) {
846 ArrayList<IElement> elements = new ArrayList<IElement>();
847 PickRequest req = new PickRequest(pickShape).context(ctx);
848 DiagramUtils.pick(diagram, req, elements);
849 for (Iterator<IElement> it = elements.iterator(); it.hasNext();) {
850 IElement e = it.next();
851 RouteGraphNode rgn = e.getHint(RouteGraphConnectionClass.KEY_RG_NODE);
852 if (rgn == null || rgn.getRouteGraph() == null)
855 if (elements.isEmpty())
858 Rectangle2D pickRect = pickShape.getBounds2D();
859 final double x = pickRect.getCenterX();
860 final double y = pickRect.getCenterY();
862 return pickNearestRouteGraphConnection(elements, x, y, pickDistance);
865 private static RouteGraphTarget pickNearestRouteGraphConnection(ArrayList<IElement> elements, double x, double y, double pd) {
866 // Find the nearest distance at which we get hits.
868 double lo = hi * .01;
871 double delta = (hi - lo);
878 for (IElement connection : elements) {
879 RouteGraphNode rgn = connection.getHint(RouteGraphConnectionClass.KEY_RG_NODE);
880 RouteLine line = rgn.getRouteGraph().pickLine(x, y, pd);
893 // Now that the nearest hitting distance is found, find the nearest intersection.
894 RouteGraphTarget nearestTarget = null;
895 double nearest = Double.MAX_VALUE;
896 for (IElement connection : elements) {
897 RouteGraphNode rgn = connection.getHint(RouteGraphConnectionClass.KEY_RG_NODE);
898 RouteLine line = rgn.getRouteGraph().pickLine(x, y, pd);
902 Point2D intersection = intersectionPoint(x, y, line);
903 if (intersection == null)
906 double dx = intersection.getX() - x;
907 double dy = intersection.getY() - y;
908 double dist = Math.sqrt(dx*dx + dy*dy);
909 if (dist < nearest) {
911 nearestTarget = new RouteGraphTarget(connection, rgn, line, new Point2D.Double(x, y), intersection);
915 return nearestTarget;
918 static Point2D intersectionPoint(double x, double y, RouteLine line) {
919 Collection<RoutePoint> points = line.getPoints();
920 if (points.size() < 2)
922 RoutePoint s = line.getBegin();
923 RoutePoint e = line.getEnd();
924 return GeometryUtils.intersectionToLine(s.getX(), s.getY(), e.getX(), e.getY(), x, y);