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 textAsShapes) {
382 super(ctx, textAsShapes);
385 public Generator(Document document) {
387 // prevent batik comment in each g-element
388 getGeneratorContext().setComment(null);
392 public Element getRoot() {
393 Element root = super.getRoot();
394 for(Element e : elements) {
401 public void setRenderingHint(Key arg0, Object arg1) {
402 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
405 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
407 newElementId = arg1.toString();
409 newElementId = UUID.randomUUID().toString();
411 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
414 Element group = getDOMFactory().createElement(SVG_G_TAG);
415 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
416 group.setAttributeNS(null, "id", newElementId);
417 group.setAttributeNS(null, "class", arg1.toString());
422 super.setRenderingHint(arg0, arg1);
427 public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
431 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
432 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
433 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
435 node.render(svgGenerator);
437 } catch (Throwable t) {
438 LOGGER.error("Problems rendering scene graph to SVG", t);
441 return svgGenerator.getRoot();
444 public static String printSVGDocument(Element doce) {
446 StringBuilder result = new StringBuilder();
448 NodeList nl = doce.getChildNodes();
450 for(int i=0;i<nl.getLength();i++) {
452 ByteArrayOutputStream os = new ByteArrayOutputStream();
456 TransformerFactory tf = TransformerFactory.newInstance();
457 Transformer transformer = tf.newTransformer();
458 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
459 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
460 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
461 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
462 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
463 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
465 transformer.transform(new DOMSource(nl.item(i)),
466 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
471 } catch (Throwable t) {
472 LOGGER.error("Problems formatting SVGDocument to text.", t);
475 result.append(new String(os.toByteArray()));
479 return result.toString();
483 public static String renderSVG3(ICanvasContext ctx) {
484 return renderSVG3(ctx, -1, -1);
487 public static String renderSVG3(ICanvasContext ctx, double width, double height) {
488 return renderSVG0(width, height, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
494 * @throws DatabaseException
496 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
497 String uri = graph.getPossibleURI(component);
498 int hashCode = uri.hashCode();
499 Random random = new Random(hashCode);
500 long l1 = random.nextLong();
501 long l2 = random.nextLong();
502 return new Object[] { l1, l2 };
506 * Default no-op mapper
508 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
510 public static String renderSVG(ICanvasContext ctx, double width, double height) {
511 return renderSVG0(width, height, ctx, mapper);
514 public static String renderSVG(ICanvasContext ctx) {
515 return renderSVG(ctx, -1, -1);
518 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
519 return renderSVGMapIdentifiers(ctx, -1, -1);
523 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
529 public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
530 return renderSVG0(width, height, ctx, new Function1<Set<?>, Map<?, ?>>() {
533 public Map<?, ?> apply(Set<?> p0) {
535 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
538 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
539 ModelingResources MOD = ModelingResources.getInstance(graph);
540 DiagramResource DIA = DiagramResource.getInstance(graph);
541 Layer0 L0 = Layer0.getInstance(graph);
542 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
544 if (p instanceof Resource) {
545 Resource element = (Resource) p;
546 if (graph.isInstanceOf(element, DIA.Element)) {
547 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
548 if (component != null) {
549 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
550 if (identifier != null) {
551 return Arrays.toString(createURIBasedL0Identifier(graph, component));
553 LOGGER.error("Component {} does not have GUID identifier!", component);
555 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
556 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
557 return graph.getURI(element).hashCode();
559 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
560 if (graph.hasStatement(element, L0.HasName))
561 return graph.getURI(element).hashCode();
566 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
569 } catch (DatabaseException e) {
570 throw new RuntimeDatabaseException(e);
575 } catch (DatabaseException e) {
576 LOGGER.error("Could not apply mappings", e);
577 throw new RuntimeDatabaseException(e);
583 static class RenderSVGContext {
585 Map<String,StringBuilder> documents = new HashMap<>();
587 public void append(String[] keys, String svgText) {
588 for(String key : keys) append(key, svgText);
591 public void append(String key, String svgText) {
592 StringBuilder builder = documents.get(key);
593 if(builder == null) {
594 builder = new StringBuilder();
595 documents.put(key, builder);
597 builder.append(svgText);
600 public void append(RenderSVGContext other) {
601 for(String key : other.documents.keySet()) {
602 append(key, other.get(key));
606 public String get(String key) {
607 StringBuilder builder = documents.get(key);
608 if(builder == null) return "";
609 else return builder.toString();
614 private static String renderSVG0(double width, double height, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
616 // Get a DOMImplementation.
617 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
619 // Create an instance of org.w3c.dom.Document.
620 String svgNS = "http://www.w3.org/2000/svg";
621 Document document = domImpl.createDocument(svgNS, "svg", null);
623 // Create an instance of the SVG Generator.
624 SVGGraphics2D svgGenerator = new Generator(document);
626 RenderSVGContext result = new RenderSVGContext();
628 double[] matrix = new double[6];
631 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
632 if (selection != null) {
633 // This prevents workbench selection from being left over.
634 // Also prevents scene graph crap from being left on the screen.
635 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
636 selection.setSelection(0, d.getElements());
639 G2DSceneGraph sg = ctx.getSceneGraph();
641 G2DParentNode root = (G2DParentNode) sg.getRootNode();
643 // rtree is the actual content of the diagram
644 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
645 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
647 // get the bounds of the content
648 Rectangle2D content = rtreeBounds;
650 // To account for dynamic padding of selection rectangles (5 units + stroke width)
653 double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
655 AffineTransform tr = new AffineTransform();
656 tr.translate(offset, offset);
657 tr.scale(scale, scale);
658 tr.translate(-content.getX(), -content.getY());
659 tr.getMatrix(matrix);
660 //svgGenerator.translate(offset, offset);
661 //svgGenerator.scale(scale, scale);
662 // translate svgGenerator to the x and y coordinates of current content
663 //svgGenerator.translate(-content.getX(), -content.getY());
665 svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
666 //svgGenerator.setClip(content);
668 result.append(MAIN_SECTION, "<g class=\"symbols\">");
669 result.append(SELECTION_SECTION, "<g class=\"selections\">");
670 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
672 KeyVisitor keyVisitor = new KeyVisitor();
673 sg.accept(keyVisitor);
675 Set<Object> keys = keyVisitor.getKeys();
677 Map<?, ?> mappings = mappingFunction.apply(keys);
679 IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
683 } catch (Throwable t) {
684 LOGGER.error("Problems rendering canvas context to SVG", t);
688 result.append(ALL_SECTIONS, "</g>");
690 StringBuilder res = new StringBuilder();
691 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
692 res.append("<g transform=\"matrix(").append(matrix[0]).append(",").append(matrix[1]).append(",").append(matrix[2]).append(",").append(matrix[3]).append(",").append(matrix[4]).append(",").append(matrix[5]).append(")\">");
693 res.append(result.get(MAIN_SECTION));
694 res.append(result.get(SELECTION_SECTION));
695 res.append(result.get(SELECTION_MASK_SECTION));
697 res.append("</svg>");
699 // System.err.println(" == FINAL RESULT == ");
700 // System.err.println(res.toString());
702 return res.toString();
708 private static class KeyVisitor implements IG2DNodeVisitor {
710 private Set<Object> keys = new HashSet<>();
713 public void enter(IG2DNode node) {
714 if (node instanceof SingleElementNode) {
715 Object key = ((SingleElementNode) node).getKey();
723 public void leave(IG2DNode node) {
727 public Set<Object> getKeys() {
732 private static class PrintingVisitor implements IG2DNodeVisitor {
736 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
738 private RenderSVGContext result;
739 private SVGGraphics2D svgGenerator;
741 private Map<?, ?> mappings;
743 public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
744 this.result = result;
745 this.mappings = mappings;
746 this.svgGenerator = svgGenerator;
749 private String getKey(SingleElementNode node) {
751 if(node.getKey() != null) {
752 if (mappings.containsKey(node.getKey()))
753 key = mappings.get(node.getKey()).toString();
755 key = node.getKey().toString();
757 key = Long.toString(node.getId());
763 public void enter(IG2DNode node) {
765 RenderSVGContext parentBuilder = getParentBuilder(node);
768 if(node instanceof ConnectionNode) {
770 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
771 n.setIgnoreSelection(true);
774 String key = getKey((ConnectionNode) node);
775 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
776 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
777 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"0.001\" id=\"" + key + "\">");
779 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
780 String svg = printSVGDocument(doc);
781 parentBuilder.append(MAIN_SECTION, svg);
783 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
784 n.setIgnoreSelection(false);
787 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
788 svg = printSVGDocument(doc);
789 parentBuilder.append(SELECTION_SECTION, svg);
791 BasicStroke bs = new BasicStroke(10f);
793 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
794 n.setDynamicStroke(bs);
797 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
798 svg = printSVGDocument(doc);
799 parentBuilder.append(SELECTION_MASK_SECTION, svg);
801 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
802 parentBuilder.append(SELECTION_SECTION, "\n</g>");
803 parentBuilder.append(MAIN_SECTION, "\n</g>");
805 } else if (node instanceof SelectionNode) {
807 SelectionNode n = (SelectionNode)node;
808 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
809 if(parentSEN != null) {
811 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
813 String key = getKey(parentSEN);
815 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
817 String svg = printSVGDocument(doc);
818 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
819 parentBuilder2.append(SELECTION_SECTION, svg);
820 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
821 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
822 Rectangle2D rect = n.getRect();
824 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
825 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"0.001\"");
826 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
827 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
828 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
830 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
833 } else if (node instanceof SVGNode) {
834 SVGNode svg = (SVGNode)node;
835 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
836 } else if (node instanceof G2DParentNode) {
837 AffineTransform at = node.getTransform();
838 if(node instanceof SingleElementNode) {
839 SingleElementNode sen = (SingleElementNode)node;
840 String key = getKey(sen);
841 String typeClass = sen.getTypeClass();
842 String clazz = "definedElement";
843 if(typeClass != null && !typeClass.isEmpty())
844 clazz = clazz + " " + typeClass;
846 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
847 senBuilders.put(sen, new RenderSVGContext());
849 if(!at.isIdentity()) {
850 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
851 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
852 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
854 double[] ds = new double[6];
856 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
857 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
862 //enters.put(node, b.length());
866 private RenderSVGContext getParentBuilder(IG2DNode node) {
868 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
869 if(parentSEN instanceof G2DSceneGraph) return result;
871 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
872 if(parentBuilder == null) return result;
874 return parentBuilder;
879 public void leave(IG2DNode node) {
881 if(node instanceof ConnectionNode || node instanceof SVGNode) {
883 } else if (node instanceof G2DParentNode) {
885 RenderSVGContext parentBuilder = getParentBuilder(node);
887 if(node instanceof SingleElementNode) {
888 SingleElementNode sen = (SingleElementNode)node;
889 RenderSVGContext b = senBuilders.get(sen);
890 String content = b.get(MAIN_SECTION);
891 if(content.isEmpty()) {
892 if(sen.getKey() != null) {
894 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
898 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
899 String svg = printSVGDocument(doc);
900 parentBuilder.append(MAIN_SECTION, svg);
903 parentBuilder.append(b);
907 AffineTransform at = node.getTransform();
908 if(!at.isIdentity()) {
909 parentBuilder.append(ALL_SECTIONS, "</g>");
911 if(node instanceof SingleElementNode) {
912 SingleElementNode sen = (SingleElementNode)node;
913 //if(sen.getKey() != null) {
914 parentBuilder.append(MAIN_SECTION, "</g>");