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