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.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.Node;
89 import org.w3c.dom.NodeList;
91 public class SCLScenegraph {
93 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
95 private static final String MAIN_SECTION = "main";
96 private static final String SELECTION_SECTION = "selection";
97 private static final String SELECTION_MASK_SECTION = "selectionMask";
99 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
101 // Changed from 0.001 to 0.0001 to prevent creation of huge BufferedImage's when
102 // generating PDF from SVG. If SVG contains any transparency then Batik uses
103 // bitmap-rendering which remarkably slows things down
104 // See org.apache.batik.gvt.AbstractGraphicsNode.paint(Graphics2D) where decisions are made
105 // if AlphaComposite should be painted
106 private static final String OPACITY = "0.0001";
109 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
110 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
115 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
119 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
120 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
123 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
124 Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
127 public Tuple2 perform(ReadGraph graph) throws DatabaseException {
128 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
129 String diagramRVI = Variables.getRVI(graph, resource);
130 return new Tuple2(indexRoot, diagramRVI);
133 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
135 return func.apply(provider);
141 public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
142 return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
145 public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
146 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
149 public static String getNodeTransform(ICanvasContext ctx, String name) {
151 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
152 for (TextNode text : texts) {
153 String nodeName = NodeUtil.getNodeName(text);
154 if (nodeName.equals(name)) {
155 String transform = text.getTransform().toString();
159 return "No node found";
162 public static String getNodeText(ICanvasContext ctx, String name) {
164 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
165 for (TextNode text : texts) {
166 String nodeName = NodeUtil.getNodeName(text);
167 if (nodeName.equals(name)) {
168 String texti = text.getText();
172 return "No node found";
175 public static String getNodeCount(ICanvasContext ctx) {
176 G2DSceneGraph g2 = ctx.getSceneGraph();
177 int amount = NodeUtil.countTreeNodes(g2);
178 return "Node count: " + amount;
181 public static String getAllNodes (ICanvasContext ctx) {
183 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
184 int amount = g2.size() +1;
185 return "All nodes: " + amount;
188 public static String getBoundsNodes (ICanvasContext ctx) {
190 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
191 int amount = bn.size();
192 return "BoundsNodes: " + amount;
195 public static String getBackgroundNodes (ICanvasContext ctx) {
197 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
198 int amount = bg.size();
199 return "BackgroundNodes: " + amount;
202 public static String getDataNodes (ICanvasContext ctx) {
204 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
205 int amount = dn.size();
206 return "DataNodes: " + amount;
209 public static String getNavigationNodes (ICanvasContext ctx) {
211 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
212 int amount = g2.size();
213 return "NavigationNodes: " + amount;
216 public static String getParentNodes (ICanvasContext ctx) {
218 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
219 int amount = g2.size();
220 return "ParentNodes: " + amount;
223 public static String getDecorationNodes (ICanvasContext ctx) {
225 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
226 int amount = deco.size();
227 return "DecorationNodes: " + amount;
230 public static String getSingleElementNodes (ICanvasContext ctx) {
232 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
233 int amount = g2.size();
234 return "SingleElementNodes: " + amount;
237 public static String getConnectionNodes (ICanvasContext ctx) {
239 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
240 int amount = g2.size();
241 return "ConnectionNodes: " + amount;
244 public static String getTextNodes (ICanvasContext ctx) {
246 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
247 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
248 int amount = tn.size() + tgn.size();
249 return "TextNodes: " + amount;
252 public static String getItemNodes (ICanvasContext ctx) {
254 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
255 int amount = item.size();
256 return "ItemNodes: " + amount;
259 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
261 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
262 for (TextNode modulenode : textGridNodes) {
263 if (module.equals(modulenode.getText())) {
264 //System.out.println("Module what we were looking for: " + module);
265 //System.out.println("Modulenode: " + modulenode.getText());
267 ParentNode<?> parentnode = modulenode.getParent();
268 //System.out.println("Parentnode: " + parentnode);
270 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
271 for (TextNode valuenode : textnodes) {
272 if (previous_value.equals(valuenode.getText())) {
273 //System.out.println("Value what we were looking for: " + previous_value);
274 //System.out.println("Valuenode: " + valuenode.getText());
276 //valuenode.setEditMode(true);
277 valuenode.activateEdit(0, null, ctx);
278 valuenode.setText(new_value);
279 valuenode.fireTextEditingEnded();
281 //System.out.println("valuenode modified: " + valuenode);
282 return "Modified module " + module + " with value " + new_value;
285 return "Not found module : " + module;
288 return "No nodes in scenegraph!";
292 * Returns background color of a canvasContext or null.
294 * @return color in RGBA List<Integer> format, or null.
296 public static List<Integer> getBackgroundColor(ICanvasContext ctx) {
297 Color color = ctx.getDefaultHintContext().getHint(Hints.KEY_BACKGROUND_COLOR);
300 ArrayList<Integer> rgba = new ArrayList<>(4);
301 rgba.add(color.getRed());
302 rgba.add(color.getGreen());
303 rgba.add(color.getBlue());
304 rgba.add(color.getAlpha());
308 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
310 boolean module_founded = false;
311 boolean value_founded = false;
313 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
314 System.out.println("Total amount of nodes: " + g2.size() + 1);
316 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
317 Integer textGridNodeAmount = grid.size();
318 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
320 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
321 Integer textNodeAmount = grid.size();
322 System.out.println("Amount of TextNodes " + textNodeAmount);
324 for (TextNode node : texts) {
325 if (module.equals(node.getText())) {
326 module_founded = true;
327 System.out.println("Correct module " + module + " founded.");
329 if (value.equals(node.getText())) {
330 value_founded = true;
331 System.out.println("Correct value " + value + " founded.");
335 if (value_founded == true && module_founded == true) {
336 return "Found both correct module " + module + " and value " + value;
338 if (value_founded == false && module_founded == true) {
339 return "Found only correct module " + module + " but not value " + value;
341 if (value_founded == true && module_founded == false) {
342 return "Found only correct value " + value + " but not module " + module;
345 return "Didn't found either module " + module + " or value " + value;
349 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
351 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
353 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
355 final Collection<IElement> newSelection = new ArrayList<IElement>();
356 for (Resource module : modules) {
357 IElement element = dem.getElement(idiagram, module);
358 if (element != null) {
359 newSelection.add(element);
361 throw new DatabaseException("Could not find IElement for " + element);
365 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
368 if (source_ctx.isDisposed())
370 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
371 if (selection != null) {
372 // This prevents workbench selection from being left over.
373 // Also prevents scene graph crap from being left on the screen.
374 selection.setSelection(0, newSelection);
376 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
377 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
383 while(source_ctx.getEventQueue().size() > 0) {
386 } catch (InterruptedException e) {
387 throw new DatabaseException(e);
391 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
401 static class Generator extends SVGGraphics2D {
404 String newElementId = null;
405 ArrayList<Element> elements = new ArrayList<Element>();
407 public static final String svgNS = "http://www.w3.org/2000/svg";
409 public Generator(SVGGeneratorContext ctx, boolean textAsShapes) {
410 super(ctx, textAsShapes);
413 public Generator(Document document) {
415 // prevent batik comment in each g-element
416 getGeneratorContext().setComment(null);
420 public Element getRoot() {
421 Element root = super.getRoot();
422 for(Element e : elements) {
429 public void setRenderingHint(Key arg0, Object arg1) {
430 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
433 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
435 newElementId = arg1.toString();
437 newElementId = UUID.randomUUID().toString();
439 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
442 Element group = getDOMFactory().createElement(SVG_G_TAG);
443 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
444 group.setAttributeNS(null, "id", newElementId);
445 group.setAttributeNS(null, "class", arg1.toString());
450 super.setRenderingHint(arg0, arg1);
455 public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
459 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
460 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
461 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
463 node.render(svgGenerator);
465 } catch (Throwable t) {
466 LOGGER.error("Problems rendering scene graph to SVG", t);
469 return svgGenerator.getRoot();
472 public static String printSVGDocument(Element doce) {
474 StringBuilder result = new StringBuilder();
476 NodeList nl = doce.getChildNodes();
478 for(int i=0;i<nl.getLength();i++) {
480 ByteArrayOutputStream os = new ByteArrayOutputStream();
484 TransformerFactory tf = TransformerFactory.newInstance();
485 Transformer transformer = tf.newTransformer();
486 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
487 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
488 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
489 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
490 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
491 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
493 transformer.transform(new DOMSource(nl.item(i)),
494 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
499 } catch (Throwable t) {
500 LOGGER.error("Problems formatting SVGDocument to text.", t);
503 result.append(new String(os.toByteArray()));
507 return result.toString();
511 public static String renderSVG3(ICanvasContext ctx) {
512 return renderSVG3(ctx, -1, -1);
515 public static String renderSVG3(ICanvasContext ctx, double width, double height) {
516 return renderSVG0(width, height, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
522 * @throws DatabaseException
524 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
525 String uri = graph.getPossibleURI(component);
526 int hashCode = uri.hashCode();
527 Random random = new Random(hashCode);
528 long l1 = random.nextLong();
529 long l2 = random.nextLong();
530 return new Object[] { l1, l2 };
534 * Default no-op mapper
536 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
538 public static String renderSVG(ICanvasContext ctx, double width, double height) {
539 return renderSVG0(width, height, ctx, mapper);
542 public static String renderSVG(ICanvasContext ctx) {
543 return renderSVG(ctx, -1, -1);
546 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
547 return renderSVGMapIdentifiers(ctx, -1, -1);
551 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
557 public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
558 return renderSVG0(width, height, ctx, new Function1<Set<?>, Map<?, ?>>() {
561 public Map<?, ?> apply(Set<?> p0) {
563 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
566 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
567 ModelingResources MOD = ModelingResources.getInstance(graph);
568 DiagramResource DIA = DiagramResource.getInstance(graph);
569 Layer0 L0 = Layer0.getInstance(graph);
570 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
572 if (p instanceof Resource) {
573 Resource element = (Resource) p;
574 if (graph.isInstanceOf(element, DIA.Element)) {
575 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
576 if (component != null) {
577 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
578 if (identifier != null) {
579 return Arrays.toString(createURIBasedL0Identifier(graph, component));
581 LOGGER.error("Component {} does not have GUID identifier!", component);
583 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
584 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
585 return graph.getURI(element).hashCode();
587 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
588 if (graph.hasStatement(element, L0.HasName))
589 return graph.getURI(element).hashCode();
594 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
597 } catch (DatabaseException e) {
598 throw new RuntimeDatabaseException(e);
603 } catch (DatabaseException e) {
604 LOGGER.error("Could not apply mappings", e);
605 throw new RuntimeDatabaseException(e);
611 static class RenderSVGContext {
613 Map<String,StringBuilder> documents = new HashMap<>();
615 public void append(String[] keys, String svgText) {
616 for(String key : keys) append(key, svgText);
619 public void append(String key, String svgText) {
620 StringBuilder builder = documents.get(key);
621 if(builder == null) {
622 builder = new StringBuilder();
623 documents.put(key, builder);
625 builder.append(svgText);
628 public void append(RenderSVGContext other) {
629 for(String key : other.documents.keySet()) {
630 append(key, other.get(key));
634 public String get(String key) {
635 StringBuilder builder = documents.get(key);
636 if(builder == null) return "";
637 else return builder.toString();
642 private static String renderSVG0(double width, double height, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
644 // Get a DOMImplementation.
645 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
647 // Create an instance of org.w3c.dom.Document.
648 String svgNS = "http://www.w3.org/2000/svg";
649 Document document = domImpl.createDocument(svgNS, "svg", null);
651 // Create an instance of the SVG Generator.
652 SVGGraphics2D svgGenerator = new Generator(document);
654 RenderSVGContext result = new RenderSVGContext();
656 double[] matrix = new double[6];
659 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
660 if (selection != null) {
661 // This prevents workbench selection from being left over.
662 // Also prevents scene graph crap from being left on the screen.
663 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
664 selection.setSelection(0, d.getElements());
667 G2DSceneGraph sg = ctx.getSceneGraph();
669 G2DParentNode root = (G2DParentNode) sg.getRootNode();
671 // rtree is the actual content of the diagram
672 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
673 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
675 // get the bounds of the content
676 Rectangle2D content = rtreeBounds;
679 if (content != null) {
680 // To account for dynamic padding of selection rectangles (5 units + stroke width)
683 double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
685 AffineTransform tr = new AffineTransform();
686 tr.translate(offset, offset);
687 tr.scale(scale, scale);
688 tr.translate(-content.getX(), -content.getY());
689 tr.getMatrix(matrix);
690 svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
692 svgGenerator.setSVGCanvasSize(new Dimension(100, 100));
694 //svgGenerator.translate(offset, offset);
695 //svgGenerator.scale(scale, scale);
696 // translate svgGenerator to the x and y coordinates of current content
697 //svgGenerator.translate(-content.getX(), -content.getY());
700 //svgGenerator.setClip(content);
702 result.append(MAIN_SECTION, "<g class=\"symbols\">");
703 result.append(SELECTION_SECTION, "<g class=\"selections\">");
704 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
706 KeyVisitor keyVisitor = new KeyVisitor();
707 sg.accept(keyVisitor);
709 Set<Object> keys = keyVisitor.getKeys();
711 Map<?, ?> mappings = mappingFunction.apply(keys);
713 IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
717 } catch (Throwable t) {
718 LOGGER.error("Problems rendering canvas context to SVG", t);
722 result.append(ALL_SECTIONS, "</g>");
724 StringBuilder res = new StringBuilder();
725 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
726 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(")\">");
727 res.append(result.get(MAIN_SECTION));
728 res.append(result.get(SELECTION_SECTION));
729 res.append(result.get(SELECTION_MASK_SECTION));
731 res.append("</svg>");
733 // System.err.println(" == FINAL RESULT == ");
734 // System.err.println(res.toString());
736 return res.toString();
742 private static class KeyVisitor implements IG2DNodeVisitor {
744 private Set<Object> keys = new HashSet<>();
747 public void enter(IG2DNode node) {
748 if (node instanceof SingleElementNode) {
749 Object key = ((SingleElementNode) node).getKey();
757 public void leave(IG2DNode node) {
761 public Set<Object> getKeys() {
766 private static class PrintingVisitor implements IG2DNodeVisitor {
770 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
772 private RenderSVGContext result;
773 private SVGGraphics2D svgGenerator;
775 private Map<?, ?> mappings;
777 public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
778 this.result = result;
779 this.mappings = mappings;
780 this.svgGenerator = svgGenerator;
783 private String getKey(SingleElementNode node) {
785 if(node.getKey() != null) {
786 if (mappings.containsKey(node.getKey()))
787 key = mappings.get(node.getKey()).toString();
789 key = node.getKey().toString();
791 key = Long.toString(node.getId());
797 public void enter(IG2DNode node) {
799 RenderSVGContext parentBuilder = getParentBuilder(node);
802 if(node instanceof ConnectionNode) {
804 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
805 n.setIgnoreSelection(true);
808 String key = getKey((ConnectionNode) node);
809 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
810 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
811 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"" + OPACITY + "\" id=\"" + key + "\">");
813 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
814 String svg = printSVGDocument(doc);
815 parentBuilder.append(MAIN_SECTION, svg);
817 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
818 n.setIgnoreSelection(false);
821 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
822 svg = printSVGDocument(doc);
823 parentBuilder.append(SELECTION_SECTION, svg);
825 BasicStroke bs = new BasicStroke(10f);
827 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
828 n.setDynamicStroke(bs);
831 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
832 svg = printSVGDocument(doc);
833 parentBuilder.append(SELECTION_MASK_SECTION, svg);
835 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
836 parentBuilder.append(SELECTION_SECTION, "\n</g>");
837 parentBuilder.append(MAIN_SECTION, "\n</g>");
839 } else if (isSelection0(node)) {
841 SelectionNode n = (SelectionNode)node;
842 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
843 if(parentSEN != null) {
845 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
847 String key = getKey(parentSEN);
849 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
851 String svg = printSVGDocument(doc);
852 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
853 parentBuilder2.append(SELECTION_SECTION, svg);
854 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
855 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
856 Rectangle2D rect = n.getRect();
858 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
859 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
860 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
861 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
862 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
864 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
867 } else if (node instanceof SelectionNode) {
869 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
870 String svg = printSVGDocument(doc);
871 parentBuilder.append(MAIN_SECTION, "<g>");
872 parentBuilder.append(MAIN_SECTION, svg);
873 parentBuilder.append(MAIN_SECTION, "\n</g>");
875 } else if (node instanceof SVGNode) {
876 SVGNode svg = (SVGNode)node;
877 AffineTransform at = svg.getTransform();
878 if (!at.isIdentity()) {
879 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
880 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
881 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
883 double[] ds = new double[6];
885 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
886 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
889 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
890 if (!at.isIdentity()) {
891 parentBuilder.append(MAIN_SECTION, "\n</g>");
893 } else if (node instanceof G2DParentNode) {
894 AffineTransform at = node.getTransform();
895 if(node instanceof SingleElementNode) {
896 SingleElementNode sen = (SingleElementNode)node;
897 String key = getKey(sen);
898 String typeClass = sen.getTypeClass();
899 String clazz = "definedElement";
900 if(typeClass != null && !typeClass.isEmpty())
901 clazz = clazz + " " + typeClass;
903 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
904 senBuilders.put(sen, new RenderSVGContext());
906 if(!at.isIdentity()) {
907 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
908 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
909 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
911 double[] ds = new double[6];
913 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
914 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
917 } else if (!(node instanceof RouteGraphNode) && !(node instanceof LinkNode)){
919 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
920 NodeList gList = doc.getElementsByTagName("g");
921 if (gList.getLength() == 0)
923 boolean hasContent = false;
924 for (int i = 0; i < gList.getLength(); i++) {
925 Node gNode = gList.item(i);
926 if (gNode.hasChildNodes()) {
933 String svg = printSVGDocument(doc);
934 parentBuilder.append(MAIN_SECTION, "<g class=\"" +node.getSimpleClassName() +"\">");
935 parentBuilder.append(MAIN_SECTION, svg);
936 parentBuilder.append(MAIN_SECTION, "\n</g>");
937 } catch (Exception e) {
938 // TODO: There are nodes that do not behave well when rendered to SVG. For backwards compatibility, we don't handle the exceptions.
942 //enters.put(node, b.length());
946 private boolean isSelection0(IG2DNode node) {
948 if(node instanceof SelectionNode) {
949 SelectionNode sn = (SelectionNode)node;
950 return sn.getSelectionId() == 0;
957 private RenderSVGContext getParentBuilder(IG2DNode node) {
959 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
960 if(parentSEN instanceof G2DSceneGraph) return result;
962 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
963 if(parentBuilder == null) return result;
965 return parentBuilder;
970 public void leave(IG2DNode node) {
972 if(node instanceof ConnectionNode || node instanceof SVGNode) {
974 } else if (node instanceof G2DParentNode) {
976 RenderSVGContext parentBuilder = getParentBuilder(node);
978 if(node instanceof SingleElementNode) {
979 SingleElementNode sen = (SingleElementNode)node;
980 RenderSVGContext b = senBuilders.get(sen);
981 String content = b.get(MAIN_SECTION);
982 if(content.isEmpty()) {
983 if(sen.getKey() != null) {
985 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
989 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
990 String svg = printSVGDocument(doc);
991 parentBuilder.append(MAIN_SECTION, svg);
994 parentBuilder.append(b);
998 AffineTransform at = node.getTransform();
999 if(!at.isIdentity()) {
1000 parentBuilder.append(ALL_SECTIONS, "</g>");
1002 if(node instanceof SingleElementNode) {
1003 SingleElementNode sen = (SingleElementNode)node;
1004 //if(sen.getKey() != null) {
1005 parentBuilder.append(MAIN_SECTION, "</g>");