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.apache.batik.svggen.SVGIDGenerator;
35 import org.simantics.Simantics;
36 import org.simantics.datatypes.literal.GUID;
37 import org.simantics.db.ReadGraph;
38 import org.simantics.db.Resource;
39 import org.simantics.db.common.request.IndexRoot;
40 import org.simantics.db.common.request.ResourceRead;
41 import org.simantics.db.common.request.UnaryRead;
42 import org.simantics.db.exception.DatabaseException;
43 import org.simantics.db.exception.RuntimeDatabaseException;
44 import org.simantics.db.layer0.variable.Variables;
45 import org.simantics.diagram.elements.DecorationSVGNode;
46 import org.simantics.diagram.elements.DiagramNodeUtil;
47 import org.simantics.diagram.elements.TextGridNode;
48 import org.simantics.diagram.elements.TextNode;
49 import org.simantics.diagram.stubs.DiagramResource;
50 import org.simantics.diagram.ui.DiagramModelHints;
51 import org.simantics.g2d.canvas.Hints;
52 import org.simantics.g2d.canvas.ICanvasContext;
53 import org.simantics.g2d.diagram.DiagramHints;
54 import org.simantics.g2d.diagram.IDiagram;
55 import org.simantics.g2d.diagram.handler.DataElementMap;
56 import org.simantics.g2d.diagram.participant.ElementPainter.SelectionShapeNode;
57 import org.simantics.g2d.diagram.participant.Selection;
58 import org.simantics.g2d.element.IElement;
59 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
60 import org.simantics.g2d.utils.CanvasUtils;
61 import org.simantics.layer0.Layer0;
62 import org.simantics.scenegraph.INode;
63 import org.simantics.scenegraph.ParentNode;
64 import org.simantics.scenegraph.g2d.G2DParentNode;
65 import org.simantics.scenegraph.g2d.G2DRenderingHints;
66 import org.simantics.scenegraph.g2d.G2DSceneGraph;
67 import org.simantics.scenegraph.g2d.IG2DNode;
68 import org.simantics.scenegraph.g2d.IG2DNodeVisitor;
69 import org.simantics.scenegraph.g2d.events.command.Commands;
70 import org.simantics.scenegraph.g2d.nodes.BackgroundNode;
71 import org.simantics.scenegraph.g2d.nodes.BoundsNode;
72 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
73 import org.simantics.scenegraph.g2d.nodes.DataNode;
74 import org.simantics.scenegraph.g2d.nodes.LinkNode;
75 import org.simantics.scenegraph.g2d.nodes.NavigationNode;
76 import org.simantics.scenegraph.g2d.nodes.SVGNode;
77 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
78 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
79 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
80 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
81 import org.simantics.scenegraph.utils.NodeUtil;
82 import org.simantics.scl.runtime.function.Function1;
83 import org.simantics.scl.runtime.tuple.Tuple2;
84 import org.simantics.trend.impl.ItemNode;
85 import org.simantics.utils.threads.ThreadUtils;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
88 import org.w3c.dom.DOMImplementation;
89 import org.w3c.dom.Document;
90 import org.w3c.dom.Element;
91 import org.w3c.dom.Node;
92 import org.w3c.dom.NodeList;
94 public class SCLScenegraph {
96 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
98 private static final String MAIN_SECTION = "main";
99 private static final String SELECTION_SECTION = "selection";
100 private static final String SELECTION_MASK_SECTION = "selectionMask";
102 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
104 // Changed from 0.001 to 0.0001 to prevent creation of huge BufferedImage's when
105 // generating PDF from SVG. If SVG contains any transparency then Batik uses
106 // bitmap-rendering which remarkably slows things down
107 // See org.apache.batik.gvt.AbstractGraphicsNode.paint(Graphics2D) where decisions are made
108 // if AlphaComposite should be painted
109 private static final String OPACITY = "0.0001";
112 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
113 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
118 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
122 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
123 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
126 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
127 Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
130 public Tuple2 perform(ReadGraph graph) throws DatabaseException {
131 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
132 String diagramRVI = Variables.getRVI(graph, resource);
133 return new Tuple2(indexRoot, diagramRVI);
136 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
138 return func.apply(provider);
144 public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
145 return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
148 public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
149 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
152 public static String getNodeTransform(ICanvasContext ctx, String name) {
154 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
155 for (TextNode text : texts) {
156 String nodeName = NodeUtil.getNodeName(text);
157 if (nodeName.equals(name)) {
158 String transform = text.getTransform().toString();
162 return "No node found";
165 public static String getNodeText(ICanvasContext ctx, String name) {
167 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
168 for (TextNode text : texts) {
169 String nodeName = NodeUtil.getNodeName(text);
170 if (nodeName.equals(name)) {
171 String texti = text.getText();
175 return "No node found";
178 public static String getNodeCount(ICanvasContext ctx) {
179 G2DSceneGraph g2 = ctx.getSceneGraph();
180 int amount = NodeUtil.countTreeNodes(g2);
181 return "Node count: " + amount;
184 public static String getAllNodes (ICanvasContext ctx) {
186 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
187 int amount = g2.size() +1;
188 return "All nodes: " + amount;
191 public static String getBoundsNodes (ICanvasContext ctx) {
193 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
194 int amount = bn.size();
195 return "BoundsNodes: " + amount;
198 public static String getBackgroundNodes (ICanvasContext ctx) {
200 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
201 int amount = bg.size();
202 return "BackgroundNodes: " + amount;
205 public static String getDataNodes (ICanvasContext ctx) {
207 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
208 int amount = dn.size();
209 return "DataNodes: " + amount;
212 public static String getNavigationNodes (ICanvasContext ctx) {
214 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
215 int amount = g2.size();
216 return "NavigationNodes: " + amount;
219 public static String getParentNodes (ICanvasContext ctx) {
221 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
222 int amount = g2.size();
223 return "ParentNodes: " + amount;
226 public static String getDecorationNodes (ICanvasContext ctx) {
228 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
229 int amount = deco.size();
230 return "DecorationNodes: " + amount;
233 public static String getSingleElementNodes (ICanvasContext ctx) {
235 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
236 int amount = g2.size();
237 return "SingleElementNodes: " + amount;
240 public static String getConnectionNodes (ICanvasContext ctx) {
242 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
243 int amount = g2.size();
244 return "ConnectionNodes: " + amount;
247 public static String getTextNodes (ICanvasContext ctx) {
249 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
250 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
251 int amount = tn.size() + tgn.size();
252 return "TextNodes: " + amount;
255 public static String getItemNodes (ICanvasContext ctx) {
257 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
258 int amount = item.size();
259 return "ItemNodes: " + amount;
262 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
264 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
265 for (TextNode modulenode : textGridNodes) {
266 if (module.equals(modulenode.getText())) {
267 //System.out.println("Module what we were looking for: " + module);
268 //System.out.println("Modulenode: " + modulenode.getText());
270 ParentNode<?> parentnode = modulenode.getParent();
271 //System.out.println("Parentnode: " + parentnode);
273 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
274 for (TextNode valuenode : textnodes) {
275 if (previous_value.equals(valuenode.getText())) {
276 //System.out.println("Value what we were looking for: " + previous_value);
277 //System.out.println("Valuenode: " + valuenode.getText());
279 //valuenode.setEditMode(true);
280 valuenode.activateEdit(0, null, ctx);
281 valuenode.setText(new_value);
282 valuenode.fireTextEditingEnded();
284 //System.out.println("valuenode modified: " + valuenode);
285 return "Modified module " + module + " with value " + new_value;
288 return "Not found module : " + module;
291 return "No nodes in scenegraph!";
295 * Returns background color of a canvasContext or null.
297 * @return color in RGBA List<Integer> format, or null.
299 public static List<Integer> getBackgroundColor(ICanvasContext ctx) {
300 Color color = ctx.getDefaultHintContext().getHint(Hints.KEY_BACKGROUND_COLOR);
303 ArrayList<Integer> rgba = new ArrayList<>(4);
304 rgba.add(color.getRed());
305 rgba.add(color.getGreen());
306 rgba.add(color.getBlue());
307 rgba.add(color.getAlpha());
311 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
313 boolean module_founded = false;
314 boolean value_founded = false;
316 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
317 System.out.println("Total amount of nodes: " + g2.size() + 1);
319 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
320 Integer textGridNodeAmount = grid.size();
321 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
323 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
324 Integer textNodeAmount = grid.size();
325 System.out.println("Amount of TextNodes " + textNodeAmount);
327 for (TextNode node : texts) {
328 if (module.equals(node.getText())) {
329 module_founded = true;
330 System.out.println("Correct module " + module + " founded.");
332 if (value.equals(node.getText())) {
333 value_founded = true;
334 System.out.println("Correct value " + value + " founded.");
338 if (value_founded == true && module_founded == true) {
339 return "Found both correct module " + module + " and value " + value;
341 if (value_founded == false && module_founded == true) {
342 return "Found only correct module " + module + " but not value " + value;
344 if (value_founded == true && module_founded == false) {
345 return "Found only correct value " + value + " but not module " + module;
348 return "Didn't found either module " + module + " or value " + value;
352 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
354 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
356 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
358 final Collection<IElement> newSelection = new ArrayList<IElement>();
359 for (Resource module : modules) {
360 IElement element = dem.getElement(idiagram, module);
361 if (element != null) {
362 newSelection.add(element);
364 throw new DatabaseException("Could not find IElement for " + element);
368 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
371 if (source_ctx.isDisposed())
373 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
374 if (selection != null) {
375 // This prevents workbench selection from being left over.
376 // Also prevents scene graph crap from being left on the screen.
377 selection.setSelection(0, newSelection);
379 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
380 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
386 while(source_ctx.getEventQueue().size() > 0) {
389 } catch (InterruptedException e) {
390 throw new DatabaseException(e);
394 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
405 static class UniqueIDGenerator extends SVGIDGenerator{
408 public UniqueIDGenerator(String overallId) {
410 this.overallId = overallId;
414 public String generateID(String prefix) {
415 return super.generateID(overallId+prefix);
420 static class Generator extends SVGGraphics2D {
423 String newElementId = null;
424 ArrayList<Element> elements = new ArrayList<Element>();
426 public static final String svgNS = "http://www.w3.org/2000/svg";
428 public Generator(SVGGeneratorContext ctx, boolean textAsShapes) {
429 super(ctx, textAsShapes);
432 public Generator(Document document) {
435 public Generator(Document document, String id) {
437 // prevent batik comment in each g-element
438 getGeneratorContext().setComment(null);
440 getGeneratorContext().setIDGenerator(new UniqueIDGenerator(id));
444 public Element getRoot() {
445 Element root = super.getRoot();
446 for(Element e : elements) {
453 public void setRenderingHint(Key arg0, Object arg1) {
454 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
457 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
459 newElementId = arg1.toString();
461 newElementId = UUID.randomUUID().toString();
463 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
466 Element group = getDOMFactory().createElement(SVG_G_TAG);
467 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
468 group.setAttributeNS(null, "id", newElementId);
469 group.setAttributeNS(null, "class", arg1.toString());
474 super.setRenderingHint(arg0, arg1);
479 public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
483 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
484 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
485 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
487 node.render(svgGenerator);
489 } catch (Throwable t) {
490 LOGGER.error("Problems rendering scene graph to SVG", t);
493 return svgGenerator.getRoot();
496 public static String printSVGDocument(Element doce) {
498 StringBuilder result = new StringBuilder();
500 NodeList nl = doce.getChildNodes();
502 for(int i=0;i<nl.getLength();i++) {
504 ByteArrayOutputStream os = new ByteArrayOutputStream();
508 TransformerFactory tf = TransformerFactory.newInstance();
509 Transformer transformer = tf.newTransformer();
510 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
511 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
512 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
513 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
514 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
515 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
517 transformer.transform(new DOMSource(nl.item(i)),
518 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
523 } catch (Throwable t) {
524 LOGGER.error("Problems formatting SVGDocument to text.", t);
527 result.append(new String(os.toByteArray()));
531 return result.toString();
535 public static String renderSVG3(ICanvasContext ctx) {
536 return renderSVG3(ctx, -1, -1);
539 public static String renderSVG3(ICanvasContext ctx, double width, double height) {
540 return renderSVG0(width, height, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
546 * @throws DatabaseException
548 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
549 String uri = graph.getPossibleURI(component);
550 int hashCode = uri.hashCode();
551 Random random = new Random(hashCode);
552 long l1 = random.nextLong();
553 long l2 = random.nextLong();
554 return new Object[] { l1, l2 };
558 * Default no-op mapper
560 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
562 public static String renderSVG(ICanvasContext ctx, double width, double height) {
563 return renderSVG0(width, height, ctx, mapper);
566 public static String renderSVG(ICanvasContext ctx) {
567 return renderSVG(ctx, -1, -1);
570 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
571 return renderSVGMapIdentifiers(ctx, -1, -1);
575 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
581 public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
582 return renderSVG0(width, height, ctx, new Function1<Set<?>, Map<?, ?>>() {
585 public Map<?, ?> apply(Set<?> p0) {
587 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
590 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
591 ModelingResources MOD = ModelingResources.getInstance(graph);
592 DiagramResource DIA = DiagramResource.getInstance(graph);
593 Layer0 L0 = Layer0.getInstance(graph);
594 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
596 if (p instanceof Resource) {
597 Resource element = (Resource) p;
598 if (graph.isInstanceOf(element, DIA.Element)) {
599 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
600 if (component != null) {
601 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
602 if (identifier != null) {
603 return Arrays.toString(createURIBasedL0Identifier(graph, component));
605 LOGGER.error("Component {} does not have GUID identifier!", component);
607 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
608 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
609 return graph.getURI(element).hashCode();
611 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
612 if (graph.hasStatement(element, L0.HasName))
613 return graph.getURI(element).hashCode();
618 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
621 } catch (DatabaseException e) {
622 throw new RuntimeDatabaseException(e);
627 } catch (DatabaseException e) {
628 LOGGER.error("Could not apply mappings", e);
629 throw new RuntimeDatabaseException(e);
635 static class RenderSVGContext {
637 Map<String,StringBuilder> documents = new HashMap<>();
639 public void append(String[] keys, String svgText) {
640 for(String key : keys) append(key, svgText);
643 public void append(String key, String svgText) {
644 StringBuilder builder = documents.get(key);
645 if(builder == null) {
646 builder = new StringBuilder();
647 documents.put(key, builder);
649 builder.append(svgText);
652 public void append(RenderSVGContext other) {
653 for(String key : other.documents.keySet()) {
654 append(key, other.get(key));
658 public String get(String key) {
659 StringBuilder builder = documents.get(key);
660 if(builder == null) return "";
661 else return builder.toString();
668 private static String renderSVG0(double width, double height, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
670 // Get a DOMImplementation.
671 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
673 // Create an instance of org.w3c.dom.Document.
674 String svgNS = "http://www.w3.org/2000/svg";
675 Document document = domImpl.createDocument(svgNS, "svg", null);
677 // Create an instance of the SVG Generator.
678 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
679 Resource r = d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
680 SVGGraphics2D svgGenerator;
682 svgGenerator = new Generator(document,r.toString());
684 svgGenerator = new Generator(document);
686 RenderSVGContext result = new RenderSVGContext();
688 double[] matrix = new double[6];
691 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
692 if (selection != null) {
693 // This prevents workbench selection from being left over.
694 // Also prevents scene graph crap from being left on the screen.
695 selection.setSelection(0, d.getElements());
698 G2DSceneGraph sg = ctx.getSceneGraph();
700 G2DParentNode root = (G2DParentNode) sg.getRootNode();
702 // rtree is the actual content of the diagram
703 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
704 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
706 // get the bounds of the content
707 Rectangle2D content = rtreeBounds;
710 if (content != null) {
711 // To account for dynamic padding of selection rectangles (5 units + stroke width)
714 double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
716 AffineTransform tr = new AffineTransform();
717 tr.translate(offset, offset);
718 tr.scale(scale, scale);
719 tr.translate(-content.getX(), -content.getY());
720 tr.getMatrix(matrix);
721 svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
723 svgGenerator.setSVGCanvasSize(new Dimension(100, 100));
725 //svgGenerator.translate(offset, offset);
726 //svgGenerator.scale(scale, scale);
727 // translate svgGenerator to the x and y coordinates of current content
728 //svgGenerator.translate(-content.getX(), -content.getY());
731 //svgGenerator.setClip(content);
733 result.append(MAIN_SECTION, "<g class=\"symbols\">");
734 result.append(SELECTION_SECTION, "<g class=\"selections\">");
735 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
737 KeyVisitor keyVisitor = new KeyVisitor();
738 sg.accept(keyVisitor);
740 Set<Object> keys = keyVisitor.getKeys();
742 Map<?, ?> mappings = mappingFunction.apply(keys);
744 IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
748 } catch (Throwable t) {
749 LOGGER.error("Problems rendering canvas context to SVG", t);
753 result.append(ALL_SECTIONS, "</g>");
755 StringBuilder res = new StringBuilder();
756 if (width > 0 && height > 0 ) {
757 res.append("<svg width=\"" + width +"px\" height=\""+height+"px\" stroke=\"black\" xmlns=\"http://www.w3.org/2000/svg\">");
759 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\" xmlns=\"http://www.w3.org/2000/svg\">");
761 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(")\">");
762 res.append(result.get(MAIN_SECTION));
763 res.append(result.get(SELECTION_SECTION));
764 res.append(result.get(SELECTION_MASK_SECTION));
766 res.append("</svg>");
768 // System.err.println(" == FINAL RESULT == ");
769 // System.err.println(res.toString());
771 return res.toString();
777 private static class KeyVisitor implements IG2DNodeVisitor {
779 private Set<Object> keys = new HashSet<>();
782 public void enter(IG2DNode node) {
783 if (node instanceof SingleElementNode) {
784 Object key = ((SingleElementNode) node).getKey();
792 public void leave(IG2DNode node) {
796 public Set<Object> getKeys() {
801 private static class PrintingVisitor implements IG2DNodeVisitor {
805 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
807 private RenderSVGContext result;
808 private SVGGraphics2D svgGenerator;
810 private Map<?, ?> mappings;
812 public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
813 this.result = result;
814 this.mappings = mappings;
815 this.svgGenerator = svgGenerator;
818 private String getKey(SingleElementNode node) {
820 if(node.getKey() != null) {
821 if (mappings.containsKey(node.getKey())) {
822 key = mappings.get(node.getKey()).toString();
825 key = node.getKey().toString();
829 key = Long.toString(node.getId());
834 private String escape(String key) {
835 // Keys may contain '<' '>' characters, which causes errors in browser SVG handling.
836 return org.apache.commons.lang.StringEscapeUtils.escapeHtml(key);
839 private String removeElem(String xml, String elemStart) {
840 // FIXME: This is rather nasty and error prone way of removing elements from XML string.
841 // This only supports elements with /> end element tag. Elements ends with </elem name> are not supported!
842 int start = xml.indexOf("<"+elemStart);
844 int end = xml.indexOf(">",start);
847 return xml.substring(0,start)+xml.substring(end+1);
849 return xml.substring(end+1);
856 public void enter(IG2DNode node) {
858 RenderSVGContext parentBuilder = getParentBuilder(node);
861 if(node instanceof ConnectionNode) {
863 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
864 n.setIgnoreSelection(true);
867 String key = getKey((ConnectionNode) node);
868 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
869 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
870 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"" + OPACITY + "\" id=\"" + key + "\">");
872 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
873 String svg = printSVGDocument(doc);
874 parentBuilder.append(MAIN_SECTION, svg);
876 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
877 n.setIgnoreSelection(false);
880 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
881 svg = printSVGDocument(doc);
882 parentBuilder.append(SELECTION_SECTION, svg);
884 BasicStroke bs = new BasicStroke(10f);
886 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
887 n.setDynamicStroke(bs);
890 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
891 svg = printSVGDocument(doc);
892 parentBuilder.append(SELECTION_MASK_SECTION, svg);
894 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
895 parentBuilder.append(SELECTION_SECTION, "\n</g>");
896 senBuilders.put((ConnectionNode)node, new RenderSVGContext());
899 } else if (isSelection0(node)) {
901 SelectionNode n = (SelectionNode)node;
902 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
903 if(parentSEN != null) {
905 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
907 String key = getKey(parentSEN);
909 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
911 String svg = printSVGDocument(doc);
912 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
913 parentBuilder2.append(SELECTION_SECTION, svg);
914 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
915 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
916 Rectangle2D rect = n.getRect();
918 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
919 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
920 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
921 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
922 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
924 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
927 } else if (node instanceof SelectionNode) {
929 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
930 String svg = printSVGDocument(doc);
931 parentBuilder.append(MAIN_SECTION, "<g>");
932 parentBuilder.append(MAIN_SECTION, svg);
933 parentBuilder.append(MAIN_SECTION, "\n</g>");
935 } else if (node instanceof SVGNode) {
936 SVGNode svg = (SVGNode)node;
937 AffineTransform at = svg.getTransform();
938 if (!at.isIdentity()) {
939 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
940 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
941 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
943 double[] ds = new double[6];
945 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
946 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
949 String svgContent = svg.getSVGText();
950 // SVGNode content may contain SVG/XML elements, which break browser compatibility
951 int start = svgContent.indexOf("<svg");
953 svgContent = svgContent.substring(start);
955 String s = removeElem(svgContent, "?xml");
957 svgContent = "<g>"+s+"</g>";
958 s = removeElem(svgContent, "!DOCTYPE");
963 parentBuilder.append(MAIN_SECTION, svgContent);
964 if (!at.isIdentity()) {
965 parentBuilder.append(MAIN_SECTION, "\n</g>");
967 } else if (node instanceof G2DParentNode) {
968 AffineTransform at = node.getTransform();
969 if(node instanceof SingleElementNode) {
970 SingleElementNode sen = (SingleElementNode)node;
971 String key = getKey(sen);
972 String typeClass = sen.getTypeClass();
973 String clazz = "definedElement";
974 if(typeClass != null && !typeClass.isEmpty())
975 clazz = clazz + " " + typeClass;
977 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
978 senBuilders.put(sen, new RenderSVGContext());
980 if(!at.isIdentity()) {
981 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
982 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
983 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
985 double[] ds = new double[6];
987 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
988 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
991 } else if (node instanceof TextNode) {
992 TextNode text = (TextNode)node;
994 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
995 if(parentSEN != null) {
997 text.setShowSelection(false);
998 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
999 String svg = printSVGDocument(doc);
1000 parentBuilder.append(MAIN_SECTION, svg);
1002 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
1004 String key = getKey(parentSEN);
1005 text.setShowSelection(true);
1006 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1007 svg = printSVGDocument(doc);
1009 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
1010 parentBuilder2.append(SELECTION_SECTION, svg);
1011 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
1012 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
1013 Rectangle2D rect = text.getBounds();
1015 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
1016 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
1017 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
1018 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
1019 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
1021 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
1024 } else if (!(node instanceof RouteGraphNode) && !(node instanceof LinkNode)){
1026 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1027 NodeList gList = doc.getElementsByTagName("g");
1028 if (gList.getLength() == 0)
1030 boolean hasContent = false;
1031 for (int i = 0; i < gList.getLength(); i++) {
1032 Node gNode = gList.item(i);
1033 if (gNode.hasChildNodes()) {
1040 String svg = printSVGDocument(doc);
1041 if (node instanceof SelectionShapeNode) {
1042 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1043 if(parentSEN != null) {
1044 String key = getKey(parentSEN);
1045 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
1046 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
1047 parentBuilder2.append(SELECTION_SECTION, svg);
1048 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
1050 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
1051 Rectangle2D rect = node.getBounds();
1053 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
1054 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
1055 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
1056 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
1057 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
1059 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
1062 parentBuilder.append(MAIN_SECTION, "<g class=\"" +node.getSimpleClassName() +"\">");
1063 parentBuilder.append(MAIN_SECTION, svg);
1064 parentBuilder.append(MAIN_SECTION, "\n</g>");
1066 } catch (Exception e) {
1067 // TODO: There are nodes that do not behave well when rendered to SVG. For backwards compatibility, we don't handle the exceptions.
1071 //enters.put(node, b.length());
1075 private boolean isSelection0(IG2DNode node) {
1077 if(node instanceof SelectionNode) {
1078 SelectionNode sn = (SelectionNode)node;
1079 return sn.getSelectionId() == 0;
1086 private RenderSVGContext getParentBuilder(IG2DNode node) {
1088 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1089 if(parentSEN instanceof G2DSceneGraph) return result;
1091 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
1092 if(parentBuilder == null) return result;
1094 return parentBuilder;
1099 public void leave(IG2DNode node) {
1101 if( node instanceof SVGNode) {
1103 } else if (node instanceof ConnectionNode) {
1104 RenderSVGContext parentBuilder = getParentBuilder(node);
1105 SingleElementNode sen = (SingleElementNode)node;
1106 RenderSVGContext b = senBuilders.get(sen);
1107 String content = b.get(MAIN_SECTION);
1108 if(content.isEmpty()) {
1109 if(sen.getKey() != null) {
1111 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
1115 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1116 String svg = printSVGDocument(doc);
1117 parentBuilder.append(MAIN_SECTION, svg);
1120 parentBuilder.append(b);
1122 parentBuilder.append(MAIN_SECTION, "\n</g>");
1123 } else if (node instanceof G2DParentNode) {
1125 RenderSVGContext parentBuilder = getParentBuilder(node);
1127 if(node instanceof SingleElementNode) {
1128 SingleElementNode sen = (SingleElementNode)node;
1129 RenderSVGContext b = senBuilders.get(sen);
1130 String content = b.get(MAIN_SECTION);
1131 if(content.isEmpty()) {
1132 if(sen.getKey() != null) {
1134 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
1138 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1139 String svg = printSVGDocument(doc);
1140 parentBuilder.append(MAIN_SECTION, svg);
1143 parentBuilder.append(b);
1147 AffineTransform at = node.getTransform();
1148 if(!at.isIdentity()) {
1149 parentBuilder.append(ALL_SECTIONS, "</g>");
1151 if(node instanceof SingleElementNode) {
1152 SingleElementNode sen = (SingleElementNode)node;
1153 //if(sen.getKey() != null) {
1154 parentBuilder.append(MAIN_SECTION, "</g>");