1 /*******************************************************************************
\r
2 * Copyright (c) 2007, 2011 Association for Decentralized Information Management in
\r
4 * All rights reserved. This program and the accompanying materials
\r
5 * are made available under the terms of the Eclipse Public License v1.0
\r
6 * which accompanies this distribution, and is available at
\r
7 * http://www.eclipse.org/legal/epl-v10.html
\r
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
12 package org.simantics.sysdyn.ui.elements.connections;
\r
14 import java.awt.BasicStroke;
\r
15 import java.awt.Color;
\r
16 import java.awt.Shape;
\r
17 import java.awt.Stroke;
\r
18 import java.awt.geom.AffineTransform;
\r
19 import java.awt.geom.Rectangle2D;
\r
20 import java.util.ArrayList;
\r
21 import java.util.Collection;
\r
22 import java.util.Collections;
\r
23 import java.util.HashMap;
\r
24 import java.util.HashSet;
\r
25 import java.util.Map;
\r
26 import java.util.Set;
\r
28 import org.simantics.databoard.Bindings;
\r
29 import org.simantics.db.AsyncReadGraph;
\r
30 import org.simantics.db.ReadGraph;
\r
31 import org.simantics.db.Resource;
\r
32 import org.simantics.db.Session;
\r
33 import org.simantics.db.Statement;
\r
34 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
\r
35 import org.simantics.db.common.utils.NameUtils;
\r
36 import org.simantics.db.exception.DatabaseException;
\r
37 import org.simantics.db.procedure.AsyncProcedure;
\r
38 import org.simantics.diagram.adapter.SyncElementFactory;
\r
39 import org.simantics.diagram.connection.ConnectionVisuals;
\r
40 import org.simantics.diagram.connection.RouteGraph;
\r
41 import org.simantics.diagram.connection.RouteGraphConnectionClass;
\r
42 import org.simantics.diagram.connection.RouteLine;
\r
43 import org.simantics.diagram.connection.RouteNode;
\r
44 import org.simantics.diagram.connection.RouteTerminal;
\r
45 import org.simantics.diagram.connection.rendering.ConnectionStyle;
\r
46 import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;
\r
47 import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;
\r
48 import org.simantics.diagram.content.EdgeResource;
\r
49 import org.simantics.diagram.content.ResourceTerminal;
\r
50 import org.simantics.diagram.content.TerminalMap;
\r
51 import org.simantics.diagram.query.DiagramRequests;
\r
52 import org.simantics.diagram.stubs.DiagramResource;
\r
53 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
\r
54 import org.simantics.diagram.synchronization.graph.RouteGraphConnection;
\r
55 import org.simantics.diagram.ui.DiagramModelHints;
\r
56 import org.simantics.g2d.canvas.ICanvasContext;
\r
57 import org.simantics.g2d.connection.ConnectionEntity;
\r
58 import org.simantics.g2d.diagram.DiagramHints;
\r
59 import org.simantics.g2d.diagram.IDiagram;
\r
60 import org.simantics.g2d.diagram.handler.DataElementMap;
\r
61 import org.simantics.g2d.diagram.handler.Topology.Connection;
\r
62 import org.simantics.g2d.diagram.handler.Topology.Terminal;
\r
63 import org.simantics.g2d.element.ElementClass;
\r
64 import org.simantics.g2d.element.ElementHints;
\r
65 import org.simantics.g2d.element.ElementUtils;
\r
66 import org.simantics.g2d.element.IElement;
\r
67 import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
\r
68 import org.simantics.g2d.element.handler.TerminalTopology;
\r
69 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
\r
70 import org.simantics.g2d.routing.algorithm2.Router4;
\r
71 import org.simantics.g2d.utils.TopologicalSelectionExpander;
\r
72 import org.simantics.layer0.Layer0;
\r
73 import org.simantics.modeling.ModelingResources;
\r
74 import org.simantics.scenegraph.g2d.nodes.connection.IRouteGraphListener;
\r
75 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphChangeEvent;
\r
76 import org.simantics.scenegraph.utils.GeometryUtils;
\r
77 import org.simantics.structural.stubs.StructuralResource2;
\r
78 import org.simantics.structural2.modelingRules.CPTerminal;
\r
79 import org.simantics.structural2.modelingRules.IAttachmentRelationMap;
\r
80 import org.simantics.structural2.modelingRules.IModelingRules;
\r
81 import org.simantics.sysdyn.SysdynResource;
\r
82 import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;
\r
84 * An element class for Sysdyn Flow elements.
\r
85 * Copied from RouteGraphConnectionClassFactory and adapted to Flow needs
\r
87 * @author Teemu Lempinen
\r
90 public class RouteFlowConnectionFactory extends SyncElementFactory {
\r
92 public static final ElementClass CLASS = RouteFlowEdgeClass.FLOW_CLASS;
\r
95 DiagramResource DIA;
\r
96 StructuralResource2 STR;
\r
97 ModelingResources MOD;
\r
99 public RouteFlowConnectionFactory(ReadGraph graph) {
\r
100 this.L0 = Layer0.getInstance(graph);
\r
101 this.DIA = DiagramResource.getInstance(graph);
\r
102 this.STR = StructuralResource2.getInstance(graph);
\r
103 this.MOD = ModelingResources.getInstance(graph);
\r
107 public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType, final AsyncProcedure<ElementClass> procedure) {
\r
108 procedure.execute(graph, CLASS.newClassWith(false, new StaticObjectAdapter(elementType)));
\r
112 protected Resource getElementClassBaseType(AsyncReadGraph graph) {
\r
113 return graph.getService(SysdynResource.class).FlowConnection;
\r
117 public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource connection,
\r
118 IElement element) throws DatabaseException {
\r
120 // Do we need this?
\r
121 element.setHint(DiagramHints.ROUTE_ALGORITHM, new Router4(false));
\r
123 IModelingRules modelingRules = diagram.getHint(DiagramModelHints.KEY_MODELING_RULES);
\r
125 IElement mappedElement = ElementUtils.getByData(diagram, connection);
\r
126 if (mappedElement == null)
\r
127 // FIXME: With undo this seems to happen, don't know why yet!
\r
130 RouteGraph rg = new RouteGraph();
\r
132 Set<Resource> nodes = new HashSet<Resource>();
\r
133 Set<EdgeResource> links = new HashSet<EdgeResource>();
\r
134 Map<Object, RouteNode> nodeByData = new HashMap<Object, RouteNode>();
\r
136 // Needed to support ConnectionEntity#getTerminalConnections
\r
137 Set<BackendConnection> backendonnections = new HashSet<BackendConnection>();
\r
139 // Load all route graph interior RouteNodes: route lines and points
\r
140 for (Resource interiorNode : graph.getObjects(connection, DIA.HasInteriorRouteNode)) {
\r
141 if (graph.isInstanceOf(interiorNode, DIA.RouteLine)) {
\r
142 Boolean isHorizontal = graph.getRelatedValue(interiorNode, DIA.IsHorizontal, Bindings.BOOLEAN);
\r
143 Double position = graph.getRelatedValue(interiorNode, DIA.HasPosition, Bindings.DOUBLE);
\r
144 RouteLine line = rg.addLine(isHorizontal, position);
\r
145 line.setData( RouteGraphConnection.serialize(graph, interiorNode) );
\r
147 nodes.add( interiorNode );
\r
148 nodeByData.put( interiorNode, line );
\r
150 for (Resource connectedTo : graph.getObjects(interiorNode, DIA.AreConnected)) {
\r
151 links.add( new EdgeResource(interiorNode, connectedTo) );
\r
153 } else if (graph.isInstanceOf(interiorNode, DIA.RoutePoint)) {
\r
154 // Not supported yet. Ignore.
\r
158 Rectangle2D bounds = new Rectangle2D.Double();
\r
160 // Load all node terminal connections as RouteTerminals
\r
161 for (Statement toConnector : graph.getStatements(connection, DIA.HasConnector)) {
\r
162 Resource connector = toConnector.getObject();
\r
163 Resource attachmentRelation = toConnector.getPredicate();
\r
165 Statement terminalStm = findTerminalStatement(graph, STR, connection, connector);
\r
166 if (terminalStm == null)
\r
167 // Ignore broken connector: attached to the connection but not to any terminal.
\r
170 Resource terminalElement = terminalStm.getObject();
\r
171 Resource terminalElementType = graph.getPossibleType(terminalElement, DIA.Element);
\r
172 if (terminalElementType == null)
\r
173 // Ignore non-element terminal elements
\r
176 Resource connectionRelation = graph.getInverse(terminalStm.getPredicate());
\r
178 // Discover node and terminal this connector is connected to.
\r
179 TerminalMap terminals = graph.syncRequest(DiagramRequests.elementTypeTerminals(terminalElementType),
\r
180 TransientCacheListener.<TerminalMap> instance());
\r
181 Resource terminal = terminals.getTerminal(connectionRelation);
\r
182 if (terminal == null) {
\r
183 System.err.println(getClass().getSimpleName()
\r
184 + ": Could not find terminal for connection point "
\r
185 + NameUtils.getSafeName(graph, connectionRelation, true)
\r
187 + NameUtils.getSafeName(graph, terminalElement, true));
\r
191 double[] position = graph.getRelatedValue(connector, DIA.HasRelativeLocation, Bindings.DOUBLE_ARRAY);
\r
192 if (position.length != 2)
\r
193 position = new double[] { 0, 0 };
\r
195 //System.out.println("terminalStm: " + NameUtils.toString(graph, terminalStm));
\r
196 AffineTransform terminalElementTr = getWorldTransform(graph, terminalElement);
\r
198 double x = terminalElementTr.getTranslateX();
\r
199 double y = terminalElementTr.getTranslateY();
\r
200 double minx = x-1, miny = y-1, maxx = x+1, maxy = y+1;
\r
201 int direction = 0x0;
\r
203 // Use modelingRules to ascertain the proper attachmentRelation
\r
204 // for this terminal connection, if available.
\r
205 if (modelingRules != null) {
\r
206 // Get attachmentRelation from modelingRules if possible.
\r
207 IAttachmentRelationMap map = modelingRules.getAttachmentRelations(graph, connection);
\r
208 Resource att = map.get(graph, new CPTerminal(terminalElement, terminal));
\r
210 //System.out.println("modeling rules attachment: " + NameUtils.getSafeLabel(graph, att));
\r
211 attachmentRelation = att;
\r
214 //System.out.println("attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
\r
216 // Get element bounds to decide allowed terminal direction(s)
\r
217 IElement te = graph.syncRequest(DiagramRequests.getElement(canvas, diagram, terminalElement, null));
\r
219 ElementUtils.getElementBounds(te, bounds);
\r
222 Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(bounds, terminalElementTr);
\r
223 bounds.setFrame(shp.getBounds2D());
\r
226 // Valve behaves differently. The flow must start inside the valve bounds
\r
227 if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
\r
228 bounds.setFrame(new Rectangle2D.Double(bounds.getCenterX() - 1, bounds.getCenterY() - 1, 2, 2));
\r
231 x = bounds.getCenterX();
\r
232 y = bounds.getCenterY();
\r
234 // Expand bounds by 4mm to make the connections enter the terminals
\r
235 // at a straight angle and from a distance instead of coming in
\r
237 GeometryUtils.expandRectangle(bounds, 4);
\r
239 minx = bounds.getMinX();
\r
240 miny = bounds.getMinY();
\r
241 maxx = bounds.getMaxX();
\r
242 maxy = bounds.getMaxY();
\r
245 Integer allowedDirections = graph.getPossibleRelatedValue(terminal, DIA.Terminal_AllowedDirections, Bindings.INTEGER);
\r
247 // Valve behaves differently. Allowed directions depend on the orientation of the valve
\r
248 if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
\r
249 SysdynResource sr = SysdynResource.getInstance(graph);
\r
250 if(graph.hasStatement(terminalElement, sr.ValveSymbol_orientation, sr.Vertical)) {
\r
251 allowedDirections = 10; // Directions up and down (1010)
\r
253 allowedDirections = 5; // Directions left and right (0101)
\r
256 if (allowedDirections != null) {
\r
257 direction |= allowedDirections;
\r
259 direction |= RouteGraphConnectionClass.shortestDirectionOutOfBounds(x, y, bounds);
\r
262 backendonnections.add(
\r
263 new BackendConnection(
\r
264 toEdgeEnd(graph, attachmentRelation, EdgeEnd.Begin),
\r
269 if (direction == 0)
\r
270 // Accept any horizontal/vertical direction if nothing is defined
\r
273 //System.out.println("load line style: " + NameUtils.getSafeLabel(graph, attachmentRelation));
\r
274 ILineEndStyle endStyle = loadLineEndStyle(graph, te, attachmentRelation, new Rectangle2D.Double(
\r
277 bounds.getWidth(),
\r
278 bounds.getHeight())
\r
281 RouteTerminal routeTerminal = rg.addTerminal(x, y, minx, miny, maxx, maxy, direction, endStyle);
\r
282 routeTerminal.setData( RouteGraphConnection.serialize(graph, connector) );
\r
284 nodes.add( connector );
\r
285 nodeByData.put( connector, routeTerminal );
\r
287 for (Resource connectedTo : graph.getObjects(connector, DIA.AreConnected)) {
\r
288 links.add( new EdgeResource(connectedTo, connector) );
\r
292 // Finish route graph loading by Linking route nodes together
\r
293 for (EdgeResource link : links) {
\r
294 RouteNode n1 = nodeByData.get(link.first());
\r
295 RouteNode n2 = nodeByData.get(link.second());
\r
296 if (n1 == null || n2 == null) {
\r
297 System.err.println("Stray connection link found: " + link.toString(graph));
\r
303 // Load connection line style
\r
304 ConnectionStyle style = readConnectionStyle(graph, modelingRules, connection, element);
\r
305 StyledRouteGraphRenderer renderer = new StyledRouteGraphRenderer(style);
\r
307 // Finish element load
\r
308 element.setHint(RouteGraphConnectionClass.KEY_ROUTEGRAPH, rg);
\r
309 element.setHint(RouteGraphConnectionClass.KEY_RENDERER, renderer);
\r
310 element.setHint(RouteGraphConnectionClass.KEY_PICK_TOLERANCE, 0.5);
\r
312 // Initialize ConnectionEntity in element
\r
313 // NOTE: MUST use the mapped element with class CE, not the connection (element) were loading into.
\r
314 // GDS will synchronize element into mappedElement in a controlled manner.
\r
315 element.setHint(ElementHints.KEY_CONNECTION_ENTITY, new CE(connection, mappedElement, backendonnections));
\r
317 // Setup graph writeback support for route graph modifications
\r
318 final Session session = graph.getSession();
\r
319 element.setHint(RouteGraphConnectionClass.KEY_RG_LISTENER, new IRouteGraphListener() {
\r
321 public void routeGraphChanged(RouteGraphChangeEvent event) {
\r
322 scheduleSynchronize(session, connection, event);
\r
327 private EdgeEnd toEdgeEnd(ReadGraph graph, Resource attachmentRelation, EdgeEnd defaultValue)
\r
328 throws DatabaseException {
\r
329 if (graph.isSubrelationOf(attachmentRelation, DIA.IsTailConnectorOf))
\r
330 return EdgeEnd.Begin;
\r
331 if (graph.isSubrelationOf(attachmentRelation, DIA.IsHeadConnectorOf))
\r
332 return EdgeEnd.End;
\r
333 return defaultValue;
\r
336 private ConnectionStyle readConnectionStyle(ReadGraph graph, IModelingRules modelingRules, Resource connection,
\r
337 IElement element) throws DatabaseException {
\r
338 Resource connectionType = null;
\r
339 if (modelingRules != null)
\r
340 connectionType = modelingRules.getConnectionType(graph, connection);
\r
341 if (connectionType == null)
\r
342 connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);
\r
344 ConnectionVisuals cv = null;
\r
345 if (connectionType != null)
\r
346 cv = graph.syncRequest(DiagramRequests.getConnectionVisuals(connectionType),
\r
347 TransientCacheListener.<ConnectionVisuals> instance());
\r
349 Color lineColor = cv != null ? cv.toColor() : null;
\r
350 if (lineColor == null)
\r
351 lineColor = Color.DARK_GRAY;
\r
352 Stroke lineStroke = cv != null ? cv.stroke : null;
\r
353 if (lineStroke == null)
\r
354 lineStroke = new BasicStroke(0.1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, null, 0);
\r
356 return new FlowConnectionStyle(
\r
364 * @param connection
\r
366 * @return connection relation statement from diagram connection connector
\r
368 * @throws DatabaseException
\r
370 private static Statement findTerminalStatement(ReadGraph graph, StructuralResource2 STR, Resource connection,
\r
371 Resource connector) throws DatabaseException {
\r
372 for (Statement stm : graph.getStatements(connector, STR.Connects)) {
\r
373 if (connection.equals(stm.getObject()))
\r
380 public ILineEndStyle loadLineEndStyle(ReadGraph graph, IElement te, Resource attachmentRelation, Rectangle2D bounds)
\r
381 throws DatabaseException {
\r
382 ILineEndStyle style;
\r
383 // TODO: change bounds according to terminal type: Very small rectangle for Valves, Text box size for Stocks and Clouds
\r
384 if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
\r
385 GeometryUtils.expandRectangle(bounds, -4);
\r
386 style = new FlowArrowLineStyle("none 0 0 0", bounds);
\r
388 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector)) {
\r
389 GeometryUtils.expandRectangle(bounds, -2.5);
\r
390 style = new FlowArrowLineStyle("fill 2 2 -1.5", bounds);
\r
392 GeometryUtils.expandRectangle(bounds, -4);
\r
393 style = new FlowArrowLineStyle("none 0 0 0", bounds);
\r
403 * @throws DatabaseException
\r
405 private static AffineTransform getWorldTransform(ReadGraph graph, Resource element) throws DatabaseException {
\r
406 ModelingResources MOD = ModelingResources.getInstance(graph);
\r
407 AffineTransform result = DiagramGraphUtil.getAffineTransform(graph, element);
\r
409 Resource parentComponent = graph.getPossibleObject(element, MOD.HasParentComponent);
\r
410 if (parentComponent == null)
\r
412 element = graph.getPossibleObject(parentComponent, MOD.ComponentToElement);
\r
413 if (element == null)
\r
415 AffineTransform tr = DiagramGraphUtil.getAffineTransform(graph, element);
\r
416 tr.setToTranslation(tr.getTranslateX(), tr.getTranslateY());
\r
417 result.preConcatenate(tr);
\r
422 protected void scheduleSynchronize(Session session, Resource connection, RouteGraphChangeEvent event) {
\r
423 session.asyncRequest(RouteGraphConnection.synchronizer(connection, event));
\r
427 * Must have this in order for {@link TopologicalSelectionExpander} to work.
\r
428 * Otherwise this is pretty useless and should be deprecated altogether.
\r
430 * @see ElementHints#KEY_CONNECTION_ENTITY
\r
432 static class CE implements ConnectionEntity {
\r
435 * The connection instance resource in the graph backend.
\r
437 final Resource connection;
\r
440 * The connection entity element which is a part of the diagram.
\r
442 final IElement connectionElement;
\r
445 * @see #getTerminalConnections(Collection)
\r
447 final Set<BackendConnection> backendConnections;
\r
452 Set<Connection> terminalConnections;
\r
454 CE(Resource connection, IElement connectionElement, Set<BackendConnection> backendConnections) {
\r
455 this.connection = connection;
\r
456 this.connectionElement = connectionElement;
\r
457 this.backendConnections = backendConnections;
\r
461 public IElement getConnection() {
\r
462 return connectionElement;
\r
465 public Object getConnectionObject() {
\r
469 public IElement getConnectionElement() {
\r
470 return connectionElement;
\r
474 public Collection<IElement> getBranchPoints(Collection<IElement> result) {
\r
475 return result != null ? result : Collections.<IElement> emptyList();
\r
479 public Collection<IElement> getSegments(Collection<IElement> result) {
\r
480 return result != null ? result : Collections.<IElement> emptyList();
\r
484 public Collection<Connection> getTerminalConnections(Collection<Connection> result) {
\r
485 if (terminalConnections == null)
\r
486 terminalConnections = calculateTerminalConnections();
\r
487 if (result == null)
\r
488 result = new ArrayList<Connection>(terminalConnections);
\r
490 result.addAll(terminalConnections);
\r
491 return terminalConnections;
\r
494 private Set<Connection> calculateTerminalConnections() {
\r
495 IDiagram diagram = connectionElement.getDiagram();
\r
496 DataElementMap dem = diagram.getDiagramClass().getSingleItem(DataElementMap.class);
\r
497 Set<Connection> result = new HashSet<Connection>();
\r
498 ArrayList<Terminal> ts = new ArrayList<Terminal>();
\r
499 for (BackendConnection bc : backendConnections) {
\r
500 IElement e = dem.getElement(diagram, bc.node);
\r
503 TerminalTopology tt = e.getElementClass().getSingleItem(TerminalTopology.class);
\r
504 tt.getTerminals(e, ts);
\r
505 for (Terminal t : ts) {
\r
506 if (t instanceof ResourceTerminal) {
\r
507 ResourceTerminal rt = (ResourceTerminal) t;
\r
508 if (bc.terminal.equals(rt.getResource())) {
\r
509 result.add(new Connection(connectionElement, bc.end, e, t));
\r
519 public void setListener(ConnectionListener listener) {
\r
520 throw new UnsupportedOperationException();
\r
524 public String toString() {
\r
525 return getClass().getSimpleName() + "[resource=" + connection + ", connectionElement=" + connectionElement
\r
531 public static class BackendConnection {
\r
532 public final Resource node;
\r
533 public final Resource terminal;
\r
534 public final EdgeEnd end;
\r
535 public BackendConnection(EdgeEnd end, Resource node, Resource terminal) {
\r
536 assert end != null;
\r
537 assert node != null;
\r
538 assert terminal != null;
\r
541 this.terminal = terminal;
\r
544 public boolean equals(Object obj) {
\r
547 if (!(obj instanceof Connection))
\r
549 Connection other = (Connection) obj;
\r
550 return other.terminal == terminal
\r
551 && other.node == node
\r
552 && other.end == end;
\r
555 public int hashCode() {
\r
556 final int prime = 31;
\r
558 result = prime * result + end.hashCode();
\r
559 result = prime * result + ((node == null) ? 0 : node.hashCode());
\r
560 result = prime * result + ((terminal == null) ? 0 : terminal.hashCode());
\r
564 public String toString() {
\r
565 return "BackendConnection[node=" + node + ", terminal=" + terminal + ", end=" + end + "]";
\r