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.ElementPainter.SelectionShapeNode;
55 import org.simantics.g2d.diagram.participant.Selection;
56 import org.simantics.g2d.element.IElement;
57 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
58 import org.simantics.g2d.utils.CanvasUtils;
59 import org.simantics.layer0.Layer0;
60 import org.simantics.scenegraph.INode;
61 import org.simantics.scenegraph.ParentNode;
62 import org.simantics.scenegraph.g2d.G2DParentNode;
63 import org.simantics.scenegraph.g2d.G2DRenderingHints;
64 import org.simantics.scenegraph.g2d.G2DSceneGraph;
65 import org.simantics.scenegraph.g2d.IG2DNode;
66 import org.simantics.scenegraph.g2d.IG2DNodeVisitor;
67 import org.simantics.scenegraph.g2d.events.command.Commands;
68 import org.simantics.scenegraph.g2d.nodes.BackgroundNode;
69 import org.simantics.scenegraph.g2d.nodes.BoundsNode;
70 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
71 import org.simantics.scenegraph.g2d.nodes.DataNode;
72 import org.simantics.scenegraph.g2d.nodes.LinkNode;
73 import org.simantics.scenegraph.g2d.nodes.NavigationNode;
74 import org.simantics.scenegraph.g2d.nodes.SVGNode;
75 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
76 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
77 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
78 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
79 import org.simantics.scenegraph.utils.NodeUtil;
80 import org.simantics.scl.runtime.function.Function1;
81 import org.simantics.scl.runtime.tuple.Tuple2;
82 import org.simantics.trend.impl.ItemNode;
83 import org.simantics.utils.threads.ThreadUtils;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86 import org.w3c.dom.DOMImplementation;
87 import org.w3c.dom.Document;
88 import org.w3c.dom.Element;
89 import org.w3c.dom.Node;
90 import org.w3c.dom.NodeList;
92 public class SCLScenegraph {
94 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
96 private static final String MAIN_SECTION = "main";
97 private static final String SELECTION_SECTION = "selection";
98 private static final String SELECTION_MASK_SECTION = "selectionMask";
100 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
102 // Changed from 0.001 to 0.0001 to prevent creation of huge BufferedImage's when
103 // generating PDF from SVG. If SVG contains any transparency then Batik uses
104 // bitmap-rendering which remarkably slows things down
105 // See org.apache.batik.gvt.AbstractGraphicsNode.paint(Graphics2D) where decisions are made
106 // if AlphaComposite should be painted
107 private static final String OPACITY = "0.0001";
110 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
111 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
116 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
120 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
121 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
124 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
125 Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
128 public Tuple2 perform(ReadGraph graph) throws DatabaseException {
129 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
130 String diagramRVI = Variables.getRVI(graph, resource);
131 return new Tuple2(indexRoot, diagramRVI);
134 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
136 return func.apply(provider);
142 public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
143 return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
146 public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
147 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
150 public static String getNodeTransform(ICanvasContext ctx, String name) {
152 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
153 for (TextNode text : texts) {
154 String nodeName = NodeUtil.getNodeName(text);
155 if (nodeName.equals(name)) {
156 String transform = text.getTransform().toString();
160 return "No node found";
163 public static String getNodeText(ICanvasContext ctx, String name) {
165 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
166 for (TextNode text : texts) {
167 String nodeName = NodeUtil.getNodeName(text);
168 if (nodeName.equals(name)) {
169 String texti = text.getText();
173 return "No node found";
176 public static String getNodeCount(ICanvasContext ctx) {
177 G2DSceneGraph g2 = ctx.getSceneGraph();
178 int amount = NodeUtil.countTreeNodes(g2);
179 return "Node count: " + amount;
182 public static String getAllNodes (ICanvasContext ctx) {
184 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
185 int amount = g2.size() +1;
186 return "All nodes: " + amount;
189 public static String getBoundsNodes (ICanvasContext ctx) {
191 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
192 int amount = bn.size();
193 return "BoundsNodes: " + amount;
196 public static String getBackgroundNodes (ICanvasContext ctx) {
198 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
199 int amount = bg.size();
200 return "BackgroundNodes: " + amount;
203 public static String getDataNodes (ICanvasContext ctx) {
205 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
206 int amount = dn.size();
207 return "DataNodes: " + amount;
210 public static String getNavigationNodes (ICanvasContext ctx) {
212 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
213 int amount = g2.size();
214 return "NavigationNodes: " + amount;
217 public static String getParentNodes (ICanvasContext ctx) {
219 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
220 int amount = g2.size();
221 return "ParentNodes: " + amount;
224 public static String getDecorationNodes (ICanvasContext ctx) {
226 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
227 int amount = deco.size();
228 return "DecorationNodes: " + amount;
231 public static String getSingleElementNodes (ICanvasContext ctx) {
233 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
234 int amount = g2.size();
235 return "SingleElementNodes: " + amount;
238 public static String getConnectionNodes (ICanvasContext ctx) {
240 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
241 int amount = g2.size();
242 return "ConnectionNodes: " + amount;
245 public static String getTextNodes (ICanvasContext ctx) {
247 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
248 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
249 int amount = tn.size() + tgn.size();
250 return "TextNodes: " + amount;
253 public static String getItemNodes (ICanvasContext ctx) {
255 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
256 int amount = item.size();
257 return "ItemNodes: " + amount;
260 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
262 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
263 for (TextNode modulenode : textGridNodes) {
264 if (module.equals(modulenode.getText())) {
265 //System.out.println("Module what we were looking for: " + module);
266 //System.out.println("Modulenode: " + modulenode.getText());
268 ParentNode<?> parentnode = modulenode.getParent();
269 //System.out.println("Parentnode: " + parentnode);
271 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
272 for (TextNode valuenode : textnodes) {
273 if (previous_value.equals(valuenode.getText())) {
274 //System.out.println("Value what we were looking for: " + previous_value);
275 //System.out.println("Valuenode: " + valuenode.getText());
277 //valuenode.setEditMode(true);
278 valuenode.activateEdit(0, null, ctx);
279 valuenode.setText(new_value);
280 valuenode.fireTextEditingEnded();
282 //System.out.println("valuenode modified: " + valuenode);
283 return "Modified module " + module + " with value " + new_value;
286 return "Not found module : " + module;
289 return "No nodes in scenegraph!";
293 * Returns background color of a canvasContext or null.
295 * @return color in RGBA List<Integer> format, or null.
297 public static List<Integer> getBackgroundColor(ICanvasContext ctx) {
298 Color color = ctx.getDefaultHintContext().getHint(Hints.KEY_BACKGROUND_COLOR);
301 ArrayList<Integer> rgba = new ArrayList<>(4);
302 rgba.add(color.getRed());
303 rgba.add(color.getGreen());
304 rgba.add(color.getBlue());
305 rgba.add(color.getAlpha());
309 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
311 boolean module_founded = false;
312 boolean value_founded = false;
314 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
315 System.out.println("Total amount of nodes: " + g2.size() + 1);
317 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
318 Integer textGridNodeAmount = grid.size();
319 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
321 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
322 Integer textNodeAmount = grid.size();
323 System.out.println("Amount of TextNodes " + textNodeAmount);
325 for (TextNode node : texts) {
326 if (module.equals(node.getText())) {
327 module_founded = true;
328 System.out.println("Correct module " + module + " founded.");
330 if (value.equals(node.getText())) {
331 value_founded = true;
332 System.out.println("Correct value " + value + " founded.");
336 if (value_founded == true && module_founded == true) {
337 return "Found both correct module " + module + " and value " + value;
339 if (value_founded == false && module_founded == true) {
340 return "Found only correct module " + module + " but not value " + value;
342 if (value_founded == true && module_founded == false) {
343 return "Found only correct value " + value + " but not module " + module;
346 return "Didn't found either module " + module + " or value " + value;
350 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
352 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
354 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
356 final Collection<IElement> newSelection = new ArrayList<IElement>();
357 for (Resource module : modules) {
358 IElement element = dem.getElement(idiagram, module);
359 if (element != null) {
360 newSelection.add(element);
362 throw new DatabaseException("Could not find IElement for " + element);
366 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
369 if (source_ctx.isDisposed())
371 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
372 if (selection != null) {
373 // This prevents workbench selection from being left over.
374 // Also prevents scene graph crap from being left on the screen.
375 selection.setSelection(0, newSelection);
377 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
378 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
384 while(source_ctx.getEventQueue().size() > 0) {
387 } catch (InterruptedException e) {
388 throw new DatabaseException(e);
392 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
402 static class Generator extends SVGGraphics2D {
405 String newElementId = null;
406 ArrayList<Element> elements = new ArrayList<Element>();
408 public static final String svgNS = "http://www.w3.org/2000/svg";
410 public Generator(SVGGeneratorContext ctx, boolean textAsShapes) {
411 super(ctx, textAsShapes);
414 public Generator(Document document) {
416 // prevent batik comment in each g-element
417 getGeneratorContext().setComment(null);
421 public Element getRoot() {
422 Element root = super.getRoot();
423 for(Element e : elements) {
430 public void setRenderingHint(Key arg0, Object arg1) {
431 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
434 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
436 newElementId = arg1.toString();
438 newElementId = UUID.randomUUID().toString();
440 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
443 Element group = getDOMFactory().createElement(SVG_G_TAG);
444 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
445 group.setAttributeNS(null, "id", newElementId);
446 group.setAttributeNS(null, "class", arg1.toString());
451 super.setRenderingHint(arg0, arg1);
456 public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
460 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
461 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
462 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
464 node.render(svgGenerator);
466 } catch (Throwable t) {
467 LOGGER.error("Problems rendering scene graph to SVG", t);
470 return svgGenerator.getRoot();
473 public static String printSVGDocument(Element doce) {
475 StringBuilder result = new StringBuilder();
477 NodeList nl = doce.getChildNodes();
479 for(int i=0;i<nl.getLength();i++) {
481 ByteArrayOutputStream os = new ByteArrayOutputStream();
485 TransformerFactory tf = TransformerFactory.newInstance();
486 Transformer transformer = tf.newTransformer();
487 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
488 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
489 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
490 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
491 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
492 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
494 transformer.transform(new DOMSource(nl.item(i)),
495 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
500 } catch (Throwable t) {
501 LOGGER.error("Problems formatting SVGDocument to text.", t);
504 result.append(new String(os.toByteArray()));
508 return result.toString();
512 public static String renderSVG3(ICanvasContext ctx) {
513 return renderSVG3(ctx, -1, -1);
516 public static String renderSVG3(ICanvasContext ctx, double width, double height) {
517 return renderSVG0(width, height, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
523 * @throws DatabaseException
525 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
526 String uri = graph.getPossibleURI(component);
527 int hashCode = uri.hashCode();
528 Random random = new Random(hashCode);
529 long l1 = random.nextLong();
530 long l2 = random.nextLong();
531 return new Object[] { l1, l2 };
535 * Default no-op mapper
537 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
539 public static String renderSVG(ICanvasContext ctx, double width, double height) {
540 return renderSVG0(width, height, ctx, mapper);
543 public static String renderSVG(ICanvasContext ctx) {
544 return renderSVG(ctx, -1, -1);
547 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
548 return renderSVGMapIdentifiers(ctx, -1, -1);
552 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
558 public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
559 return renderSVG0(width, height, ctx, new Function1<Set<?>, Map<?, ?>>() {
562 public Map<?, ?> apply(Set<?> p0) {
564 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
567 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
568 ModelingResources MOD = ModelingResources.getInstance(graph);
569 DiagramResource DIA = DiagramResource.getInstance(graph);
570 Layer0 L0 = Layer0.getInstance(graph);
571 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
573 if (p instanceof Resource) {
574 Resource element = (Resource) p;
575 if (graph.isInstanceOf(element, DIA.Element)) {
576 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
577 if (component != null) {
578 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
579 if (identifier != null) {
580 return Arrays.toString(createURIBasedL0Identifier(graph, component));
582 LOGGER.error("Component {} does not have GUID identifier!", component);
584 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
585 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
586 return graph.getURI(element).hashCode();
588 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
589 if (graph.hasStatement(element, L0.HasName))
590 return graph.getURI(element).hashCode();
595 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
598 } catch (DatabaseException e) {
599 throw new RuntimeDatabaseException(e);
604 } catch (DatabaseException e) {
605 LOGGER.error("Could not apply mappings", e);
606 throw new RuntimeDatabaseException(e);
612 static class RenderSVGContext {
614 Map<String,StringBuilder> documents = new HashMap<>();
616 public void append(String[] keys, String svgText) {
617 for(String key : keys) append(key, svgText);
620 public void append(String key, String svgText) {
621 StringBuilder builder = documents.get(key);
622 if(builder == null) {
623 builder = new StringBuilder();
624 documents.put(key, builder);
626 builder.append(svgText);
629 public void append(RenderSVGContext other) {
630 for(String key : other.documents.keySet()) {
631 append(key, other.get(key));
635 public String get(String key) {
636 StringBuilder builder = documents.get(key);
637 if(builder == null) return "";
638 else return builder.toString();
643 private static String renderSVG0(double width, double height, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
645 // Get a DOMImplementation.
646 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
648 // Create an instance of org.w3c.dom.Document.
649 String svgNS = "http://www.w3.org/2000/svg";
650 Document document = domImpl.createDocument(svgNS, "svg", null);
652 // Create an instance of the SVG Generator.
653 SVGGraphics2D svgGenerator = new Generator(document);
655 RenderSVGContext result = new RenderSVGContext();
657 double[] matrix = new double[6];
660 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
661 if (selection != null) {
662 // This prevents workbench selection from being left over.
663 // Also prevents scene graph crap from being left on the screen.
664 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
665 selection.setSelection(0, d.getElements());
668 G2DSceneGraph sg = ctx.getSceneGraph();
670 G2DParentNode root = (G2DParentNode) sg.getRootNode();
672 // rtree is the actual content of the diagram
673 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
674 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
676 // get the bounds of the content
677 Rectangle2D content = rtreeBounds;
680 if (content != null) {
681 // To account for dynamic padding of selection rectangles (5 units + stroke width)
684 double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
686 AffineTransform tr = new AffineTransform();
687 tr.translate(offset, offset);
688 tr.scale(scale, scale);
689 tr.translate(-content.getX(), -content.getY());
690 tr.getMatrix(matrix);
691 svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
693 svgGenerator.setSVGCanvasSize(new Dimension(100, 100));
695 //svgGenerator.translate(offset, offset);
696 //svgGenerator.scale(scale, scale);
697 // translate svgGenerator to the x and y coordinates of current content
698 //svgGenerator.translate(-content.getX(), -content.getY());
701 //svgGenerator.setClip(content);
703 result.append(MAIN_SECTION, "<g class=\"symbols\">");
704 result.append(SELECTION_SECTION, "<g class=\"selections\">");
705 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
707 KeyVisitor keyVisitor = new KeyVisitor();
708 sg.accept(keyVisitor);
710 Set<Object> keys = keyVisitor.getKeys();
712 Map<?, ?> mappings = mappingFunction.apply(keys);
714 IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
718 } catch (Throwable t) {
719 LOGGER.error("Problems rendering canvas context to SVG", t);
723 result.append(ALL_SECTIONS, "</g>");
725 StringBuilder res = new StringBuilder();
726 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
727 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(")\">");
728 res.append(result.get(MAIN_SECTION));
729 res.append(result.get(SELECTION_SECTION));
730 res.append(result.get(SELECTION_MASK_SECTION));
732 res.append("</svg>");
734 // System.err.println(" == FINAL RESULT == ");
735 // System.err.println(res.toString());
737 return res.toString();
743 private static class KeyVisitor implements IG2DNodeVisitor {
745 private Set<Object> keys = new HashSet<>();
748 public void enter(IG2DNode node) {
749 if (node instanceof SingleElementNode) {
750 Object key = ((SingleElementNode) node).getKey();
758 public void leave(IG2DNode node) {
762 public Set<Object> getKeys() {
767 private static class PrintingVisitor implements IG2DNodeVisitor {
771 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
773 private RenderSVGContext result;
774 private SVGGraphics2D svgGenerator;
776 private Map<?, ?> mappings;
778 public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
779 this.result = result;
780 this.mappings = mappings;
781 this.svgGenerator = svgGenerator;
784 private String getKey(SingleElementNode node) {
786 if(node.getKey() != null) {
787 if (mappings.containsKey(node.getKey()))
788 key = mappings.get(node.getKey()).toString();
790 key = node.getKey().toString();
792 key = Long.toString(node.getId());
798 public void enter(IG2DNode node) {
800 RenderSVGContext parentBuilder = getParentBuilder(node);
803 if(node instanceof ConnectionNode) {
805 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
806 n.setIgnoreSelection(true);
809 String key = getKey((ConnectionNode) node);
810 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
811 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
812 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"" + OPACITY + "\" id=\"" + key + "\">");
814 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
815 String svg = printSVGDocument(doc);
816 parentBuilder.append(MAIN_SECTION, svg);
818 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
819 n.setIgnoreSelection(false);
822 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
823 svg = printSVGDocument(doc);
824 parentBuilder.append(SELECTION_SECTION, svg);
826 BasicStroke bs = new BasicStroke(10f);
828 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
829 n.setDynamicStroke(bs);
832 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
833 svg = printSVGDocument(doc);
834 parentBuilder.append(SELECTION_MASK_SECTION, svg);
836 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
837 parentBuilder.append(SELECTION_SECTION, "\n</g>");
838 parentBuilder.append(MAIN_SECTION, "\n</g>");
840 } else if (isSelection0(node)) {
842 SelectionNode n = (SelectionNode)node;
843 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
844 if(parentSEN != null) {
846 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
848 String key = getKey(parentSEN);
850 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
852 String svg = printSVGDocument(doc);
853 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
854 parentBuilder2.append(SELECTION_SECTION, svg);
855 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
856 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
857 Rectangle2D rect = n.getRect();
859 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
860 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
861 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
862 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
863 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
865 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
868 } else if (node instanceof SelectionNode) {
870 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
871 String svg = printSVGDocument(doc);
872 parentBuilder.append(MAIN_SECTION, "<g>");
873 parentBuilder.append(MAIN_SECTION, svg);
874 parentBuilder.append(MAIN_SECTION, "\n</g>");
876 } else if (node instanceof SVGNode) {
877 SVGNode svg = (SVGNode)node;
878 AffineTransform at = svg.getTransform();
879 if (!at.isIdentity()) {
880 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
881 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
882 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
884 double[] ds = new double[6];
886 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
887 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
890 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
891 if (!at.isIdentity()) {
892 parentBuilder.append(MAIN_SECTION, "\n</g>");
894 } else if (node instanceof G2DParentNode) {
895 AffineTransform at = node.getTransform();
896 if(node instanceof SingleElementNode) {
897 SingleElementNode sen = (SingleElementNode)node;
898 String key = getKey(sen);
899 String typeClass = sen.getTypeClass();
900 String clazz = "definedElement";
901 if(typeClass != null && !typeClass.isEmpty())
902 clazz = clazz + " " + typeClass;
904 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
905 senBuilders.put(sen, new RenderSVGContext());
907 if(!at.isIdentity()) {
908 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
909 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
910 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
912 double[] ds = new double[6];
914 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
915 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
918 } else if (node instanceof TextNode) {
919 TextNode text = (TextNode)node;
921 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
922 if(parentSEN != null) {
924 text.setShowSelection(false);
925 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
926 String svg = printSVGDocument(doc);
927 parentBuilder.append(MAIN_SECTION, svg);
929 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
931 String key = getKey(parentSEN);
932 text.setShowSelection(true);
933 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
934 svg = printSVGDocument(doc);
936 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
937 parentBuilder2.append(SELECTION_SECTION, svg);
938 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
939 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
940 Rectangle2D rect = text.getBounds();
942 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
943 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
944 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
945 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
946 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
948 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
951 } else if (!(node instanceof RouteGraphNode) && !(node instanceof LinkNode)){
953 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
954 NodeList gList = doc.getElementsByTagName("g");
955 if (gList.getLength() == 0)
957 boolean hasContent = false;
958 for (int i = 0; i < gList.getLength(); i++) {
959 Node gNode = gList.item(i);
960 if (gNode.hasChildNodes()) {
967 String svg = printSVGDocument(doc);
968 if (node instanceof SelectionShapeNode) {
969 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
970 if(parentSEN != null) {
971 String key = getKey(parentSEN);
972 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
973 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
974 parentBuilder2.append(SELECTION_SECTION, svg);
975 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
977 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
978 Rectangle2D rect = node.getBounds();
980 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
981 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
982 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
983 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
984 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
986 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
989 parentBuilder.append(MAIN_SECTION, "<g class=\"" +node.getSimpleClassName() +"\">");
990 parentBuilder.append(MAIN_SECTION, svg);
991 parentBuilder.append(MAIN_SECTION, "\n</g>");
993 } catch (Exception e) {
994 // TODO: There are nodes that do not behave well when rendered to SVG. For backwards compatibility, we don't handle the exceptions.
998 //enters.put(node, b.length());
1002 private boolean isSelection0(IG2DNode node) {
1004 if(node instanceof SelectionNode) {
1005 SelectionNode sn = (SelectionNode)node;
1006 return sn.getSelectionId() == 0;
1013 private RenderSVGContext getParentBuilder(IG2DNode node) {
1015 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1016 if(parentSEN instanceof G2DSceneGraph) return result;
1018 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
1019 if(parentBuilder == null) return result;
1021 return parentBuilder;
1026 public void leave(IG2DNode node) {
1028 if(node instanceof ConnectionNode || node instanceof SVGNode) {
1030 } else if (node instanceof G2DParentNode) {
1032 RenderSVGContext parentBuilder = getParentBuilder(node);
1034 if(node instanceof SingleElementNode) {
1035 SingleElementNode sen = (SingleElementNode)node;
1036 RenderSVGContext b = senBuilders.get(sen);
1037 String content = b.get(MAIN_SECTION);
1038 if(content.isEmpty()) {
1039 if(sen.getKey() != null) {
1041 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
1045 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1046 String svg = printSVGDocument(doc);
1047 parentBuilder.append(MAIN_SECTION, svg);
1050 parentBuilder.append(b);
1054 AffineTransform at = node.getTransform();
1055 if(!at.isIdentity()) {
1056 parentBuilder.append(ALL_SECTIONS, "</g>");
1058 if(node instanceof SingleElementNode) {
1059 SingleElementNode sen = (SingleElementNode)node;
1060 //if(sen.getKey() != null) {
1061 parentBuilder.append(MAIN_SECTION, "</g>");