Improved scaling of diagrams rendered into selectable SVG. (refs #7593)
[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 joku) {
382                         super(ctx, joku);
383                 }
384
385                 public Generator(Document document) {
386                         super(document);
387                 }
388
389                 @Override
390                 public Element getRoot() {
391                         Element root = super.getRoot();
392                         for(Element e : elements) {
393                                 root.appendChild(e);
394                         }
395                         return root;
396                 }
397
398                 @Override
399                 public void setRenderingHint(Key arg0, Object arg1) {
400                         if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
401                                 elemLevel++;
402                         }
403                         if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
404                                 if(arg1 != null)
405                                         newElementId = arg1.toString();
406                                 else
407                                         newElementId = UUID.randomUUID().toString();
408                         }
409                         if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
410                                 elemLevel--;
411                                 if(elemLevel == 0) {
412                                         Element group = getDOMFactory().createElement(SVG_G_TAG);
413                                         //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
414                                         group.setAttributeNS(null, "id", newElementId);
415                                         group.setAttributeNS(null, "class", arg1.toString());
416                                         getRoot(group);
417                                         elements.add(group);
418                                 }
419                         }
420                         super.setRenderingHint(arg0, arg1);
421                 }
422
423         }
424
425         public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
426
427                 try {
428
429                         svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
430                         svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
431                         svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
432
433                         node.render(svgGenerator);
434
435                 } catch (Throwable t) {
436                         LOGGER.error("Problems rendering scene graph to SVG", t);
437                 }
438
439                 return svgGenerator.getRoot();
440         }
441
442         public static String printSVGDocument(Element doce) {
443
444                 StringBuilder result = new StringBuilder();
445
446                 NodeList nl =  doce.getChildNodes();
447
448                 for(int i=0;i<nl.getLength();i++) {
449
450                         ByteArrayOutputStream os = new ByteArrayOutputStream();
451
452                         try {
453
454                                 TransformerFactory tf = TransformerFactory.newInstance();
455                                 Transformer transformer = tf.newTransformer();
456                                 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
457                                 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
458                                 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
459                                 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
460                                 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
461                                 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
462
463                                 transformer.transform(new DOMSource(nl.item(i)), 
464                                                 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
465
466                                 os.flush();
467                                 os.close();
468
469                         } catch (Throwable t) {
470                                 LOGGER.error("Problems formatting SVGDocument to text.", t);
471                         }
472
473                         result.append(new String(os.toByteArray()));
474
475                 }
476
477                 return result.toString();
478
479         }
480
481         public static String renderSVG3(ICanvasContext ctx) {
482                 return renderSVG3(ctx, -1, -1);
483         }
484
485         public static String renderSVG3(ICanvasContext ctx, double width, double height) {
486         return renderSVG0(width, height, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
487         }
488
489     /**
490      * @param graph
491      * @param component
492      * @throws DatabaseException
493      */
494     private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
495         String uri = graph.getPossibleURI(component);
496         int hashCode = uri.hashCode();
497         Random random = new Random(hashCode);
498         long l1 = random.nextLong();
499         long l2 = random.nextLong();
500         return new Object[] { l1, l2 };
501     }
502
503     /**
504      * Default no-op mapper
505      */
506     private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
507
508     public static String renderSVG(ICanvasContext ctx, double width, double height) {
509         return renderSVG0(width, height, ctx, mapper);
510     }
511
512     public static String renderSVG(ICanvasContext ctx) {
513         return renderSVG(ctx, -1, -1);
514     }
515
516     public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
517                 return renderSVGMapIdentifiers(ctx, -1, -1);
518     }
519     
520     /**
521      * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
522      * GUID's
523      * 
524      * @param ctx
525      * @return
526      */
527     public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
528         return renderSVG0(width, height, ctx, new Function1<Set<?>, Map<?, ?>>() {
529
530             @Override
531             public Map<?, ?> apply(Set<?> p0) {
532                 try {
533                     return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
534
535                         @Override
536                         public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
537                             ModelingResources MOD = ModelingResources.getInstance(graph);
538                             DiagramResource DIA = DiagramResource.getInstance(graph);
539                             Layer0 L0 = Layer0.getInstance(graph);
540                             return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
541                                 try {
542                                     if (p instanceof Resource) {
543                                         Resource element = (Resource) p;
544                                         if (graph.isInstanceOf(element, DIA.Element)) {
545                                             Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
546                                             if (component != null) {
547                                                 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
548                                                 if (identifier != null) {
549                                                     return Arrays.toString(createURIBasedL0Identifier(graph, component));
550                                                 } else {
551                                                     LOGGER.error("Component {} does not have GUID identifier!", component);
552                                                 }
553                                             } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
554                                                 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers 
555                                                 return graph.getURI(element).hashCode();
556                                             } else {
557                                                 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
558                                                 if (graph.hasStatement(element, L0.HasName))
559                                                     return graph.getURI(element).hashCode();
560                                                 return "";
561                                             }
562                                         }
563                                     } else {
564                                         LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
565                                     }
566                                     return p;
567                                 } catch (DatabaseException e) {
568                                     throw new RuntimeDatabaseException(e);
569                                 }
570                             }));
571                         }
572                     });
573                 } catch (DatabaseException e) {
574                     LOGGER.error("Could not apply mappings", e);
575                     throw new RuntimeDatabaseException(e);
576                 }
577             }
578         });
579         }
580         
581     static class RenderSVGContext {
582         
583         Map<String,StringBuilder> documents = new HashMap<>();
584         
585         public void append(String[] keys, String svgText) {
586                 for(String key : keys) append(key, svgText);
587         }
588
589         public void append(String key, String svgText) {
590                 StringBuilder builder = documents.get(key);
591                 if(builder == null) {
592                         builder = new StringBuilder();
593                         documents.put(key, builder);
594                 }
595                 builder.append(svgText);
596         }
597         
598         public void append(RenderSVGContext other) {
599                 for(String key : other.documents.keySet()) {
600                         append(key, other.get(key));
601                 }
602         }
603         
604         public String get(String key) {
605                 StringBuilder builder = documents.get(key);
606                 if(builder == null) return "";
607                 else return builder.toString();
608         }
609         
610     }
611     
612         private static String renderSVG0(double width, double height, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
613
614                 // Get a DOMImplementation.
615                 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
616
617                 // Create an instance of org.w3c.dom.Document.
618                 String svgNS = "http://www.w3.org/2000/svg";
619                 Document document = domImpl.createDocument(svgNS, "svg", null);
620
621                 // Create an instance of the SVG Generator.
622                 SVGGraphics2D svgGenerator = new Generator(document);
623
624                 RenderSVGContext result = new RenderSVGContext();
625
626                 try {
627
628             Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
629             if (selection != null) {
630                 // This prevents workbench selection from being left over.
631                 // Also prevents scene graph crap from being left on the screen.
632                 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
633                 selection.setSelection(0, d.getElements());
634             }
635
636                         G2DSceneGraph sg = ctx.getSceneGraph();
637                         sg.performCleanup();
638                         G2DParentNode root = (G2DParentNode) sg.getRootNode();
639
640                         // rtree is the actual content of the diagram
641                         RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
642                         Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
643
644                         // get the bounds of the content
645                         Rectangle2D content = rtreeBounds;
646                         
647                         // To account for dynamic padding of selection rectangles (5 units + stroke width)
648                         int offset = 6;
649                         
650                         double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
651                 
652                         svgGenerator.translate(offset, offset);
653                         svgGenerator.scale(scale, scale);
654                         // translate svgGenerator to the x and y coordinates of current content
655                         svgGenerator.translate(-content.getX(), -content.getY());
656
657                         svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
658                         //svgGenerator.setClip(content);
659                         
660                         result.append(MAIN_SECTION, "<g class=\"symbols\">");
661                         result.append(SELECTION_SECTION, "<g class=\"selections\">");
662                         result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
663
664                         KeyVisitor keyVisitor = new KeyVisitor();
665                         sg.accept(keyVisitor);
666                         
667                         Set<Object> keys = keyVisitor.getKeys();
668                         
669                         Map<?, ?> mappings = mappingFunction.apply(keys);
670
671                         IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
672                         
673                         sg.accept(visitor);
674
675                 } catch (Throwable t) {
676                         LOGGER.error("Problems rendering canvas context to SVG", t);
677                 }
678
679
680                 result.append(ALL_SECTIONS, "</g>");
681
682                 StringBuilder res = new StringBuilder();
683                 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
684                 res.append(result.get(MAIN_SECTION));
685                 res.append(result.get(SELECTION_SECTION));
686                 res.append(result.get(SELECTION_MASK_SECTION));
687                 res.append("</svg>");
688
689 //              System.err.println(" == FINAL RESULT == ");
690 //              System.err.println(res.toString());
691                 
692                 return res.toString();
693                 
694         }
695         
696         
697         
698         private static class KeyVisitor implements IG2DNodeVisitor {
699
700         private Set<Object> keys = new HashSet<>();
701
702         @Override
703         public void enter(IG2DNode node) {
704             if (node instanceof SingleElementNode) {
705                 Object key = ((SingleElementNode) node).getKey();
706                 if (key != null) {
707                     keys.add(key);
708                 }
709             }
710         }
711
712         @Override
713         public void leave(IG2DNode node) {
714             // Nothing to do
715         }
716
717         public Set<Object> getKeys() {
718             return keys;
719         }
720         }
721
722         private static class PrintingVisitor implements IG2DNodeVisitor {
723
724         int indent = 0;
725
726         HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
727
728         private RenderSVGContext result;
729         private SVGGraphics2D svgGenerator;
730
731         private Map<?, ?> mappings;
732
733         public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
734             this.result = result;
735             this.mappings = mappings;
736             this.svgGenerator = svgGenerator;
737         }
738
739         private String getKey(SingleElementNode node) {
740             String key;
741                 if(node.getKey() != null) {
742                 if (mappings.containsKey(node.getKey()))
743                     key = mappings.get(node.getKey()).toString();
744                 else
745                     key = node.getKey().toString();
746                 } else {
747                         key = Long.toString(node.getId());
748                 }
749             return key;
750         }
751
752         @Override
753         public void enter(IG2DNode node) {
754             
755                 RenderSVGContext parentBuilder = getParentBuilder(node);
756             
757             indent++;
758             if(node instanceof ConnectionNode) {
759                 
760                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
761                     n.setIgnoreSelection(true);
762                 }
763
764                 String key = getKey((ConnectionNode) node);
765                 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
766                 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
767                 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"0.001\" id=\"" + key + "\">");
768                 
769                 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
770                 String svg = printSVGDocument(doc);
771                 parentBuilder.append(MAIN_SECTION, svg);
772
773                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
774                     n.setIgnoreSelection(false);
775                 }
776
777                 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
778                 svg = printSVGDocument(doc);
779                 parentBuilder.append(SELECTION_SECTION, svg);
780
781                 BasicStroke bs = new BasicStroke(10f);
782                 
783                 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
784                     n.setDynamicStroke(bs);
785                 }
786
787                 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
788                 svg = printSVGDocument(doc);
789                 parentBuilder.append(SELECTION_MASK_SECTION, svg);
790
791                 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
792                 parentBuilder.append(SELECTION_SECTION, "\n</g>");
793                 parentBuilder.append(MAIN_SECTION, "\n</g>");
794                 
795             } else if (node instanceof SelectionNode) {
796                 
797                 SelectionNode n = (SelectionNode)node;
798                 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
799                 if(parentSEN != null) {
800                     
801                         RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
802                     
803                     String key = getKey(parentSEN);
804                     n.setIgnore(false);
805                     Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
806                     n.setIgnore(true);
807                     String svg = printSVGDocument(doc);
808                     parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
809                     parentBuilder2.append(SELECTION_SECTION, svg);
810                     parentBuilder2.append(SELECTION_SECTION, "\n</g>");
811                     AffineTransform transform = svgGenerator.getTransform();
812                     double[] matrix = new double[6];
813                     transform.getMatrix(matrix);
814                     String matrixString = String.format("matrix(%f,%f,%f,%f,%f,%f)", matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
815                     parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key + "\" transform=\"" + matrixString + "\">");
816                     Rectangle2D rect = n.getRect();
817                     // NaN
818                     if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
819                             parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"0.001\"");
820                             parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
821                             parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
822                             parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
823                     }
824                     parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
825                    
826                 }
827             } else if (node instanceof SVGNode) {
828                 SVGNode svg = (SVGNode)node;
829                 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
830             } else if (node instanceof G2DParentNode) {
831                 AffineTransform at = node.getTransform();
832                 if(node instanceof SingleElementNode) {
833                     SingleElementNode sen = (SingleElementNode)node;
834                     String key = getKey(sen);
835                     String typeClass = sen.getTypeClass();
836                     String clazz = "definedElement";
837                     if(typeClass != null && !typeClass.isEmpty())
838                         clazz = clazz + " " + typeClass;
839
840                     parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
841                     senBuilders.put(sen, new RenderSVGContext());
842                 }
843                 if(!at.isIdentity()) {
844                     if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
845                         String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
846                         parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
847                     } else {
848                         double[] ds = new double[6];
849                         at.getMatrix(ds);
850                         String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
851                         parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
852                     }
853                 }
854             }
855
856             //enters.put(node, b.length());
857
858         }
859         
860         private RenderSVGContext getParentBuilder(IG2DNode node) {
861             
862             INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
863             if(parentSEN instanceof G2DSceneGraph) return result;
864
865             RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
866             if(parentBuilder == null) return result;
867             
868             return parentBuilder;
869             
870         }
871
872         @Override
873         public void leave(IG2DNode node) {
874
875             if(node instanceof ConnectionNode || node instanceof SVGNode) {
876                 // We are done
877             } else if (node instanceof G2DParentNode) {
878                 
879                 RenderSVGContext parentBuilder = getParentBuilder(node);
880                 
881                 if(node instanceof SingleElementNode) {
882                         SingleElementNode sen = (SingleElementNode)node;
883                         RenderSVGContext b = senBuilders.get(sen);
884                         String content = b.get(MAIN_SECTION);
885                         if(content.isEmpty()) {
886                                 if(sen.getKey() != null) {
887
888                                         for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
889                                                 n.setIgnore(true);
890                                         }
891
892                                         Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
893                                         String svg = printSVGDocument(doc);
894                                         parentBuilder.append(MAIN_SECTION, svg);
895                                 }
896                         } else {
897                                 parentBuilder.append(b);
898                         }
899                 }
900                 
901                 AffineTransform at = node.getTransform();
902                 if(!at.isIdentity()) {
903                     parentBuilder.append(ALL_SECTIONS, "</g>");
904                 }
905                 if(node instanceof SingleElementNode) {
906                     SingleElementNode sen = (SingleElementNode)node;
907                     //if(sen.getKey() != null) {
908                         parentBuilder.append(MAIN_SECTION, "</g>");
909                     //}
910                 }
911             }
912             indent --;
913         }
914         }
915 }