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.eclipse.swt.SWT;
36 import org.simantics.Simantics;
37 import org.simantics.datatypes.literal.GUID;
38 import org.simantics.db.ReadGraph;
39 import org.simantics.db.Resource;
40 import org.simantics.db.common.request.IndexRoot;
41 import org.simantics.db.common.request.ResourceRead;
42 import org.simantics.db.common.request.UnaryRead;
43 import org.simantics.db.exception.DatabaseException;
44 import org.simantics.db.exception.RuntimeDatabaseException;
45 import org.simantics.db.layer0.variable.Variables;
46 import org.simantics.diagram.elements.DecorationSVGNode;
47 import org.simantics.diagram.elements.DiagramNodeUtil;
48 import org.simantics.diagram.elements.TextGridNode;
49 import org.simantics.diagram.elements.TextNode;
50 import org.simantics.diagram.stubs.DiagramResource;
51 import org.simantics.diagram.ui.DiagramModelHints;
52 import org.simantics.g2d.canvas.Hints;
53 import org.simantics.g2d.canvas.ICanvasContext;
54 import org.simantics.g2d.diagram.DiagramHints;
55 import org.simantics.g2d.diagram.IDiagram;
56 import org.simantics.g2d.diagram.handler.DataElementMap;
57 import org.simantics.g2d.diagram.participant.ElementPainter.SelectionShapeNode;
58 import org.simantics.g2d.diagram.participant.Selection;
59 import org.simantics.g2d.element.IElement;
60 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
61 import org.simantics.g2d.utils.CanvasUtils;
62 import org.simantics.layer0.Layer0;
63 import org.simantics.scenegraph.INode;
64 import org.simantics.scenegraph.ParentNode;
65 import org.simantics.scenegraph.g2d.G2DParentNode;
66 import org.simantics.scenegraph.g2d.G2DRenderingHints;
67 import org.simantics.scenegraph.g2d.G2DSceneGraph;
68 import org.simantics.scenegraph.g2d.IG2DNode;
69 import org.simantics.scenegraph.g2d.IG2DNodeVisitor;
70 import org.simantics.scenegraph.g2d.events.command.Commands;
71 import org.simantics.scenegraph.g2d.nodes.BackgroundNode;
72 import org.simantics.scenegraph.g2d.nodes.BoundsNode;
73 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
74 import org.simantics.scenegraph.g2d.nodes.DataNode;
75 import org.simantics.scenegraph.g2d.nodes.LinkNode;
76 import org.simantics.scenegraph.g2d.nodes.NavigationNode;
77 import org.simantics.scenegraph.g2d.nodes.SVGNode;
78 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
79 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
80 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
81 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
82 import org.simantics.scenegraph.utils.NodeUtil;
83 import org.simantics.scl.runtime.function.Function1;
84 import org.simantics.scl.runtime.tuple.Tuple2;
85 import org.simantics.trend.impl.ItemNode;
86 import org.simantics.utils.threads.ThreadUtils;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89 import org.w3c.dom.DOMImplementation;
90 import org.w3c.dom.Document;
91 import org.w3c.dom.Element;
92 import org.w3c.dom.Node;
93 import org.w3c.dom.NodeList;
95 public class SCLScenegraph {
97 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
99 private static final String MAIN_SECTION = "main";
100 private static final String SELECTION_SECTION = "selection";
101 private static final String SELECTION_MASK_SECTION = "selectionMask";
103 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
105 // Changed from 0.001 to 0.0001 to prevent creation of huge BufferedImage's when
106 // generating PDF from SVG. If SVG contains any transparency then Batik uses
107 // bitmap-rendering which remarkably slows things down
108 // See org.apache.batik.gvt.AbstractGraphicsNode.paint(Graphics2D) where decisions are made
109 // if AlphaComposite should be painted
110 private static final String OPACITY = "0.0001";
113 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
114 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
119 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
123 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
124 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
127 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
128 Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
131 public Tuple2 perform(ReadGraph graph) throws DatabaseException {
132 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
133 String diagramRVI = Variables.getRVI(graph, resource);
134 return new Tuple2(indexRoot, diagramRVI);
137 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
139 return func.apply(provider);
145 public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
146 return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
149 public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
150 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
153 public static String getNodeTransform(ICanvasContext ctx, String name) {
155 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
156 for (TextNode text : texts) {
157 String nodeName = NodeUtil.getNodeName(text);
158 if (nodeName.equals(name)) {
159 String transform = text.getTransform().toString();
163 return "No node found";
166 public static String getNodeText(ICanvasContext ctx, String name) {
168 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
169 for (TextNode text : texts) {
170 String nodeName = NodeUtil.getNodeName(text);
171 if (nodeName.equals(name)) {
172 String texti = text.getText();
176 return "No node found";
179 public static String getNodeCount(ICanvasContext ctx) {
180 G2DSceneGraph g2 = ctx.getSceneGraph();
181 int amount = NodeUtil.countTreeNodes(g2);
182 return "Node count: " + amount;
185 public static String getAllNodes (ICanvasContext ctx) {
187 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
188 int amount = g2.size() +1;
189 return "All nodes: " + amount;
192 public static String getBoundsNodes (ICanvasContext ctx) {
194 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
195 int amount = bn.size();
196 return "BoundsNodes: " + amount;
199 public static String getBackgroundNodes (ICanvasContext ctx) {
201 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
202 int amount = bg.size();
203 return "BackgroundNodes: " + amount;
206 public static String getDataNodes (ICanvasContext ctx) {
208 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
209 int amount = dn.size();
210 return "DataNodes: " + amount;
213 public static String getNavigationNodes (ICanvasContext ctx) {
215 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
216 int amount = g2.size();
217 return "NavigationNodes: " + amount;
220 public static String getParentNodes (ICanvasContext ctx) {
222 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
223 int amount = g2.size();
224 return "ParentNodes: " + amount;
227 public static String getDecorationNodes (ICanvasContext ctx) {
229 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
230 int amount = deco.size();
231 return "DecorationNodes: " + amount;
234 public static String getSingleElementNodes (ICanvasContext ctx) {
236 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
237 int amount = g2.size();
238 return "SingleElementNodes: " + amount;
241 public static String getConnectionNodes (ICanvasContext ctx) {
243 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
244 int amount = g2.size();
245 return "ConnectionNodes: " + amount;
248 public static String getTextNodes (ICanvasContext ctx) {
250 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
251 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
252 int amount = tn.size() + tgn.size();
253 return "TextNodes: " + amount;
256 public static String getItemNodes (ICanvasContext ctx) {
258 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
259 int amount = item.size();
260 return "ItemNodes: " + amount;
263 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
265 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
266 for (TextNode modulenode : textGridNodes) {
267 if (module.equals(modulenode.getText())) {
268 //System.out.println("Module what we were looking for: " + module);
269 //System.out.println("Modulenode: " + modulenode.getText());
271 ParentNode<?> parentnode = modulenode.getParent();
272 //System.out.println("Parentnode: " + parentnode);
274 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
275 for (TextNode valuenode : textnodes) {
276 if (previous_value.equals(valuenode.getText())) {
277 //System.out.println("Value what we were looking for: " + previous_value);
278 //System.out.println("Valuenode: " + valuenode.getText());
280 //valuenode.setEditMode(true);
281 valuenode.activateEdit(0, null, ctx);
282 valuenode.setText(new_value);
283 valuenode.fireTextEditingEnded();
285 //System.out.println("valuenode modified: " + valuenode);
286 return "Modified module " + module + " with value " + new_value;
289 return "Not found module : " + module;
292 return "No nodes in scenegraph!";
296 * Returns background color of a canvasContext or null.
298 * @return color in RGBA List<Integer> format, or null.
300 public static List<Integer> getBackgroundColor(ICanvasContext ctx) {
301 Color color = ctx.getDefaultHintContext().getHint(Hints.KEY_BACKGROUND_COLOR);
304 ArrayList<Integer> rgba = new ArrayList<>(4);
305 rgba.add(color.getRed());
306 rgba.add(color.getGreen());
307 rgba.add(color.getBlue());
308 rgba.add(color.getAlpha());
312 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
314 boolean module_founded = false;
315 boolean value_founded = false;
317 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
318 System.out.println("Total amount of nodes: " + g2.size() + 1);
320 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
321 Integer textGridNodeAmount = grid.size();
322 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
324 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
325 Integer textNodeAmount = grid.size();
326 System.out.println("Amount of TextNodes " + textNodeAmount);
328 for (TextNode node : texts) {
329 if (module.equals(node.getText())) {
330 module_founded = true;
331 System.out.println("Correct module " + module + " founded.");
333 if (value.equals(node.getText())) {
334 value_founded = true;
335 System.out.println("Correct value " + value + " founded.");
339 if (value_founded == true && module_founded == true) {
340 return "Found both correct module " + module + " and value " + value;
342 if (value_founded == false && module_founded == true) {
343 return "Found only correct module " + module + " but not value " + value;
345 if (value_founded == true && module_founded == false) {
346 return "Found only correct value " + value + " but not module " + module;
349 return "Didn't found either module " + module + " or value " + value;
353 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
355 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
357 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
359 final Collection<IElement> newSelection = new ArrayList<IElement>();
360 for (Resource module : modules) {
361 IElement element = dem.getElement(idiagram, module);
362 if (element != null) {
363 newSelection.add(element);
365 throw new DatabaseException("Could not find IElement for " + element);
369 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
372 if (source_ctx.isDisposed())
374 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
375 if (selection != null) {
376 // This prevents workbench selection from being left over.
377 // Also prevents scene graph crap from being left on the screen.
378 selection.setSelection(0, newSelection);
380 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
381 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
387 while(source_ctx.getEventQueue().size() > 0) {
390 } catch (InterruptedException e) {
391 throw new DatabaseException(e);
395 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
406 static class UniqueIDGenerator extends SVGIDGenerator{
409 public UniqueIDGenerator(String overallId) {
411 this.overallId = overallId;
415 public String generateID(String prefix) {
416 return super.generateID(overallId+prefix);
421 static class Generator extends SVGGraphics2D {
424 String newElementId = null;
425 ArrayList<Element> elements = new ArrayList<Element>();
427 public static final String svgNS = "http://www.w3.org/2000/svg";
429 public Generator(SVGGeneratorContext ctx, boolean textAsShapes) {
430 super(ctx, textAsShapes);
433 public Generator(Document document) {
436 public Generator(Document document, String id) {
438 // prevent batik comment in each g-element
439 getGeneratorContext().setComment(null);
441 getGeneratorContext().setIDGenerator(new UniqueIDGenerator(id));
445 public Element getRoot() {
446 Element root = super.getRoot();
447 for(Element e : elements) {
454 public void setRenderingHint(Key arg0, Object arg1) {
455 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
458 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
460 newElementId = arg1.toString();
462 newElementId = UUID.randomUUID().toString();
464 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
467 Element group = getDOMFactory().createElement(SVG_G_TAG);
468 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
469 group.setAttributeNS(null, "id", newElementId);
470 group.setAttributeNS(null, "class", arg1.toString());
475 super.setRenderingHint(arg0, arg1);
480 public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
484 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
485 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
486 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
488 node.render(svgGenerator);
490 } catch (Throwable t) {
491 LOGGER.error("Problems rendering scene graph to SVG", t);
494 return svgGenerator.getRoot();
497 public static String printSVGDocument(Element doce) {
499 StringBuilder result = new StringBuilder();
501 NodeList nl = doce.getChildNodes();
503 for(int i=0;i<nl.getLength();i++) {
505 ByteArrayOutputStream os = new ByteArrayOutputStream();
509 TransformerFactory tf = TransformerFactory.newInstance();
510 Transformer transformer = tf.newTransformer();
511 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
512 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
513 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
514 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
515 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
516 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
518 transformer.transform(new DOMSource(nl.item(i)),
519 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
524 } catch (Throwable t) {
525 LOGGER.error("Problems formatting SVGDocument to text.", t);
528 result.append(new String(os.toByteArray()));
532 return result.toString();
536 public static String renderSVG3(ICanvasContext ctx) {
537 return renderSVG3(ctx, -1, -1);
540 public static String renderSVG3(ICanvasContext ctx, double width, double height) {
541 return renderSVG0(width, height, SWT.LEFT, SWT.TOP, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
547 * @throws DatabaseException
549 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
550 String uri = graph.getPossibleURI(component);
551 int hashCode = uri.hashCode();
552 Random random = new Random(hashCode);
553 long l1 = random.nextLong();
554 long l2 = random.nextLong();
555 return new Object[] { l1, l2 };
559 * Default no-op mapper
561 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
565 * Renders CanvasContext to SVG.
567 * @param width Width of output image. Use -1 for autosize.
568 * @param height Height of output image. Use -1 for autosize.
569 * @param ax horizontal alignment. SWT.LEFT SWT.CENTER SWT.RIGHT are accepted values. Value is not used with autosize.
570 * @param ay vertical alignment. SWT.TOP SWT.CENTER SWT.BOTTOM are accepted values. Value is not used with autosize.
573 public static String renderSVG(ICanvasContext ctx, double width, double height, int ax, int ay) {
574 return renderSVG0(width, height, ax, ay, ctx, mapper);
577 public static String renderSVG(ICanvasContext ctx, double width, double height) {
578 return renderSVG(ctx,width,height, SWT.LEFT, SWT.TOP);
581 public static String renderSVG(ICanvasContext ctx) {
582 return renderSVG(ctx, -1, -1, SWT.LEFT, SWT.TOP);
585 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
586 return renderSVGMapIdentifiers(ctx, -1, -1);
590 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
596 public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
597 return renderSVG0(width, height, SWT.LEFT, SWT.TOP, ctx, new Function1<Set<?>, Map<?, ?>>() {
600 public Map<?, ?> apply(Set<?> p0) {
602 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
605 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
606 ModelingResources MOD = ModelingResources.getInstance(graph);
607 DiagramResource DIA = DiagramResource.getInstance(graph);
608 Layer0 L0 = Layer0.getInstance(graph);
609 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
611 if (p instanceof Resource) {
612 Resource element = (Resource) p;
613 if (graph.isInstanceOf(element, DIA.Element)) {
614 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
615 if (component != null) {
616 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
617 if (identifier != null) {
618 return Arrays.toString(createURIBasedL0Identifier(graph, component));
620 LOGGER.error("Component {} does not have GUID identifier!", component);
622 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
623 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
624 return graph.getURI(element).hashCode();
626 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
627 if (graph.hasStatement(element, L0.HasName))
628 return graph.getURI(element).hashCode();
633 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
636 } catch (DatabaseException e) {
637 throw new RuntimeDatabaseException(e);
642 } catch (DatabaseException e) {
643 LOGGER.error("Could not apply mappings", e);
644 throw new RuntimeDatabaseException(e);
650 static class RenderSVGContext {
652 Map<String,StringBuilder> documents = new HashMap<>();
654 public void append(String[] keys, String svgText) {
655 for(String key : keys) append(key, svgText);
658 public void append(String key, String svgText) {
659 StringBuilder builder = documents.get(key);
660 if(builder == null) {
661 builder = new StringBuilder();
662 documents.put(key, builder);
664 builder.append(svgText);
667 public void append(RenderSVGContext other) {
668 for(String key : other.documents.keySet()) {
669 append(key, other.get(key));
673 public String get(String key) {
674 StringBuilder builder = documents.get(key);
675 if(builder == null) return "";
676 else return builder.toString();
683 private static String renderSVG0(double width, double height, int ax, int ay, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
685 // Get a DOMImplementation.
686 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
688 // Create an instance of org.w3c.dom.Document.
689 String svgNS = "http://www.w3.org/2000/svg";
690 Document document = domImpl.createDocument(svgNS, "svg", null);
692 // Create an instance of the SVG Generator.
693 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
694 Resource r = d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
695 SVGGraphics2D svgGenerator;
697 svgGenerator = new Generator(document,r.toString());
699 svgGenerator = new Generator(document);
701 RenderSVGContext result = new RenderSVGContext();
703 double[] matrix = new double[6];
706 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
707 if (selection != null) {
708 // This prevents workbench selection from being left over.
709 // Also prevents scene graph crap from being left on the screen.
710 selection.setSelection(0, d.getElements());
713 G2DSceneGraph sg = ctx.getSceneGraph();
715 G2DParentNode root = (G2DParentNode) sg.getRootNode();
717 // rtree is the actual content of the diagram
718 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
719 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
721 // get the bounds of the content
722 Rectangle2D content = rtreeBounds;
724 // int ax = SWT.LEFT;
726 // int ax = SWT.CENTER;
727 // int ay = SWT.CENTER;
729 if (content != null) {
730 // To account for dynamic padding of selection rectangles (5 units + stroke width)
733 double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
735 AffineTransform tr = new AffineTransform();
736 tr.translate(offset, offset);
737 tr.scale(scale, scale);
738 double dx = -content.getX();
739 double dy = -content.getY();
740 if (width > 0.0 && height > 0.0) {
741 if (ax == SWT.LEFT) {
742 dx = -content.getX();
743 } else if (ax == SWT.RIGHT) {
744 double t = ((width - 2*offset)/scale - content.getWidth());
745 dx = -content.getX() + t;
747 double t = ((width - 2*offset)/scale - content.getWidth()) *0.5;
748 dx = -content.getX() + t;
751 dy = -content.getY();
752 } else if (ay == SWT.BOTTOM) {
753 double t = ((height - 2*offset)/scale - content.getHeight());
754 dy = -content.getY() + t;
756 double t = ((height - 2*offset)/scale - content.getHeight()) * 0.5;
757 dy = -content.getY() + t;
760 tr.translate(dx, dy);
761 tr.getMatrix(matrix);
762 svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
764 svgGenerator.setSVGCanvasSize(new Dimension(100, 100));
766 //svgGenerator.translate(offset, offset);
767 //svgGenerator.scale(scale, scale);
768 // translate svgGenerator to the x and y coordinates of current content
769 //svgGenerator.translate(-content.getX(), -content.getY());
772 //svgGenerator.setClip(content);
774 result.append(MAIN_SECTION, "<g class=\"symbols\">");
775 result.append(SELECTION_SECTION, "<g class=\"selections\">");
776 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
778 KeyVisitor keyVisitor = new KeyVisitor();
779 sg.accept(keyVisitor);
781 Set<Object> keys = keyVisitor.getKeys();
783 Map<?, ?> mappings = mappingFunction.apply(keys);
785 IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
789 } catch (Throwable t) {
790 LOGGER.error("Problems rendering canvas context to SVG", t);
794 result.append(ALL_SECTIONS, "</g>");
796 StringBuilder res = new StringBuilder();
797 if (width > 0 && height > 0 ) {
798 res.append("<svg width=\"" + width +"px\" height=\""+height+"px\" stroke=\"black\" xmlns=\"http://www.w3.org/2000/svg\">");
800 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\" xmlns=\"http://www.w3.org/2000/svg\">");
802 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(")\">");
803 res.append(result.get(MAIN_SECTION));
804 res.append(result.get(SELECTION_SECTION));
805 res.append(result.get(SELECTION_MASK_SECTION));
807 res.append("</svg>");
809 // System.err.println(" == FINAL RESULT == ");
810 // System.err.println(res.toString());
812 return res.toString();
818 private static class KeyVisitor implements IG2DNodeVisitor {
820 private Set<Object> keys = new HashSet<>();
823 public void enter(IG2DNode node) {
824 if (node instanceof SingleElementNode) {
825 Object key = ((SingleElementNode) node).getKey();
833 public void leave(IG2DNode node) {
837 public Set<Object> getKeys() {
842 private static class PrintingVisitor implements IG2DNodeVisitor {
846 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
848 private RenderSVGContext result;
849 private SVGGraphics2D svgGenerator;
851 private Map<?, ?> mappings;
853 public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
854 this.result = result;
855 this.mappings = mappings;
856 this.svgGenerator = svgGenerator;
859 private String getKey(SingleElementNode node) {
861 if(node.getKey() != null) {
862 if (mappings.containsKey(node.getKey())) {
863 key = mappings.get(node.getKey()).toString();
866 key = node.getKey().toString();
870 key = Long.toString(node.getId());
875 private String escape(String key) {
876 // Keys may contain '<' '>' characters, which causes errors in browser SVG handling.
877 return org.apache.commons.lang.StringEscapeUtils.escapeHtml(key);
880 private String removeElem(String xml, String elemStart) {
881 // FIXME: This is rather nasty and error prone way of removing elements from XML string.
882 // This only supports elements with /> end element tag. Elements ends with </elem name> are not supported!
883 int start = xml.indexOf("<"+elemStart);
885 int end = xml.indexOf(">",start);
888 return xml.substring(0,start)+xml.substring(end+1);
890 return xml.substring(end+1);
897 public void enter(IG2DNode node) {
899 RenderSVGContext parentBuilder = getParentBuilder(node);
902 if(node instanceof ConnectionNode) {
904 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
905 n.setIgnoreSelection(true);
908 String key = getKey((ConnectionNode) node);
909 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
910 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
911 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"" + OPACITY + "\" id=\"" + key + "\">");
913 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
914 String svg = printSVGDocument(doc);
915 parentBuilder.append(MAIN_SECTION, svg);
917 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
918 n.setIgnoreSelection(false);
921 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
922 svg = printSVGDocument(doc);
923 parentBuilder.append(SELECTION_SECTION, svg);
925 BasicStroke bs = new BasicStroke(10f);
927 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
928 n.setDynamicStroke(bs);
931 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
932 svg = printSVGDocument(doc);
933 parentBuilder.append(SELECTION_MASK_SECTION, svg);
935 senBuilders.put((ConnectionNode)node, new RenderSVGContext());
938 } else if (isSelection0(node)) {
940 SelectionNode n = (SelectionNode)node;
941 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
942 if(parentSEN != null) {
944 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
946 String key = getKey(parentSEN);
948 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
950 String svg = printSVGDocument(doc);
951 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
952 parentBuilder2.append(SELECTION_SECTION, svg);
953 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
954 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
955 Rectangle2D rect = n.getRect();
957 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
958 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
959 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
960 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
961 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
963 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
966 } else if (node instanceof SelectionNode) {
968 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
969 String svg = printSVGDocument(doc);
970 parentBuilder.append(MAIN_SECTION, "<g>");
971 parentBuilder.append(MAIN_SECTION, svg);
972 parentBuilder.append(MAIN_SECTION, "\n</g>");
974 } else if (node instanceof SVGNode) {
975 SVGNode svg = (SVGNode)node;
976 AffineTransform at = svg.getTransform();
977 if (!at.isIdentity()) {
978 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
979 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
980 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
982 double[] ds = new double[6];
984 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
985 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
988 String svgContent = svg.getSVGText();
989 // SVGNode content may contain SVG/XML elements, which break browser compatibility
990 int start = svgContent.indexOf("<svg");
992 svgContent = svgContent.substring(start);
994 String s = removeElem(svgContent, "?xml");
996 svgContent = "<g>"+s+"</g>";
997 s = removeElem(svgContent, "!DOCTYPE");
1002 parentBuilder.append(MAIN_SECTION, svgContent);
1003 if (!at.isIdentity()) {
1004 parentBuilder.append(MAIN_SECTION, "\n</g>");
1006 } else if (node instanceof G2DParentNode) {
1007 AffineTransform at = node.getTransform();
1008 if(node instanceof SingleElementNode) {
1009 SingleElementNode sen = (SingleElementNode)node;
1010 String key = getKey(sen);
1011 String typeClass = sen.getTypeClass();
1012 String clazz = "definedElement";
1013 if(typeClass != null && !typeClass.isEmpty())
1014 clazz = clazz + " " + typeClass;
1016 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
1017 senBuilders.put(sen, new RenderSVGContext());
1019 if(!at.isIdentity()) {
1020 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
1021 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
1022 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
1024 double[] ds = new double[6];
1026 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
1027 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
1030 } else if (node instanceof TextNode) {
1031 TextNode text = (TextNode)node;
1033 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1034 if(parentSEN != null) {
1036 text.setShowSelection(false);
1037 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1038 String svg = printSVGDocument(doc);
1039 parentBuilder.append(MAIN_SECTION, svg);
1041 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
1043 String key = getKey(parentSEN);
1044 text.setShowSelection(true);
1045 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1046 svg = printSVGDocument(doc);
1048 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
1049 parentBuilder2.append(SELECTION_SECTION, svg);
1050 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
1051 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
1052 Rectangle2D rect = text.getBounds();
1054 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
1055 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
1056 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
1057 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
1058 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
1060 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
1063 } else if (!(node instanceof RouteGraphNode) && !(node instanceof LinkNode)){
1065 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1066 NodeList gList = doc.getElementsByTagName("g");
1067 if (gList.getLength() == 0)
1069 boolean hasContent = false;
1070 for (int i = 0; i < gList.getLength(); i++) {
1071 Node gNode = gList.item(i);
1072 if (gNode.hasChildNodes()) {
1079 String svg = printSVGDocument(doc);
1080 if (node instanceof SelectionShapeNode) {
1081 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1082 if(parentSEN != null) {
1083 String key = getKey(parentSEN);
1084 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
1085 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
1086 parentBuilder2.append(SELECTION_SECTION, svg);
1087 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
1089 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
1090 Rectangle2D rect = node.getBounds();
1092 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
1093 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
1094 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
1095 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
1096 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
1098 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
1101 parentBuilder.append(MAIN_SECTION, "<g class=\"" +node.getSimpleClassName() +"\">");
1102 parentBuilder.append(MAIN_SECTION, svg);
1103 parentBuilder.append(MAIN_SECTION, "\n</g>");
1105 } catch (Exception e) {
1106 // TODO: There are nodes that do not behave well when rendered to SVG. For backwards compatibility, we don't handle the exceptions.
1110 //enters.put(node, b.length());
1114 private boolean isSelection0(IG2DNode node) {
1116 if(node instanceof SelectionNode) {
1117 SelectionNode sn = (SelectionNode)node;
1118 return sn.getSelectionId() == 0;
1125 private RenderSVGContext getParentBuilder(IG2DNode node) {
1127 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
1128 if(parentSEN instanceof G2DSceneGraph) return result;
1130 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
1131 if(parentBuilder == null) return result;
1133 return parentBuilder;
1138 public void leave(IG2DNode node) {
1140 if( node instanceof SVGNode) {
1142 } else if (node instanceof ConnectionNode) {
1143 RenderSVGContext parentBuilder = getParentBuilder(node);
1144 SingleElementNode sen = (SingleElementNode)node;
1145 RenderSVGContext b = senBuilders.get(sen);
1146 String content = b.get(MAIN_SECTION);
1147 if(content.isEmpty()) {
1148 // Handling connection the same way as SingleElementNode would draw connection twice..
1149 // if(sen.getKey() != null) {
1151 // for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
1152 // n.setIgnore(true);
1155 // Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1156 // String svg = printSVGDocument(doc);
1157 // parentBuilder.append(MAIN_SECTION, svg);
1160 parentBuilder.append(b);
1162 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
1163 parentBuilder.append(SELECTION_SECTION, "\n</g>");
1164 parentBuilder.append(MAIN_SECTION, "\n</g>");
1166 } else if (node instanceof G2DParentNode) {
1168 RenderSVGContext parentBuilder = getParentBuilder(node);
1170 if(node instanceof SingleElementNode) {
1171 SingleElementNode sen = (SingleElementNode)node;
1172 RenderSVGContext b = senBuilders.get(sen);
1173 String content = b.get(MAIN_SECTION);
1174 if(content.isEmpty()) {
1175 if(sen.getKey() != null) {
1177 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
1181 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
1182 String svg = printSVGDocument(doc);
1183 parentBuilder.append(MAIN_SECTION, svg);
1186 parentBuilder.append(b);
1190 AffineTransform at = node.getTransform();
1191 if(!at.isIdentity()) {
1192 parentBuilder.append(ALL_SECTIONS, "</g>");
1194 if(node instanceof SingleElementNode) {
1195 SingleElementNode sen = (SingleElementNode)node;
1196 //if(sen.getKey() != null) {
1197 parentBuilder.append(MAIN_SECTION, "</g>");