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