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