]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram/src/org/simantics/diagram/flag/RouteGraphConnectionSplitter.java
Added `possibleInvertibleExpressionReferencedTransformedProperty`
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / flag / RouteGraphConnectionSplitter.java
1 package org.simantics.diagram.flag;
2
3 import gnu.trove.map.hash.TObjectIntHashMap;
4
5 import java.awt.geom.AffineTransform;
6 import java.awt.geom.Point2D;
7 import java.util.ArrayList;
8 import java.util.Collection;
9
10 import org.simantics.databoard.Bindings;
11 import org.simantics.db.ReadGraph;
12 import org.simantics.db.Resource;
13 import org.simantics.db.Statement;
14 import org.simantics.db.WriteGraph;
15 import org.simantics.db.common.request.PossibleTypedParent;
16 import org.simantics.db.common.utils.NameUtils;
17 import org.simantics.db.common.utils.OrderedSetUtils;
18 import org.simantics.db.exception.DatabaseException;
19 import org.simantics.db.service.SerialisationSupport;
20 import org.simantics.diagram.adapter.RouteGraphUtils;
21 import org.simantics.diagram.connection.RouteGraph;
22 import org.simantics.diagram.connection.RouteLine;
23 import org.simantics.diagram.connection.RouteNode;
24 import org.simantics.diagram.connection.RoutePoint;
25 import org.simantics.diagram.connection.RouteTerminal;
26 import org.simantics.diagram.connection.splitting.SplittedRouteGraph;
27 import org.simantics.diagram.content.ConnectionUtil;
28 import org.simantics.diagram.stubs.DiagramResource;
29 import org.simantics.diagram.synchronization.graph.AddElement;
30 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
31 import org.simantics.diagram.synchronization.graph.RouteGraphModification;
32 import org.simantics.g2d.elementclass.FlagClass;
33 import org.simantics.layer0.Layer0;
34 import org.simantics.modeling.ModelingResources;
35 import org.simantics.structural.stubs.StructuralResource2;
36
37 /**
38  * A class that handles splitting a route graph connection in two with diagram
39  * local flags.
40  * 
41  * The connection splitting process consists of the following steps:
42  * <ol>
43  * <li>Disconnect the end points of the selected connection edge segment (SEG).
44  * An end point is either :DIA.BranchPoint or (terminal) DIA:Connector. This
45  * operation will always split a valid connection into two separate parts.</li>
46  * <li>Calculate the contents of the two separated connection parts (branch
47  * points and connectors) and decide which part to leave with the existing
48  * connection (=P1) and which part to move into a new connection (=P2). The
49  * current strategy is to move the parts that
50  * <em>do not contain output terminal connectors</em> into a new connection.
51  * This works well with diagram to composite mappings where output terminals
52  * generate modules behind connections.</li>
53  * <li>Create new connection C' with the same type and STR.HasConnectionType as
54  * the original connection C.</li>
55  * <li>Copy connection routing settings from C to C'.</li>
56  * <li>Move P2 into C'.</li>
57  * <li>Create two new flag elements into the same diagram, set their type and
58  * interpolate a proper transformation for both along the existing connection
59  * line.</li>
60  * <li>Connect the new flags to begin(SEG) and end(SEG) connectors.</li>
61  * <li>Join the flags together.</li>
62  * </ol>
63  * 
64  * @author Tuukka Lehtonen
65  * @author Hannu Niemist&ouml;
66  */
67 public class RouteGraphConnectionSplitter {
68
69     private final static boolean DEBUG = false;
70
71     Layer0              L0;
72     DiagramResource     DIA;
73     StructuralResource2 STR;
74     ModelingResources   MOD;
75     SerialisationSupport ss;
76
77     public RouteGraphConnectionSplitter(ReadGraph graph) {
78         this.L0 = Layer0.getInstance(graph);
79         this.DIA = DiagramResource.getInstance(graph);
80         this.STR = StructuralResource2.getInstance(graph);
81         this.MOD = ModelingResources.getInstance(graph);
82         this.ss = graph.getService(SerialisationSupport.class);
83     }
84     
85     public void split(WriteGraph graph, Resource connection, RouteGraph rg, Point2D splitCanvasPos) throws DatabaseException {
86         // Create modification writer
87         RouteGraphModification modis = new RouteGraphModification(ss, rg);
88         TObjectIntHashMap<RouteNode> idMap = modis.getIdMap();
89
90         // Find the edge to disconnect in the graph.
91         // Bisect the nearest route line.
92         RouteLine line = SplittedRouteGraph.findNearestLine(rg, splitCanvasPos);
93         if (DEBUG)
94             rg.print();
95         if (line == null)
96             return;
97         if (DEBUG) {
98             line.print(System.out);
99             for (RoutePoint rp : line.getPoints())
100                 System.out.println("RP: " + rp.getX() + ", " + rp.getY());
101         }
102
103         // Get exact intersection point on the line
104         double isectX = splitCanvasPos.getX();
105         double isectY = splitCanvasPos.getY();
106         SplittedRouteGraph srg;
107         if (line.isHorizontal()) {
108             isectY = line.getPosition();
109             srg = rg.splitGraph(line, isectX);
110         }
111         else {
112             isectX = line.getPosition();
113             srg = rg.splitGraph(line, isectY);
114         }
115         if (DEBUG)
116             System.out.println(srg);
117         
118         // Disconnect
119         if(rg.isSimpleConnection()) {
120             RouteNode na = srg.terminals1.iterator().next();
121             RouteNode nb = srg.terminals2.iterator().next();
122             Resource a = ss.getResource((Long)na.getData());
123             Resource b = ss.getResource((Long)nb.getData());
124             graph.deny(a, DIA.AreConnected, b);
125             modis.addModi(new RouteGraphModification.RemoveLink(
126                     idMap.get(na), idMap.get(nb)
127                     ));
128         }
129         else if(srg.splitLine.isTransient()) {
130             RouteTerminal terminal = srg.splitLine.getTerminal();
131             Resource connector = ss.getResource((Long)terminal.getData());
132             graph.deny(connector, DIA.AreConnected);
133             modis.addModi(new RouteGraphModification.RemoveLink(
134                     idMap.get(terminal), idMap.get(terminal.getLine())
135                     ));
136         }
137         else  {
138             graph.deny(ss.getResource((Long)srg.splitLine.getData()));
139             // TODO remove links
140             modis.addModi(new RouteGraphModification.RemoveLine(
141                     idMap.get(srg.splitLine)
142                     ));
143         }
144         
145         ArrayList<Resource> interfaceNodes1Resources = new ArrayList<Resource>(srg.interfaceNodes1.size());
146         for(RouteNode n : srg.interfaceNodes1)
147             interfaceNodes1Resources.add(ss.getResource((Long)n.getData()));
148         ArrayList<Resource> interfaceNodes2Resources = new ArrayList<Resource>(srg.interfaceNodes2.size());
149         for(RouteNode n : srg.interfaceNodes2)
150             interfaceNodes2Resources.add(ss.getResource((Long)n.getData()));
151         
152         ArrayList<Resource> lines2Resources = new ArrayList<Resource>(srg.lines2.size());
153         for(RouteLine n : srg.lines2)
154             lines2Resources.add(ss.getResource((Long)n.getData()));
155         
156         ArrayList<Resource> terminals1Resources = new ArrayList<Resource>(srg.terminals1.size());
157         for(RouteTerminal n : srg.terminals1)
158             terminals1Resources.add(ss.getResource((Long)n.getData()));
159         ArrayList<Resource> terminals2Resources = new ArrayList<Resource>(srg.terminals2.size());
160         for(RouteTerminal n : srg.terminals2)
161             terminals2Resources.add(ss.getResource((Long)n.getData()));
162         doSplit(graph, connection,
163                 interfaceNodes1Resources,
164                 interfaceNodes2Resources,
165                 lines2Resources,
166                 terminals1Resources,
167                 terminals2Resources,
168                 line.isHorizontal(),
169                 isectX, isectY);
170         modis.addModi(new RouteGraphModification.Split(
171                 modis.toIds(interfaceNodes1Resources),
172                 modis.toIds(interfaceNodes2Resources),
173                 modis.toIds(lines2Resources),
174                 modis.toIds(terminals1Resources),
175                 modis.toIds(terminals2Resources),
176                 line.isHorizontal(),
177                 isectX, isectY
178                 ));
179         
180     }
181     
182     public void doSplit(WriteGraph graph, 
183             Resource connection,
184             ArrayList<Resource> interfaceNodes1Resources,
185             ArrayList<Resource> interfaceNodes2Resources,
186             ArrayList<Resource> lines2Resources,
187             ArrayList<Resource> terminals1Resources,
188             ArrayList<Resource> terminals2Resources,
189             boolean isHorizontal, 
190             double isectX, double isectY) throws DatabaseException {
191
192         if (DEBUG) {
193             System.out.println("doSplit:");
194             System.out.println(NameUtils.getSafeName(graph, connection, true));
195             for (Resource i : interfaceNodes1Resources)
196                 System.out.println("i1: " + NameUtils.getSafeName(graph, i, true));
197             for (Resource i : interfaceNodes2Resources)
198                 System.out.println("i2: " + NameUtils.getSafeName(graph, i, true));
199             for (Resource l : lines2Resources)
200                 System.out.println("l2r: " + NameUtils.getSafeName(graph, l, true));
201             for (Resource t : terminals1Resources)
202                 System.out.println("t1: " + NameUtils.getSafeName(graph, t, true));
203             for (Resource t : terminals2Resources)
204                 System.out.println("t2: " + NameUtils.getSafeName(graph, t, true));
205             System.out.println("is horizontal: " + isHorizontal);
206             System.out.println("@(x,y): " + isectX + ", " + isectY);
207         }
208
209         ConnectionUtil cu = new ConnectionUtil(graph);
210         Resource diagram = OrderedSetUtils.getSingleOwnerList(graph, connection, DIA.Diagram);
211
212         Resource connectionType = graph.getSingleType(connection, DIA.Connection);
213         Resource hasConnectionType = graph.getPossibleObject(connection, STR.HasConnectionType);
214         Resource newConnection = cu.newConnection(diagram, connectionType);
215         if (hasConnectionType != null)
216             graph.claim(newConnection, STR.HasConnectionType, null, hasConnectionType);
217
218         // Give running name to connection increment the counter attached to the diagram.
219         AddElement.claimFreshElementName(graph, diagram, newConnection);
220
221         // WORKAROUND for mapping problems:
222         // If any terminal of the split connection contains a flag, make sure their STR.Joins relations are all removed
223         // to give mapping a chance to fix them properly.
224         removeFlagJoins(graph, cu, connection, terminals1Resources);
225         removeFlagJoins(graph, cu, connection, terminals2Resources);
226
227         // Move route nodes to correct connections
228         for(Resource rn : lines2Resources) {
229             // TODO: use same predicate that was removed
230             graph.denyStatement(connection, DIA.HasInteriorRouteNode, rn);
231             graph.claim(newConnection, DIA.HasInteriorRouteNode, rn);
232         }
233         for(Resource rn : terminals2Resources) {
234             Statement stat = graph.getSingleStatement(rn, DIA.IsConnectorOf);
235             Resource predicate = stat.getPredicate();
236             graph.deny(rn, predicate);
237             graph.claim(rn, predicate, newConnection);
238         }
239
240         // 1 = output, 2 = input
241         FlagClass.Type type1, type2;
242
243         FlagLabelingScheme scheme = DiagramFlagPreferences.getActiveFlagLabelingScheme(graph);
244         String commonLabel = scheme.generateLabel(graph, diagram);
245
246         // Create flags and connect both disconnected ends to them.
247         Point2D pos1, pos2;
248         double theta;
249         double flagDist = 3.0;
250         if(isHorizontal) {
251             theta = 0.0;
252             pos1 = new Point2D.Double(isectX-flagDist, isectY);
253             pos2 = new Point2D.Double(isectX+flagDist, isectY);
254         }
255         else {
256             theta = Math.PI*0.5;
257             pos1 = new Point2D.Double(isectX, isectY-flagDist);
258             pos2 = new Point2D.Double(isectX, isectY+flagDist);
259         }
260
261         // Chooses flag directions
262         {
263             @SuppressWarnings("unused")
264             int inputs1 = 0, outputs1 = 0;
265             for(Resource connector : terminals1Resources) {
266                 if(graph.hasStatement(connector, DIA.IsHeadConnectorOf))
267                     ++inputs1;
268                 else
269                     ++outputs1;
270             }
271             @SuppressWarnings("unused")
272             int inputs2 = 0, outputs2 = 0;
273             for(Resource connector : terminals2Resources) {
274                 if(graph.hasStatement(connector, DIA.IsHeadConnectorOf))
275                     ++inputs2;
276                 else
277                     ++outputs2;
278             }
279             
280             if(outputs1 == 0) {
281                 type1 = FlagClass.Type.In;
282                 type2 = FlagClass.Type.Out;
283                 theta += Math.PI;
284             }
285             else {
286                 type1 = FlagClass.Type.Out;
287                 type2 = FlagClass.Type.In;
288             }
289             if (DEBUG) {
290                 System.out.println("inputs1:  " + inputs1);
291                 System.out.println("outputs1: " + outputs1);
292                 System.out.println("=> type1:  " + type1);
293                 System.out.println("inputs2:  " + inputs2);
294                 System.out.println("outputs2: " + outputs2);
295                 System.out.println("=> type2:  " + type2);
296             }
297         }
298         Resource flag1 = createFlag(graph, diagram, getFlagTransform(pos1, theta), type1, commonLabel);
299         Resource flag2 = createFlag(graph, diagram, getFlagTransform(pos2, theta), type2, commonLabel);
300         if (DEBUG) {
301             System.out.println("FLAG1: " + NameUtils.getSafeName(graph, flag1, true));
302             System.out.println("FLAG2: " + NameUtils.getSafeName(graph, flag2, true));
303         }
304
305 //        System.out.println("conn1: " + NameUtils.getSafeLabel(graph, type1 == FlagClass.Type.In ? DIA.HasPlainConnector : DIA.HasArrowConnector));
306 //        System.out.println("conn2: " + NameUtils.getSafeLabel(graph, type2 == FlagClass.Type.In ? DIA.HasPlainConnector : DIA.HasArrowConnector));
307         Resource flagConnector1 = cu.newConnector(connection, 
308                 type1 == FlagClass.Type.In ? DIA.HasPlainConnector : DIA.HasArrowConnector);
309         Resource flagConnector2 = cu.newConnector(newConnection, 
310                 type2 == FlagClass.Type.In ? DIA.HasPlainConnector : DIA.HasArrowConnector);
311         graph.claim(flag1, DIA.Flag_ConnectionPoint, flagConnector1);
312         graph.claim(flag2, DIA.Flag_ConnectionPoint, flagConnector2);
313
314         double position = isHorizontal ? isectY : isectX;
315         connectFlag(graph, isHorizontal, position, connection, flagConnector1, 
316                 interfaceNodes1Resources);
317         connectFlag(graph, isHorizontal, position, newConnection, flagConnector2, 
318                 interfaceNodes2Resources);
319
320         FlagUtil.join(graph, flag1, flag2);
321
322         // Move mapping relations to new connection if necessary
323         if(type1 == FlagClass.Type.In) {
324             moveStatements(graph, connection, newConnection, MOD.ElementToComponent);
325             moveStatements(graph, connection, newConnection, MOD.DiagramConnectionToConnection);
326             moveStatements(graph, connection, newConnection, MOD.DiagramConnectionToConnectionSpecial);
327             FlagUtil.fixBindsStatements(graph, graph.getPossibleObject(newConnection, MOD.DiagramConnectionToConnection));
328         }
329         else
330             FlagUtil.fixBindsStatements(graph, graph.getPossibleObject(connection, MOD.DiagramConnectionToConnection));
331     }
332
333     /**
334      * A workaround for problems with mapping not removing the necessary
335      * STR.Joins relations from flags after a split.
336      * 
337      * @param graph
338      * @param cu
339      * @param connection
340      * @param connectors
341      * @throws DatabaseException
342      */
343     private void removeFlagJoins(WriteGraph graph, ConnectionUtil cu, Resource connection, ArrayList<Resource> connectors) throws DatabaseException {
344         for (Resource connector : connectors) {
345             Resource e = cu.getConnectedComponent(connection, connector);
346             if (graph.isInstanceOf(e, DIA.Flag)) {
347                 Resource diagram = graph.syncRequest(new PossibleTypedParent(e, DIA.Diagram));
348                 if (diagram == null)
349                     continue;
350                 for (Resource join : graph.getObjects(e, DIA.FlagIsJoinedBy)) {
351                     Collection<Resource> joinsComposites = graph.getObjects(join, STR.JoinsComposite);
352                     if (joinsComposites.size() == 1) {
353                         // Only remove joins that are internal to a diagram.
354                         graph.deny(join, STR.Joins);
355                     } else if (joinsComposites.size() == 2) {
356                         // Only remove the joins relations that refer to
357                         // connections that are part of the same diagram.
358                         for (Resource joins : graph.getObjects(join, STR.Joins)) {
359                             Resource diagramConnection = graph.getPossibleObject(joins, MOD.ConnectionToDiagramConnection);
360                             if (diagramConnection == null)
361                                 continue;
362                             Resource partOfDiagram = graph.syncRequest(new PossibleTypedParent(diagramConnection, DIA.Diagram));
363                             if (diagram.equals(partOfDiagram)) {
364                                 graph.deny(join, STR.Joins, joins);
365                             }
366                         }
367                     }
368                 }
369             }
370         }
371     }
372
373     private static void moveStatements(WriteGraph graph, Resource from, Resource to, Resource relation) throws DatabaseException {
374         if(from.equals(to))
375                 return;
376         for(Statement stat : graph.getStatements(from, relation))
377                 if(stat.getSubject().equals(from))
378                         graph.claim(to, stat.getPredicate(), stat.getObject());
379         graph.deny(from, relation);
380     }
381     
382     private void connectFlag(WriteGraph graph, boolean isHorizontal, double position, Resource connection, Resource flagConnector, Collection<Resource> interfaceNodes) 
383             throws DatabaseException {
384         if(interfaceNodes.size() > 1) {
385             Resource routeLine = graph.newResource();
386             graph.claim(routeLine, L0.InstanceOf, DIA.RouteLine);
387             graph.claim(connection, DIA.HasInteriorRouteNode, routeLine);
388             graph.claimLiteral(routeLine, DIA.IsHorizontal, isHorizontal);
389             graph.claimLiteral(routeLine, DIA.HasPosition, position);
390             graph.claim(routeLine, DIA.AreConnected, flagConnector);
391             flagConnector = routeLine;
392         }
393         for(Resource rn : interfaceNodes) {
394             graph.claim(flagConnector, DIA.AreConnected, rn);
395         }
396     }
397
398     private AffineTransform getFlagTransform(Point2D pos, double theta) {
399         AffineTransform at = AffineTransform.getTranslateInstance(pos.getX(), pos.getY());
400         at.rotate(theta);
401         return at;
402     }
403
404     private Resource createFlag(WriteGraph graph, Resource diagram, AffineTransform tr, FlagClass.Type type, String label) throws DatabaseException {
405         DiagramResource DIA = DiagramResource.getInstance(graph);
406
407         Resource flag = graph.newResource();
408         graph.claim(flag, L0.InstanceOf, null, DIA.Flag);
409         AddElement.claimFreshElementName(graph, diagram, flag);
410         graph.claim(flag, L0.PartOf, L0.ConsistsOf, diagram);
411         
412         DiagramGraphUtil.setTransform(graph, flag, tr);
413         if (type != null)
414             FlagUtil.setFlagType(graph, flag, type);
415
416         if (label != null)
417             graph.claimLiteral(flag, L0.HasLabel, DIA.FlagLabel, label, Bindings.STRING);
418
419         OrderedSetUtils.add(graph, diagram, flag);
420         return flag;
421     }
422
423     public static void splitConnection(WriteGraph graph, Resource connection, double x, double y) throws DatabaseException {
424         RouteGraph rg = RouteGraphUtils.load(graph, null, connection);
425         new RouteGraphConnectionSplitter(graph).split(graph, connection, rg, new Point2D.Double(x, y));
426     }
427 }