1 package org.simantics.modeling;
3 import java.awt.BasicStroke;
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;
19 import java.util.Random;
21 import java.util.UUID;
22 import java.util.function.Function;
23 import java.util.stream.Collectors;
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;
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.NavigationNode;
72 import org.simantics.scenegraph.g2d.nodes.SVGNode;
73 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
74 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
75 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
76 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
77 import org.simantics.scenegraph.utils.NodeUtil;
78 import org.simantics.scl.runtime.function.Function1;
79 import org.simantics.scl.runtime.tuple.Tuple2;
80 import org.simantics.trend.impl.ItemNode;
81 import org.simantics.utils.threads.ThreadUtils;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.w3c.dom.DOMImplementation;
85 import org.w3c.dom.Document;
86 import org.w3c.dom.Element;
87 import org.w3c.dom.NodeList;
89 public class SCLScenegraph {
91 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
93 private static final String MAIN_SECTION = "main";
94 private static final String SELECTION_SECTION = "selection";
95 private static final String SELECTION_MASK_SECTION = "selectionMask";
97 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
100 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
101 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
106 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
110 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
111 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
114 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
115 Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
118 public Tuple2 perform(ReadGraph graph) throws DatabaseException {
119 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
120 String diagramRVI = Variables.getRVI(graph, resource);
121 return new Tuple2(indexRoot, diagramRVI);
124 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
126 return func.apply(provider);
132 public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
133 return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
136 public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
137 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
140 public static String getNodeTransform(ICanvasContext ctx, String name) {
142 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
143 for (TextNode text : texts) {
144 String nodeName = NodeUtil.getNodeName(text);
145 if (nodeName.equals(name)) {
146 String transform = text.getTransform().toString();
150 return "No node found";
153 public static String getNodeText(ICanvasContext ctx, String name) {
155 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
156 for (TextNode text : texts) {
157 String nodeName = NodeUtil.getNodeName(text);
158 if (nodeName.equals(name)) {
159 String texti = text.getText();
163 return "No node found";
166 public static String getNodeCount(ICanvasContext ctx) {
167 G2DSceneGraph g2 = ctx.getSceneGraph();
168 int amount = NodeUtil.countTreeNodes(g2);
169 return "Node count: " + amount;
172 public static String getAllNodes (ICanvasContext ctx) {
174 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
175 int amount = g2.size() +1;
176 return "All nodes: " + amount;
179 public static String getBoundsNodes (ICanvasContext ctx) {
181 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
182 int amount = bn.size();
183 return "BoundsNodes: " + amount;
186 public static String getBackgroundNodes (ICanvasContext ctx) {
188 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
189 int amount = bg.size();
190 return "BackgroundNodes: " + amount;
193 public static String getDataNodes (ICanvasContext ctx) {
195 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
196 int amount = dn.size();
197 return "DataNodes: " + amount;
200 public static String getNavigationNodes (ICanvasContext ctx) {
202 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
203 int amount = g2.size();
204 return "NavigationNodes: " + amount;
207 public static String getParentNodes (ICanvasContext ctx) {
209 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
210 int amount = g2.size();
211 return "ParentNodes: " + amount;
214 public static String getDecorationNodes (ICanvasContext ctx) {
216 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
217 int amount = deco.size();
218 return "DecorationNodes: " + amount;
221 public static String getSingleElementNodes (ICanvasContext ctx) {
223 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
224 int amount = g2.size();
225 return "SingleElementNodes: " + amount;
228 public static String getConnectionNodes (ICanvasContext ctx) {
230 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
231 int amount = g2.size();
232 return "ConnectionNodes: " + amount;
235 public static String getTextNodes (ICanvasContext ctx) {
237 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
238 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
239 int amount = tn.size() + tgn.size();
240 return "TextNodes: " + amount;
243 public static String getItemNodes (ICanvasContext ctx) {
245 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
246 int amount = item.size();
247 return "ItemNodes: " + amount;
250 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
252 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
253 for (TextNode modulenode : textGridNodes) {
254 if (module.equals(modulenode.getText())) {
255 //System.out.println("Module what we were looking for: " + module);
256 //System.out.println("Modulenode: " + modulenode.getText());
258 ParentNode<?> parentnode = modulenode.getParent();
259 //System.out.println("Parentnode: " + parentnode);
261 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
262 for (TextNode valuenode : textnodes) {
263 if (previous_value.equals(valuenode.getText())) {
264 //System.out.println("Value what we were looking for: " + previous_value);
265 //System.out.println("Valuenode: " + valuenode.getText());
267 //valuenode.setEditMode(true);
268 valuenode.activateEdit(0, null, ctx);
269 valuenode.setText(new_value);
270 valuenode.fireTextEditingEnded();
272 //System.out.println("valuenode modified: " + valuenode);
273 return "Modified module " + module + " with value " + new_value;
276 return "Not found module : " + module;
279 return "No nodes in scenegraph!";
283 * Returns background color of a canvasContext or null.
285 * @return color in RGBA List<Integer> format, or null.
287 public static List<Integer> getBackgroundColor(ICanvasContext ctx) {
288 Color color = ctx.getDefaultHintContext().getHint(Hints.KEY_BACKGROUND_COLOR);
291 ArrayList<Integer> rgba = new ArrayList<>(4);
292 rgba.add(color.getRed());
293 rgba.add(color.getGreen());
294 rgba.add(color.getBlue());
295 rgba.add(color.getAlpha());
299 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
301 boolean module_founded = false;
302 boolean value_founded = false;
304 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
305 System.out.println("Total amount of nodes: " + g2.size() + 1);
307 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
308 Integer textGridNodeAmount = grid.size();
309 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
311 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
312 Integer textNodeAmount = grid.size();
313 System.out.println("Amount of TextNodes " + textNodeAmount);
315 for (TextNode node : texts) {
316 if (module.equals(node.getText())) {
317 module_founded = true;
318 System.out.println("Correct module " + module + " founded.");
320 if (value.equals(node.getText())) {
321 value_founded = true;
322 System.out.println("Correct value " + value + " founded.");
326 if (value_founded == true && module_founded == true) {
327 return "Found both correct module " + module + " and value " + value;
329 if (value_founded == false && module_founded == true) {
330 return "Found only correct module " + module + " but not value " + value;
332 if (value_founded == true && module_founded == false) {
333 return "Found only correct value " + value + " but not module " + module;
336 return "Didn't found either module " + module + " or value " + value;
340 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
342 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
344 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
346 final Collection<IElement> newSelection = new ArrayList<IElement>();
347 for (Resource module : modules) {
348 IElement element = dem.getElement(idiagram, module);
349 if (element != null) {
350 newSelection.add(element);
352 throw new DatabaseException("Could not find IElement for " + element);
356 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
359 if (source_ctx.isDisposed())
361 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
362 if (selection != null) {
363 // This prevents workbench selection from being left over.
364 // Also prevents scene graph crap from being left on the screen.
365 selection.setSelection(0, newSelection);
367 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
368 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
374 while(source_ctx.getEventQueue().size() > 0) {
377 } catch (InterruptedException e) {
378 throw new DatabaseException(e);
382 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
392 static class Generator extends SVGGraphics2D {
395 String newElementId = null;
396 ArrayList<Element> elements = new ArrayList<Element>();
398 public static final String svgNS = "http://www.w3.org/2000/svg";
400 public Generator(SVGGeneratorContext ctx, boolean textAsShapes) {
401 super(ctx, textAsShapes);
404 public Generator(Document document) {
406 // prevent batik comment in each g-element
407 getGeneratorContext().setComment(null);
411 public Element getRoot() {
412 Element root = super.getRoot();
413 for(Element e : elements) {
420 public void setRenderingHint(Key arg0, Object arg1) {
421 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
424 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
426 newElementId = arg1.toString();
428 newElementId = UUID.randomUUID().toString();
430 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
433 Element group = getDOMFactory().createElement(SVG_G_TAG);
434 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
435 group.setAttributeNS(null, "id", newElementId);
436 group.setAttributeNS(null, "class", arg1.toString());
441 super.setRenderingHint(arg0, arg1);
446 public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
450 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
451 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
452 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
454 node.render(svgGenerator);
456 } catch (Throwable t) {
457 LOGGER.error("Problems rendering scene graph to SVG", t);
460 return svgGenerator.getRoot();
463 public static String printSVGDocument(Element doce) {
465 StringBuilder result = new StringBuilder();
467 NodeList nl = doce.getChildNodes();
469 for(int i=0;i<nl.getLength();i++) {
471 ByteArrayOutputStream os = new ByteArrayOutputStream();
475 TransformerFactory tf = TransformerFactory.newInstance();
476 Transformer transformer = tf.newTransformer();
477 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
478 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
479 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
480 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
481 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
482 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
484 transformer.transform(new DOMSource(nl.item(i)),
485 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
490 } catch (Throwable t) {
491 LOGGER.error("Problems formatting SVGDocument to text.", t);
494 result.append(new String(os.toByteArray()));
498 return result.toString();
502 public static String renderSVG3(ICanvasContext ctx) {
503 return renderSVG3(ctx, -1, -1);
506 public static String renderSVG3(ICanvasContext ctx, double width, double height) {
507 return renderSVG0(width, height, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
513 * @throws DatabaseException
515 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
516 String uri = graph.getPossibleURI(component);
517 int hashCode = uri.hashCode();
518 Random random = new Random(hashCode);
519 long l1 = random.nextLong();
520 long l2 = random.nextLong();
521 return new Object[] { l1, l2 };
525 * Default no-op mapper
527 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
529 public static String renderSVG(ICanvasContext ctx, double width, double height) {
530 return renderSVG0(width, height, ctx, mapper);
533 public static String renderSVG(ICanvasContext ctx) {
534 return renderSVG(ctx, -1, -1);
537 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
538 return renderSVGMapIdentifiers(ctx, -1, -1);
542 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
548 public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
549 return renderSVG0(width, height, ctx, new Function1<Set<?>, Map<?, ?>>() {
552 public Map<?, ?> apply(Set<?> p0) {
554 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
557 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
558 ModelingResources MOD = ModelingResources.getInstance(graph);
559 DiagramResource DIA = DiagramResource.getInstance(graph);
560 Layer0 L0 = Layer0.getInstance(graph);
561 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
563 if (p instanceof Resource) {
564 Resource element = (Resource) p;
565 if (graph.isInstanceOf(element, DIA.Element)) {
566 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
567 if (component != null) {
568 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
569 if (identifier != null) {
570 return Arrays.toString(createURIBasedL0Identifier(graph, component));
572 LOGGER.error("Component {} does not have GUID identifier!", component);
574 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
575 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
576 return graph.getURI(element).hashCode();
578 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
579 if (graph.hasStatement(element, L0.HasName))
580 return graph.getURI(element).hashCode();
585 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
588 } catch (DatabaseException e) {
589 throw new RuntimeDatabaseException(e);
594 } catch (DatabaseException e) {
595 LOGGER.error("Could not apply mappings", e);
596 throw new RuntimeDatabaseException(e);
602 static class RenderSVGContext {
604 Map<String,StringBuilder> documents = new HashMap<>();
606 public void append(String[] keys, String svgText) {
607 for(String key : keys) append(key, svgText);
610 public void append(String key, String svgText) {
611 StringBuilder builder = documents.get(key);
612 if(builder == null) {
613 builder = new StringBuilder();
614 documents.put(key, builder);
616 builder.append(svgText);
619 public void append(RenderSVGContext other) {
620 for(String key : other.documents.keySet()) {
621 append(key, other.get(key));
625 public String get(String key) {
626 StringBuilder builder = documents.get(key);
627 if(builder == null) return "";
628 else return builder.toString();
633 private static String renderSVG0(double width, double height, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
635 // Get a DOMImplementation.
636 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
638 // Create an instance of org.w3c.dom.Document.
639 String svgNS = "http://www.w3.org/2000/svg";
640 Document document = domImpl.createDocument(svgNS, "svg", null);
642 // Create an instance of the SVG Generator.
643 SVGGraphics2D svgGenerator = new Generator(document);
645 RenderSVGContext result = new RenderSVGContext();
647 double[] matrix = new double[6];
650 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
651 if (selection != null) {
652 // This prevents workbench selection from being left over.
653 // Also prevents scene graph crap from being left on the screen.
654 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
655 selection.setSelection(0, d.getElements());
658 G2DSceneGraph sg = ctx.getSceneGraph();
660 G2DParentNode root = (G2DParentNode) sg.getRootNode();
662 // rtree is the actual content of the diagram
663 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
664 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
666 // get the bounds of the content
667 Rectangle2D content = rtreeBounds;
669 // To account for dynamic padding of selection rectangles (5 units + stroke width)
672 double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
674 AffineTransform tr = new AffineTransform();
675 tr.translate(offset, offset);
676 tr.scale(scale, scale);
677 tr.translate(-content.getX(), -content.getY());
678 tr.getMatrix(matrix);
679 //svgGenerator.translate(offset, offset);
680 //svgGenerator.scale(scale, scale);
681 // translate svgGenerator to the x and y coordinates of current content
682 //svgGenerator.translate(-content.getX(), -content.getY());
684 svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
685 //svgGenerator.setClip(content);
687 result.append(MAIN_SECTION, "<g class=\"symbols\">");
688 result.append(SELECTION_SECTION, "<g class=\"selections\">");
689 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
691 KeyVisitor keyVisitor = new KeyVisitor();
692 sg.accept(keyVisitor);
694 Set<Object> keys = keyVisitor.getKeys();
696 Map<?, ?> mappings = mappingFunction.apply(keys);
698 IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
702 } catch (Throwable t) {
703 LOGGER.error("Problems rendering canvas context to SVG", t);
707 result.append(ALL_SECTIONS, "</g>");
709 StringBuilder res = new StringBuilder();
710 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
711 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(")\">");
712 res.append(result.get(MAIN_SECTION));
713 res.append(result.get(SELECTION_SECTION));
714 res.append(result.get(SELECTION_MASK_SECTION));
716 res.append("</svg>");
718 // System.err.println(" == FINAL RESULT == ");
719 // System.err.println(res.toString());
721 return res.toString();
727 private static class KeyVisitor implements IG2DNodeVisitor {
729 private Set<Object> keys = new HashSet<>();
732 public void enter(IG2DNode node) {
733 if (node instanceof SingleElementNode) {
734 Object key = ((SingleElementNode) node).getKey();
742 public void leave(IG2DNode node) {
746 public Set<Object> getKeys() {
751 private static class PrintingVisitor implements IG2DNodeVisitor {
755 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
757 private RenderSVGContext result;
758 private SVGGraphics2D svgGenerator;
760 private Map<?, ?> mappings;
762 public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
763 this.result = result;
764 this.mappings = mappings;
765 this.svgGenerator = svgGenerator;
768 private String getKey(SingleElementNode node) {
770 if(node.getKey() != null) {
771 if (mappings.containsKey(node.getKey()))
772 key = mappings.get(node.getKey()).toString();
774 key = node.getKey().toString();
776 key = Long.toString(node.getId());
782 public void enter(IG2DNode node) {
784 RenderSVGContext parentBuilder = getParentBuilder(node);
787 if(node instanceof ConnectionNode) {
789 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
790 n.setIgnoreSelection(true);
793 String key = getKey((ConnectionNode) node);
794 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
795 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
796 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"0.001\" id=\"" + key + "\">");
798 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
799 String svg = printSVGDocument(doc);
800 parentBuilder.append(MAIN_SECTION, svg);
802 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
803 n.setIgnoreSelection(false);
806 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
807 svg = printSVGDocument(doc);
808 parentBuilder.append(SELECTION_SECTION, svg);
810 BasicStroke bs = new BasicStroke(10f);
812 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
813 n.setDynamicStroke(bs);
816 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
817 svg = printSVGDocument(doc);
818 parentBuilder.append(SELECTION_MASK_SECTION, svg);
820 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
821 parentBuilder.append(SELECTION_SECTION, "\n</g>");
822 parentBuilder.append(MAIN_SECTION, "\n</g>");
824 } else if (node instanceof SelectionNode) {
826 SelectionNode n = (SelectionNode)node;
827 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
828 if(parentSEN != null) {
830 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
832 String key = getKey(parentSEN);
834 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
836 String svg = printSVGDocument(doc);
837 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
838 parentBuilder2.append(SELECTION_SECTION, svg);
839 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
840 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
841 Rectangle2D rect = n.getRect();
843 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
844 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"0.001\"");
845 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
846 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
847 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
849 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
852 } else if (node instanceof SVGNode) {
853 SVGNode svg = (SVGNode)node;
854 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
855 } else if (node instanceof G2DParentNode) {
856 AffineTransform at = node.getTransform();
857 if(node instanceof SingleElementNode) {
858 SingleElementNode sen = (SingleElementNode)node;
859 String key = getKey(sen);
860 String typeClass = sen.getTypeClass();
861 String clazz = "definedElement";
862 if(typeClass != null && !typeClass.isEmpty())
863 clazz = clazz + " " + typeClass;
865 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
866 senBuilders.put(sen, new RenderSVGContext());
868 if(!at.isIdentity()) {
869 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
870 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
871 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
873 double[] ds = new double[6];
875 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
876 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
881 //enters.put(node, b.length());
885 private RenderSVGContext getParentBuilder(IG2DNode node) {
887 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
888 if(parentSEN instanceof G2DSceneGraph) return result;
890 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
891 if(parentBuilder == null) return result;
893 return parentBuilder;
898 public void leave(IG2DNode node) {
900 if(node instanceof ConnectionNode || node instanceof SVGNode) {
902 } else if (node instanceof G2DParentNode) {
904 RenderSVGContext parentBuilder = getParentBuilder(node);
906 if(node instanceof SingleElementNode) {
907 SingleElementNode sen = (SingleElementNode)node;
908 RenderSVGContext b = senBuilders.get(sen);
909 String content = b.get(MAIN_SECTION);
910 if(content.isEmpty()) {
911 if(sen.getKey() != null) {
913 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
917 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
918 String svg = printSVGDocument(doc);
919 parentBuilder.append(MAIN_SECTION, svg);
922 parentBuilder.append(b);
926 AffineTransform at = node.getTransform();
927 if(!at.isIdentity()) {
928 parentBuilder.append(ALL_SECTIONS, "</g>");
930 if(node instanceof SingleElementNode) {
931 SingleElementNode sen = (SingleElementNode)node;
932 //if(sen.getKey() != null) {
933 parentBuilder.append(MAIN_SECTION, "</g>");