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.G2DUtils;
\r
39 import org.simantics.diagram.adapter.SyncElementFactory;
\r
40 import org.simantics.diagram.connection.ConnectionVisuals;
\r
41 import org.simantics.diagram.connection.RouteGraph;
\r
42 import org.simantics.diagram.connection.RouteGraphConnectionClass;
\r
43 import org.simantics.diagram.connection.RouteLine;
\r
44 import org.simantics.diagram.connection.RouteNode;
\r
45 import org.simantics.diagram.connection.RouteTerminal;
\r
46 import org.simantics.diagram.connection.rendering.ConnectionStyle;
\r
47 import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;
\r
48 import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;
\r
49 import org.simantics.diagram.content.EdgeResource;
\r
50 import org.simantics.diagram.content.ResourceTerminal;
\r
51 import org.simantics.diagram.content.TerminalMap;
\r
52 import org.simantics.diagram.query.DiagramRequests;
\r
53 import org.simantics.diagram.stubs.DiagramResource;
\r
54 import org.simantics.diagram.stubs.G2DResource;
\r
55 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
\r
56 import org.simantics.diagram.synchronization.graph.RouteGraphConnection;
\r
57 import org.simantics.diagram.ui.DiagramModelHints;
\r
58 import org.simantics.g2d.canvas.ICanvasContext;
\r
59 import org.simantics.g2d.connection.ConnectionEntity;
\r
60 import org.simantics.g2d.diagram.DiagramHints;
\r
61 import org.simantics.g2d.diagram.IDiagram;
\r
62 import org.simantics.g2d.diagram.handler.DataElementMap;
\r
63 import org.simantics.g2d.diagram.handler.Topology.Connection;
\r
64 import org.simantics.g2d.diagram.handler.Topology.Terminal;
\r
65 import org.simantics.g2d.element.ElementClass;
\r
66 import org.simantics.g2d.element.ElementHints;
\r
67 import org.simantics.g2d.element.ElementUtils;
\r
68 import org.simantics.g2d.element.IElement;
\r
69 import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
\r
70 import org.simantics.g2d.element.handler.TerminalTopology;
\r
71 import org.simantics.g2d.element.handler.impl.StaticObjectAdapter;
\r
72 import org.simantics.g2d.routing.algorithm2.Router4;
\r
73 import org.simantics.g2d.utils.TopologicalSelectionExpander;
\r
74 import org.simantics.layer0.Layer0;
\r
75 import org.simantics.modeling.ModelingResources;
\r
76 import org.simantics.scenegraph.g2d.nodes.connection.IRouteGraphListener;
\r
77 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphChangeEvent;
\r
78 import org.simantics.structural.stubs.StructuralResource2;
\r
79 import org.simantics.structural2.modelingRules.CPTerminal;
\r
80 import org.simantics.structural2.modelingRules.IAttachmentRelationMap;
\r
81 import org.simantics.structural2.modelingRules.IModelingRules;
\r
82 import org.simantics.sysdyn.SysdynResource;
\r
83 import org.simantics.sysdyn.ui.elements.ValveFactory.ValveSceneGraph;
\r
85 * An element class for Sysdyn Flow elements.
\r
86 * Copied from RouteGraphConnectionClassFactory and adapted to Flow needs
\r
88 * @author Teemu Lempinen
\r
91 public class RouteFlowConnectionFactory extends SyncElementFactory {
\r
93 public static final ElementClass CLASS = RouteFlowEdgeClass.FLOW_CLASS;
\r
96 DiagramResource DIA;
\r
97 StructuralResource2 STR;
\r
98 ModelingResources MOD;
\r
100 public RouteFlowConnectionFactory(ReadGraph graph) {
\r
101 this.L0 = Layer0.getInstance(graph);
\r
102 this.DIA = DiagramResource.getInstance(graph);
\r
103 this.STR = StructuralResource2.getInstance(graph);
\r
104 this.MOD = ModelingResources.getInstance(graph);
\r
108 public void create(AsyncReadGraph graph, ICanvasContext canvas, IDiagram diagram, Resource elementType, final AsyncProcedure<ElementClass> procedure) {
\r
109 procedure.execute(graph, CLASS.newClassWith(false, new StaticObjectAdapter(elementType)));
\r
113 protected Resource getElementClassBaseType(AsyncReadGraph graph) {
\r
114 return graph.getService(SysdynResource.class).FlowConnection;
\r
118 public void load(ReadGraph graph, final ICanvasContext canvas, final IDiagram diagram, final Resource connection,
\r
119 IElement element) throws DatabaseException {
\r
121 // Do we need this?
\r
122 element.setHint(DiagramHints.ROUTE_ALGORITHM, new Router4(false));
\r
124 IModelingRules modelingRules = diagram.getHint(DiagramModelHints.KEY_MODELING_RULES);
\r
126 IElement mappedElement = ElementUtils.getByData(diagram, connection);
\r
127 if (mappedElement == null)
\r
128 // FIXME: With undo this seems to happen, don't know why yet!
\r
131 Resource colorResource = graph.getPossibleObject(connection, G2DResource.getInstance(graph).HasColor);
\r
132 Color color = null;
\r
133 if(colorResource != null) {
\r
134 color = G2DUtils.getColor(graph, colorResource);
\r
135 element.setHint(ElementHints.KEY_TEXT_COLOR, color);
\r
138 RouteGraph rg = new RouteGraph();
\r
140 Set<Resource> nodes = new HashSet<Resource>();
\r
141 Set<EdgeResource> links = new HashSet<EdgeResource>();
\r
142 Map<Object, RouteNode> nodeByData = new HashMap<Object, RouteNode>();
\r
144 // Needed to support ConnectionEntity#getTerminalConnections
\r
145 Set<BackendConnection> backendonnections = new HashSet<BackendConnection>();
\r
147 // Load all route graph interior RouteNodes: route lines and points
\r
148 for (Resource interiorNode : graph.getObjects(connection, DIA.HasInteriorRouteNode)) {
\r
149 if (graph.isInstanceOf(interiorNode, DIA.RouteLine)) {
\r
150 Boolean isHorizontal = graph.getRelatedValue(interiorNode, DIA.IsHorizontal, Bindings.BOOLEAN);
\r
151 Double position = graph.getRelatedValue(interiorNode, DIA.HasPosition, Bindings.DOUBLE);
\r
152 RouteLine line = rg.addLine(isHorizontal, position);
\r
153 line.setData( RouteGraphConnection.serialize(graph, interiorNode) );
\r
155 nodes.add( interiorNode );
\r
156 nodeByData.put( interiorNode, line );
\r
158 for (Resource connectedTo : graph.getObjects(interiorNode, DIA.AreConnected)) {
\r
159 links.add( new EdgeResource(interiorNode, connectedTo) );
\r
161 } else if (graph.isInstanceOf(interiorNode, DIA.RoutePoint)) {
\r
162 // Not supported yet. Ignore.
\r
166 Rectangle2D bounds = new Rectangle2D.Double();
\r
168 // Load all node terminal connections as RouteTerminals
\r
169 for (Statement toConnector : graph.getStatements(connection, DIA.HasConnector)) {
\r
170 Resource connector = toConnector.getObject();
\r
171 Resource attachmentRelation = toConnector.getPredicate();
\r
173 Statement terminalStm = findTerminalStatement(graph, STR, connection, connector);
\r
174 if (terminalStm == null)
\r
175 // Ignore broken connector: attached to the connection but not to any terminal.
\r
178 Resource terminalElement = terminalStm.getObject();
\r
179 Resource terminalElementType = graph.getPossibleType(terminalElement, DIA.Element);
\r
180 if (terminalElementType == null)
\r
181 // Ignore non-element terminal elements
\r
184 Resource connectionRelation = graph.getInverse(terminalStm.getPredicate());
\r
186 // Discover node and terminal this connector is connected to.
\r
187 TerminalMap terminals = graph.syncRequest(DiagramRequests.elementTypeTerminals(terminalElementType),
\r
188 TransientCacheListener.<TerminalMap> instance());
\r
189 Resource terminal = terminals.getTerminal(connectionRelation);
\r
190 if (terminal == null) {
\r
191 System.err.println(getClass().getSimpleName()
\r
192 + ": Could not find terminal for connection point "
\r
193 + NameUtils.getSafeName(graph, connectionRelation, true)
\r
195 + NameUtils.getSafeName(graph, terminalElement, true));
\r
199 double[] position = graph.getRelatedValue(connector, DIA.HasRelativeLocation, Bindings.DOUBLE_ARRAY);
\r
200 if (position.length != 2)
\r
201 position = new double[] { 0, 0 };
\r
203 //System.out.println("terminalStm: " + NameUtils.toString(graph, terminalStm));
\r
204 AffineTransform terminalElementTr = getWorldTransform(graph, terminalElement);
\r
206 double x = terminalElementTr.getTranslateX();
\r
207 double y = terminalElementTr.getTranslateY();
\r
208 double minx = x-1, miny = y-1, maxx = x+1, maxy = y+1;
\r
209 int direction = 0x0;
\r
211 // Use modelingRules to ascertain the proper attachmentRelation
\r
212 // for this terminal connection, if available.
\r
213 if (modelingRules != null) {
\r
214 // Get attachmentRelation from modelingRules if possible.
\r
215 IAttachmentRelationMap map = modelingRules.getAttachmentRelations(graph, connection);
\r
216 Resource att = map.get(graph, new CPTerminal(terminalElement, terminal));
\r
218 //System.out.println("modeling rules attachment: " + NameUtils.getSafeLabel(graph, att));
\r
219 attachmentRelation = att;
\r
222 //System.out.println("attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
\r
224 // Get element bounds to decide allowed terminal direction(s)
\r
225 IElement te = graph.syncRequest(DiagramRequests.getElement(canvas, diagram, terminalElement, null));
\r
227 ElementUtils.getElementBounds(te, bounds);
\r
230 Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(bounds, terminalElementTr);
\r
231 bounds.setFrame(shp.getBounds2D());
\r
234 // Valve behaves differently. The flow must start inside the valve bounds
\r
235 if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
\r
236 bounds.setFrame(new Rectangle2D.Double(bounds.getCenterX() - 1, bounds.getCenterY() - 1, 2, 2));
\r
239 x = bounds.getCenterX();
\r
240 y = bounds.getCenterY();
\r
242 // Expand bounds by 4mm to make the connections enter the terminals
\r
243 // at a straight angle and from a distance instead of coming in
\r
245 //GeometryUtils.expandRectangle(bounds, 4);
\r
247 minx = bounds.getMinX();
\r
248 miny = bounds.getMinY();
\r
249 maxx = bounds.getMaxX();
\r
250 maxy = bounds.getMaxY();
\r
253 Integer allowedDirections = graph.getPossibleRelatedValue(terminal, DIA.Terminal_AllowedDirections, Bindings.INTEGER);
\r
255 // Valve behaves differently. Allowed directions depend on the orientation of the valve
\r
256 if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
\r
257 SysdynResource sr = SysdynResource.getInstance(graph);
\r
258 if(graph.hasStatement(terminalElement, sr.ValveSymbol_orientation, sr.Vertical)) {
\r
259 allowedDirections = 10; // Directions up and down (1010)
\r
261 allowedDirections = 5; // Directions left and right (0101)
\r
264 if (allowedDirections != null) {
\r
265 direction |= allowedDirections;
\r
267 direction |= RouteGraphConnectionClass.shortestDirectionOutOfBounds(x, y, bounds);
\r
270 backendonnections.add(
\r
271 new BackendConnection(
\r
272 toEdgeEnd(graph, attachmentRelation, EdgeEnd.Begin),
\r
277 if (direction == 0)
\r
278 // Accept any horizontal/vertical direction if nothing is defined
\r
281 //System.out.println("load line style: " + NameUtils.getSafeLabel(graph, attachmentRelation));
\r
282 ILineEndStyle endStyle = loadLineEndStyle(graph, te, attachmentRelation, color);
\r
284 RouteTerminal routeTerminal = rg.addBigTerminal(/*x, y,*/ minx, miny, maxx, maxy, /*direction,*/ endStyle);
\r
285 routeTerminal.setData( RouteGraphConnection.serialize(graph, connector) );
\r
287 nodes.add( connector );
\r
288 nodeByData.put( connector, routeTerminal );
\r
290 for (Resource connectedTo : graph.getObjects(connector, DIA.AreConnected)) {
\r
291 links.add( new EdgeResource(connectedTo, connector) );
\r
295 // Finish route graph loading by Linking route nodes together
\r
296 for (EdgeResource link : links) {
\r
297 RouteNode n1 = nodeByData.get(link.first());
\r
298 RouteNode n2 = nodeByData.get(link.second());
\r
299 if (n1 == null || n2 == null) {
\r
300 System.err.println("Stray connection link found: " + link.toString(graph));
\r
306 // Load connection line style
\r
307 ConnectionStyle style = readConnectionStyle(graph, modelingRules, connection, element);
\r
308 StyledRouteGraphRenderer renderer = new StyledRouteGraphRenderer(style);
\r
310 // Finish element load
\r
311 element.setHint(RouteGraphConnectionClass.KEY_ROUTEGRAPH, rg);
\r
312 element.setHint(RouteGraphConnectionClass.KEY_RENDERER, renderer);
\r
313 element.setHint(RouteGraphConnectionClass.KEY_PICK_TOLERANCE, 0.5);
\r
315 // Initialize ConnectionEntity in element
\r
316 // NOTE: MUST use the mapped element with class CE, not the connection (element) were loading into.
\r
317 // GDS will synchronize element into mappedElement in a controlled manner.
\r
318 element.setHint(ElementHints.KEY_CONNECTION_ENTITY, new CE(connection, mappedElement, backendonnections));
\r
320 // Setup graph writeback support for route graph modifications
\r
321 final Session session = graph.getSession();
\r
322 element.setHint(RouteGraphConnectionClass.KEY_RG_LISTENER, new IRouteGraphListener() {
\r
324 public void routeGraphChanged(RouteGraphChangeEvent event) {
\r
325 scheduleSynchronize(session, connection, event);
\r
330 private EdgeEnd toEdgeEnd(ReadGraph graph, Resource attachmentRelation, EdgeEnd defaultValue)
\r
331 throws DatabaseException {
\r
332 if (graph.isSubrelationOf(attachmentRelation, DIA.IsTailConnectorOf))
\r
333 return EdgeEnd.Begin;
\r
334 if (graph.isSubrelationOf(attachmentRelation, DIA.IsHeadConnectorOf))
\r
335 return EdgeEnd.End;
\r
336 return defaultValue;
\r
339 private ConnectionStyle readConnectionStyle(ReadGraph graph, IModelingRules modelingRules, Resource connection,
\r
340 IElement element) throws DatabaseException {
\r
341 Resource connectionType = null;
\r
342 if (modelingRules != null)
\r
343 connectionType = modelingRules.getConnectionType(graph, connection);
\r
344 if (connectionType == null)
\r
345 connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);
\r
347 ConnectionVisuals cv = null;
\r
348 if (connectionType != null)
\r
349 cv = graph.syncRequest(DiagramRequests.getConnectionVisuals(connectionType),
\r
350 TransientCacheListener.<ConnectionVisuals> instance());
\r
353 Color lineColor = element.getHint(ElementHints.KEY_TEXT_COLOR);
\r
354 if (lineColor == null)
\r
355 lineColor = cv != null ? cv.toColor() : Color.DARK_GRAY;
\r
357 Stroke lineStroke = cv != null ? cv.stroke : null;
\r
358 if (lineStroke == null)
\r
359 lineStroke = new BasicStroke(0.1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, null, 0);
\r
361 return new FlowConnectionStyle(
\r
369 * @param connection
\r
371 * @return connection relation statement from diagram connection connector
\r
373 * @throws DatabaseException
\r
375 private static Statement findTerminalStatement(ReadGraph graph, StructuralResource2 STR, Resource connection,
\r
376 Resource connector) throws DatabaseException {
\r
377 for (Statement stm : graph.getStatements(connector, STR.Connects)) {
\r
378 if (connection.equals(stm.getObject()))
\r
385 public ILineEndStyle loadLineEndStyle(ReadGraph graph, IElement te, Resource attachmentRelation, Color color)
\r
386 throws DatabaseException {
\r
387 ILineEndStyle style;
\r
388 // TODO: change bounds according to terminal type: Very small rectangle for Valves, Text box size for Stocks and Clouds
\r
389 if(te.getElementClass().containsClass(ValveSceneGraph.class)) {
\r
390 style = new FlowArrowLineStyle("none 0 0 0", color);
\r
392 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector)) {
\r
393 style = new FlowArrowLineStyle("fill 2 2 0", color);
\r
395 style = new FlowArrowLineStyle("none 0 0 0", color);
\r
405 * @throws DatabaseException
\r
407 private static AffineTransform getWorldTransform(ReadGraph graph, Resource element) throws DatabaseException {
\r
408 ModelingResources MOD = ModelingResources.getInstance(graph);
\r
409 AffineTransform result = DiagramGraphUtil.getAffineTransform(graph, element);
\r
411 Resource parentComponent = graph.getPossibleObject(element, MOD.HasParentComponent);
\r
412 if (parentComponent == null)
\r
414 element = graph.getPossibleObject(parentComponent, MOD.ComponentToElement);
\r
415 if (element == null)
\r
417 AffineTransform tr = DiagramGraphUtil.getAffineTransform(graph, element);
\r
418 tr.setToTranslation(tr.getTranslateX(), tr.getTranslateY());
\r
419 result.preConcatenate(tr);
\r
424 protected void scheduleSynchronize(Session session, Resource connection, RouteGraphChangeEvent event) {
\r
425 session.asyncRequest(RouteGraphConnection.synchronizer(connection, event));
\r
429 * Must have this in order for {@link TopologicalSelectionExpander} to work.
\r
430 * Otherwise this is pretty useless and should be deprecated altogether.
\r
432 * @see ElementHints#KEY_CONNECTION_ENTITY
\r
434 static class CE implements ConnectionEntity {
\r
437 * The connection instance resource in the graph backend.
\r
439 final Resource connection;
\r
442 * The connection entity element which is a part of the diagram.
\r
444 final IElement connectionElement;
\r
447 * @see #getTerminalConnections(Collection)
\r
449 final Set<BackendConnection> backendConnections;
\r
454 Set<Connection> terminalConnections;
\r
456 CE(Resource connection, IElement connectionElement, Set<BackendConnection> backendConnections) {
\r
457 this.connection = connection;
\r
458 this.connectionElement = connectionElement;
\r
459 this.backendConnections = backendConnections;
\r
463 public IElement getConnection() {
\r
464 return connectionElement;
\r
467 public Object getConnectionObject() {
\r
471 public IElement getConnectionElement() {
\r
472 return connectionElement;
\r
476 public Collection<IElement> getBranchPoints(Collection<IElement> result) {
\r
477 return result != null ? result : Collections.<IElement> emptyList();
\r
481 public Collection<IElement> getSegments(Collection<IElement> result) {
\r
482 return result != null ? result : Collections.<IElement> emptyList();
\r
486 public Collection<Connection> getTerminalConnections(Collection<Connection> result) {
\r
487 if (terminalConnections == null)
\r
488 terminalConnections = calculateTerminalConnections();
\r
489 if (result == null)
\r
490 result = new ArrayList<Connection>(terminalConnections);
\r
492 result.addAll(terminalConnections);
\r
493 return terminalConnections;
\r
496 private Set<Connection> calculateTerminalConnections() {
\r
497 IDiagram diagram = connectionElement.getDiagram();
\r
498 DataElementMap dem = diagram.getDiagramClass().getSingleItem(DataElementMap.class);
\r
499 Set<Connection> result = new HashSet<Connection>();
\r
500 ArrayList<Terminal> ts = new ArrayList<Terminal>();
\r
501 for (BackendConnection bc : backendConnections) {
\r
502 IElement e = dem.getElement(diagram, bc.node);
\r
505 TerminalTopology tt = e.getElementClass().getSingleItem(TerminalTopology.class);
\r
506 tt.getTerminals(e, ts);
\r
507 for (Terminal t : ts) {
\r
508 if (t instanceof ResourceTerminal) {
\r
509 ResourceTerminal rt = (ResourceTerminal) t;
\r
510 if (bc.terminal.equals(rt.getResource())) {
\r
511 result.add(new Connection(connectionElement, bc.end, e, t));
\r
521 public void setListener(ConnectionListener listener) {
\r
522 throw new UnsupportedOperationException();
\r
526 public String toString() {
\r
527 return getClass().getSimpleName() + "[resource=" + connection + ", connectionElement=" + connectionElement
\r
533 public static class BackendConnection {
\r
534 public final Resource node;
\r
535 public final Resource terminal;
\r
536 public final EdgeEnd end;
\r
537 public BackendConnection(EdgeEnd end, Resource node, Resource terminal) {
\r
538 assert end != null;
\r
539 assert node != null;
\r
540 assert terminal != null;
\r
543 this.terminal = terminal;
\r
546 public boolean equals(Object obj) {
\r
549 if (!(obj instanceof Connection))
\r
551 Connection other = (Connection) obj;
\r
552 return other.terminal == terminal
\r
553 && other.node == node
\r
554 && other.end == end;
\r
557 public int hashCode() {
\r
558 final int prime = 31;
\r
560 result = prime * result + end.hashCode();
\r
561 result = prime * result + ((node == null) ? 0 : node.hashCode());
\r
562 result = prime * result + ((terminal == null) ? 0 : terminal.hashCode());
\r
566 public String toString() {
\r
567 return "BackendConnection[node=" + node + ", terminal=" + terminal + ", end=" + end + "]";
\r