e0c198388e41f20a0f6848c22b2e70ae34b0ea2f
[simantics/platform.git] / bundles / org.simantics.modeling / src / org / simantics / modeling / SCLScenegraph.java
1 package org.simantics.modeling;
2
3 import java.awt.BasicStroke;
4 import java.awt.Dimension;
5 import java.awt.RenderingHints;
6 import java.awt.RenderingHints.Key;
7 import java.awt.geom.AffineTransform;
8 import java.awt.geom.Rectangle2D;
9 import java.io.ByteArrayOutputStream;
10 import java.io.OutputStreamWriter;
11 import java.util.ArrayList;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Random;
19 import java.util.Set;
20 import java.util.UUID;
21 import java.util.function.Function;
22 import java.util.stream.Collectors;
23
24 import javax.xml.transform.OutputKeys;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerFactory;
27 import javax.xml.transform.dom.DOMSource;
28 import javax.xml.transform.stream.StreamResult;
29
30 import org.apache.batik.dom.GenericDOMImplementation;
31 import org.apache.batik.svggen.SVGGeneratorContext;
32 import org.apache.batik.svggen.SVGGraphics2D;
33 import org.simantics.Simantics;
34 import org.simantics.datatypes.literal.GUID;
35 import org.simantics.db.ReadGraph;
36 import org.simantics.db.Resource;
37 import org.simantics.db.common.request.IndexRoot;
38 import org.simantics.db.common.request.ResourceRead;
39 import org.simantics.db.common.request.UnaryRead;
40 import org.simantics.db.exception.DatabaseException;
41 import org.simantics.db.exception.RuntimeDatabaseException;
42 import org.simantics.db.layer0.variable.Variables;
43 import org.simantics.diagram.elements.DecorationSVGNode;
44 import org.simantics.diagram.elements.DiagramNodeUtil;
45 import org.simantics.diagram.elements.TextGridNode;
46 import org.simantics.diagram.elements.TextNode;
47 import org.simantics.diagram.stubs.DiagramResource;
48 import org.simantics.g2d.canvas.ICanvasContext;
49 import org.simantics.g2d.diagram.DiagramHints;
50 import org.simantics.g2d.diagram.IDiagram;
51 import org.simantics.g2d.diagram.handler.DataElementMap;
52 import org.simantics.g2d.diagram.participant.Selection;
53 import org.simantics.g2d.element.IElement;
54 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
55 import org.simantics.g2d.utils.CanvasUtils;
56 import org.simantics.layer0.Layer0;
57 import org.simantics.scenegraph.INode;
58 import org.simantics.scenegraph.ParentNode;
59 import org.simantics.scenegraph.g2d.G2DParentNode;
60 import org.simantics.scenegraph.g2d.G2DRenderingHints;
61 import org.simantics.scenegraph.g2d.G2DSceneGraph;
62 import org.simantics.scenegraph.g2d.IG2DNode;
63 import org.simantics.scenegraph.g2d.IG2DNodeVisitor;
64 import org.simantics.scenegraph.g2d.events.command.Commands;
65 import org.simantics.scenegraph.g2d.nodes.BackgroundNode;
66 import org.simantics.scenegraph.g2d.nodes.BoundsNode;
67 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
68 import org.simantics.scenegraph.g2d.nodes.DataNode;
69 import org.simantics.scenegraph.g2d.nodes.NavigationNode;
70 import org.simantics.scenegraph.g2d.nodes.SVGNode;
71 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
72 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
73 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
74 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
75 import org.simantics.scenegraph.utils.NodeUtil;
76 import org.simantics.scl.runtime.function.Function1;
77 import org.simantics.scl.runtime.tuple.Tuple2;
78 import org.simantics.trend.impl.ItemNode;
79 import org.simantics.utils.threads.ThreadUtils;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82 import org.w3c.dom.DOMImplementation;
83 import org.w3c.dom.Document;
84 import org.w3c.dom.Element;
85 import org.w3c.dom.NodeList;
86
87 public class SCLScenegraph {
88
89         private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
90         
91         private static final String MAIN_SECTION = "main";
92         private static final String SELECTION_SECTION = "selection";
93         private static final String SELECTION_MASK_SECTION = "selectionMask";
94         
95         private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
96
97         @Deprecated
98         public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
99                 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
100                 return provider;
101         }
102         
103         @Deprecated
104         public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
105                 provider.dispose();
106         }
107
108     public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
109         return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
110     }
111
112     public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
113         Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
114
115             @Override
116             public Tuple2 perform(ReadGraph graph) throws DatabaseException {
117                 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
118                 String diagramRVI = Variables.getRVI(graph, resource);
119                 return new Tuple2(indexRoot, diagramRVI);
120             }
121         });
122         ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
123         try {
124             return func.apply(provider);
125         } finally {
126             provider.dispose();
127         }
128     }
129
130     public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
131         return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
132     }
133
134     public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
135         return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
136     }
137
138         public static String getNodeTransform(ICanvasContext ctx, String name) {
139                 
140                 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
141                 for (TextNode text : texts) {
142                         String nodeName = NodeUtil.getNodeName(text);
143                         if (nodeName.equals(name)) {
144                                 String transform = text.getTransform().toString();
145                                 return transform;
146                         }
147                 }
148                 return "No node found";
149         }
150         
151         public static String getNodeText(ICanvasContext ctx, String name) {
152                 
153                 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
154                 for (TextNode text : texts) {
155                         String nodeName = NodeUtil.getNodeName(text);
156                         if (nodeName.equals(name)) {
157                                 String texti = text.getText();
158                                 return texti;
159                         }
160                 }
161                 return "No node found";
162         }
163         
164         public static String getNodeCount(ICanvasContext ctx) {
165                 G2DSceneGraph g2 = ctx.getSceneGraph();
166                 int amount = NodeUtil.countTreeNodes(g2);
167                 return "Node count: " + amount;
168         }
169         
170     public static String getAllNodes (ICanvasContext ctx) {
171         
172         Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
173         int amount = g2.size() +1;
174         return "All nodes: " + amount;
175     }
176     
177     public static String getBoundsNodes (ICanvasContext ctx) {
178         
179         Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
180         int amount = bn.size();
181         return "BoundsNodes: " + amount;
182     }
183     
184     public static String getBackgroundNodes (ICanvasContext ctx) {
185         
186         Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
187         int amount = bg.size();
188         return "BackgroundNodes: " + amount;
189     }
190     
191     public static String getDataNodes (ICanvasContext ctx) {
192         
193         Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
194         int amount = dn.size();
195         return "DataNodes: " + amount;
196     }
197     
198     public static String getNavigationNodes (ICanvasContext ctx) {
199         
200         Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
201         int amount = g2.size();
202         return "NavigationNodes: " + amount;
203     }
204     
205     public static String getParentNodes (ICanvasContext ctx) {
206         
207         Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
208         int amount = g2.size();
209         return "ParentNodes: " + amount;
210     }
211     
212     public static String getDecorationNodes (ICanvasContext ctx) {
213         
214         Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
215         int amount = deco.size();
216         return "DecorationNodes: " + amount;
217     }
218     
219     public static String getSingleElementNodes (ICanvasContext ctx) {
220         
221         Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
222         int amount = g2.size();
223         return "SingleElementNodes: " + amount;
224     }
225     
226     public static String getConnectionNodes (ICanvasContext ctx) {
227         
228         Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
229         int amount = g2.size();
230         return "ConnectionNodes: " + amount;
231     }
232     
233     public static String getTextNodes (ICanvasContext ctx) {
234         
235         Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
236         Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
237         int amount = tn.size() + tgn.size();
238         return "TextNodes: " + amount;
239     }
240     
241     public static String getItemNodes (ICanvasContext ctx) {
242         
243         Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
244         int amount = item.size();
245         return "ItemNodes: " + amount;
246     }
247   
248     public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
249                 
250         Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
251         for (TextNode modulenode : textGridNodes) {
252                 if (module.equals(modulenode.getText())) {
253                         //System.out.println("Module what we were looking for: " + module);
254                         //System.out.println("Modulenode: " + modulenode.getText());
255                         
256                         ParentNode<?> parentnode = modulenode.getParent();
257                         //System.out.println("Parentnode: " + parentnode);
258                         
259                         Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
260                         for (TextNode valuenode : textnodes) {
261                                 if (previous_value.equals(valuenode.getText())) {
262                                         //System.out.println("Value what we were looking for: " + previous_value);
263                                         //System.out.println("Valuenode: " + valuenode.getText());
264                                         
265                                         //valuenode.setEditMode(true);
266                                         valuenode.activateEdit(0, null, ctx);
267                                         valuenode.setText(new_value);
268                                         valuenode.fireTextEditingEnded();
269                                         
270                                         //System.out.println("valuenode modified: " + valuenode);
271                                         return "Modified module " + module + " with value " + new_value;
272                                 }
273                         }
274                         return "Not found module : " + module;
275                 }
276         }
277         return "No nodes in scenegraph!";
278     }
279
280     public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
281         
282         boolean module_founded = false;
283         boolean value_founded = false;
284         
285         Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
286         System.out.println("Total amount of nodes: " + g2.size() + 1);
287         
288         Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
289         Integer textGridNodeAmount = grid.size();
290         System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
291         
292         Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
293         Integer textNodeAmount = grid.size();
294         System.out.println("Amount of TextNodes " + textNodeAmount);
295
296         for (TextNode node : texts) {
297             if (module.equals(node.getText())) {
298                 module_founded = true;
299                 System.out.println("Correct module " + module + " founded.");
300             }
301             if (value.equals(node.getText())) {
302                 value_founded = true;
303                 System.out.println("Correct value " + value + " founded.");
304             }
305         }
306         
307         if (value_founded == true && module_founded == true) {
308                 return "Found both correct module " + module + " and value " + value;
309         }
310         if (value_founded == false && module_founded == true) {
311                 return "Found only correct module " + module + " but not value " + value;
312         }
313         if (value_founded == true && module_founded == false) {
314                 return "Found only correct value " + value + " but not module " + module;
315         }
316         else {
317                 return "Didn't found either module " + module + " or value " + value;
318         }
319     }
320     
321     public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
322         
323         IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
324
325                 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
326                 if (dem != null) {
327                         final Collection<IElement> newSelection = new ArrayList<IElement>();
328                         for (Resource module : modules) {
329                                 IElement element = dem.getElement(idiagram, module);
330                                 if (element != null) {
331                                         newSelection.add(element);
332                                 } else {
333                                         throw new DatabaseException("Could not find IElement for " + element);
334                                 }
335                         }
336                         
337                         ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
338                     @Override
339                     public void run() {
340                         if (source_ctx.isDisposed())
341                             return;
342                         Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
343                         if (selection != null) {
344                             // This prevents workbench selection from being left over.
345                             // Also prevents scene graph crap from being left on the screen.
346                             selection.setSelection(0, newSelection);
347                         }
348                                 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
349                                 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
350                     }
351                 });
352                         
353                 //}
354                 
355                 while(source_ctx.getEventQueue().size() > 0) {
356                         try {
357                                 Thread.sleep(10);
358                         } catch (InterruptedException e) {
359                                 throw new DatabaseException(e);
360                         }
361                 }
362
363                 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
364             @Override
365             public void run() {
366             }
367         });             
368                                 
369                 }
370                 return true;
371     }
372
373         static class Generator extends SVGGraphics2D {
374
375                 int elemLevel = 0;
376                 String newElementId = null;
377                 ArrayList<Element> elements = new ArrayList<Element>();
378
379                 public static final String svgNS = "http://www.w3.org/2000/svg";
380
381                 public Generator(SVGGeneratorContext ctx, boolean joku) {
382                         super(ctx, joku);
383                 }
384
385                 public Generator(Document document) {
386                         super(document);
387                 }
388
389                 @Override
390                 public Element getRoot() {
391                         Element root = super.getRoot();
392                         for(Element e : elements) {
393                                 root.appendChild(e);
394                         }
395                         return root;
396                 }
397
398                 @Override
399                 public void setRenderingHint(Key arg0, Object arg1) {
400                         if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
401                                 elemLevel++;
402                         }
403                         if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
404                                 if(arg1 != null)
405                                         newElementId = arg1.toString();
406                                 else
407                                         newElementId = UUID.randomUUID().toString();
408                         }
409                         if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
410                                 elemLevel--;
411                                 if(elemLevel == 0) {
412                                         Element group = getDOMFactory().createElement(SVG_G_TAG);
413                                         //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
414                                         group.setAttributeNS(null, "id", newElementId);
415                                         group.setAttributeNS(null, "class", arg1.toString());
416                                         getRoot(group);
417                                         elements.add(group);
418                                 }
419                         }
420                         super.setRenderingHint(arg0, arg1);
421                 }
422
423         }
424
425         public static Element renderSVGNode(IG2DNode node) {
426
427                 // Get a DOMImplementation.
428                 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
429
430                 // Create an instance of org.w3c.dom.Document.
431                 String svgNS = "http://www.w3.org/2000/svg";
432                 Document document = domImpl.createDocument(svgNS, "svg", null);
433
434                 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
435                 ctx.setComment(null);
436
437                 // Create an instance of the SVG Generator.
438                 SVGGraphics2D svgGenerator = new Generator(ctx, false);
439
440                 try {
441
442                         svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
443                         svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
444                         svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
445
446                         node.render(svgGenerator);
447
448                 } catch (Throwable t) {
449                         LOGGER.error("Problems rendering scene graph to SVG", t);
450                 }
451
452                 return svgGenerator.getRoot();
453         }
454
455         public static String printSVGDocument(Element doce) {
456
457                 StringBuilder result = new StringBuilder();
458
459                 NodeList nl =  doce.getChildNodes();
460
461                 for(int i=0;i<nl.getLength();i++) {
462
463                         ByteArrayOutputStream os = new ByteArrayOutputStream();
464
465                         try {
466
467                                 TransformerFactory tf = TransformerFactory.newInstance();
468                                 Transformer transformer = tf.newTransformer();
469                                 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
470                                 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
471                                 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
472                                 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
473                                 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
474                                 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
475
476                                 transformer.transform(new DOMSource(nl.item(i)), 
477                                                 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
478
479                                 os.flush();
480                                 os.close();
481
482                         } catch (Throwable t) {
483                                 LOGGER.error("Problems formatting SVGDocument to text.", t);
484                         }
485
486                         result.append(new String(os.toByteArray()));
487
488                 }
489
490                 return result.toString();
491
492         }
493
494         public static String renderSVG3(ICanvasContext ctx) {
495         return renderSVG0(ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
496         }
497
498     /**
499      * @param graph
500      * @param component
501      * @throws DatabaseException
502      */
503     private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
504         String uri = graph.getPossibleURI(component);
505         int hashCode = uri.hashCode();
506         Random random = new Random(hashCode);
507         long l1 = random.nextLong();
508         long l2 = random.nextLong();
509         return new Object[] { l1, l2 };
510     }
511
512     /**
513      * Default no-op mapper
514      */
515     private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
516     
517     public static String renderSVG(ICanvasContext ctx) {
518         return renderSVG0(ctx, mapper);
519     }
520
521     /**
522      * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
523      * GUID's
524      * 
525      * @param ctx
526      * @return
527      */
528     public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
529         return renderSVG0(ctx, new Function1<Set<?>, Map<?, ?>>() {
530
531             @Override
532             public Map<?, ?> apply(Set<?> p0) {
533                 try {
534                     return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
535
536                         @Override
537                         public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
538                             ModelingResources MOD = ModelingResources.getInstance(graph);
539                             DiagramResource DIA = DiagramResource.getInstance(graph);
540                             Layer0 L0 = Layer0.getInstance(graph);
541                             return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
542                                 try {
543                                     if (p instanceof Resource) {
544                                         Resource element = (Resource) p;
545                                         if (graph.isInstanceOf(element, DIA.Element)) {
546                                             Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
547                                             if (component != null) {
548                                                 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
549                                                 if (identifier != null) {
550                                                     return Arrays.toString(createURIBasedL0Identifier(graph, component));
551                                                 } else {
552                                                     LOGGER.error("Component {} does not have GUID identifier!", component);
553                                                 }
554                                             } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
555                                                 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers 
556                                                 return graph.getURI(element).hashCode();
557                                             } else {
558                                                 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
559                                                 if (graph.hasStatement(element, L0.HasName))
560                                                     return graph.getURI(element).hashCode();
561                                                 return "";
562                                             }
563                                         }
564                                     } else {
565                                         LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
566                                     }
567                                     return p;
568                                 } catch (DatabaseException e) {
569                                     throw new RuntimeDatabaseException(e);
570                                 }
571                             }));
572                         }
573                     });
574                 } catch (DatabaseException e) {
575                     LOGGER.error("Could not apply mappings", e);
576                     throw new RuntimeDatabaseException(e);
577                 }
578             }
579         });
580         }
581         
582     static class RenderSVGContext {
583         
584         Map<String,StringBuilder> documents = new HashMap<>();
585         
586         public void append(String[] keys, String svgText) {
587                 for(String key : keys) append(key, svgText);
588         }
589
590         public void append(String key, String svgText) {
591                 StringBuilder builder = documents.get(key);
592                 if(builder == null) {
593                         builder = new StringBuilder();
594                         documents.put(key, builder);
595                 }
596                 builder.append(svgText);
597         }
598         
599         public void append(RenderSVGContext other) {
600                 for(String key : other.documents.keySet()) {
601                         append(key, other.get(key));
602                 }
603         }
604         
605         public String get(String key) {
606                 StringBuilder builder = documents.get(key);
607                 if(builder == null) return "";
608                 else return builder.toString();
609         }
610         
611     }
612     
613         private static String renderSVG0(ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
614
615                 // Get a DOMImplementation.
616                 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
617
618                 // Create an instance of org.w3c.dom.Document.
619                 String svgNS = "http://www.w3.org/2000/svg";
620                 Document document = domImpl.createDocument(svgNS, "svg", null);
621
622                 // Create an instance of the SVG Generator.
623                 SVGGraphics2D svgGenerator = new Generator(document);
624
625                 RenderSVGContext result = new RenderSVGContext();
626
627                 try {
628
629             Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
630             if (selection != null) {
631                 // This prevents workbench selection from being left over.
632                 // Also prevents scene graph crap from being left on the screen.
633                 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
634                 selection.setSelection(0, d.getElements());
635             }
636
637                         G2DSceneGraph sg = ctx.getSceneGraph();
638                         sg.performCleanup();
639                         G2DParentNode root = (G2DParentNode) sg.getRootNode();
640
641                         // rtree is the actual content of the diagram
642                         RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
643                         Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
644
645                         // nav is a node that has zooming functionalities
646                         NavigationNode nav = NodeUtil.getNearestChildByClass(root, NavigationNode.class);
647                         nav.setZoomEnabled(true);
648
649                         // fit view with the contents of rtreeBounds
650                         nav.zoomTo(rtreeBounds);
651
652                         // get the bounds of the content
653                         Rectangle2D content = NodeUtil.getLocalBounds(nav);
654
655                         svgGenerator.scale(3,3);
656
657                         // translate svgGenerator to the x and y coordinates of current content
658                         svgGenerator.translate(-1 * content.getX(), (-1 * content.getY()));
659
660                         Rectangle2D destination = new Rectangle2D.Double(0,0,1000,1000);
661                         double sx = destination.getWidth() / content.getWidth();
662                         double sy = destination.getHeight() / content.getHeight();
663                         double scale = sx < sy ? sx : sy;
664
665                         // Set svgCanvasSize to the given size parameters
666                         svgGenerator.setSVGCanvasSize(new Dimension((int)(scale * content.getWidth()), (int)(scale * content.getHeight())));
667                         svgGenerator.setClip(content);
668
669                         double trX = -1 * content.getX();
670                         double trY = -1 * content.getY();
671                         
672                         // NaNs
673                         if(!Double.isFinite(trX)) trX = 0;
674                         if(!Double.isFinite(trY)) trY = 0;
675                         
676                         result.append(MAIN_SECTION, "<g class=\"symbols\">");
677                         result.append(SELECTION_SECTION, "<g class=\"selections\">");
678                         result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
679
680                         result.append(ALL_SECTIONS, "<g transform=\"translate(");
681                         result.append(ALL_SECTIONS, "" + trX);
682                         result.append(ALL_SECTIONS, ", ");
683                         result.append(ALL_SECTIONS, "" + trY);
684                         result.append(ALL_SECTIONS, ")\">");
685
686                         
687                         KeyVisitor keyVisitor = new KeyVisitor();
688                         sg.accept(keyVisitor);
689                         
690                         Set<Object> keys = keyVisitor.getKeys();
691                         
692                         Map<?, ?> mappings = mappingFunction.apply(keys);
693
694                         IG2DNodeVisitor visitor = new PrintingVisitor(result, mappings);
695                         
696                         sg.accept(visitor);
697
698                 } catch (Throwable t) {
699                         LOGGER.error("Problems rendering canvas context to SVG", t);
700                 }
701
702
703                 result.append(ALL_SECTIONS, "</g></g>");
704
705                 StringBuilder res = new StringBuilder();
706                 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
707                 res.append(result.get(MAIN_SECTION));
708                 res.append(result.get(SELECTION_SECTION));
709                 res.append(result.get(SELECTION_MASK_SECTION));
710                 res.append("</svg>");
711
712 //              System.err.println(" == FINAL RESULT == ");
713 //              System.err.println(res.toString());
714                 
715                 return res.toString();
716                 
717         }
718         
719         
720         
721         private static class KeyVisitor implements IG2DNodeVisitor {
722
723         private Set<Object> keys = new HashSet<>();
724
725         @Override
726         public void enter(IG2DNode node) {
727             if (node instanceof SingleElementNode) {
728                 Object key = ((SingleElementNode) node).getKey();
729                 if (key != null) {
730                     keys.add(key);
731                 }
732             }
733         }
734
735         @Override
736         public void leave(IG2DNode node) {
737             // Nothing to do
738         }
739
740         public Set<Object> getKeys() {
741             return keys;
742         }
743         }
744
745         private static class PrintingVisitor implements IG2DNodeVisitor {
746
747         int indent = 0;
748
749         HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
750
751         private RenderSVGContext result;
752
753         private Map<?, ?> mappings;
754
755         public PrintingVisitor(RenderSVGContext result, Map<?, ?> mappings) {
756             this.result = result;
757             this.mappings = mappings;
758         }
759
760         private String getKey(SingleElementNode node) {
761             String key;
762                 if(node.getKey() != null) {
763                 if (mappings.containsKey(node.getKey()))
764                     key = mappings.get(node.getKey()).toString();
765                 else
766                     key = node.getKey().toString();
767                 } else {
768                         key = Long.toString(node.getId());
769                 }
770             return key;
771         }
772
773         @Override
774         public void enter(IG2DNode node) {
775             
776                 RenderSVGContext parentBuilder = getParentBuilder(node);
777             
778             indent++;
779             if(node instanceof ConnectionNode) {
780                 
781                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
782                     n.setIgnoreSelection(true);
783                 }
784
785                 String key = getKey((ConnectionNode) node);
786                 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
787                 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
788                 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"0.001\" id=\"" + key + "\">");
789                 
790                 Element doc = renderSVGNode((IG2DNode)node);
791                 String svg = printSVGDocument(doc);
792                 parentBuilder.append(MAIN_SECTION, svg);
793
794                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
795                     n.setIgnoreSelection(false);
796                 }
797
798                 doc = renderSVGNode((IG2DNode)node);
799                 svg = printSVGDocument(doc);
800                 parentBuilder.append(SELECTION_SECTION, svg);
801
802                 BasicStroke bs = new BasicStroke(10f);
803                 
804                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
805                     n.setDynamicStroke(bs);
806                 }
807
808                 doc = renderSVGNode((IG2DNode)node);
809                 svg = printSVGDocument(doc);
810                 parentBuilder.append(SELECTION_MASK_SECTION, svg);
811
812                 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
813                 parentBuilder.append(SELECTION_SECTION, "\n</g>");
814                 parentBuilder.append(MAIN_SECTION, "\n</g>");
815                 
816             } else if (node instanceof SelectionNode) {
817                 
818                 SelectionNode n = (SelectionNode)node;
819                 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
820                 if(parentSEN != null) {
821                     
822                         RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
823                     
824                     String key = getKey(parentSEN);
825                     n.setIgnore(false);
826                     Element doc = renderSVGNode((IG2DNode)node);
827                     n.setIgnore(true);
828                     String svg = printSVGDocument(doc);
829                     parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
830                     parentBuilder2.append(SELECTION_SECTION, svg);
831                     parentBuilder2.append(SELECTION_SECTION, "\n</g>");
832                     parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key + "\">");
833                     Rectangle2D rect = n.getRect();
834                     // NaN
835                     if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
836                             parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"0.001\"");
837                             parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
838                             parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
839                             parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
840                     }
841                     parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
842                    
843                 }
844             } else if (node instanceof SVGNode) {
845                 SVGNode svg = (SVGNode)node;
846                 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
847             } else if (node instanceof G2DParentNode) {
848                 AffineTransform at = node.getTransform();
849                 if(node instanceof SingleElementNode) {
850                     SingleElementNode sen = (SingleElementNode)node;
851                     String key = getKey(sen);
852                     String typeClass = sen.getTypeClass();
853                     String clazz = "definedElement";
854                     if(typeClass != null && !typeClass.isEmpty())
855                         clazz = clazz + " " + typeClass;
856
857                     parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
858                     senBuilders.put(sen, new RenderSVGContext());
859                 }
860                 if(!at.isIdentity()) {
861                     if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
862                         String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
863                         parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
864                     } else {
865                         double[] ds = new double[6];
866                         at.getMatrix(ds);
867                         String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
868                         parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
869                     }
870                 }
871             }
872
873             //enters.put(node, b.length());
874
875         }
876         
877         private RenderSVGContext getParentBuilder(IG2DNode node) {
878             
879             INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
880             if(parentSEN instanceof G2DSceneGraph) return result;
881
882             RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
883             if(parentBuilder == null) return result;
884             
885             return parentBuilder;
886             
887         }
888
889         @Override
890         public void leave(IG2DNode node) {
891
892             if(node instanceof ConnectionNode || node instanceof SVGNode) {
893                 // We are done
894             } else if (node instanceof G2DParentNode) {
895                 
896                 RenderSVGContext parentBuilder = getParentBuilder(node);
897                 
898                 if(node instanceof SingleElementNode) {
899                         SingleElementNode sen = (SingleElementNode)node;
900                         RenderSVGContext b = senBuilders.get(sen);
901                         String content = b.get(MAIN_SECTION);
902                         if(content.isEmpty()) {
903                                 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
904                                         n.setIgnore(true);
905                                 }
906                                 Element doc = renderSVGNode((IG2DNode)node);
907                                 String svg = printSVGDocument(doc);
908                                 parentBuilder.append(MAIN_SECTION, svg);
909                         } else {
910                                 parentBuilder.append(b);
911                         }
912                 }
913                 
914                 AffineTransform at = node.getTransform();
915                 if(!at.isIdentity()) {
916                     parentBuilder.append(ALL_SECTIONS, "</g>");
917                 }
918                 if(node instanceof SingleElementNode) {
919                     SingleElementNode sen = (SingleElementNode)node;
920                     //if(sen.getKey() != null) {
921                         parentBuilder.append(MAIN_SECTION, "</g>");
922                     //}
923                 }
924             }
925             indent --;
926         }
927         }
928 }