]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling/src/org/simantics/modeling/SCLScenegraph.java
cc4489f8230812b15badd4287bae73582c47421d
[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.Color;
5 import java.awt.Dimension;
6 import java.awt.RenderingHints;
7 import java.awt.RenderingHints.Key;
8 import java.awt.geom.AffineTransform;
9 import java.awt.geom.Rectangle2D;
10 import java.io.ByteArrayOutputStream;
11 import java.io.OutputStreamWriter;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Random;
20 import java.util.Set;
21 import java.util.UUID;
22 import java.util.function.Function;
23 import java.util.stream.Collectors;
24
25 import javax.xml.transform.OutputKeys;
26 import javax.xml.transform.Transformer;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30
31 import org.apache.batik.dom.GenericDOMImplementation;
32 import org.apache.batik.svggen.SVGGeneratorContext;
33 import org.apache.batik.svggen.SVGGraphics2D;
34 import org.apache.batik.svggen.SVGIDGenerator;
35 import org.eclipse.swt.SWT;
36 import org.simantics.Simantics;
37 import org.simantics.datatypes.literal.GUID;
38 import org.simantics.db.ReadGraph;
39 import org.simantics.db.Resource;
40 import org.simantics.db.common.request.IndexRoot;
41 import org.simantics.db.common.request.ResourceRead;
42 import org.simantics.db.common.request.UnaryRead;
43 import org.simantics.db.exception.DatabaseException;
44 import org.simantics.db.exception.RuntimeDatabaseException;
45 import org.simantics.db.layer0.variable.Variables;
46 import org.simantics.diagram.elements.DecorationSVGNode;
47 import org.simantics.diagram.elements.DiagramNodeUtil;
48 import org.simantics.diagram.elements.TextGridNode;
49 import org.simantics.diagram.elements.TextNode;
50 import org.simantics.diagram.stubs.DiagramResource;
51 import org.simantics.diagram.ui.DiagramModelHints;
52 import org.simantics.g2d.canvas.Hints;
53 import org.simantics.g2d.canvas.ICanvasContext;
54 import org.simantics.g2d.diagram.DiagramHints;
55 import org.simantics.g2d.diagram.IDiagram;
56 import org.simantics.g2d.diagram.handler.DataElementMap;
57 import org.simantics.g2d.diagram.participant.ElementPainter.SelectionShapeNode;
58 import org.simantics.g2d.diagram.participant.Selection;
59 import org.simantics.g2d.element.IElement;
60 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
61 import org.simantics.g2d.utils.CanvasUtils;
62 import org.simantics.layer0.Layer0;
63 import org.simantics.scenegraph.INode;
64 import org.simantics.scenegraph.ParentNode;
65 import org.simantics.scenegraph.g2d.G2DParentNode;
66 import org.simantics.scenegraph.g2d.G2DRenderingHints;
67 import org.simantics.scenegraph.g2d.G2DSceneGraph;
68 import org.simantics.scenegraph.g2d.IG2DNode;
69 import org.simantics.scenegraph.g2d.IG2DNodeVisitor;
70 import org.simantics.scenegraph.g2d.events.command.Commands;
71 import org.simantics.scenegraph.g2d.nodes.BackgroundNode;
72 import org.simantics.scenegraph.g2d.nodes.BoundsNode;
73 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
74 import org.simantics.scenegraph.g2d.nodes.DataNode;
75 import org.simantics.scenegraph.g2d.nodes.LinkNode;
76 import org.simantics.scenegraph.g2d.nodes.NavigationNode;
77 import org.simantics.scenegraph.g2d.nodes.SVGNode;
78 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
79 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
80 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
81 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
82 import org.simantics.scenegraph.utils.NodeUtil;
83 import org.simantics.scl.runtime.function.Function1;
84 import org.simantics.scl.runtime.tuple.Tuple2;
85 import org.simantics.trend.impl.ItemNode;
86 import org.simantics.utils.threads.ThreadUtils;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89 import org.w3c.dom.DOMImplementation;
90 import org.w3c.dom.Document;
91 import org.w3c.dom.Element;
92 import org.w3c.dom.Node;
93 import org.w3c.dom.NodeList;
94
95 public class SCLScenegraph {
96
97         private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
98         
99         private static final String MAIN_SECTION = "main";
100         private static final String SELECTION_SECTION = "selection";
101         private static final String SELECTION_MASK_SECTION = "selectionMask";
102
103         private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
104
105         // Changed from 0.001 to 0.0001 to prevent creation of huge BufferedImage's when
106         // generating PDF from SVG. If SVG contains any transparency then Batik uses
107         // bitmap-rendering which remarkably slows things down
108         // See org.apache.batik.gvt.AbstractGraphicsNode.paint(Graphics2D) where decisions are made
109         // if AlphaComposite should be painted 
110         private static final String OPACITY = "0.0001";
111
112         @Deprecated
113         public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
114                 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
115                 return provider;
116         }
117         
118         @Deprecated
119         public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
120                 provider.dispose();
121         }
122
123     public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
124         return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
125     }
126
127     public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
128         Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
129
130             @Override
131             public Tuple2 perform(ReadGraph graph) throws DatabaseException {
132                 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
133                 String diagramRVI = Variables.getRVI(graph, resource);
134                 return new Tuple2(indexRoot, diagramRVI);
135             }
136         });
137         ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
138         try {
139             return func.apply(provider);
140         } finally {
141             provider.dispose();
142         }
143     }
144
145     public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
146         return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
147     }
148
149     public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
150         return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
151     }
152
153         public static String getNodeTransform(ICanvasContext ctx, String name) {
154                 
155                 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
156                 for (TextNode text : texts) {
157                         String nodeName = NodeUtil.getNodeName(text);
158                         if (nodeName.equals(name)) {
159                                 String transform = text.getTransform().toString();
160                                 return transform;
161                         }
162                 }
163                 return "No node found";
164         }
165         
166         public static String getNodeText(ICanvasContext ctx, String name) {
167                 
168                 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
169                 for (TextNode text : texts) {
170                         String nodeName = NodeUtil.getNodeName(text);
171                         if (nodeName.equals(name)) {
172                                 String texti = text.getText();
173                                 return texti;
174                         }
175                 }
176                 return "No node found";
177         }
178         
179         public static String getNodeCount(ICanvasContext ctx) {
180                 G2DSceneGraph g2 = ctx.getSceneGraph();
181                 int amount = NodeUtil.countTreeNodes(g2);
182                 return "Node count: " + amount;
183         }
184         
185     public static String getAllNodes (ICanvasContext ctx) {
186         
187         Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
188         int amount = g2.size() +1;
189         return "All nodes: " + amount;
190     }
191     
192     public static String getBoundsNodes (ICanvasContext ctx) {
193         
194         Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
195         int amount = bn.size();
196         return "BoundsNodes: " + amount;
197     }
198     
199     public static String getBackgroundNodes (ICanvasContext ctx) {
200         
201         Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
202         int amount = bg.size();
203         return "BackgroundNodes: " + amount;
204     }
205     
206     public static String getDataNodes (ICanvasContext ctx) {
207         
208         Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
209         int amount = dn.size();
210         return "DataNodes: " + amount;
211     }
212     
213     public static String getNavigationNodes (ICanvasContext ctx) {
214         
215         Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
216         int amount = g2.size();
217         return "NavigationNodes: " + amount;
218     }
219     
220     public static String getParentNodes (ICanvasContext ctx) {
221         
222         Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
223         int amount = g2.size();
224         return "ParentNodes: " + amount;
225     }
226     
227     public static String getDecorationNodes (ICanvasContext ctx) {
228         
229         Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
230         int amount = deco.size();
231         return "DecorationNodes: " + amount;
232     }
233     
234     public static String getSingleElementNodes (ICanvasContext ctx) {
235         
236         Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
237         int amount = g2.size();
238         return "SingleElementNodes: " + amount;
239     }
240     
241     public static String getConnectionNodes (ICanvasContext ctx) {
242         
243         Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
244         int amount = g2.size();
245         return "ConnectionNodes: " + amount;
246     }
247     
248     public static String getTextNodes (ICanvasContext ctx) {
249         
250         Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
251         Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
252         int amount = tn.size() + tgn.size();
253         return "TextNodes: " + amount;
254     }
255     
256     public static String getItemNodes (ICanvasContext ctx) {
257         
258         Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
259         int amount = item.size();
260         return "ItemNodes: " + amount;
261     }
262   
263     public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
264                 
265         Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
266         for (TextNode modulenode : textGridNodes) {
267                 if (module.equals(modulenode.getText())) {
268                         //System.out.println("Module what we were looking for: " + module);
269                         //System.out.println("Modulenode: " + modulenode.getText());
270                         
271                         ParentNode<?> parentnode = modulenode.getParent();
272                         //System.out.println("Parentnode: " + parentnode);
273                         
274                         Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
275                         for (TextNode valuenode : textnodes) {
276                                 if (previous_value.equals(valuenode.getText())) {
277                                         //System.out.println("Value what we were looking for: " + previous_value);
278                                         //System.out.println("Valuenode: " + valuenode.getText());
279                                         
280                                         //valuenode.setEditMode(true);
281                                         valuenode.activateEdit(0, null, ctx);
282                                         valuenode.setText(new_value);
283                                         valuenode.fireTextEditingEnded();
284                                         
285                                         //System.out.println("valuenode modified: " + valuenode);
286                                         return "Modified module " + module + " with value " + new_value;
287                                 }
288                         }
289                         return "Not found module : " + module;
290                 }
291         }
292         return "No nodes in scenegraph!";
293     }
294     
295     /**
296      * Returns background color of a canvasContext or null.
297      * @param ctx
298      * @return color in RGBA List<Integer> format, or null.
299      */
300     public static List<Integer> getBackgroundColor(ICanvasContext ctx) {
301         Color color = ctx.getDefaultHintContext().getHint(Hints.KEY_BACKGROUND_COLOR);
302         if (color == null)
303                 return null;
304         ArrayList<Integer> rgba = new ArrayList<>(4);
305         rgba.add(color.getRed());
306         rgba.add(color.getGreen());
307         rgba.add(color.getBlue());
308         rgba.add(color.getAlpha());
309         return rgba;
310     }
311
312     public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
313         
314         boolean module_founded = false;
315         boolean value_founded = false;
316         
317         Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
318         System.out.println("Total amount of nodes: " + g2.size() + 1);
319         
320         Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
321         Integer textGridNodeAmount = grid.size();
322         System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
323         
324         Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
325         Integer textNodeAmount = grid.size();
326         System.out.println("Amount of TextNodes " + textNodeAmount);
327
328         for (TextNode node : texts) {
329             if (module.equals(node.getText())) {
330                 module_founded = true;
331                 System.out.println("Correct module " + module + " founded.");
332             }
333             if (value.equals(node.getText())) {
334                 value_founded = true;
335                 System.out.println("Correct value " + value + " founded.");
336             }
337         }
338         
339         if (value_founded == true && module_founded == true) {
340                 return "Found both correct module " + module + " and value " + value;
341         }
342         if (value_founded == false && module_founded == true) {
343                 return "Found only correct module " + module + " but not value " + value;
344         }
345         if (value_founded == true && module_founded == false) {
346                 return "Found only correct value " + value + " but not module " + module;
347         }
348         else {
349                 return "Didn't found either module " + module + " or value " + value;
350         }
351     }
352     
353     public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
354         
355         IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
356
357                 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
358                 if (dem != null) {
359                         final Collection<IElement> newSelection = new ArrayList<IElement>();
360                         for (Resource module : modules) {
361                                 IElement element = dem.getElement(idiagram, module);
362                                 if (element != null) {
363                                         newSelection.add(element);
364                                 } else {
365                                         throw new DatabaseException("Could not find IElement for " + element);
366                                 }
367                         }
368                         
369                         ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
370                     @Override
371                     public void run() {
372                         if (source_ctx.isDisposed())
373                             return;
374                         Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
375                         if (selection != null) {
376                             // This prevents workbench selection from being left over.
377                             // Also prevents scene graph crap from being left on the screen.
378                             selection.setSelection(0, newSelection);
379                         }
380                                 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
381                                 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
382                     }
383                 });
384                         
385                 //}
386                 
387                 while(source_ctx.getEventQueue().size() > 0) {
388                         try {
389                                 Thread.sleep(10);
390                         } catch (InterruptedException e) {
391                                 throw new DatabaseException(e);
392                         }
393                 }
394
395                 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
396             @Override
397             public void run() {
398             }
399         });             
400                                 
401                 }
402                 return true;
403     }
404
405     
406     static class UniqueIDGenerator extends SVGIDGenerator{
407         
408         String overallId;
409         public UniqueIDGenerator(String overallId) {
410                 super();
411                 this.overallId = overallId;
412         }
413         
414         @Override
415         public String generateID(String prefix) {
416                 return super.generateID(overallId+prefix);
417         }
418
419     }
420
421         static class Generator extends SVGGraphics2D {
422
423                 int elemLevel = 0;
424                 String newElementId = null;
425                 ArrayList<Element> elements = new ArrayList<Element>();
426
427                 public static final String svgNS = "http://www.w3.org/2000/svg";
428
429                 public Generator(SVGGeneratorContext ctx, boolean textAsShapes) {
430                         super(ctx, textAsShapes);
431                 }
432
433                 public Generator(Document document) {
434                         this(document,null);
435                 }
436                 public Generator(Document document, String id) {
437                         super(document);
438                         // prevent batik comment in each g-element
439                         getGeneratorContext().setComment(null);
440                         if (id != null)
441                                 getGeneratorContext().setIDGenerator(new UniqueIDGenerator(id));
442                 }
443
444                 @Override
445                 public Element getRoot() {
446                         Element root = super.getRoot();
447                         for(Element e : elements) {
448                                 root.appendChild(e);
449                         }
450                         return root;
451                 }
452
453                 @Override
454                 public void setRenderingHint(Key arg0, Object arg1) {
455                         if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
456                                 elemLevel++;
457                         }
458                         if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
459                                 if(arg1 != null)
460                                         newElementId = arg1.toString();
461                                 else
462                                         newElementId = UUID.randomUUID().toString();
463                         }
464                         if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
465                                 elemLevel--;
466                                 if(elemLevel == 0) {
467                                         Element group = getDOMFactory().createElement(SVG_G_TAG);
468                                         //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
469                                         group.setAttributeNS(null, "id", newElementId);
470                                         group.setAttributeNS(null, "class", arg1.toString());
471                                         getRoot(group);
472                                         elements.add(group);
473                                 }
474                         }
475                         super.setRenderingHint(arg0, arg1);
476                 }
477
478         }
479
480         public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
481
482                 try {
483
484                         svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
485                         svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
486                         svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
487
488                         node.render(svgGenerator);
489
490                 } catch (Throwable t) {
491                         LOGGER.error("Problems rendering scene graph to SVG", t);
492                 }
493
494                 return svgGenerator.getRoot();
495         }
496
497         public static String printSVGDocument(Element doce) {
498
499                 StringBuilder result = new StringBuilder();
500
501                 NodeList nl =  doce.getChildNodes();
502
503                 for(int i=0;i<nl.getLength();i++) {
504
505                         ByteArrayOutputStream os = new ByteArrayOutputStream();
506
507                         try {
508
509                                 TransformerFactory tf = TransformerFactory.newInstance();
510                                 Transformer transformer = tf.newTransformer();
511                                 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
512                                 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
513                                 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
514                                 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
515                                 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
516                                 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
517
518                                 transformer.transform(new DOMSource(nl.item(i)), 
519                                                 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
520
521                                 os.flush();
522                                 os.close();
523
524                         } catch (Throwable t) {
525                                 LOGGER.error("Problems formatting SVGDocument to text.", t);
526                         }
527
528                         result.append(new String(os.toByteArray()));
529
530                 }
531
532                 return result.toString();
533
534         }
535
536         public static String renderSVG3(ICanvasContext ctx) {
537                 return renderSVG3(ctx, -1, -1);
538         }
539
540         public static String renderSVG3(ICanvasContext ctx, double width, double height) {
541         return renderSVG0(width, height, SWT.LEFT, SWT.TOP, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
542         }
543
544     /**
545      * @param graph
546      * @param component
547      * @throws DatabaseException
548      */
549     private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
550         String uri = graph.getPossibleURI(component);
551         int hashCode = uri.hashCode();
552         Random random = new Random(hashCode);
553         long l1 = random.nextLong();
554         long l2 = random.nextLong();
555         return new Object[] { l1, l2 };
556     }
557
558     /**
559      * Default no-op mapper
560      */
561     private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
562
563     
564     /**
565      * Renders CanvasContext to SVG.
566      * @param ctx
567      * @param width Width of output image. Use -1 for autosize.
568      * @param height Height of output image. Use -1 for autosize.
569      * @param ax horizontal alignment. SWT.LEFT SWT.CENTER SWT.RIGHT are accepted values. Value is not used with autosize. 
570      * @param ay vertical alignment. SWT.TOP SWT.CENTER SWT.BOTTOM are accepted values. Value is not used with autosize.
571      * @return
572      */
573     public static String renderSVG(ICanvasContext ctx, double width, double height, int ax, int ay) {
574         return renderSVG0(width, height, ax, ay, ctx, mapper);
575     }
576     
577     public static String renderSVG(ICanvasContext ctx, double width, double height) {
578         return renderSVG(ctx,width,height, SWT.LEFT, SWT.TOP);
579     }
580
581     public static String renderSVG(ICanvasContext ctx) {
582         return renderSVG(ctx, -1, -1, SWT.LEFT, SWT.TOP);
583     }
584
585     public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
586                 return renderSVGMapIdentifiers(ctx, -1, -1);
587     }
588     
589     /**
590      * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
591      * GUID's
592      * 
593      * @param ctx
594      * @return
595      */
596     public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
597         return renderSVG0(width, height, SWT.LEFT, SWT.TOP, ctx, new Function1<Set<?>, Map<?, ?>>() {
598
599             @Override
600             public Map<?, ?> apply(Set<?> p0) {
601                 try {
602                     return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
603
604                         @Override
605                         public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
606                             ModelingResources MOD = ModelingResources.getInstance(graph);
607                             DiagramResource DIA = DiagramResource.getInstance(graph);
608                             Layer0 L0 = Layer0.getInstance(graph);
609                             return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
610                                 try {
611                                     if (p instanceof Resource) {
612                                         Resource element = (Resource) p;
613                                         if (graph.isInstanceOf(element, DIA.Element)) {
614                                             Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
615                                             if (component != null) {
616                                                 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
617                                                 if (identifier != null) {
618                                                     return Arrays.toString(createURIBasedL0Identifier(graph, component));
619                                                 } else {
620                                                     LOGGER.error("Component {} does not have GUID identifier!", component);
621                                                 }
622                                             } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
623                                                 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers 
624                                                 return graph.getURI(element).hashCode();
625                                             } else {
626                                                 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
627                                                 if (graph.hasStatement(element, L0.HasName))
628                                                     return graph.getURI(element).hashCode();
629                                                 return "";
630                                             }
631                                         }
632                                     } else {
633                                         LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
634                                     }
635                                     return p;
636                                 } catch (DatabaseException e) {
637                                     throw new RuntimeDatabaseException(e);
638                                 }
639                             }));
640                         }
641                     });
642                 } catch (DatabaseException e) {
643                     LOGGER.error("Could not apply mappings", e);
644                     throw new RuntimeDatabaseException(e);
645                 }
646             }
647         });
648         }
649         
650     static class RenderSVGContext {
651         
652         Map<String,StringBuilder> documents = new HashMap<>();
653         
654         public void append(String[] keys, String svgText) {
655                 for(String key : keys) append(key, svgText);
656         }
657
658         public void append(String key, String svgText) {
659                 StringBuilder builder = documents.get(key);
660                 if(builder == null) {
661                         builder = new StringBuilder();
662                         documents.put(key, builder);
663                 }
664                 builder.append(svgText);
665         }
666         
667         public void append(RenderSVGContext other) {
668                 for(String key : other.documents.keySet()) {
669                         append(key, other.get(key));
670                 }
671         }
672         
673         public String get(String key) {
674                 StringBuilder builder = documents.get(key);
675                 if(builder == null) return "";
676                 else return builder.toString();
677         }
678         
679     }
680     
681     
682     
683         private static String renderSVG0(double width, double height, int ax, int ay, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
684
685                 // Get a DOMImplementation.
686                 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
687
688                 // Create an instance of org.w3c.dom.Document.
689                 String svgNS = "http://www.w3.org/2000/svg";
690                 Document document = domImpl.createDocument(svgNS, "svg", null);
691
692                 // Create an instance of the SVG Generator.
693                 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
694                 Resource r = d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
695                 SVGGraphics2D svgGenerator;
696                 if (r != null)
697                         svgGenerator = new Generator(document,r.toString());
698                 else
699                         svgGenerator = new Generator(document);
700
701                 RenderSVGContext result = new RenderSVGContext();
702
703                 double[] matrix = new double[6];
704                 try {
705
706             Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
707             if (selection != null) {
708                 // This prevents workbench selection from being left over.
709                 // Also prevents scene graph crap from being left on the screen.
710                 selection.setSelection(0, d.getElements());
711             }
712
713                         G2DSceneGraph sg = ctx.getSceneGraph();
714                         sg.performCleanup();
715                         G2DParentNode root = (G2DParentNode) sg.getRootNode();
716
717                         // rtree is the actual content of the diagram
718                         RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
719                         Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
720
721                         // get the bounds of the content
722                         Rectangle2D content = rtreeBounds;
723                         
724 //                      int ax = SWT.LEFT;
725 //                      int ay = SWT.TOP;
726 //                      int ax = SWT.CENTER;
727 //                      int ay = SWT.CENTER;
728                         
729                         if (content != null) {
730                          // To account for dynamic padding of selection rectangles (5 units + stroke width)
731                     int offset = 6;
732                     
733                     double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
734                 
735                     AffineTransform tr = new AffineTransform();
736                     tr.translate(offset, offset);
737                     tr.scale(scale, scale);
738                     double dx = -content.getX();
739                     double dy = -content.getY();
740                     if (width > 0.0 && height > 0.0) {
741                             if (ax == SWT.LEFT) {
742                                 dx = -content.getX();
743                             } else if (ax == SWT.RIGHT) {
744                                 double t = ((width - 2*offset)/scale - content.getWidth());
745                                 dx = -content.getX() + t;
746                             } else {
747                                 double t = ((width - 2*offset)/scale - content.getWidth()) *0.5;
748                                 dx = -content.getX() + t;
749                             }
750                             if (ay == SWT.TOP) {
751                                 dy = -content.getY();
752                             } else if (ay == SWT.BOTTOM) {
753                                 double t = ((height - 2*offset)/scale - content.getHeight());
754                                 dy = -content.getY() + t;
755                             } else {
756                                 double t = ((height - 2*offset)/scale - content.getHeight()) * 0.5;
757                                 dy = -content.getY() + t;
758                             }
759                     }
760                             tr.translate(dx, dy);
761                             tr.getMatrix(matrix);
762                             svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
763                         } else {
764                             svgGenerator.setSVGCanvasSize(new Dimension(100, 100));
765                         }
766                         //svgGenerator.translate(offset, offset);
767                         //svgGenerator.scale(scale, scale);
768                         // translate svgGenerator to the x and y coordinates of current content
769                         //svgGenerator.translate(-content.getX(), -content.getY());
770
771                         
772                         //svgGenerator.setClip(content);
773                         
774                         result.append(MAIN_SECTION, "<g class=\"symbols\">");
775                         result.append(SELECTION_SECTION, "<g class=\"selections\">");
776                         result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
777
778                         KeyVisitor keyVisitor = new KeyVisitor();
779                         sg.accept(keyVisitor);
780                         
781                         Set<Object> keys = keyVisitor.getKeys();
782                         
783                         Map<?, ?> mappings = mappingFunction.apply(keys);
784
785                         IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
786                         
787                         sg.accept(visitor);
788
789                 } catch (Throwable t) {
790                         LOGGER.error("Problems rendering canvas context to SVG", t);
791                 }
792
793
794                 result.append(ALL_SECTIONS, "</g>");
795
796                 StringBuilder res = new StringBuilder();
797                 if (width > 0 && height > 0 ) {
798                         res.append("<svg width=\"" + width +"px\" height=\""+height+"px\" stroke=\"black\" xmlns=\"http://www.w3.org/2000/svg\">");
799                 } else {
800                         res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\" xmlns=\"http://www.w3.org/2000/svg\">");
801                 }
802                 res.append("<g transform=\"matrix(").append(matrix[0]).append(",").append(matrix[1]).append(",").append(matrix[2]).append(",").append(matrix[3]).append(",").append(matrix[4]).append(",").append(matrix[5]).append(")\">");
803                 res.append(result.get(MAIN_SECTION));
804                 res.append(result.get(SELECTION_SECTION));
805                 res.append(result.get(SELECTION_MASK_SECTION));
806                 res.append("</g>");
807                 res.append("</svg>");
808
809 //              System.err.println(" == FINAL RESULT == ");
810 //              System.err.println(res.toString());
811                 
812                 return res.toString();
813                 
814         }
815         
816         
817         
818         private static class KeyVisitor implements IG2DNodeVisitor {
819
820         private Set<Object> keys = new HashSet<>();
821
822         @Override
823         public void enter(IG2DNode node) {
824             if (node instanceof SingleElementNode) {
825                 Object key = ((SingleElementNode) node).getKey();
826                 if (key != null) {
827                     keys.add(key);
828                 }
829             }
830         }
831
832         @Override
833         public void leave(IG2DNode node) {
834             // Nothing to do
835         }
836
837         public Set<Object> getKeys() {
838             return keys;
839         }
840         }
841
842         private static class PrintingVisitor implements IG2DNodeVisitor {
843
844         int indent = 0;
845
846         HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
847
848         private RenderSVGContext result;
849         private SVGGraphics2D svgGenerator;
850
851         private Map<?, ?> mappings;
852
853         public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
854             this.result = result;
855             this.mappings = mappings;
856             this.svgGenerator = svgGenerator;
857         }
858
859         private String getKey(SingleElementNode node) {
860             String key;
861                 if(node.getKey() != null) {
862                 if (mappings.containsKey(node.getKey())) {
863                     key = mappings.get(node.getKey()).toString();
864                     key = escape(key);
865                 } else {
866                     key = node.getKey().toString();
867                     key = escape(key);
868                 }
869                 } else {
870                         key = Long.toString(node.getId());
871                 }
872             return key;
873         }
874         
875         private String escape(String key) {
876                 // Keys may contain  '<' '>' characters, which causes errors in browser SVG handling.
877                 return org.apache.commons.lang.StringEscapeUtils.escapeHtml(key);
878         }
879         
880         private String removeElem(String xml, String elemStart) {
881                 // FIXME: This is rather nasty and error prone way of removing elements from XML string.
882                 // This only supports elements with /> end element tag. Elements ends with </elem name> are not supported!
883                 int start = xml.indexOf("<"+elemStart);
884                 if (start>=0) {
885                         int end = xml.indexOf(">",start);
886                         if (end >= 0) {
887                                 if (start > 0)
888                                         return xml.substring(0,start)+xml.substring(end+1);
889                                 else
890                                         return xml.substring(end+1);
891                         }
892                 }
893                 return null;
894         }
895
896         @Override
897         public void enter(IG2DNode node) {
898             
899                 RenderSVGContext parentBuilder = getParentBuilder(node);
900             
901             indent++;
902             if(node instanceof ConnectionNode) {
903                 
904                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
905                     n.setIgnoreSelection(true);
906                 }
907
908                 String key = getKey((ConnectionNode) node);
909                 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
910                 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
911                 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"" + OPACITY + "\" id=\"" + key + "\">");
912                 
913                 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
914                 String svg = printSVGDocument(doc);
915                 parentBuilder.append(MAIN_SECTION, svg);
916
917                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
918                     n.setIgnoreSelection(false);
919                 }
920
921                 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
922                 svg = printSVGDocument(doc);
923                 parentBuilder.append(SELECTION_SECTION, svg);
924
925                 BasicStroke bs = new BasicStroke(10f);
926                 
927                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
928                     n.setDynamicStroke(bs);
929                 }
930
931                 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
932                 svg = printSVGDocument(doc);
933                 parentBuilder.append(SELECTION_MASK_SECTION, svg);
934
935                 senBuilders.put((ConnectionNode)node, new RenderSVGContext());
936                 
937                 
938             } else if (isSelection0(node)) {
939                 
940                 SelectionNode n = (SelectionNode)node;
941                 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
942                 if(parentSEN != null) {
943                     
944                         RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
945                     
946                     String key = getKey(parentSEN);
947                     n.setIgnore(false);
948                     Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
949                     n.setIgnore(true);
950                     String svg = printSVGDocument(doc);
951                     parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
952                     parentBuilder2.append(SELECTION_SECTION, svg);
953                     parentBuilder2.append(SELECTION_SECTION, "\n</g>");
954                     parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
955                     Rectangle2D rect = n.getRect();
956                     // NaN
957                     if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
958                             parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
959                             parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
960                             parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
961                             parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
962                     }
963                     parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
964                    
965                 }
966             } else if (node instanceof SelectionNode) {
967
968                 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
969                 String svg = printSVGDocument(doc);
970                 parentBuilder.append(MAIN_SECTION, "<g>");
971                 parentBuilder.append(MAIN_SECTION, svg);
972                 parentBuilder.append(MAIN_SECTION, "\n</g>");
973
974             } else if (node instanceof SVGNode) {
975                 SVGNode svg = (SVGNode)node;
976                 AffineTransform at = svg.getTransform();
977                 if (!at.isIdentity()) {
978                          if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
979                          String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
980                          parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
981                      } else {
982                          double[] ds = new double[6];
983                          at.getMatrix(ds);
984                          String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
985                          parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
986                      }
987                 }
988                 String svgContent = svg.getSVGText();
989                 // SVGNode content may contain SVG/XML elements, which break browser compatibility
990                 int start = svgContent.indexOf("<svg");
991                 if (start >= 0)
992                         svgContent = svgContent.substring(start);
993                 else  {
994                         String s = removeElem(svgContent, "?xml");
995                         if (s != null) {
996                                 svgContent = "<g>"+s+"</g>";
997                                 s = removeElem(svgContent, "!DOCTYPE");
998                                 if (s != null)
999                                         svgContent = s;
1000                         }
1001                 }
1002                 parentBuilder.append(MAIN_SECTION, svgContent);
1003                 if (!at.isIdentity()) {
1004                         parentBuilder.append(MAIN_SECTION, "\n</g>");
1005                 }
1006             } else if (node instanceof G2DParentNode) {
1007                 AffineTransform at = node.getTransform();
1008                 if(node instanceof SingleElementNode) {
1009                     SingleElementNode sen = (SingleElementNode)node;
1010                     String key = getKey(sen);
1011                     String typeClass = sen.getTypeClass();
1012                     String clazz = "definedElement";
1013                     if(typeClass != null && !typeClass.isEmpty())
1014                         clazz = clazz + " " + typeClass;
1015
1016                     parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
1017                     senBuilders.put(sen, new RenderSVGContext());
1018                 }
1019                 if(!at.isIdentity()) {
1020                     if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
1021                         String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
1022                         parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
1023                     } else {
1024                         double[] ds = new double[6];
1025                         at.getMatrix(ds);
1026                         String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
1027                         parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
1028                     }
1029                 }
1030             } else if (node instanceof TextNode) {
1031                  TextNode text = (TextNode)node;
1032                                 
1033                  SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1034                  if(parentSEN != null) {
1035                          
1036                          text.setShowSelection(false);
1037                          Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1038                      String svg = printSVGDocument(doc);
1039                      parentBuilder.append(MAIN_SECTION, svg);
1040                      
1041                          RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
1042                      
1043                      String key = getKey(parentSEN);
1044                      text.setShowSelection(true);
1045                      doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1046                      svg = printSVGDocument(doc);
1047                      
1048                      parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
1049                      parentBuilder2.append(SELECTION_SECTION, svg);
1050                      parentBuilder2.append(SELECTION_SECTION, "\n</g>");
1051                      parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
1052                      Rectangle2D rect = text.getBounds();
1053                      // NaN
1054                      if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
1055                             parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
1056                             parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
1057                             parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
1058                             parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
1059                      }
1060                      parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
1061                     
1062                  }
1063             } else if (!(node instanceof RouteGraphNode) && !(node instanceof LinkNode)){
1064                 try {
1065                         Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1066                         NodeList gList = doc.getElementsByTagName("g");
1067                         if (gList.getLength() == 0)
1068                                 return;
1069                         boolean hasContent = false;
1070                         for (int i = 0; i < gList.getLength(); i++) {
1071                             Node gNode = gList.item(i);
1072                             if (gNode.hasChildNodes()) {
1073                                 hasContent = true;
1074                                 break;
1075                             }
1076                         }
1077                         if (!hasContent)
1078                             return;
1079                         String svg = printSVGDocument(doc);
1080                         if (node instanceof SelectionShapeNode) {
1081                                 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1082                         if(parentSEN != null) {
1083                                  String key = getKey(parentSEN);
1084                                  RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
1085                                  parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
1086                              parentBuilder2.append(SELECTION_SECTION, svg);
1087                              parentBuilder2.append(SELECTION_SECTION, "\n</g>");
1088                              
1089                              parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
1090                              Rectangle2D rect = node.getBounds();
1091                              // NaN
1092                              if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
1093                                     parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
1094                                     parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
1095                                     parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
1096                                     parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
1097                              }
1098                              parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
1099                         }
1100                         } else {
1101                                 parentBuilder.append(MAIN_SECTION, "<g class=\"" +node.getSimpleClassName() +"\">");
1102                                 parentBuilder.append(MAIN_SECTION, svg);
1103                                 parentBuilder.append(MAIN_SECTION, "\n</g>");
1104                         }
1105                 } catch (Exception e) {
1106                         // TODO: There are nodes that do not behave well when rendered to SVG. For backwards compatibility, we don't handle the exceptions.
1107                 }
1108             }
1109
1110             //enters.put(node, b.length());
1111
1112         }
1113         
1114         private boolean isSelection0(IG2DNode node) {
1115             
1116             if(node instanceof SelectionNode) {
1117                 SelectionNode sn = (SelectionNode)node;
1118                 return sn.getSelectionId() == 0;
1119             } else {
1120                 return false;
1121             }
1122             
1123         }
1124         
1125         private RenderSVGContext getParentBuilder(IG2DNode node) {
1126             
1127             INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1128             if(parentSEN instanceof G2DSceneGraph) return result;
1129
1130             RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
1131             if(parentBuilder == null) return result;
1132             
1133             return parentBuilder;
1134             
1135         }
1136
1137         @Override
1138         public void leave(IG2DNode node) {
1139
1140             if( node instanceof SVGNode) {
1141                 // We are done
1142             } else if (node instanceof ConnectionNode) {
1143                 RenderSVGContext parentBuilder = getParentBuilder(node);
1144                 SingleElementNode sen = (SingleElementNode)node;
1145                 RenderSVGContext b = senBuilders.get(sen);
1146                 String content = b.get(MAIN_SECTION);
1147                 if(content.isEmpty()) {
1148 //                      Handling connection the same way as SingleElementNode would draw connection twice..
1149 //                      if(sen.getKey() != null) {
1150 //
1151 //                              for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
1152 //                                      n.setIgnore(true);
1153 //                              }
1154 //
1155 //                              Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1156 //                              String svg = printSVGDocument(doc);
1157 //                              parentBuilder.append(MAIN_SECTION, svg);
1158 //                      }
1159                 } else {
1160                         parentBuilder.append(b);
1161                 }
1162                 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
1163                 parentBuilder.append(SELECTION_SECTION, "\n</g>");
1164                 parentBuilder.append(MAIN_SECTION, "\n</g>");
1165                 
1166             } else if (node instanceof G2DParentNode) {
1167                 
1168                 RenderSVGContext parentBuilder = getParentBuilder(node);
1169                 
1170                 if(node instanceof SingleElementNode) {
1171                         SingleElementNode sen = (SingleElementNode)node;
1172                         RenderSVGContext b = senBuilders.get(sen);
1173                         String content = b.get(MAIN_SECTION);
1174                         if(content.isEmpty()) {
1175                                 if(sen.getKey() != null) {
1176
1177                                         for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
1178                                                 n.setIgnore(true);
1179                                         }
1180
1181                                         Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1182                                         String svg = printSVGDocument(doc);
1183                                         parentBuilder.append(MAIN_SECTION, svg);
1184                                 }
1185                         } else {
1186                                 parentBuilder.append(b);
1187                         }
1188                 }
1189                 
1190                 AffineTransform at = node.getTransform();
1191                 if(!at.isIdentity()) {
1192                     parentBuilder.append(ALL_SECTIONS, "</g>");
1193                 }
1194                 if(node instanceof SingleElementNode) {
1195                     SingleElementNode sen = (SingleElementNode)node;
1196                     //if(sen.getKey() != null) {
1197                         parentBuilder.append(MAIN_SECTION, "</g>");
1198                     //}
1199                 }
1200             }
1201             indent --;
1202         }
1203         }
1204 }