1 package org.simantics.modeling;
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;
18 import java.util.Random;
20 import java.util.UUID;
21 import java.util.function.Function;
22 import java.util.stream.Collectors;
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;
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;
87 public class SCLScenegraph {
89 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
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";
95 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
98 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
99 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
104 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
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));
112 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
113 Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
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);
122 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
124 return func.apply(provider);
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));
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()));
138 public static String getNodeTransform(ICanvasContext ctx, String name) {
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();
148 return "No node found";
151 public static String getNodeText(ICanvasContext ctx, String name) {
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();
161 return "No node found";
164 public static String getNodeCount(ICanvasContext ctx) {
165 G2DSceneGraph g2 = ctx.getSceneGraph();
166 int amount = NodeUtil.countTreeNodes(g2);
167 return "Node count: " + amount;
170 public static String getAllNodes (ICanvasContext ctx) {
172 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
173 int amount = g2.size() +1;
174 return "All nodes: " + amount;
177 public static String getBoundsNodes (ICanvasContext ctx) {
179 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
180 int amount = bn.size();
181 return "BoundsNodes: " + amount;
184 public static String getBackgroundNodes (ICanvasContext ctx) {
186 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
187 int amount = bg.size();
188 return "BackgroundNodes: " + amount;
191 public static String getDataNodes (ICanvasContext ctx) {
193 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
194 int amount = dn.size();
195 return "DataNodes: " + amount;
198 public static String getNavigationNodes (ICanvasContext ctx) {
200 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
201 int amount = g2.size();
202 return "NavigationNodes: " + amount;
205 public static String getParentNodes (ICanvasContext ctx) {
207 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
208 int amount = g2.size();
209 return "ParentNodes: " + amount;
212 public static String getDecorationNodes (ICanvasContext ctx) {
214 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
215 int amount = deco.size();
216 return "DecorationNodes: " + amount;
219 public static String getSingleElementNodes (ICanvasContext ctx) {
221 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
222 int amount = g2.size();
223 return "SingleElementNodes: " + amount;
226 public static String getConnectionNodes (ICanvasContext ctx) {
228 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
229 int amount = g2.size();
230 return "ConnectionNodes: " + amount;
233 public static String getTextNodes (ICanvasContext ctx) {
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;
241 public static String getItemNodes (ICanvasContext ctx) {
243 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
244 int amount = item.size();
245 return "ItemNodes: " + amount;
248 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
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());
256 ParentNode<?> parentnode = modulenode.getParent();
257 //System.out.println("Parentnode: " + parentnode);
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());
265 //valuenode.setEditMode(true);
266 valuenode.activateEdit(0, null, ctx);
267 valuenode.setText(new_value);
268 valuenode.fireTextEditingEnded();
270 //System.out.println("valuenode modified: " + valuenode);
271 return "Modified module " + module + " with value " + new_value;
274 return "Not found module : " + module;
277 return "No nodes in scenegraph!";
280 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
282 boolean module_founded = false;
283 boolean value_founded = false;
285 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
286 System.out.println("Total amount of nodes: " + g2.size() + 1);
288 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
289 Integer textGridNodeAmount = grid.size();
290 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
292 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
293 Integer textNodeAmount = grid.size();
294 System.out.println("Amount of TextNodes " + textNodeAmount);
296 for (TextNode node : texts) {
297 if (module.equals(node.getText())) {
298 module_founded = true;
299 System.out.println("Correct module " + module + " founded.");
301 if (value.equals(node.getText())) {
302 value_founded = true;
303 System.out.println("Correct value " + value + " founded.");
307 if (value_founded == true && module_founded == true) {
308 return "Found both correct module " + module + " and value " + value;
310 if (value_founded == false && module_founded == true) {
311 return "Found only correct module " + module + " but not value " + value;
313 if (value_founded == true && module_founded == false) {
314 return "Found only correct value " + value + " but not module " + module;
317 return "Didn't found either module " + module + " or value " + value;
321 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
323 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
325 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
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);
333 throw new DatabaseException("Could not find IElement for " + element);
337 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
340 if (source_ctx.isDisposed())
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);
348 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
349 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
355 while(source_ctx.getEventQueue().size() > 0) {
358 } catch (InterruptedException e) {
359 throw new DatabaseException(e);
363 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
373 static class Generator extends SVGGraphics2D {
376 String newElementId = null;
377 ArrayList<Element> elements = new ArrayList<Element>();
379 public static final String svgNS = "http://www.w3.org/2000/svg";
381 public Generator(SVGGeneratorContext ctx, boolean joku) {
385 public Generator(Document document) {
390 public Element getRoot() {
391 Element root = super.getRoot();
392 for(Element e : elements) {
399 public void setRenderingHint(Key arg0, Object arg1) {
400 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
403 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
405 newElementId = arg1.toString();
407 newElementId = UUID.randomUUID().toString();
409 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
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());
420 super.setRenderingHint(arg0, arg1);
425 public static Element renderSVGNode(IG2DNode node) {
427 // Get a DOMImplementation.
428 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
430 // Create an instance of org.w3c.dom.Document.
431 String svgNS = "http://www.w3.org/2000/svg";
432 Document document = domImpl.createDocument(svgNS, "svg", null);
434 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
435 ctx.setComment(null);
437 // Create an instance of the SVG Generator.
438 SVGGraphics2D svgGenerator = new Generator(ctx, false);
442 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
443 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
444 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
446 node.render(svgGenerator);
448 } catch (Throwable t) {
449 LOGGER.error("Problems rendering scene graph to SVG", t);
452 return svgGenerator.getRoot();
455 public static String printSVGDocument(Element doce) {
457 StringBuilder result = new StringBuilder();
459 NodeList nl = doce.getChildNodes();
461 for(int i=0;i<nl.getLength();i++) {
463 ByteArrayOutputStream os = new ByteArrayOutputStream();
467 TransformerFactory tf = TransformerFactory.newInstance();
468 Transformer transformer = tf.newTransformer();
469 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
470 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
471 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
472 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
473 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
474 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
476 transformer.transform(new DOMSource(nl.item(i)),
477 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
482 } catch (Throwable t) {
483 LOGGER.error("Problems formatting SVGDocument to text.", t);
486 result.append(new String(os.toByteArray()));
490 return result.toString();
494 public static String renderSVG3(ICanvasContext ctx) {
495 return renderSVG0(ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
501 * @throws DatabaseException
503 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
504 String uri = graph.getPossibleURI(component);
505 int hashCode = uri.hashCode();
506 Random random = new Random(hashCode);
507 long l1 = random.nextLong();
508 long l2 = random.nextLong();
509 return new Object[] { l1, l2 };
513 * Default no-op mapper
515 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
517 public static String renderSVG(ICanvasContext ctx) {
518 return renderSVG0(ctx, mapper);
522 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
528 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
529 return renderSVG0(ctx, new Function1<Set<?>, Map<?, ?>>() {
532 public Map<?, ?> apply(Set<?> p0) {
534 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
537 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
538 ModelingResources MOD = ModelingResources.getInstance(graph);
539 DiagramResource DIA = DiagramResource.getInstance(graph);
540 Layer0 L0 = Layer0.getInstance(graph);
541 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
543 if (p instanceof Resource) {
544 Resource element = (Resource) p;
545 if (graph.isInstanceOf(element, DIA.Element)) {
546 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
547 if (component != null) {
548 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
549 if (identifier != null) {
550 return Arrays.toString(createURIBasedL0Identifier(graph, component));
552 LOGGER.error("Component {} does not have GUID identifier!", component);
554 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
555 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
556 return graph.getURI(element).hashCode();
558 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
559 if (graph.hasStatement(element, L0.HasName))
560 return graph.getURI(element).hashCode();
565 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
568 } catch (DatabaseException e) {
569 throw new RuntimeDatabaseException(e);
574 } catch (DatabaseException e) {
575 LOGGER.error("Could not apply mappings", e);
576 throw new RuntimeDatabaseException(e);
582 static class RenderSVGContext {
584 Map<String,StringBuilder> documents = new HashMap<>();
586 public void append(String[] keys, String svgText) {
587 for(String key : keys) append(key, svgText);
590 public void append(String key, String svgText) {
591 StringBuilder builder = documents.get(key);
592 if(builder == null) {
593 builder = new StringBuilder();
594 documents.put(key, builder);
596 builder.append(svgText);
599 public void append(RenderSVGContext other) {
600 for(String key : other.documents.keySet()) {
601 append(key, other.get(key));
605 public String get(String key) {
606 StringBuilder builder = documents.get(key);
607 if(builder == null) return "";
608 else return builder.toString();
613 private static String renderSVG0(ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
615 // Get a DOMImplementation.
616 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
618 // Create an instance of org.w3c.dom.Document.
619 String svgNS = "http://www.w3.org/2000/svg";
620 Document document = domImpl.createDocument(svgNS, "svg", null);
622 // Create an instance of the SVG Generator.
623 SVGGraphics2D svgGenerator = new Generator(document);
625 RenderSVGContext result = new RenderSVGContext();
629 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
630 if (selection != null) {
631 // This prevents workbench selection from being left over.
632 // Also prevents scene graph crap from being left on the screen.
633 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
634 selection.setSelection(0, d.getElements());
637 G2DSceneGraph sg = ctx.getSceneGraph();
639 G2DParentNode root = (G2DParentNode) sg.getRootNode();
641 // rtree is the actual content of the diagram
642 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
643 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
645 // nav is a node that has zooming functionalities
646 NavigationNode nav = NodeUtil.getNearestChildByClass(root, NavigationNode.class);
647 nav.setZoomEnabled(true);
649 // fit view with the contents of rtreeBounds
650 nav.zoomTo(rtreeBounds);
652 // get the bounds of the content
653 Rectangle2D content = NodeUtil.getLocalBounds(nav);
655 svgGenerator.scale(3,3);
657 // translate svgGenerator to the x and y coordinates of current content
658 svgGenerator.translate(-1 * content.getX(), (-1 * content.getY()));
660 Rectangle2D destination = new Rectangle2D.Double(0,0,1000,1000);
661 double sx = destination.getWidth() / content.getWidth();
662 double sy = destination.getHeight() / content.getHeight();
663 double scale = sx < sy ? sx : sy;
665 // Set svgCanvasSize to the given size parameters
666 svgGenerator.setSVGCanvasSize(new Dimension((int)(scale * content.getWidth()), (int)(scale * content.getHeight())));
667 svgGenerator.setClip(content);
669 double trX = -1 * content.getX();
670 double trY = -1 * content.getY();
673 if(!Double.isFinite(trX)) trX = 0;
674 if(!Double.isFinite(trY)) trY = 0;
676 result.append(MAIN_SECTION, "<g class=\"symbols\">");
677 result.append(SELECTION_SECTION, "<g class=\"selections\">");
678 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
680 result.append(ALL_SECTIONS, "<g transform=\"translate(");
681 result.append(ALL_SECTIONS, "" + trX);
682 result.append(ALL_SECTIONS, ", ");
683 result.append(ALL_SECTIONS, "" + trY);
684 result.append(ALL_SECTIONS, ")\">");
687 KeyVisitor keyVisitor = new KeyVisitor();
688 sg.accept(keyVisitor);
690 Set<Object> keys = keyVisitor.getKeys();
692 Map<?, ?> mappings = mappingFunction.apply(keys);
694 IG2DNodeVisitor visitor = new PrintingVisitor(result, mappings);
698 } catch (Throwable t) {
699 LOGGER.error("Problems rendering canvas context to SVG", t);
703 result.append(ALL_SECTIONS, "</g></g>");
705 StringBuilder res = new StringBuilder();
706 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
707 res.append(result.get(MAIN_SECTION));
708 res.append(result.get(SELECTION_SECTION));
709 res.append(result.get(SELECTION_MASK_SECTION));
710 res.append("</svg>");
712 // System.err.println(" == FINAL RESULT == ");
713 // System.err.println(res.toString());
715 return res.toString();
721 private static class KeyVisitor implements IG2DNodeVisitor {
723 private Set<Object> keys = new HashSet<>();
726 public void enter(IG2DNode node) {
727 if (node instanceof SingleElementNode) {
728 Object key = ((SingleElementNode) node).getKey();
736 public void leave(IG2DNode node) {
740 public Set<Object> getKeys() {
745 private static class PrintingVisitor implements IG2DNodeVisitor {
749 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
751 private RenderSVGContext result;
753 private Map<?, ?> mappings;
755 public PrintingVisitor(RenderSVGContext result, Map<?, ?> mappings) {
756 this.result = result;
757 this.mappings = mappings;
760 private String getKey(SingleElementNode node) {
762 if (mappings.containsKey(node.getKey()))
763 key = mappings.get(node.getKey()).toString();
765 key = node.getKey().toString();
770 public void enter(IG2DNode node) {
772 RenderSVGContext parentBuilder = getParentBuilder(node);
775 if(node instanceof ConnectionNode) {
777 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
778 n.setIgnoreSelection(true);
781 String key = getKey((ConnectionNode) node);
782 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
783 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
784 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"0.001\" id=\"" + key + "\">");
786 Element doc = renderSVGNode((IG2DNode)node);
787 String svg = printSVGDocument(doc);
788 parentBuilder.append(MAIN_SECTION, svg);
790 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
791 n.setIgnoreSelection(false);
794 doc = renderSVGNode((IG2DNode)node);
795 svg = printSVGDocument(doc);
796 parentBuilder.append(SELECTION_SECTION, svg);
798 BasicStroke bs = new BasicStroke(10f);
800 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
801 n.setDynamicStroke(bs);
804 doc = renderSVGNode((IG2DNode)node);
805 svg = printSVGDocument(doc);
806 parentBuilder.append(SELECTION_MASK_SECTION, svg);
808 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
809 parentBuilder.append(SELECTION_SECTION, "\n</g>");
810 parentBuilder.append(MAIN_SECTION, "\n</g>");
812 } else if (node instanceof SelectionNode) {
814 SelectionNode n = (SelectionNode)node;
815 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
816 if(parentSEN != null && parentSEN.getKey() != null) {
818 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
820 String key = getKey(parentSEN);
822 Element doc = renderSVGNode((IG2DNode)node);
824 String svg = printSVGDocument(doc);
825 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
826 parentBuilder2.append(SELECTION_SECTION, svg);
827 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
828 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key + "\">");
829 Rectangle2D rect = n.getRect();
831 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
832 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"0.001\"");
833 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
834 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
835 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
837 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
840 } else if (node instanceof SVGNode) {
841 SVGNode svg = (SVGNode)node;
842 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
843 } else if (node instanceof G2DParentNode) {
844 AffineTransform at = node.getTransform();
845 if(node instanceof SingleElementNode) {
846 SingleElementNode sen = (SingleElementNode)node;
847 if(sen.getKey() != null) {
848 String key = getKey(sen);
849 String typeClass = sen.getTypeClass();
850 String clazz = "definedElement";
851 if(typeClass != null && !typeClass.isEmpty())
852 clazz = clazz + " " + typeClass;
854 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
856 senBuilders.put(sen, new RenderSVGContext());
858 if(!at.isIdentity()) {
859 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
860 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
861 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
863 double[] ds = new double[6];
865 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
866 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
871 //enters.put(node, b.length());
875 private RenderSVGContext getParentBuilder(IG2DNode node) {
877 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
878 if(parentSEN instanceof G2DSceneGraph) return result;
880 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
881 if(parentBuilder == null) return result;
883 return parentBuilder;
888 public void leave(IG2DNode node) {
890 if(node instanceof ConnectionNode || node instanceof SVGNode) {
892 } else if (node instanceof G2DParentNode) {
894 RenderSVGContext parentBuilder = getParentBuilder(node);
896 if(node instanceof SingleElementNode) {
897 SingleElementNode sen = (SingleElementNode)node;
898 RenderSVGContext b = senBuilders.get(sen);
899 String content = b.get(MAIN_SECTION);
900 if(content.isEmpty()) {
901 if(sen.getKey() != null) {
903 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
907 Element doc = renderSVGNode((IG2DNode)node);
908 String svg = printSVGDocument(doc);
909 parentBuilder.append(MAIN_SECTION, svg);
912 parentBuilder.append(b);
916 AffineTransform at = node.getTransform();
917 if(!at.isIdentity()) {
918 parentBuilder.append(ALL_SECTIONS, "</g>");
920 if(node instanceof SingleElementNode) {
921 SingleElementNode sen = (SingleElementNode)node;
922 if(sen.getKey() != null) {
923 parentBuilder.append(MAIN_SECTION, "</g>");