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