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.NodeList;
90 public class SCLScenegraph {
92 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
94 private static final String MAIN_SECTION = "main";
95 private static final String SELECTION_SECTION = "selection";
96 private static final String SELECTION_MASK_SECTION = "selectionMask";
98 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
100 // Changed from 0.001 to 0.0001 to prevent creation of huge BufferedImage's when
101 // generating PDF from SVG. If SVG contains any transparency then Batik uses
102 // bitmap-rendering which remarkably slows things down
103 // See org.apache.batik.gvt.AbstractGraphicsNode.paint(Graphics2D) where decisions are made
104 // if AlphaComposite should be painted
105 private static final String OPACITY = "0.0001";
108 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
109 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
114 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
118 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
119 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
122 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
123 Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
126 public Tuple2 perform(ReadGraph graph) throws DatabaseException {
127 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
128 String diagramRVI = Variables.getRVI(graph, resource);
129 return new Tuple2(indexRoot, diagramRVI);
132 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
134 return func.apply(provider);
140 public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
141 return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
144 public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
145 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
148 public static String getNodeTransform(ICanvasContext ctx, String name) {
150 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
151 for (TextNode text : texts) {
152 String nodeName = NodeUtil.getNodeName(text);
153 if (nodeName.equals(name)) {
154 String transform = text.getTransform().toString();
158 return "No node found";
161 public static String getNodeText(ICanvasContext ctx, String name) {
163 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
164 for (TextNode text : texts) {
165 String nodeName = NodeUtil.getNodeName(text);
166 if (nodeName.equals(name)) {
167 String texti = text.getText();
171 return "No node found";
174 public static String getNodeCount(ICanvasContext ctx) {
175 G2DSceneGraph g2 = ctx.getSceneGraph();
176 int amount = NodeUtil.countTreeNodes(g2);
177 return "Node count: " + amount;
180 public static String getAllNodes (ICanvasContext ctx) {
182 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
183 int amount = g2.size() +1;
184 return "All nodes: " + amount;
187 public static String getBoundsNodes (ICanvasContext ctx) {
189 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
190 int amount = bn.size();
191 return "BoundsNodes: " + amount;
194 public static String getBackgroundNodes (ICanvasContext ctx) {
196 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
197 int amount = bg.size();
198 return "BackgroundNodes: " + amount;
201 public static String getDataNodes (ICanvasContext ctx) {
203 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
204 int amount = dn.size();
205 return "DataNodes: " + amount;
208 public static String getNavigationNodes (ICanvasContext ctx) {
210 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
211 int amount = g2.size();
212 return "NavigationNodes: " + amount;
215 public static String getParentNodes (ICanvasContext ctx) {
217 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
218 int amount = g2.size();
219 return "ParentNodes: " + amount;
222 public static String getDecorationNodes (ICanvasContext ctx) {
224 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
225 int amount = deco.size();
226 return "DecorationNodes: " + amount;
229 public static String getSingleElementNodes (ICanvasContext ctx) {
231 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
232 int amount = g2.size();
233 return "SingleElementNodes: " + amount;
236 public static String getConnectionNodes (ICanvasContext ctx) {
238 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
239 int amount = g2.size();
240 return "ConnectionNodes: " + amount;
243 public static String getTextNodes (ICanvasContext ctx) {
245 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
246 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
247 int amount = tn.size() + tgn.size();
248 return "TextNodes: " + amount;
251 public static String getItemNodes (ICanvasContext ctx) {
253 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
254 int amount = item.size();
255 return "ItemNodes: " + amount;
258 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
260 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
261 for (TextNode modulenode : textGridNodes) {
262 if (module.equals(modulenode.getText())) {
263 //System.out.println("Module what we were looking for: " + module);
264 //System.out.println("Modulenode: " + modulenode.getText());
266 ParentNode<?> parentnode = modulenode.getParent();
267 //System.out.println("Parentnode: " + parentnode);
269 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
270 for (TextNode valuenode : textnodes) {
271 if (previous_value.equals(valuenode.getText())) {
272 //System.out.println("Value what we were looking for: " + previous_value);
273 //System.out.println("Valuenode: " + valuenode.getText());
275 //valuenode.setEditMode(true);
276 valuenode.activateEdit(0, null, ctx);
277 valuenode.setText(new_value);
278 valuenode.fireTextEditingEnded();
280 //System.out.println("valuenode modified: " + valuenode);
281 return "Modified module " + module + " with value " + new_value;
284 return "Not found module : " + module;
287 return "No nodes in scenegraph!";
291 * Returns background color of a canvasContext or null.
293 * @return color in RGBA List<Integer> format, or null.
295 public static List<Integer> getBackgroundColor(ICanvasContext ctx) {
296 Color color = ctx.getDefaultHintContext().getHint(Hints.KEY_BACKGROUND_COLOR);
299 ArrayList<Integer> rgba = new ArrayList<>(4);
300 rgba.add(color.getRed());
301 rgba.add(color.getGreen());
302 rgba.add(color.getBlue());
303 rgba.add(color.getAlpha());
307 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
309 boolean module_founded = false;
310 boolean value_founded = false;
312 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
313 System.out.println("Total amount of nodes: " + g2.size() + 1);
315 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
316 Integer textGridNodeAmount = grid.size();
317 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
319 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
320 Integer textNodeAmount = grid.size();
321 System.out.println("Amount of TextNodes " + textNodeAmount);
323 for (TextNode node : texts) {
324 if (module.equals(node.getText())) {
325 module_founded = true;
326 System.out.println("Correct module " + module + " founded.");
328 if (value.equals(node.getText())) {
329 value_founded = true;
330 System.out.println("Correct value " + value + " founded.");
334 if (value_founded == true && module_founded == true) {
335 return "Found both correct module " + module + " and value " + value;
337 if (value_founded == false && module_founded == true) {
338 return "Found only correct module " + module + " but not value " + value;
340 if (value_founded == true && module_founded == false) {
341 return "Found only correct value " + value + " but not module " + module;
344 return "Didn't found either module " + module + " or value " + value;
348 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
350 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
352 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
354 final Collection<IElement> newSelection = new ArrayList<IElement>();
355 for (Resource module : modules) {
356 IElement element = dem.getElement(idiagram, module);
357 if (element != null) {
358 newSelection.add(element);
360 throw new DatabaseException("Could not find IElement for " + element);
364 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
367 if (source_ctx.isDisposed())
369 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
370 if (selection != null) {
371 // This prevents workbench selection from being left over.
372 // Also prevents scene graph crap from being left on the screen.
373 selection.setSelection(0, newSelection);
375 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
376 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
382 while(source_ctx.getEventQueue().size() > 0) {
385 } catch (InterruptedException e) {
386 throw new DatabaseException(e);
390 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
400 static class Generator extends SVGGraphics2D {
403 String newElementId = null;
404 ArrayList<Element> elements = new ArrayList<Element>();
406 public static final String svgNS = "http://www.w3.org/2000/svg";
408 public Generator(SVGGeneratorContext ctx, boolean textAsShapes) {
409 super(ctx, textAsShapes);
412 public Generator(Document document) {
414 // prevent batik comment in each g-element
415 getGeneratorContext().setComment(null);
419 public Element getRoot() {
420 Element root = super.getRoot();
421 for(Element e : elements) {
428 public void setRenderingHint(Key arg0, Object arg1) {
429 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
432 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
434 newElementId = arg1.toString();
436 newElementId = UUID.randomUUID().toString();
438 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
441 Element group = getDOMFactory().createElement(SVG_G_TAG);
442 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
443 group.setAttributeNS(null, "id", newElementId);
444 group.setAttributeNS(null, "class", arg1.toString());
449 super.setRenderingHint(arg0, arg1);
454 public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
458 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
459 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
460 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
462 node.render(svgGenerator);
464 } catch (Throwable t) {
465 LOGGER.error("Problems rendering scene graph to SVG", t);
468 return svgGenerator.getRoot();
471 public static String printSVGDocument(Element doce) {
473 StringBuilder result = new StringBuilder();
475 NodeList nl = doce.getChildNodes();
477 for(int i=0;i<nl.getLength();i++) {
479 ByteArrayOutputStream os = new ByteArrayOutputStream();
483 TransformerFactory tf = TransformerFactory.newInstance();
484 Transformer transformer = tf.newTransformer();
485 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
486 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
487 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
488 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
489 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
490 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
492 transformer.transform(new DOMSource(nl.item(i)),
493 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
498 } catch (Throwable t) {
499 LOGGER.error("Problems formatting SVGDocument to text.", t);
502 result.append(new String(os.toByteArray()));
506 return result.toString();
510 public static String renderSVG3(ICanvasContext ctx) {
511 return renderSVG3(ctx, -1, -1);
514 public static String renderSVG3(ICanvasContext ctx, double width, double height) {
515 return renderSVG0(width, height, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
521 * @throws DatabaseException
523 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
524 String uri = graph.getPossibleURI(component);
525 int hashCode = uri.hashCode();
526 Random random = new Random(hashCode);
527 long l1 = random.nextLong();
528 long l2 = random.nextLong();
529 return new Object[] { l1, l2 };
533 * Default no-op mapper
535 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
537 public static String renderSVG(ICanvasContext ctx, double width, double height) {
538 return renderSVG0(width, height, ctx, mapper);
541 public static String renderSVG(ICanvasContext ctx) {
542 return renderSVG(ctx, -1, -1);
545 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
546 return renderSVGMapIdentifiers(ctx, -1, -1);
550 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
556 public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
557 return renderSVG0(width, height, ctx, new Function1<Set<?>, Map<?, ?>>() {
560 public Map<?, ?> apply(Set<?> p0) {
562 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
565 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
566 ModelingResources MOD = ModelingResources.getInstance(graph);
567 DiagramResource DIA = DiagramResource.getInstance(graph);
568 Layer0 L0 = Layer0.getInstance(graph);
569 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
571 if (p instanceof Resource) {
572 Resource element = (Resource) p;
573 if (graph.isInstanceOf(element, DIA.Element)) {
574 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
575 if (component != null) {
576 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
577 if (identifier != null) {
578 return Arrays.toString(createURIBasedL0Identifier(graph, component));
580 LOGGER.error("Component {} does not have GUID identifier!", component);
582 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
583 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
584 return graph.getURI(element).hashCode();
586 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
587 if (graph.hasStatement(element, L0.HasName))
588 return graph.getURI(element).hashCode();
593 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
596 } catch (DatabaseException e) {
597 throw new RuntimeDatabaseException(e);
602 } catch (DatabaseException e) {
603 LOGGER.error("Could not apply mappings", e);
604 throw new RuntimeDatabaseException(e);
610 static class RenderSVGContext {
612 Map<String,StringBuilder> documents = new HashMap<>();
614 public void append(String[] keys, String svgText) {
615 for(String key : keys) append(key, svgText);
618 public void append(String key, String svgText) {
619 StringBuilder builder = documents.get(key);
620 if(builder == null) {
621 builder = new StringBuilder();
622 documents.put(key, builder);
624 builder.append(svgText);
627 public void append(RenderSVGContext other) {
628 for(String key : other.documents.keySet()) {
629 append(key, other.get(key));
633 public String get(String key) {
634 StringBuilder builder = documents.get(key);
635 if(builder == null) return "";
636 else return builder.toString();
641 private static String renderSVG0(double width, double height, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
643 // Get a DOMImplementation.
644 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
646 // Create an instance of org.w3c.dom.Document.
647 String svgNS = "http://www.w3.org/2000/svg";
648 Document document = domImpl.createDocument(svgNS, "svg", null);
650 // Create an instance of the SVG Generator.
651 SVGGraphics2D svgGenerator = new Generator(document);
653 RenderSVGContext result = new RenderSVGContext();
655 double[] matrix = new double[6];
658 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
659 if (selection != null) {
660 // This prevents workbench selection from being left over.
661 // Also prevents scene graph crap from being left on the screen.
662 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
663 selection.setSelection(0, d.getElements());
666 G2DSceneGraph sg = ctx.getSceneGraph();
668 G2DParentNode root = (G2DParentNode) sg.getRootNode();
670 // rtree is the actual content of the diagram
671 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
672 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
674 // get the bounds of the content
675 Rectangle2D content = rtreeBounds;
678 if (content != null) {
679 // To account for dynamic padding of selection rectangles (5 units + stroke width)
682 double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
684 AffineTransform tr = new AffineTransform();
685 tr.translate(offset, offset);
686 tr.scale(scale, scale);
687 tr.translate(-content.getX(), -content.getY());
688 tr.getMatrix(matrix);
689 svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
691 svgGenerator.setSVGCanvasSize(new Dimension(100, 100));
693 //svgGenerator.translate(offset, offset);
694 //svgGenerator.scale(scale, scale);
695 // translate svgGenerator to the x and y coordinates of current content
696 //svgGenerator.translate(-content.getX(), -content.getY());
699 //svgGenerator.setClip(content);
701 result.append(MAIN_SECTION, "<g class=\"symbols\">");
702 result.append(SELECTION_SECTION, "<g class=\"selections\">");
703 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
705 KeyVisitor keyVisitor = new KeyVisitor();
706 sg.accept(keyVisitor);
708 Set<Object> keys = keyVisitor.getKeys();
710 Map<?, ?> mappings = mappingFunction.apply(keys);
712 IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
716 } catch (Throwable t) {
717 LOGGER.error("Problems rendering canvas context to SVG", t);
721 result.append(ALL_SECTIONS, "</g>");
723 StringBuilder res = new StringBuilder();
724 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
725 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(")\">");
726 res.append(result.get(MAIN_SECTION));
727 res.append(result.get(SELECTION_SECTION));
728 res.append(result.get(SELECTION_MASK_SECTION));
730 res.append("</svg>");
732 // System.err.println(" == FINAL RESULT == ");
733 // System.err.println(res.toString());
735 return res.toString();
741 private static class KeyVisitor implements IG2DNodeVisitor {
743 private Set<Object> keys = new HashSet<>();
746 public void enter(IG2DNode node) {
747 if (node instanceof SingleElementNode) {
748 Object key = ((SingleElementNode) node).getKey();
756 public void leave(IG2DNode node) {
760 public Set<Object> getKeys() {
765 private static class PrintingVisitor implements IG2DNodeVisitor {
769 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
771 private RenderSVGContext result;
772 private SVGGraphics2D svgGenerator;
774 private Map<?, ?> mappings;
776 public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
777 this.result = result;
778 this.mappings = mappings;
779 this.svgGenerator = svgGenerator;
782 private String getKey(SingleElementNode node) {
784 if(node.getKey() != null) {
785 if (mappings.containsKey(node.getKey()))
786 key = mappings.get(node.getKey()).toString();
788 key = node.getKey().toString();
790 key = Long.toString(node.getId());
796 public void enter(IG2DNode node) {
798 RenderSVGContext parentBuilder = getParentBuilder(node);
801 if(node instanceof ConnectionNode) {
803 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
804 n.setIgnoreSelection(true);
807 String key = getKey((ConnectionNode) node);
808 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
809 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
810 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"" + OPACITY + "\" id=\"" + key + "\">");
812 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
813 String svg = printSVGDocument(doc);
814 parentBuilder.append(MAIN_SECTION, svg);
816 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
817 n.setIgnoreSelection(false);
820 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
821 svg = printSVGDocument(doc);
822 parentBuilder.append(SELECTION_SECTION, svg);
824 BasicStroke bs = new BasicStroke(10f);
826 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
827 n.setDynamicStroke(bs);
830 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
831 svg = printSVGDocument(doc);
832 parentBuilder.append(SELECTION_MASK_SECTION, svg);
834 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
835 parentBuilder.append(SELECTION_SECTION, "\n</g>");
836 parentBuilder.append(MAIN_SECTION, "\n</g>");
838 } else if (isSelection0(node)) {
840 SelectionNode n = (SelectionNode)node;
841 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
842 if(parentSEN != null) {
844 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
846 String key = getKey(parentSEN);
848 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
850 String svg = printSVGDocument(doc);
851 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
852 parentBuilder2.append(SELECTION_SECTION, svg);
853 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
854 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
855 Rectangle2D rect = n.getRect();
857 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
858 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
859 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
860 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
861 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
863 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
866 } else if (node instanceof SelectionNode) {
868 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
869 String svg = printSVGDocument(doc);
870 parentBuilder.append(MAIN_SECTION, "<g>");
871 parentBuilder.append(MAIN_SECTION, svg);
872 parentBuilder.append(MAIN_SECTION, "\n</g>");
874 } else if (node instanceof SVGNode) {
875 SVGNode svg = (SVGNode)node;
876 AffineTransform at = svg.getTransform();
877 if (!at.isIdentity()) {
878 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
879 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
880 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
882 double[] ds = new double[6];
884 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
885 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
888 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
889 if (!at.isIdentity()) {
890 parentBuilder.append(MAIN_SECTION, "\n</g>");
892 } else if (node instanceof G2DParentNode) {
893 AffineTransform at = node.getTransform();
894 if(node instanceof SingleElementNode) {
895 SingleElementNode sen = (SingleElementNode)node;
896 String key = getKey(sen);
897 String typeClass = sen.getTypeClass();
898 String clazz = "definedElement";
899 if(typeClass != null && !typeClass.isEmpty())
900 clazz = clazz + " " + typeClass;
902 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
903 senBuilders.put(sen, new RenderSVGContext());
905 if(!at.isIdentity()) {
906 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
907 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
908 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
910 double[] ds = new double[6];
912 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
913 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
916 } else if (!(node instanceof RouteGraphNode) && !(node instanceof LinkNode)){
918 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
919 if (doc.getElementsByTagName("g").getLength() == 0)
921 String svg = printSVGDocument(doc);
922 parentBuilder.append(MAIN_SECTION, "<g>");
923 parentBuilder.append(MAIN_SECTION, svg);
924 parentBuilder.append(MAIN_SECTION, "\n</g>");
925 } catch (Exception e) {
926 // TODO: There are nodes that do not behave well when rendered to SVG. For backwards compatibility, we don't handle the exceptions.
930 //enters.put(node, b.length());
934 private boolean isSelection0(IG2DNode node) {
936 if(node instanceof SelectionNode) {
937 SelectionNode sn = (SelectionNode)node;
938 return sn.getSelectionId() == 0;
945 private RenderSVGContext getParentBuilder(IG2DNode node) {
947 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
948 if(parentSEN instanceof G2DSceneGraph) return result;
950 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
951 if(parentBuilder == null) return result;
953 return parentBuilder;
958 public void leave(IG2DNode node) {
960 if(node instanceof ConnectionNode || node instanceof SVGNode) {
962 } else if (node instanceof G2DParentNode) {
964 RenderSVGContext parentBuilder = getParentBuilder(node);
966 if(node instanceof SingleElementNode) {
967 SingleElementNode sen = (SingleElementNode)node;
968 RenderSVGContext b = senBuilders.get(sen);
969 String content = b.get(MAIN_SECTION);
970 if(content.isEmpty()) {
971 if(sen.getKey() != null) {
973 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
977 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
978 String svg = printSVGDocument(doc);
979 parentBuilder.append(MAIN_SECTION, svg);
982 parentBuilder.append(b);
986 AffineTransform at = node.getTransform();
987 if(!at.isIdentity()) {
988 parentBuilder.append(ALL_SECTIONS, "</g>");
990 if(node instanceof SingleElementNode) {
991 SingleElementNode sen = (SingleElementNode)node;
992 //if(sen.getKey() != null) {
993 parentBuilder.append(MAIN_SECTION, "</g>");