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