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