1 /*******************************************************************************
2 * Copyright (c) 2012, 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 - refactoring
12 *******************************************************************************/
13 package org.simantics.diagram.adapter;
15 import java.awt.BasicStroke;
16 import java.awt.Color;
17 import java.awt.Shape;
18 import java.awt.Stroke;
19 import java.awt.geom.AffineTransform;
20 import java.awt.geom.Rectangle2D;
21 import java.util.Collection;
22 import java.util.Collections;
26 import org.simantics.databoard.Bindings;
27 import org.simantics.db.ReadGraph;
28 import org.simantics.db.Resource;
29 import org.simantics.db.Session;
30 import org.simantics.db.Statement;
31 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
32 import org.simantics.db.common.request.ResourceRead2;
33 import org.simantics.db.common.request.UnaryRead;
34 import org.simantics.db.common.utils.NameUtils;
35 import org.simantics.db.exception.DatabaseException;
36 import org.simantics.diagram.connection.ConnectionVisuals;
37 import org.simantics.diagram.connection.RouteGraph;
38 import org.simantics.diagram.connection.RouteGraphConnectionClass;
39 import org.simantics.diagram.connection.RouteLine;
40 import org.simantics.diagram.connection.RouteNode;
41 import org.simantics.diagram.connection.RouteTerminal;
42 import org.simantics.diagram.connection.RouteTerminalPosition;
43 import org.simantics.diagram.connection.rendering.BasicConnectionStyle;
44 import org.simantics.diagram.connection.rendering.ConnectionStyle;
45 import org.simantics.diagram.connection.rendering.ExampleConnectionStyle;
46 import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;
47 import org.simantics.diagram.connection.rendering.arrows.ArrowLineEndStyle;
48 import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;
49 import org.simantics.diagram.connection.rendering.arrows.PlainLineEndStyle;
50 import org.simantics.diagram.content.EdgeResource;
51 import org.simantics.diagram.content.ResourceTerminal;
52 import org.simantics.diagram.content.TerminalMap;
53 import org.simantics.diagram.query.DiagramRequests;
54 import org.simantics.diagram.stubs.DiagramResource;
55 import org.simantics.diagram.stubs.G2DResource;
56 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
57 import org.simantics.diagram.synchronization.graph.RouteGraphConnection;
58 import org.simantics.g2d.canvas.ICanvasContext;
59 import org.simantics.g2d.canvas.impl.CanvasContext;
60 import org.simantics.g2d.diagram.IDiagram;
61 import org.simantics.g2d.diagram.handler.DataElementMap;
62 import org.simantics.g2d.diagram.handler.Topology.Connection;
63 import org.simantics.g2d.diagram.handler.Topology.Terminal;
64 import org.simantics.g2d.diagram.impl.ElementDiagram;
65 import org.simantics.g2d.element.ElementUtils;
66 import org.simantics.g2d.element.IElement;
67 import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
68 import org.simantics.g2d.element.handler.TerminalLayout;
69 import org.simantics.g2d.elementclass.FlagClass.Type;
70 import org.simantics.layer0.Layer0;
71 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphChangeEvent;
72 import org.simantics.scenegraph.utils.GeometryUtils;
73 import org.simantics.structural.stubs.StructuralResource2;
74 import org.simantics.structural2.modelingRules.CPTerminal;
75 import org.simantics.structural2.modelingRules.IAttachmentRelationMap;
76 import org.simantics.structural2.modelingRules.IModelingRules;
77 import org.simantics.utils.threads.CurrentThread;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
81 import gnu.trove.map.hash.THashMap;
82 import gnu.trove.set.hash.THashSet;
84 public class RouteGraphUtils {
86 private static final Logger LOGGER = LoggerFactory.getLogger(RouteGraph.class);
87 public static boolean DEBUG = false;
89 public static final ILineEndStyle HEAD = new ArrowLineEndStyle("fill 2 1 0");
90 public static final ILineEndStyle TAIL = PlainLineEndStyle.INSTANCE;
92 public static RouteGraph load(ReadGraph graph, Resource diagramRuntime, Resource connection) throws DatabaseException {
93 ICanvasContext canvas = new CanvasContext(CurrentThread.getThreadAccess());
94 IDiagram diagram = new ElementDiagram(canvas);
95 return load(graph, diagramRuntime, connection, canvas, diagram);
98 public static RouteGraph load(ReadGraph graph, Resource diagramRuntime, Resource connection, ICanvasContext canvas, IDiagram diagram) throws DatabaseException {
99 Layer0 L0 = Layer0.getInstance(graph);
100 Resource diagramResource = graph.getPossibleObject(connection, L0.PartOf);
101 IModelingRules modelingRules = graph.syncRequest(DiagramRequests.getModelingRules(diagramResource, null), TransientCacheListener.<IModelingRules>instance());
102 return load(graph, diagramRuntime, connection, canvas, diagram, null, modelingRules, null);
105 public static RouteGraph load(ReadGraph graph, Resource diagramRuntime, Resource connection, ICanvasContext canvas, IDiagram diagram, IElement element, IModelingRules modelingRules, Set<BackendConnection> backendConnections) throws DatabaseException {
107 DiagramResource DIA = DiagramResource.getInstance(graph);
108 StructuralResource2 STR = StructuralResource2.getInstance(graph);
110 RouteGraph rg = new RouteGraph();
112 // Default capacity should be enough for common cases.
113 Set<EdgeResource> links = new THashSet<EdgeResource>();
114 Map<Object, RouteNode> nodeByData = new THashMap<Object, RouteNode>();
116 // Load all route graph interior RouteNodes: route lines and points
117 for (Resource interiorNode : graph.getObjects(connection, DIA.HasInteriorRouteNode)) {
118 if (graph.isInstanceOf(interiorNode, DIA.RouteLine)) {
119 Boolean isHorizontal = graph.getRelatedValue(interiorNode, DIA.IsHorizontal, Bindings.BOOLEAN);
120 Double position = graph.getRelatedValue(interiorNode, DIA.HasPosition, Bindings.DOUBLE);
121 RouteLine line = rg.addLine(isHorizontal, position);
122 line.setData( RouteGraphConnection.serialize(graph, interiorNode) );
124 nodeByData.put( interiorNode, line );
126 for (Resource connectedTo : graph.getObjects(interiorNode, DIA.AreConnected)) {
127 links.add( new EdgeResource(interiorNode, connectedTo) );
129 } else if (graph.isInstanceOf(interiorNode, DIA.RoutePoint)) {
130 // Not supported yet. Ignore.
134 Rectangle2D bounds = new Rectangle2D.Double();
135 Map<Resource, Resource> connectorToModeledAttachment = null;
137 // Primarily the loader will believe what modeling rules say about
138 // connector attachment relations.
140 // If modeling rules decide nothing, then we simply believe what the
141 // the attachment relations in the graph say.
143 // Special case 1: connection with two (2) terminals
144 // If the attachment of one of two terminals is decided by modeling
145 // rules, the other attachment shall be the opposite of the decided
146 // attachment (see forcedAttachmentRelation below).
148 // Special case 2: connected to a flag
149 // If the attached element is a flag and modeling rules say nothing
150 // about it, believe the direction stated by the flag type.
152 Collection<Statement> toConnectorStatements = graph.getStatements(connection, DIA.HasConnector);
153 int terminalCount = 0;
155 // See if modeling rules judge any of the connection terminal attachments.
156 if (modelingRules != null) {
157 for (Statement toConnector : toConnectorStatements) {
158 Resource connector = toConnector.getObject();
160 Statement terminalStm = findTerminalStatement(graph, connection, connector, STR);
161 if (terminalStm == null)
162 // Ignore broken connector: attached to the connection but not to any terminal.
165 Resource terminalElement = terminalStm.getObject();
166 Resource connectionRelation = graph.getPossibleInverse(terminalStm.getPredicate());
167 if (connectionRelation == null)
172 IAttachmentRelationMap map = modelingRules.getAttachmentRelations(graph, connection);
173 Resource attachment = map.get(graph, new CPTerminal(terminalElement, connectionRelation));
174 if (attachment != null) {
175 // Primary: believe modeling rules
176 if (connectorToModeledAttachment == null)
177 connectorToModeledAttachment = new THashMap<Resource, Resource>(toConnectorStatements.size());
178 connectorToModeledAttachment.put(connector, attachment);
180 LOGGER.debug("modeling rules decided attachment: " + NameUtils.getSafeName(graph, attachment, true) + " for (" + NameUtils.toString(graph, toConnector, true) + ") & (" + NameUtils.toString(graph, terminalStm, true) + ")");
181 } else if (graph.isInstanceOf(terminalElement, DIA.Flag)) {
182 // Secondary: believe flag type
183 attachment = resolveFlagAttachment(graph, connection, terminalElement, modelingRules, DIA);
184 if (attachment != null) {
185 if (connectorToModeledAttachment == null)
186 connectorToModeledAttachment = new THashMap<Resource, Resource>(toConnectorStatements.size());
187 connectorToModeledAttachment.put(connector, attachment);
189 LOGGER.debug("flag type decided attachment: " + NameUtils.getSafeName(graph, attachment, true) + " for (" + NameUtils.toString(graph, toConnector, true) + ") & (" + NameUtils.toString(graph, terminalStm, true) + ")");
195 if (connectorToModeledAttachment == null)
196 connectorToModeledAttachment = Collections.emptyMap();
198 Resource forcedAttachmentRelation = null;
199 if (terminalCount == 2 && connectorToModeledAttachment.size() == 1) {
200 forcedAttachmentRelation = getInverseAttachment(graph, connectorToModeledAttachment.values().iterator().next(), DIA);
202 LOGGER.debug("set forced attachment: " + NameUtils.getSafeLabel(graph, forcedAttachmentRelation));
205 Resource connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);
206 DataElementMap diagramDataElementMap = diagram.getDiagramClass().getSingleItem(DataElementMap.class);
208 // Load all node terminal connections as RouteTerminals
209 for (Statement toConnector : toConnectorStatements) {
210 Resource connector = toConnector.getObject();
211 Resource attachmentRelation = toConnector.getPredicate();
213 LOGGER.debug("original attachment relation: " + NameUtils.getSafeLabel(graph, attachmentRelation));
215 Statement terminalStm = findTerminalStatement(graph, connection, connector, STR);
216 if (terminalStm == null)
217 // Ignore broken connector: attached to the connection but not to any terminal.
220 Resource terminalElement = terminalStm.getObject();
221 Resource terminalElementType = graph.getPossibleType(terminalElement, DIA.Element);
222 if (terminalElementType == null)
223 // Ignore non-element terminal elements
226 Resource connectionRelation = graph.getPossibleInverse(terminalStm.getPredicate());
227 if (connectionRelation == null)
230 // Discover node and terminal this connector is connected to.
231 TerminalMap terminals = graph.syncRequest(DiagramRequests.elementTypeTerminals(terminalElementType),
232 TransientCacheListener.<TerminalMap>instance());
233 Resource terminal = terminals.getTerminal(connectionRelation);
234 if (terminal == null) {
236 "RouteGraphUtils: Could not find terminal for connection point "
237 + NameUtils.getSafeName(graph, connectionRelation, true)
239 + NameUtils.getSafeName(graph, terminalElement, true));
243 double[] position = graph.getRelatedValue(connector, DIA.HasRelativeLocation, Bindings.DOUBLE_ARRAY);
244 if (position.length != 2)
245 position = new double[] { 0, 0 };
247 AffineTransform terminalTr = DiagramGraphUtil.getDynamicWorldTransform(graph, diagramRuntime, terminalElement);
248 final AffineTransform terminalElementTransform = new AffineTransform(terminalTr);
251 LOGGER.debug("terminalStm: " + NameUtils.toString(graph, terminalStm));
252 LOGGER.debug("terminal: " + NameUtils.getURIOrSafeNameInternal(graph, terminalStm.getPredicate()));
253 LOGGER.debug("terminalElement: " + NameUtils.getURIOrSafeNameInternal(graph, terminalElement) + " : " + NameUtils.getURIOrSafeNameInternal(graph, terminalElementType));
254 LOGGER.debug("terminalElementTr: " + terminalTr);
257 double x = terminalTr.getTranslateX();
258 double y = terminalTr.getTranslateY();
259 double minx = x-1, miny = y-1, maxx = x+1, maxy = y+1;
262 // Use modelingRules to ascertain the proper attachmentRelation
263 // for this terminal connection, if available.
264 Resource att = connectorToModeledAttachment.get(connector);
266 attachmentRelation = att;
268 LOGGER.debug("modeling rules attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
269 } else if (forcedAttachmentRelation != null) {
270 attachmentRelation = forcedAttachmentRelation;
272 LOGGER.debug("forced rules attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
275 LOGGER.debug("decided attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
277 // Get element bounds to decide allowed terminal direction(s)
278 IElement te = graph.syncRequest(DiagramRequests.getElement(canvas, diagram, terminalElement, null));
279 ElementUtils.getElementBounds(te, bounds);
281 Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(bounds, terminalTr);
282 bounds.setFrame(shp.getBounds2D());
285 // Expand bounds by 2mm to make the connections enter the terminals
286 // at a straight angle and from a distance instead of coming in
288 GeometryUtils.expandRectangle(bounds, 2);
289 minx = bounds.getMinX();
290 miny = bounds.getMinY();
291 maxx = bounds.getMaxX();
292 maxy = bounds.getMaxY();
294 final ResourceTerminal rt = new ResourceTerminal(terminal);
295 final TerminalLayout tl = te.getElementClass().getSingleItem(TerminalLayout.class);
296 AffineTransform terminalPos = tl.getTerminalPosition(element, rt);
298 if (terminalPos != null) {
299 terminalTr.concatenate(terminalPos);
300 x = terminalTr.getTranslateX();
301 y = terminalTr.getTranslateY();
303 LOGGER.debug("terminalPos/Tr: " + terminalPos + ", " + terminalTr);
306 Integer allowedDirections = graph.getPossibleRelatedValue(terminal, DIA.Terminal_AllowedDirections, Bindings.INTEGER);
307 if (allowedDirections != null) {
308 direction |= allowedDirections;
309 direction = rotateDirection(direction, terminalTr);
311 direction |= RouteGraphConnectionClass.shortestDirectionOutOfBounds(x, y, bounds);
313 //LOGGER.debug("DIR(" + x + ", " + y + ", " + bounds + "): " + Integer.toHexString(direction));
315 if (backendConnections != null) {
316 backendConnections.add(
317 new BackendConnection(
318 toEdgeEnd(graph, attachmentRelation, EdgeEnd.Begin, DIA),
325 // Accept any horizontal/vertical direction if nothing is defined
328 if (graph.<Boolean>getRelatedValue(connector, DIA.Connector_straight, Bindings.BOOLEAN))
329 direction |= RouteTerminal.DIR_DIRECT;
330 // FIXME: routegraph crashes if this is done for all terminals regardless of the amount of terminals.
333 LOGGER.debug("load line style: " + NameUtils.getSafeLabel(graph, attachmentRelation));
334 ILineEndStyle endStyle = loadLineEndStyle(graph, attachmentRelation, connectionType, TAIL);
336 RouteTerminal routeTerminal = rg.addTerminal(x, y, minx, miny, maxx, maxy, direction, endStyle,
337 new RouteTerminalPositionImpl(diagram, diagramDataElementMap, terminalElement, terminalElementTransform, tl, rt));
338 routeTerminal.setData( RouteGraphConnection.serialize(graph, connector) );
340 nodeByData.put( connector, routeTerminal );
342 for (Resource connectedTo : graph.getObjects(connector, DIA.AreConnected)) {
343 links.add( new EdgeResource(connectedTo, connector) );
347 // Finish route graph loading by Linking route nodes together
348 for (EdgeResource link : links) {
349 RouteNode n1 = nodeByData.get(link.first());
350 RouteNode n2 = nodeByData.get(link.second());
351 if (n1 == null || n2 == null) {
352 LOGGER.warn("Stray connection link found: " + link.toString(graph));
362 public static EdgeEnd toEdgeEnd(ReadGraph graph, Resource attachmentRelation, EdgeEnd defaultValue, DiagramResource DIA)
363 throws DatabaseException {
364 if (graph.isSubrelationOf(attachmentRelation, DIA.HasTailConnector))
365 return EdgeEnd.Begin;
366 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector))
371 public static Resource resolveFlagAttachment(ReadGraph graph, Resource connection, Resource flag, IModelingRules modelingRules, DiagramResource DIA) throws DatabaseException {
372 Type type = resolveFlagType(graph, connection, flag, modelingRules, DIA);
375 case In: return DIA.HasPlainConnector;
376 case Out: return DIA.HasArrowConnector;
382 private static Type resolveFlagType(ReadGraph graph, Resource connection, Resource flag, IModelingRules modelingRules, DiagramResource DIA) throws DatabaseException {
383 return readFlagType(graph, flag, DIA);
386 private static Type readFlagType(ReadGraph graph, Resource flag, DiagramResource DIA) throws DatabaseException {
387 Resource flagType = graph.getPossibleObject(flag, DIA.HasFlagType);
388 Type type = DiagramGraphUtil.toFlagType(DIA, flagType);
392 public static Statement findTerminalStatement(ReadGraph graph, Resource connection, Resource connector, StructuralResource2 STR)
393 throws DatabaseException {
394 for (Statement stm : graph.getStatements(connector, STR.Connects)) {
395 if (connection.equals(stm.getObject()))
402 public static Resource getInverseAttachment(ReadGraph graph, Resource attachmentRelation, DiagramResource DIA)
403 throws DatabaseException {
404 Resource inverse = graph.getPossibleObject(attachmentRelation, DIA.HasInverseAttachment);
407 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector))
408 return DIA.HasPlainConnector;
409 if (graph.isSubrelationOf(attachmentRelation, DIA.HasTailConnector))
410 return DIA.HasArrowConnector;
414 public static ILineEndStyle loadLineEndStyle(ReadGraph graph, Resource attachmentRelation, ILineEndStyle defaultValue)
415 throws DatabaseException {
416 ILineEndStyle style = graph.syncRequest(new LineEndStyle(attachmentRelation),
417 TransientCacheListener.<ILineEndStyle>instance());
418 return style != null ? style : defaultValue;
421 public static ILineEndStyle loadLineEndStyle(ReadGraph graph, Resource attachmentRelation, Resource connectionType, ILineEndStyle defaultValue)
422 throws DatabaseException {
423 if(connectionType != null) {
424 ILineEndStyle style = graph.syncRequest(new LineEndStyleWithType(attachmentRelation, connectionType),
425 TransientCacheListener.<ILineEndStyle>instance());
426 return style != null ? style : defaultValue;
428 ILineEndStyle style = graph.syncRequest(new LineEndStyle(attachmentRelation),
429 TransientCacheListener.<ILineEndStyle>instance());
430 return style != null ? style : defaultValue;
435 * A request for caching ILineEndStyle results.
437 public static class LineEndStyle extends UnaryRead<Resource, ILineEndStyle> {
438 public LineEndStyle(Resource attachmentRelation) {
439 super(attachmentRelation);
442 public ILineEndStyle perform(ReadGraph graph) throws DatabaseException {
443 return loadLineEndStyle0(graph, parameter);
447 public static class LineEndStyleWithType extends ResourceRead2<ILineEndStyle> {
448 public LineEndStyleWithType(Resource attachmentRelation, Resource connectionType) {
449 super(attachmentRelation, connectionType);
452 public ILineEndStyle perform(ReadGraph graph) throws DatabaseException {
453 return loadLineEndStyle0(graph, resource, resource2);
457 private static ILineEndStyle loadLineEndStyle0(ReadGraph graph, Resource attachmentRelation)
458 throws DatabaseException {
459 ILineEndStyle style = graph.getPossibleAdapter(attachmentRelation, ILineEndStyle.class);
462 DiagramResource DIA = DiagramResource.getInstance(graph);
463 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector))
465 if (graph.isSubrelationOf(attachmentRelation, DIA.HasTailConnector))
470 private static ILineEndStyle loadLineEndStyle0(ReadGraph graph, Resource attachmentRelation, Resource connectionType)
471 throws DatabaseException {
472 DiagramResource DIA = DiagramResource.getInstance(graph);
473 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector)) {
474 if(connectionType != null) {
475 G2DResource G2D = G2DResource.getInstance(graph);
476 Resource end = graph.getPossibleObject(connectionType, G2D.HasEndArrow);
478 Double size = graph.getPossibleRelatedValue(end, G2D.HasSize, Bindings.DOUBLE);
479 if(size == null) size = 0.0;
480 Double widthRatio = graph.getPossibleRelatedValue(end, G2D.HasWidthRatio, Bindings.DOUBLE);
481 if(widthRatio == null) widthRatio = 1.0;
482 Double space = graph.getPossibleRelatedValue(end, G2D.HasSpace, Bindings.DOUBLE);
483 if(space == null) space = 0.0;
485 Resource c = graph.getPossibleObject(end, G2D.HasColor);
488 float[] col = graph.getPossibleValue(c, Bindings.FLOAT_ARRAY);
489 if (col != null && col.length >= 3) {
490 color = new Color(col[0], col[1], col[2]);
494 return new ArrowLineEndStyle(size, widthRatio*size, space, color);
498 return loadLineEndStyle0(graph, attachmentRelation);
506 * @throws DatabaseException
508 public static StyledRouteGraphRenderer getRenderer(ReadGraph graph, ConnectionStyle style)
509 throws DatabaseException {
510 return graph.syncRequest(new Renderer(style),
511 TransientCacheListener.<StyledRouteGraphRenderer>instance());
515 * A request for caching StyledRouteGraphRenderer results.
517 public static class Renderer extends UnaryRead<ConnectionStyle, StyledRouteGraphRenderer> {
518 public Renderer(ConnectionStyle style) {
522 public StyledRouteGraphRenderer perform(ReadGraph graph) throws DatabaseException {
523 return new StyledRouteGraphRenderer(parameter);
527 private static final ConnectionStyle DEFAULT_CONNECTION_STYLE = new BasicConnectionStyle(Color.BLACK, Color.BLACK, 3, ExampleConnectionStyle.SOLID, ExampleConnectionStyle.SOLID, 8);
532 * @param modelingRules
535 * @throws DatabaseException
537 protected static ConnectionStyle readConnectionStyle(ReadGraph graph, IModelingRules modelingRules, Resource connection, StructuralResource2 STR) throws DatabaseException {
538 Resource connectionType = null;
539 if (modelingRules != null)
540 connectionType = modelingRules.getConnectionType(graph, connection);
541 if (connectionType == null)
542 connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);
543 return connectionType != null ? readConnectionStyleFromConnectionType(graph, connectionType) : DEFAULT_CONNECTION_STYLE;
546 protected static ConnectionStyle readConnectionStyleFromConnectionType(ReadGraph graph, Resource connectionType) throws DatabaseException {
547 return graph.syncRequest(new ReadConnectionStyleFromConnectionType(connectionType),
548 TransientCacheListener.<ConnectionStyle>instance());
552 * A request for caching ConnectionStyle results.
554 public static class ReadConnectionStyleFromConnectionType extends UnaryRead<Resource, ConnectionStyle> {
555 public ReadConnectionStyleFromConnectionType(Resource connectionType) {
556 super(connectionType);
559 public ConnectionStyle perform(ReadGraph graph) throws DatabaseException {
560 return readConnectionStyleFromConnectionType0(graph, parameter);
564 protected static ConnectionStyle readConnectionStyleFromConnectionType0(ReadGraph graph, Resource connectionType) throws DatabaseException {
565 ConnectionVisuals cv = null;
566 if (connectionType != null)
567 cv = graph.syncRequest(DiagramRequests.getConnectionVisuals(connectionType),
568 TransientCacheListener.<ConnectionVisuals>instance());
570 // Fixed style settings
571 Color branchPointColor = Color.BLACK;
572 double branchPointRadius = 0.5;
573 double degenerateLineLength = 0.8;
575 Color lineColor = cv != null ? cv.toColor() : null;
576 if (lineColor == null)
577 lineColor = Color.DARK_GRAY;
578 Stroke lineStroke = cv != null ? cv.stroke : null;
579 if (lineStroke == null)
580 lineStroke = new BasicStroke(0.1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, null, 0);
581 Stroke routeLineStroke = GeometryUtils.scaleStrokeWidth(lineStroke, 2);
582 double rounding = cv.rounding == null ? 0.0 : cv.rounding;
584 return new BasicConnectionStyle(
590 degenerateLineLength,
594 public static void scheduleSynchronize(Session session, Resource connection, RouteGraphChangeEvent event) {
595 session.asyncRequest(RouteGraphConnection.synchronizer(connection, event));
598 // ------------------------------------------------------------------------
599 // RouteGraph RouteTerminal allowed direction rotation support
600 // ------------------------------------------------------------------------
602 public static int rotateDirection(int direction, AffineTransform at) {
603 // When direct routing is enabled, no point in wasting time rotating.
604 if ((direction & RouteTerminal.DIR_DIRECT) != 0)
607 final int mask = (AffineTransform.TYPE_MASK_ROTATION | AffineTransform.TYPE_FLIP);
608 boolean rotatedOrFlipped = (at.getType() & mask) != 0;
609 if (rotatedOrFlipped) {
610 double xAxisAngle = Math.atan2( at.getShearY(), at.getScaleX() );
611 double yAxisAngle = Math.atan2( at.getScaleY(), at.getShearX() );
613 int xQuadrant = mainQuadrant(xAxisAngle);
614 int yQuadrant = mainQuadrant(yAxisAngle);
616 int xDirMask = direction & (RouteTerminal.DIR_LEFT | RouteTerminal.DIR_RIGHT);
617 int yDirMask = direction & (RouteTerminal.DIR_DOWN | RouteTerminal.DIR_UP);
619 int xDirMaskRotated = rotl4(xDirMask, xQuadrant);
620 int yDirMaskRotated = rotl4(yDirMask, yQuadrant-1);
622 direction = xDirMaskRotated | yDirMaskRotated;
629 * 4-bit rotate left without carry operation.
630 * Operates on the 4 least sensitive bits of the integer
631 * and leaves the higher bits untouched.
632 * @param x the bits to rotate
633 * @param n the amount of rotation [0..3]
636 private static int rotl4(int x, int n) {
640 int hx = x & 0xfffffff0;
642 int xh = (lx << n) & 0xf;
643 int xl = (lx >>> (4-n));
655 * @param theta angle in radians
656 * @return the quadrant based on the ASCII art above
658 private static int mainQuadrant(double theta) {
659 if (theta > -DEG_45 && theta <= DEG_45) {
661 } else if ((theta > DEG_45 && theta <= DEG_135)) {
663 } else if (theta >= -DEG_135 && theta < -DEG_45) {
669 private static final double DEG_45 = Math.PI/4.;
670 private static final double DEG_135 = Math.PI*3./4.;
672 public static class BackendConnection {
673 public final Resource node;
674 public final Resource terminal;
675 public final EdgeEnd end;
676 public final int hash;
677 public BackendConnection(EdgeEnd end, Resource node, Resource terminal) {
680 assert terminal != null;
683 this.terminal = terminal;
684 this.hash = makeHash();
687 public boolean equals(Object obj) {
690 if (!(obj instanceof Connection))
692 Connection other = (Connection) obj;
693 return other.terminal == terminal
694 && other.node == node
697 private int makeHash() {
698 final int prime = 31;
700 result = prime * result + end.hashCode();
701 result = prime * result + ((node == null) ? 0 : node.hashCode());
702 result = prime * result + ((terminal == null) ? 0 : terminal.hashCode());
706 public int hashCode() {
710 public String toString() {
711 return "BackendConnection[node=" + node + ", terminal=" + terminal + ", end=" + end + "]";
715 private static class RouteTerminalPositionImpl implements RouteTerminalPosition {
717 private IDiagram diagram;
718 private DataElementMap dataElementMap;
719 private Resource element;
720 private AffineTransform elementTransform;
721 private TerminalLayout terminalLayout;
722 private Terminal elementTerminal;
724 private transient AffineTransform lastTerminalTr;
725 private transient AffineTransform transform;
727 public RouteTerminalPositionImpl(IDiagram diagram, DataElementMap dem, Resource element, AffineTransform elementTransform, TerminalLayout terminalLayout, Terminal terminal) {
728 this.diagram = diagram;
729 this.dataElementMap = dem;
730 this.element = element;
731 this.elementTransform = elementTransform;
732 this.terminalLayout = terminalLayout;
733 this.elementTerminal = terminal;
737 public AffineTransform getTransform() {
738 IElement actualElement = dataElementMap.getElement(diagram, element);
739 AffineTransform terminalTr = actualElement != null ? terminalLayout.getTerminalPosition(actualElement, elementTerminal) : null;
740 if (terminalTr == null)
741 return elementTransform;
743 // Return cached transform if terminal transform has not changed.
744 AffineTransform result = this.transform;
745 AffineTransform lastTerminalTr = this.lastTerminalTr;
746 if (lastTerminalTr != null) {
747 if (terminalTr.equals(lastTerminalTr))
749 lastTerminalTr.setTransform(terminalTr);
751 lastTerminalTr = this.lastTerminalTr = new AffineTransform(terminalTr);
752 result = this.transform = new AffineTransform();
755 result.setTransform(elementTransform);
756 result.concatenate(terminalTr);