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;
29 import org.simantics.Simantics;
30 import org.simantics.db.Resource;
31 import org.simantics.db.WriteGraph;
32 import org.simantics.db.common.request.WriteRequest;
33 import org.simantics.db.exception.DatabaseException;
34 import org.simantics.diagram.connection.RouteGraph;
35 import org.simantics.diagram.connection.RouteGraphConnectionClass;
36 import org.simantics.diagram.connection.RouteLine;
37 import org.simantics.diagram.connection.RoutePoint;
38 import org.simantics.diagram.connection.RouteTerminal;
39 import org.simantics.diagram.connection.delta.RouteGraphDelta;
40 import org.simantics.diagram.connection.rendering.IRouteGraphRenderer;
41 import org.simantics.diagram.connection.rendering.arrows.ArrowLineEndStyle;
42 import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;
43 import org.simantics.diagram.connection.rendering.arrows.PlainLineEndStyle;
44 import org.simantics.diagram.synchronization.ISynchronizationContext;
45 import org.simantics.diagram.synchronization.SynchronizationHints;
46 import org.simantics.diagram.synchronization.graph.RouteGraphConnection;
47 import org.simantics.g2d.canvas.ICanvasContext;
48 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
49 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGCleanup;
50 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
51 import org.simantics.g2d.connection.ConnectionEntity;
52 import org.simantics.g2d.connection.IConnectionAdvisor;
53 import org.simantics.g2d.diagram.DiagramHints;
54 import org.simantics.g2d.diagram.DiagramUtils;
55 import org.simantics.g2d.diagram.IDiagram;
56 import org.simantics.g2d.diagram.handler.PickRequest;
57 import org.simantics.g2d.diagram.handler.Topology.Connection;
58 import org.simantics.g2d.diagram.handler.Topology.Terminal;
59 import org.simantics.g2d.diagram.participant.ElementPainter;
60 import org.simantics.g2d.diagram.participant.TerminalPainter;
61 import org.simantics.g2d.diagram.participant.TerminalPainter.TerminalHoverStrategy;
62 import org.simantics.g2d.diagram.participant.pointertool.AbstractMode;
63 import org.simantics.g2d.diagram.participant.pointertool.PointerInteractor;
64 import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil;
65 import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;
66 import org.simantics.g2d.element.ElementClass;
67 import org.simantics.g2d.element.ElementClasses;
68 import org.simantics.g2d.element.ElementHints;
69 import org.simantics.g2d.element.ElementUtils;
70 import org.simantics.g2d.element.IElement;
71 import org.simantics.g2d.element.IElementClassProvider;
72 import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
73 import org.simantics.g2d.element.handler.SceneGraph;
74 import org.simantics.g2d.element.handler.TerminalTopology;
75 import org.simantics.g2d.element.handler.impl.BranchPointTerminal;
76 import org.simantics.g2d.element.impl.Element;
77 import org.simantics.g2d.elementclass.FlagClass;
78 import org.simantics.g2d.elementclass.FlagHandler;
79 import org.simantics.g2d.participant.TransformUtil;
80 import org.simantics.g2d.utils.geom.DirectionSet;
81 import org.simantics.scenegraph.g2d.G2DParentNode;
82 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
83 import org.simantics.scenegraph.g2d.events.KeyEvent;
84 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;
85 import org.simantics.scenegraph.g2d.events.MouseEvent;
86 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonEvent;
87 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;
88 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;
89 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
90 import org.simantics.scenegraph.g2d.events.command.Commands;
91 import org.simantics.scenegraph.g2d.nodes.BranchPointNode;
92 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
93 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
94 import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;
95 import org.simantics.scenegraph.utils.GeometryUtils;
96 import org.simantics.structural2.modelingRules.ConnectionJudgement;
97 import org.simantics.utils.datastructures.Callback;
98 import org.simantics.utils.datastructures.Pair;
99 import org.simantics.utils.datastructures.Triple;
100 import org.simantics.utils.logging.TimeLogger;
101 import org.simantics.utils.ui.ErrorLogger;
102 import org.simantics.utils.ui.ExceptionUtils;
104 import gnu.trove.map.hash.THashMap;
107 * A basic tool for making connection on diagrams.
109 * This version defines the starting, ending and route points of a connection.
110 * The routing itself is left up to the diagram router employed by
111 * {@link DiagramUtils#validateAndFix(IDiagram, ICanvasContext)}.
115 * This tool is added to the diagram when a connection sequence is initiated by
116 * another participant. PointerInteractor is one such participant which adds the
117 * tool when a terminal or non-terminal-occupied canvas space is ALT+clicked
118 * (see {@link PointerInteractor#checkInitiateConnectTool(MouseEvent, Point2D)}
119 * ). The connection will be finished when another allowed terminal is clicked
120 * upon or empty canvas space is ALT+clicked. Route points for the connection
121 * can be created by clicking around on non-terminal-occupied canvas space while
125 * Connections can be started from and ended in flags by pressing ALT while
128 * @author Tuukka Lehtonen
130 public class RouteGraphConnectTool extends AbstractMode {
132 private static final String END_TERMINAL_DATA = "END";
134 public static final int PAINT_PRIORITY = ElementPainter.ELEMENT_PAINT_PRIORITY + 5;
137 protected TransformUtil util;
140 protected ElementPainter diagramPainter;
143 protected PointerInteractor pi;
146 * Starting point designation.
148 * The value is received by the constructor.
150 protected RouteGraphTarget startingPoint;
152 protected TerminalInfo startTerminal = new TerminalInfo();
155 * <code>true</code> if this tool should create connection continuation
156 * flags, <code>false</code> otherwise.
158 protected boolean createFlags;
163 protected IElementClassProvider elementClassProvider;
168 protected Deque<ControlPoint> controlPoints = new ArrayDeque<ControlPoint>();
171 * Element terminal of connection end element. <code>null</code> if
172 * connection cannot be ended where it is currently being attempted to end.
174 protected TerminalInfo endTerminal;
177 * The latest connectability judgment from the active
178 * {@link IConnectionAdvisor} should the connection happen between
179 * {@link #startTerminal} and {@link #endTerminal}.
181 protected ConnectionJudgement connectionJudgment;
184 * A temporary variable for use with
185 * {@link TerminalTopology#getTerminals(IElement, Collection)}.
187 protected Collection<Terminal> terminals = new ArrayList<Terminal>();
190 * Previous mouse canvas position recorded by
191 * {@link #processMouseMove(MouseMovedEvent)}.
193 protected Point2D lastMouseCanvasPos = new Point2D.Double();
196 * Set to true once {@link #processMouseMove(MouseMovedEvent)} has been
197 * invoked at least once. This is used to tell whether to allow creation of
198 * branch points or finising the connection in thin air. It will not be
199 * allowed if the mouse has not moved at all since starting the connection.
201 protected boolean mouseHasMoved = false;
203 protected TerminalHoverStrategy originalStrategy = null;
205 protected TerminalHoverStrategy terminalHoverStrategy = new TerminalHoverStrategy() {
207 public boolean highlightEnabled() {
208 return !isEndingInFlag();
212 public boolean highlight(TerminalInfo ti) {
213 return canConnect(ti.e, ti.t) != null;
217 protected final static Composite ALPHA_COMPOSITE = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.75f);
220 * Root scene graph node for all visualization performed by this tool.
222 protected ConnectionNode ghostNode;
224 protected RouteGraphNode rgNode;
226 protected RouteGraph routeGraph;
227 protected RouteTerminal endRouteTerminal;
228 private ILineEndStyle endTerminalStyle;
231 * Indicates whether the connection is about to be ended into a new
232 * flag/branchpoint or not.
234 protected TerminalInfo endFlag;
236 protected G2DParentNode endFlagNode;
238 private RouteLine attachedToRouteLine;
240 protected RouteGraph beforeRouteGraph;
242 private IRouteGraphRenderer beforeRenderer;
244 private boolean beforeEditable;
246 protected RouteGraphDelta routeGraphDelta;
248 private Set<Pair<IElement, Terminal>> alreadyConnected;
251 * @param startElement
252 * @param routeGraphConnection
254 * @param startCanvasPos
256 public RouteGraphConnectTool(RouteGraphTarget startingPoint, int mouseId) {
259 Point2D intersection = startingPoint.getIntersectionPosition();
261 this.startingPoint = startingPoint;
262 this.lastMouseCanvasPos.setLocation(intersection);
264 BranchPointTerminal t = BranchPointTerminal.existingTerminal(
265 AffineTransform.getTranslateInstance(intersection.getX(), intersection.getY()),
267 BranchPointNode.SHAPE);
269 Point2D p = startingPoint.getIntersectionPosition();
270 AffineTransform at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
272 startTerminal.e = startingPoint.getElement();
274 startTerminal.posElem = at;
275 startTerminal.posDia = at;
276 startTerminal.shape = t.getShape();
278 controlPoints.add( newControlPoint( startingPoint.getIntersectionPosition() ) );
279 controlPoints.add( newControlPoint( startingPoint.getCanvasPosition() ) );
281 alreadyConnected = new HashSet<Pair<IElement,Terminal>>();
282 IElement connection = startingPoint.getElement();
283 ConnectionEntity ce = connection.getHint(ElementHints.KEY_CONNECTION_ENTITY);
284 Collection<Connection> tcs = ce.getTerminalConnections(null);
285 for (Connection tc : tcs)
286 alreadyConnected.add(Pair.make(tc.node, tc.terminal));
290 public void addedToContext(ICanvasContext ctx) {
291 super.addedToContext(ctx);
293 // Force terminals to always be highlighted without pressing certain
294 // keys or key combinations.
295 originalStrategy = getHint(TerminalPainter.TERMINAL_HOVER_STRATEGY);
296 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
300 protected void onDiagramSet(IDiagram newDiagram, IDiagram oldDiagram) {
301 if (newDiagram != null) {
302 // Get IElementClassProvider
303 ISynchronizationContext ctx = newDiagram.getHint(SynchronizationHints.CONTEXT);
305 this.elementClassProvider = ctx.get(SynchronizationHints.ELEMENT_CLASS_PROVIDER);
308 // See if flags should be created or not.
309 this.createFlags = Boolean.TRUE.equals(newDiagram.getHint(DiagramHints.KEY_USE_CONNECTION_FLAGS));
314 public void removedFromContext(ICanvasContext ctx) {
315 if (getHint(TerminalPainter.TERMINAL_HOVER_STRATEGY) == terminalHoverStrategy) {
316 if (originalStrategy != null)
317 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, originalStrategy);
319 removeHint(TerminalPainter.TERMINAL_HOVER_STRATEGY);
322 super.removedFromContext(ctx);
325 int straightDirections(RouteLine line) {
326 return line.isHorizontal()
327 ? (RouteTerminal.DIR_DOWN | RouteTerminal.DIR_UP)
328 : (RouteTerminal.DIR_LEFT | RouteTerminal.DIR_RIGHT);
331 private static RouteTerminal addTerminal(Object data, RouteGraph rg, double x, double y, Rectangle2D bounds, int allowedDirections, ILineEndStyle style) {
334 rt = rg.addTerminal(x, y, bounds.getMinX(), bounds.getMinY(), bounds.getMaxX(), bounds.getMaxY(), allowedDirections, style);
336 rt = rg.addTerminal(x, y, x, y, x, y, allowedDirections, style);
341 private RouteTerminal setEndTerminal(double x, double y, Rectangle2D bounds, int allowedDirections) {
343 // First add then remove to prevent deletion of route lines in case there are 2 only terminals
345 RouteTerminal toRemove = endRouteTerminal;
347 endRouteTerminal = addTerminal( END_TERMINAL_DATA, routeGraph, x, y, bounds, allowedDirections, endTerminalStyle );
348 routeGraph.link( attachedToRouteLine, endRouteTerminal );
350 if (toRemove != null)
351 routeGraph.remove(toRemove);
353 return endRouteTerminal;
357 protected void setEndTerminal(TerminalInfo ti) {
358 Rectangle2D bounds = ElementUtils.getElementBoundsOnDiagram(ti.e, new Rectangle2D.Double());
359 GeometryUtils.expandRectangle(bounds, 2);
360 int dir = RouteGraphConnectionClass.shortestDirectionOutOfBounds(
361 ti.posDia.getTranslateX(), ti.posDia.getTranslateY(), bounds);
362 setEndTerminal(ti.posDia.getTranslateX(), ti.posDia.getTranslateY(), bounds, dir);
366 public void initSG(G2DParentNode parent) {
367 ghostNode = parent.addNode("branched connection", ConnectionNode.class);
368 //ghostNode.setComposite(AlphaComposite.SrcOver.derive(0.5f));
369 ghostNode.setZIndex(PAINT_PRIORITY);
371 rgNode = ghostNode.addNode("branch", RouteGraphNode.class);
373 double ex = startingPoint.getCanvasPosition().getX();
374 double ey = startingPoint.getCanvasPosition().getY();
376 beforeRouteGraph = startingPoint.getNode().getRouteGraph();
377 beforeEditable = startingPoint.getNode().isEditable();
379 RouteGraphNode beforeRgNode = startingPoint.getNode();
380 beforeRenderer = beforeRgNode.getRenderer();
382 rgNode.setRenderer(beforeRenderer);
383 rgNode.setEditable(false);
385 beforeRgNode.setEditable(beforeEditable);
386 beforeRgNode.setRenderer(null);
392 public void initRG(double ex, double ey) {
394 THashMap<Object, Object> map = new THashMap<Object, Object>();
395 routeGraph = beforeRouteGraph.copy(map);
397 endTerminalStyle = PlainLineEndStyle.INSTANCE;
398 for (RouteTerminal t : routeGraph.getTerminals()) {
399 if (t.getRenderStyle() instanceof ArrowLineEndStyle) {
400 endTerminalStyle = t.getRenderStyle();
405 attachedToRouteLine = (RouteLine) map.get(startingPoint.getLine());
406 routeGraph.makePersistent(attachedToRouteLine);
407 for (RouteLine line : routeGraph.getAllLines()) {
408 if (!line.isTransient() && line.isHorizontal() == attachedToRouteLine.isHorizontal()
409 && line.getPosition() == attachedToRouteLine.getPosition()) {
410 attachedToRouteLine = line;
414 routeGraphDelta = new RouteGraphDelta(beforeRouteGraph, routeGraph);
416 // beforeRouteGraph.print();
417 // routeGraph.print();
418 // routeGraphDelta.print();
420 setEndTerminal(ex, ey, null, 0xf);
422 rgNode.setRouteGraph(routeGraph);
427 public void cleanupSG() {
428 RouteGraphNode beforeRgNode = startingPoint.getNode();
429 beforeRgNode.setRouteGraph(beforeRouteGraph);
430 beforeRgNode.setRenderer(beforeRenderer);
431 beforeRgNode.setEditable(beforeEditable);
439 @EventHandler(priority = 200)
440 public boolean handleCommandEvents(CommandEvent ce) {
441 if (ce.command.equals(Commands.CANCEL)) {
445 } else if (ce.command.equals(Commands.ROTATE_ELEMENT_CCW) || ce.command.equals(Commands.ROTATE_ELEMENT_CW)) {
446 // TODO: rotate flag?
451 @EventHandler(priority = PointerInteractor.TOOL_PRIORITY + 20)
452 public boolean handleKeyEvents(KeyEvent ke) {
453 if (ke instanceof KeyPressedEvent) {
454 // Back-space, cancel prev bend
455 if (ke.keyCode == java.awt.event.KeyEvent.VK_BACK_SPACE)
456 return cancelPreviousBend();
459 if (ke.keyCode == java.awt.event.KeyEvent.VK_ALT) {
461 endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(ke instanceof KeyPressedEvent));
469 @EventHandler(priority = PointerInteractor.TOOL_PRIORITY + 20)
470 public boolean handleEvent(MouseEvent me) {
471 // Only handle events for the connection-initiating mouse
472 if (me.mouseId != mouseId)
475 if (me instanceof MouseMovedEvent)
476 return processMouseMove((MouseMovedEvent) me);
478 if (me instanceof MouseButtonPressedEvent)
479 return processMouseButtonPress((MouseButtonPressedEvent) me);
484 protected boolean processMouseMove(MouseMovedEvent me) {
485 mouseHasMoved = true;
487 Point2D mouseControlPos = me.controlPosition;
488 Point2D mouseCanvasPos = util.controlToCanvas(mouseControlPos, new Point2D.Double());
490 ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
491 if (snapAdvisor != null)
492 snapAdvisor.snap(mouseCanvasPos);
494 // Record last snapped canvas position of mouse.
495 this.lastMouseCanvasPos.setLocation(mouseCanvasPos);
497 if (isEndingInFlag()) {
498 endFlagNode.setTransform(AffineTransform.getTranslateInstance(mouseCanvasPos.getX(), mouseCanvasPos.getY()));
501 TerminalInfo ti = pi.pickTerminal(me.controlPosition);
503 Object canConnect = canConnect(ti.e, ti.t);
504 if (canConnect != null) {
505 connectionJudgment = (ConnectionJudgement) canConnect;
507 if (!isEndingInFlag() || !TerminalUtil.isSameTerminal(ti, endTerminal)) {
508 controlPoints.getLast()
509 .setPosition(ti.posDia)
510 .setAttachedToTerminal(ti);
518 // Make sure that we are ending with a flag if ALT is pressed
519 // and no end terminal is defined.
520 endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));
522 updateSG(new Point2D.Double(ti.posDia.getTranslateX(), ti.posDia.getTranslateY()));
527 connectionJudgment = null;
528 if (isEndTerminalDefined()) {
529 // CASE: Mouse was previously on top of a valid terminal to end
530 // the connection. Now the mouse has been moved where there is
531 // no longer a terminal to connect to.
533 // => Disconnect the last edge segment from the previous
534 // terminal, mark endElement/endTerminal non-existent
535 // and connect the disconnected edge to a new branch point.
537 disconnect(mouseCanvasPos);
539 controlPoints.getLast()
540 .setPosition(mouseCanvasPos)
541 .setAttachedToTerminal(null);
545 // CASE: Mouse was not previously on top of a valid ending
548 // => Move and re-orient last branch point.
550 controlPoints.getLast()
551 .setPosition(mouseCanvasPos);
554 // Make sure that we are ending with a flag if ALT is pressed and no end
555 // terminal is defined.
556 endWithoutTerminal(lastMouseCanvasPos, shouldEndWithFlag(me));
558 updateSG(lastMouseCanvasPos);
563 protected void connect(TerminalInfo ti) {
567 protected void disconnect(Point2D mouseCanvasPos) {
568 setEndTerminal(mouseCanvasPos.getX(), mouseCanvasPos.getY(), null, 0xf);
571 protected boolean processMouseButtonPress(MouseButtonPressedEvent e) {
572 MouseButtonEvent me = e;
574 // Do nothing before the mouse has moved at least a little.
575 // This prevents the user from ending the connection right where
580 if (me.button == MouseEvent.LEFT_BUTTON) {
581 Point2D mouseControlPos = me.controlPosition;
582 Point2D mouseCanvasPos = util.getInverseTransform().transform(mouseControlPos, new Point2D.Double());
584 ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
585 if (snapAdvisor != null)
586 snapAdvisor.snap(mouseCanvasPos);
588 // Clicked on an allowed end terminal. End connection & end mode.
589 if (isEndTerminalDefined()) {
594 // Finish connection in thin air only if the
595 // connection was started from a valid terminal.
596 if ((me.stateMask & MouseEvent.ALT_MASK) != 0 && startTerminal != null) {
597 connectionJudgment = (ConnectionJudgement) canConnect(null, null);
598 if (connectionJudgment == null)
603 } else if (routePointsAllowed()
604 && (me.stateMask & (MouseEvent.ALT_MASK | MouseEvent.SHIFT_MASK | MouseEvent.CTRL_MASK)) == 0) {
605 // Add new connection control point.
606 controlPoints.add(newControlPoint(mouseCanvasPos));
607 updateSG(mouseCanvasPos);
611 // Eat the event to prevent other participants from doing
612 // incompatible things while in this connection mode.
614 } else if (me.button == MouseEvent.RIGHT_BUTTON) {
615 return cancelPreviousBend();
621 protected boolean cancelPreviousBend() {
622 if (!routePointsAllowed())
625 // Just to make this code more comprehensible, prevent an editing
626 // case that requires ugly code to work.
627 if (isEndingInFlag())
630 // If there are no real route points, cancel whole connection.
631 if (controlPoints.size() <= 2) {
638 controlPoints.removeLast();
639 controlPoints.getLast().setPosition(lastMouseCanvasPos);
641 updateSG(lastMouseCanvasPos);
645 protected void updateSG(Point2D mousePos) {
646 routeGraph.setLocation(endRouteTerminal, mousePos.getX(), mousePos.getY());
647 //routeGraph.print(System.err);
651 protected boolean shouldEndWithFlag(MouseEvent me) {
652 return shouldEndWithFlag((me.stateMask & MouseEvent.ALT_MASK) != 0);
655 protected boolean shouldEndWithFlag(boolean altPressed) {
656 return altPressed && !isEndTerminalDefined() && createFlags;
659 protected boolean isEndTerminalDefined() {
660 return endTerminal != null;
663 protected boolean isFlagTerminal(TerminalInfo ti) {
664 return ti.e.getElementClass().containsClass(FlagHandler.class);
668 protected boolean isEndingInFlag() {
669 return endFlag != null;
672 protected void endWithoutTerminal(Point2D mousePos, boolean altDown) {
673 // Just go with branch points if flags are not allowed.
677 boolean endTerminalDefined = isEndTerminalDefined();
680 if (!isEndingInFlag()) {
681 endFlag = createFlag(EdgeEnd.End);
682 endFlagNode = showElement(ghostNode, "endFlag", endFlag.e, mousePos);
683 controlPoints.getLast()
684 .setAttachedToTerminal(endFlag);
686 // TerminalPainter must refresh
687 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
692 if (isEndingInFlag()) {
693 // Currently ending with flag but ALT is no longer down
694 // so that flag must be removed.
696 endFlagNode.remove();
699 ControlPoint cp = controlPoints.getLast();
700 cp.setAttachedToTerminal(endTerminal);
702 if (endTerminalDefined) {
703 cp.setPosition(endTerminal.posDia);
705 cp.setPosition(mousePos);
708 // Force Terminalpainter refresh
709 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, terminalHoverStrategy);
716 private G2DParentNode showElement(G2DParentNode parent, String nodeId, IElement element, Point2D pos) {
717 return showElement(parent, nodeId, element, AffineTransform.getTranslateInstance(pos.getX(), pos.getY()));
720 private G2DParentNode showElement(G2DParentNode parent, String nodeId, IElement element, AffineTransform tr) {
721 G2DParentNode elementParent = parent.getOrCreateNode(nodeId, G2DParentNode.class);
722 elementParent.setTransform(tr);
723 elementParent.removeNodes();
724 for (SceneGraph sg : element.getElementClass().getItemsByClass(SceneGraph.class))
725 sg.init(element, elementParent);
726 return elementParent;
733 protected ControlPoint newControlPoint(Point2D canvasPos) {
734 return new ControlPoint(canvasPos);
737 protected Triple<RouteGraph,RouteGraph,RouteGraphDelta> prepareRouteGraphDelta() {
738 // Prevent route graph connection synchronization from crashing on the
739 // transient route terminal that doesn't exist yet. It is created after
740 // persisting the route line, which is the only purpose of this route
741 // graph synchronization.
742 routeGraph.remove(endRouteTerminal);
743 return Triple.make(beforeRouteGraph, routeGraph, routeGraphDelta);
746 protected void createConnection() {
747 TimeLogger.resetTimeAndLog(getClass(), "createConnection");
748 final ConnectionJudgement judgment = this.connectionJudgment;
749 if (judgment == null) {
750 ErrorLogger.defaultLogError("Cannot create connection, no judgment available on connection validity", null);
754 final ConnectionBuilder builder = new ConnectionBuilder(this.diagram);
755 final Triple<RouteGraph,RouteGraph,RouteGraphDelta> rgs = prepareRouteGraphDelta();
757 Simantics.getSession().asyncRequest(new WriteRequest() {
759 public void perform(WriteGraph graph) throws DatabaseException {
760 graph.markUndoPoint();
761 Resource connection = ElementUtils.getObject(startTerminal.e);
762 if (!rgs.third.isEmpty()) {
763 new RouteGraphConnection(graph, connection).synchronize(graph, rgs.first, rgs.second, rgs.third);
765 Resource attachToLine = RouteGraphConnection.deserialize(graph, attachedToRouteLine.getData());
766 builder.attachToRouteGraph(graph, judgment, connection, attachToLine, controlPoints, endTerminal, FlagClass.Type.Out);
768 }, new Callback<DatabaseException>() {
770 public void run(DatabaseException parameter) {
771 if (parameter != null)
772 ExceptionUtils.logAndShowError(parameter);
777 protected boolean routePointsAllowed() {
778 return Boolean.TRUE.equals(diagram.getHint(DiagramHints.KEY_ALLOW_ROUTE_POINTS));
781 protected Object canConnect(IElement endElement, Terminal endTerminal) {
782 IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);
783 return canConnect(advisor, endElement, endTerminal);
786 protected Object canConnect(IConnectionAdvisor advisor, IElement endElement, Terminal endTerminal) {
788 return ConnectionJudgement.CANBEMADELEGAL;
789 if (alreadyConnected.contains(Pair.make(endElement, endTerminal)))
791 return advisor.canBeConnected(null, startTerminal.e, startTerminal.t, endElement, endTerminal);
794 protected static FlagClass.Type endToFlagType(EdgeEnd end) {
797 return FlagClass.Type.In;
799 return FlagClass.Type.Out;
801 throw new IllegalArgumentException("unrecognized edge end: " + end);
805 protected TerminalInfo createFlag(EdgeEnd connectionEnd) {
806 ElementClass flagClass = elementClassProvider.get(ElementClasses.FLAG);
807 IElement e = Element.spawnNew(flagClass);
809 e.setHint(FlagClass.KEY_FLAG_TYPE, endToFlagType(connectionEnd));
810 e.setHint(FlagClass.KEY_FLAG_MODE, FlagClass.Mode.Internal);
812 TerminalInfo ti = new TerminalInfo();
814 ti.t = ElementUtils.getSingleTerminal(e);
815 ti.posElem = TerminalUtil.getTerminalPosOnElement(e, ti.t);
816 ti.posDia = TerminalUtil.getTerminalPosOnDiagram(e, ti.t);
821 // ------------------------------------------------------------------------
823 static RouteGraphTarget pickRouteGraphConnection(IDiagram diagram, Shape pickShape, double pickDistance) {
824 ArrayList<IElement> elements = new ArrayList<IElement>();
825 PickRequest req = new PickRequest(pickShape);
826 DiagramUtils.pick(diagram, req, elements);
827 for (Iterator<IElement> it = elements.iterator(); it.hasNext();) {
828 IElement e = it.next();
829 RouteGraphNode rgn = e.getHint(RouteGraphConnectionClass.KEY_RG_NODE);
830 if (rgn == null || rgn.getRouteGraph() == null)
833 if (elements.isEmpty())
836 Rectangle2D pickRect = pickShape.getBounds2D();
837 final double x = pickRect.getCenterX();
838 final double y = pickRect.getCenterY();
840 return pickNearestRouteGraphConnection(elements, x, y, pickDistance);
843 private static RouteGraphTarget pickNearestRouteGraphConnection(ArrayList<IElement> elements, double x, double y, double pd) {
844 // Find the nearest distance at which we get hits.
846 double lo = hi * .01;
849 double delta = (hi - lo);
856 for (IElement connection : elements) {
857 RouteGraphNode rgn = connection.getHint(RouteGraphConnectionClass.KEY_RG_NODE);
858 RouteLine line = rgn.getRouteGraph().pickLine(x, y, pd);
871 // Now that the nearest hitting distance is found, find the nearest intersection.
872 RouteGraphTarget nearestTarget = null;
873 double nearest = Double.MAX_VALUE;
874 for (IElement connection : elements) {
875 RouteGraphNode rgn = connection.getHint(RouteGraphConnectionClass.KEY_RG_NODE);
876 RouteLine line = rgn.getRouteGraph().pickLine(x, y, pd);
880 Point2D intersection = intersectionPoint(x, y, line);
881 if (intersection == null)
884 double dx = intersection.getX() - x;
885 double dy = intersection.getY() - y;
886 double dist = Math.sqrt(dx*dx + dy*dy);
887 if (dist < nearest) {
889 nearestTarget = new RouteGraphTarget(connection, rgn, line, new Point2D.Double(x, y), intersection);
893 return nearestTarget;
896 static Point2D intersectionPoint(double x, double y, RouteLine line) {
897 Collection<RoutePoint> points = line.getPoints();
898 if (points.size() < 2)
900 RoutePoint s = line.getBegin();
901 RoutePoint e = line.getEnd();
902 return GeometryUtils.intersectionToLine(s.getX(), s.getY(), e.getX(), e.getY(), x, y);