]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling/src/org/simantics/modeling/SCLScenegraph.java
559469d4a21ce908aff65f9574355363a989d2f3
[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                 if (width > 0 && height > 0 ) {
727                         res.append("<svg width=\"" + width +"px\" height=\""+height+"px\" stroke=\"black\" xmlns=\"http://www.w3.org/2000/svg\">");
728                 } else {
729                         res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\" xmlns=\"http://www.w3.org/2000/svg\">");
730                 }
731                 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(")\">");
732                 res.append(result.get(MAIN_SECTION));
733                 res.append(result.get(SELECTION_SECTION));
734                 res.append(result.get(SELECTION_MASK_SECTION));
735                 res.append("</g>");
736                 res.append("</svg>");
737
738 //              System.err.println(" == FINAL RESULT == ");
739 //              System.err.println(res.toString());
740                 
741                 return res.toString();
742                 
743         }
744         
745         
746         
747         private static class KeyVisitor implements IG2DNodeVisitor {
748
749         private Set<Object> keys = new HashSet<>();
750
751         @Override
752         public void enter(IG2DNode node) {
753             if (node instanceof SingleElementNode) {
754                 Object key = ((SingleElementNode) node).getKey();
755                 if (key != null) {
756                     keys.add(key);
757                 }
758             }
759         }
760
761         @Override
762         public void leave(IG2DNode node) {
763             // Nothing to do
764         }
765
766         public Set<Object> getKeys() {
767             return keys;
768         }
769         }
770
771         private static class PrintingVisitor implements IG2DNodeVisitor {
772
773         int indent = 0;
774
775         HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
776
777         private RenderSVGContext result;
778         private SVGGraphics2D svgGenerator;
779
780         private Map<?, ?> mappings;
781
782         public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
783             this.result = result;
784             this.mappings = mappings;
785             this.svgGenerator = svgGenerator;
786         }
787
788         private String getKey(SingleElementNode node) {
789             String key;
790                 if(node.getKey() != null) {
791                 if (mappings.containsKey(node.getKey())) {
792                     key = mappings.get(node.getKey()).toString();
793                     key = escape(key);
794                 } else {
795                     key = node.getKey().toString();
796                     key = escape(key);
797                 }
798                 } else {
799                         key = Long.toString(node.getId());
800                 }
801             return key;
802         }
803         
804         private String escape(String key) {
805                 // Keys may contain  '<' '>' characters, which causes errors in browser SVG handling.
806                 return org.apache.commons.lang.StringEscapeUtils.escapeHtml(key);
807         }
808         
809         private String removeElem(String xml, String elemStart) {
810                 // FIXME: This is rather nasty and error prone way of removing elements from XML string.
811                 // This only supports elements with /> end element tag. Elements ends with </elem name> are not supported!
812                 int start = xml.indexOf("<"+elemStart);
813                 if (start>=0) {
814                         int end = xml.indexOf(">",start);
815                         if (end >= 0) {
816                                 if (start > 0)
817                                         return xml.substring(0,start)+xml.substring(end+1);
818                                 else
819                                         return xml.substring(end+1);
820                         }
821                 }
822                 return null;
823         }
824
825         @Override
826         public void enter(IG2DNode node) {
827             
828                 RenderSVGContext parentBuilder = getParentBuilder(node);
829             
830             indent++;
831             if(node instanceof ConnectionNode) {
832                 
833                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
834                     n.setIgnoreSelection(true);
835                 }
836
837                 String key = getKey((ConnectionNode) node);
838                 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
839                 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
840                 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"" + OPACITY + "\" id=\"" + key + "\">");
841                 
842                 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
843                 String svg = printSVGDocument(doc);
844                 parentBuilder.append(MAIN_SECTION, svg);
845
846                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
847                     n.setIgnoreSelection(false);
848                 }
849
850                 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
851                 svg = printSVGDocument(doc);
852                 parentBuilder.append(SELECTION_SECTION, svg);
853
854                 BasicStroke bs = new BasicStroke(10f);
855                 
856                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
857                     n.setDynamicStroke(bs);
858                 }
859
860                 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
861                 svg = printSVGDocument(doc);
862                 parentBuilder.append(SELECTION_MASK_SECTION, svg);
863
864                 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
865                 parentBuilder.append(SELECTION_SECTION, "\n</g>");
866                 parentBuilder.append(MAIN_SECTION, "\n</g>");
867                 
868             } else if (isSelection0(node)) {
869                 
870                 SelectionNode n = (SelectionNode)node;
871                 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
872                 if(parentSEN != null) {
873                     
874                         RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
875                     
876                     String key = getKey(parentSEN);
877                     n.setIgnore(false);
878                     Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
879                     n.setIgnore(true);
880                     String svg = printSVGDocument(doc);
881                     parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
882                     parentBuilder2.append(SELECTION_SECTION, svg);
883                     parentBuilder2.append(SELECTION_SECTION, "\n</g>");
884                     parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
885                     Rectangle2D rect = n.getRect();
886                     // NaN
887                     if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
888                             parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
889                             parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
890                             parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
891                             parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
892                     }
893                     parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
894                    
895                 }
896             } else if (node instanceof SelectionNode) {
897
898                 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
899                 String svg = printSVGDocument(doc);
900                 parentBuilder.append(MAIN_SECTION, "<g>");
901                 parentBuilder.append(MAIN_SECTION, svg);
902                 parentBuilder.append(MAIN_SECTION, "\n</g>");
903
904             } else if (node instanceof SVGNode) {
905                 SVGNode svg = (SVGNode)node;
906                 AffineTransform at = svg.getTransform();
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(MAIN_SECTION, "\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(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
916                      }
917                 }
918                 String svgContent = svg.getSVGText();
919                 // SVGNode content may contain SVG/XML elements, which break browser compatibility
920                 int start = svgContent.indexOf("<svg");
921                 if (start >= 0)
922                         svgContent = svgContent.substring(start);
923                 else  {
924                         String s = removeElem(svgContent, "?xml");
925                         if (s != null) {
926                                 svgContent = "<g>"+s+"</g>";
927                                 s = removeElem(svgContent, "!DOCTYPE");
928                                 if (s != null)
929                                         svgContent = s;
930                         }
931                 }
932                 parentBuilder.append(MAIN_SECTION, svgContent);
933                 if (!at.isIdentity()) {
934                         parentBuilder.append(MAIN_SECTION, "\n</g>");
935                 }
936             } else if (node instanceof G2DParentNode) {
937                 AffineTransform at = node.getTransform();
938                 if(node instanceof SingleElementNode) {
939                     SingleElementNode sen = (SingleElementNode)node;
940                     String key = getKey(sen);
941                     String typeClass = sen.getTypeClass();
942                     String clazz = "definedElement";
943                     if(typeClass != null && !typeClass.isEmpty())
944                         clazz = clazz + " " + typeClass;
945
946                     parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
947                     senBuilders.put(sen, new RenderSVGContext());
948                 }
949                 if(!at.isIdentity()) {
950                     if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
951                         String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
952                         parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
953                     } else {
954                         double[] ds = new double[6];
955                         at.getMatrix(ds);
956                         String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
957                         parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
958                     }
959                 }
960             } else if (node instanceof TextNode) {
961                  TextNode text = (TextNode)node;
962                                 
963                  SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
964                  if(parentSEN != null) {
965                          
966                          text.setShowSelection(false);
967                          Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
968                      String svg = printSVGDocument(doc);
969                      parentBuilder.append(MAIN_SECTION, svg);
970                      
971                          RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
972                      
973                      String key = getKey(parentSEN);
974                      text.setShowSelection(true);
975                      doc = renderSVGNode(svgGenerator, (IG2DNode)node);
976                      svg = printSVGDocument(doc);
977                      
978                      parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
979                      parentBuilder2.append(SELECTION_SECTION, svg);
980                      parentBuilder2.append(SELECTION_SECTION, "\n</g>");
981                      parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
982                      Rectangle2D rect = text.getBounds();
983                      // NaN
984                      if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
985                             parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
986                             parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
987                             parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
988                             parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
989                      }
990                      parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
991                     
992                  }
993             } else if (!(node instanceof RouteGraphNode) && !(node instanceof LinkNode)){
994                 try {
995                         Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
996                         NodeList gList = doc.getElementsByTagName("g");
997                         if (gList.getLength() == 0)
998                                 return;
999                         boolean hasContent = false;
1000                         for (int i = 0; i < gList.getLength(); i++) {
1001                             Node gNode = gList.item(i);
1002                             if (gNode.hasChildNodes()) {
1003                                 hasContent = true;
1004                                 break;
1005                             }
1006                         }
1007                         if (!hasContent)
1008                             return;
1009                         String svg = printSVGDocument(doc);
1010                         if (node instanceof SelectionShapeNode) {
1011                                 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1012                         if(parentSEN != null) {
1013                                  String key = getKey(parentSEN);
1014                                  RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
1015                                  parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
1016                              parentBuilder2.append(SELECTION_SECTION, svg);
1017                              parentBuilder2.append(SELECTION_SECTION, "\n</g>");
1018                              
1019                              parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
1020                              Rectangle2D rect = node.getBounds();
1021                              // NaN
1022                              if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
1023                                     parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
1024                                     parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
1025                                     parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
1026                                     parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
1027                              }
1028                              parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
1029                         }
1030                         } else {
1031                                 parentBuilder.append(MAIN_SECTION, "<g class=\"" +node.getSimpleClassName() +"\">");
1032                                 parentBuilder.append(MAIN_SECTION, svg);
1033                                 parentBuilder.append(MAIN_SECTION, "\n</g>");
1034                         }
1035                 } catch (Exception e) {
1036                         // TODO: There are nodes that do not behave well when rendered to SVG. For backwards compatibility, we don't handle the exceptions.
1037                 }
1038             }
1039
1040             //enters.put(node, b.length());
1041
1042         }
1043         
1044         private boolean isSelection0(IG2DNode node) {
1045             
1046             if(node instanceof SelectionNode) {
1047                 SelectionNode sn = (SelectionNode)node;
1048                 return sn.getSelectionId() == 0;
1049             } else {
1050                 return false;
1051             }
1052             
1053         }
1054         
1055         private RenderSVGContext getParentBuilder(IG2DNode node) {
1056             
1057             INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1058             if(parentSEN instanceof G2DSceneGraph) return result;
1059
1060             RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
1061             if(parentBuilder == null) return result;
1062             
1063             return parentBuilder;
1064             
1065         }
1066
1067         @Override
1068         public void leave(IG2DNode node) {
1069
1070             if(node instanceof ConnectionNode || node instanceof SVGNode) {
1071                 // We are done
1072             } else if (node instanceof G2DParentNode) {
1073                 
1074                 RenderSVGContext parentBuilder = getParentBuilder(node);
1075                 
1076                 if(node instanceof SingleElementNode) {
1077                         SingleElementNode sen = (SingleElementNode)node;
1078                         RenderSVGContext b = senBuilders.get(sen);
1079                         String content = b.get(MAIN_SECTION);
1080                         if(content.isEmpty()) {
1081                                 if(sen.getKey() != null) {
1082
1083                                         for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
1084                                                 n.setIgnore(true);
1085                                         }
1086
1087                                         Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1088                                         String svg = printSVGDocument(doc);
1089                                         parentBuilder.append(MAIN_SECTION, svg);
1090                                 }
1091                         } else {
1092                                 parentBuilder.append(b);
1093                         }
1094                 }
1095                 
1096                 AffineTransform at = node.getTransform();
1097                 if(!at.isIdentity()) {
1098                     parentBuilder.append(ALL_SECTIONS, "</g>");
1099                 }
1100                 if(node instanceof SingleElementNode) {
1101                     SingleElementNode sen = (SingleElementNode)node;
1102                     //if(sen.getKey() != null) {
1103                         parentBuilder.append(MAIN_SECTION, "</g>");
1104                     //}
1105                 }
1106             }
1107             indent --;
1108         }
1109         }
1110 }