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