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.NavigationNode;
72 import org.simantics.scenegraph.g2d.nodes.SVGNode;
73 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
74 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
75 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
76 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
77 import org.simantics.scenegraph.utils.NodeUtil;
78 import org.simantics.scl.runtime.function.Function1;
79 import org.simantics.scl.runtime.tuple.Tuple2;
80 import org.simantics.trend.impl.ItemNode;
81 import org.simantics.utils.threads.ThreadUtils;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.w3c.dom.DOMImplementation;
85 import org.w3c.dom.Document;
86 import org.w3c.dom.Element;
87 import org.w3c.dom.NodeList;
89 public class SCLScenegraph {
91 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
93 private static final String MAIN_SECTION = "main";
94 private static final String SELECTION_SECTION = "selection";
95 private static final String SELECTION_MASK_SECTION = "selectionMask";
97 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
99 // Changed from 0.001 to 0.0001 to prevent creation of huge BufferedImage's when
100 // generating PDF from SVG. If SVG contains any transparency then Batik uses
101 // bitmap-rendering which remarkably slows things down
102 // See org.apache.batik.gvt.AbstractGraphicsNode.paint(Graphics2D) where decisions are made
103 // if AlphaComposite should be painted
104 private static final String OPACITY = "0.0001";
107 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
108 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
113 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
117 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function1<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
118 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider));
121 public static <T> T doWithICanvasSceneGraphProvider(Resource diagram, Function<ICanvasSceneGraphProvider, T> func) throws DatabaseException {
122 Tuple2 result = Simantics.getSession().syncRequest(new ResourceRead<Tuple2>(diagram) {
125 public Tuple2 perform(ReadGraph graph) throws DatabaseException {
126 Resource indexRoot = graph.syncRequest(new IndexRoot(resource));
127 String diagramRVI = Variables.getRVI(graph, resource);
128 return new Tuple2(indexRoot, diagramRVI);
131 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider((Resource) result.c0, diagram, (String) result.c1);
133 return func.apply(provider);
139 public static <T> T doWithCanvasContext(Resource diagram, Function1<ICanvasContext, T> func) throws DatabaseException {
140 return doWithCanvasContext(diagram, (Function<ICanvasContext, T>) canvasContext -> func.apply(canvasContext));
143 public static <T> T doWithCanvasContext(Resource diagram, Function<ICanvasContext, T> func) throws DatabaseException {
144 return doWithICanvasSceneGraphProvider(diagram, (Function<ICanvasSceneGraphProvider, T>) provider -> func.apply(provider.getCanvasContext()));
147 public static String getNodeTransform(ICanvasContext ctx, String name) {
149 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
150 for (TextNode text : texts) {
151 String nodeName = NodeUtil.getNodeName(text);
152 if (nodeName.equals(name)) {
153 String transform = text.getTransform().toString();
157 return "No node found";
160 public static String getNodeText(ICanvasContext ctx, String name) {
162 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
163 for (TextNode text : texts) {
164 String nodeName = NodeUtil.getNodeName(text);
165 if (nodeName.equals(name)) {
166 String texti = text.getText();
170 return "No node found";
173 public static String getNodeCount(ICanvasContext ctx) {
174 G2DSceneGraph g2 = ctx.getSceneGraph();
175 int amount = NodeUtil.countTreeNodes(g2);
176 return "Node count: " + amount;
179 public static String getAllNodes (ICanvasContext ctx) {
181 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
182 int amount = g2.size() +1;
183 return "All nodes: " + amount;
186 public static String getBoundsNodes (ICanvasContext ctx) {
188 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
189 int amount = bn.size();
190 return "BoundsNodes: " + amount;
193 public static String getBackgroundNodes (ICanvasContext ctx) {
195 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
196 int amount = bg.size();
197 return "BackgroundNodes: " + amount;
200 public static String getDataNodes (ICanvasContext ctx) {
202 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
203 int amount = dn.size();
204 return "DataNodes: " + amount;
207 public static String getNavigationNodes (ICanvasContext ctx) {
209 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
210 int amount = g2.size();
211 return "NavigationNodes: " + amount;
214 public static String getParentNodes (ICanvasContext ctx) {
216 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
217 int amount = g2.size();
218 return "ParentNodes: " + amount;
221 public static String getDecorationNodes (ICanvasContext ctx) {
223 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
224 int amount = deco.size();
225 return "DecorationNodes: " + amount;
228 public static String getSingleElementNodes (ICanvasContext ctx) {
230 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
231 int amount = g2.size();
232 return "SingleElementNodes: " + amount;
235 public static String getConnectionNodes (ICanvasContext ctx) {
237 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
238 int amount = g2.size();
239 return "ConnectionNodes: " + amount;
242 public static String getTextNodes (ICanvasContext ctx) {
244 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
245 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
246 int amount = tn.size() + tgn.size();
247 return "TextNodes: " + amount;
250 public static String getItemNodes (ICanvasContext ctx) {
252 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
253 int amount = item.size();
254 return "ItemNodes: " + amount;
257 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
259 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
260 for (TextNode modulenode : textGridNodes) {
261 if (module.equals(modulenode.getText())) {
262 //System.out.println("Module what we were looking for: " + module);
263 //System.out.println("Modulenode: " + modulenode.getText());
265 ParentNode<?> parentnode = modulenode.getParent();
266 //System.out.println("Parentnode: " + parentnode);
268 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
269 for (TextNode valuenode : textnodes) {
270 if (previous_value.equals(valuenode.getText())) {
271 //System.out.println("Value what we were looking for: " + previous_value);
272 //System.out.println("Valuenode: " + valuenode.getText());
274 //valuenode.setEditMode(true);
275 valuenode.activateEdit(0, null, ctx);
276 valuenode.setText(new_value);
277 valuenode.fireTextEditingEnded();
279 //System.out.println("valuenode modified: " + valuenode);
280 return "Modified module " + module + " with value " + new_value;
283 return "Not found module : " + module;
286 return "No nodes in scenegraph!";
290 * Returns background color of a canvasContext or null.
292 * @return color in RGBA List<Integer> format, or null.
294 public static List<Integer> getBackgroundColor(ICanvasContext ctx) {
295 Color color = ctx.getDefaultHintContext().getHint(Hints.KEY_BACKGROUND_COLOR);
298 ArrayList<Integer> rgba = new ArrayList<>(4);
299 rgba.add(color.getRed());
300 rgba.add(color.getGreen());
301 rgba.add(color.getBlue());
302 rgba.add(color.getAlpha());
306 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
308 boolean module_founded = false;
309 boolean value_founded = false;
311 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
312 System.out.println("Total amount of nodes: " + g2.size() + 1);
314 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
315 Integer textGridNodeAmount = grid.size();
316 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
318 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
319 Integer textNodeAmount = grid.size();
320 System.out.println("Amount of TextNodes " + textNodeAmount);
322 for (TextNode node : texts) {
323 if (module.equals(node.getText())) {
324 module_founded = true;
325 System.out.println("Correct module " + module + " founded.");
327 if (value.equals(node.getText())) {
328 value_founded = true;
329 System.out.println("Correct value " + value + " founded.");
333 if (value_founded == true && module_founded == true) {
334 return "Found both correct module " + module + " and value " + value;
336 if (value_founded == false && module_founded == true) {
337 return "Found only correct module " + module + " but not value " + value;
339 if (value_founded == true && module_founded == false) {
340 return "Found only correct value " + value + " but not module " + module;
343 return "Didn't found either module " + module + " or value " + value;
347 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
349 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
351 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
353 final Collection<IElement> newSelection = new ArrayList<IElement>();
354 for (Resource module : modules) {
355 IElement element = dem.getElement(idiagram, module);
356 if (element != null) {
357 newSelection.add(element);
359 throw new DatabaseException("Could not find IElement for " + element);
363 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
366 if (source_ctx.isDisposed())
368 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
369 if (selection != null) {
370 // This prevents workbench selection from being left over.
371 // Also prevents scene graph crap from being left on the screen.
372 selection.setSelection(0, newSelection);
374 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
375 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
381 while(source_ctx.getEventQueue().size() > 0) {
384 } catch (InterruptedException e) {
385 throw new DatabaseException(e);
389 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
399 static class Generator extends SVGGraphics2D {
402 String newElementId = null;
403 ArrayList<Element> elements = new ArrayList<Element>();
405 public static final String svgNS = "http://www.w3.org/2000/svg";
407 public Generator(SVGGeneratorContext ctx, boolean textAsShapes) {
408 super(ctx, textAsShapes);
411 public Generator(Document document) {
413 // prevent batik comment in each g-element
414 getGeneratorContext().setComment(null);
418 public Element getRoot() {
419 Element root = super.getRoot();
420 for(Element e : elements) {
427 public void setRenderingHint(Key arg0, Object arg1) {
428 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
431 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
433 newElementId = arg1.toString();
435 newElementId = UUID.randomUUID().toString();
437 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
440 Element group = getDOMFactory().createElement(SVG_G_TAG);
441 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
442 group.setAttributeNS(null, "id", newElementId);
443 group.setAttributeNS(null, "class", arg1.toString());
448 super.setRenderingHint(arg0, arg1);
453 public static Element renderSVGNode(SVGGraphics2D svgGenerator, IG2DNode node) {
457 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
458 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
459 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
461 node.render(svgGenerator);
463 } catch (Throwable t) {
464 LOGGER.error("Problems rendering scene graph to SVG", t);
467 return svgGenerator.getRoot();
470 public static String printSVGDocument(Element doce) {
472 StringBuilder result = new StringBuilder();
474 NodeList nl = doce.getChildNodes();
476 for(int i=0;i<nl.getLength();i++) {
478 ByteArrayOutputStream os = new ByteArrayOutputStream();
482 TransformerFactory tf = TransformerFactory.newInstance();
483 Transformer transformer = tf.newTransformer();
484 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
485 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
486 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
487 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
488 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
489 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
491 transformer.transform(new DOMSource(nl.item(i)),
492 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
497 } catch (Throwable t) {
498 LOGGER.error("Problems formatting SVGDocument to text.", t);
501 result.append(new String(os.toByteArray()));
505 return result.toString();
509 public static String renderSVG3(ICanvasContext ctx) {
510 return renderSVG3(ctx, -1, -1);
513 public static String renderSVG3(ICanvasContext ctx, double width, double height) {
514 return renderSVG0(width, height, ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
520 * @throws DatabaseException
522 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
523 String uri = graph.getPossibleURI(component);
524 int hashCode = uri.hashCode();
525 Random random = new Random(hashCode);
526 long l1 = random.nextLong();
527 long l2 = random.nextLong();
528 return new Object[] { l1, l2 };
532 * Default no-op mapper
534 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
536 public static String renderSVG(ICanvasContext ctx, double width, double height) {
537 return renderSVG0(width, height, ctx, mapper);
540 public static String renderSVG(ICanvasContext ctx) {
541 return renderSVG(ctx, -1, -1);
544 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
545 return renderSVGMapIdentifiers(ctx, -1, -1);
549 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
555 public static String renderSVGMapIdentifiers(ICanvasContext ctx, double width, double height) {
556 return renderSVG0(width, height, ctx, new Function1<Set<?>, Map<?, ?>>() {
559 public Map<?, ?> apply(Set<?> p0) {
561 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
564 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
565 ModelingResources MOD = ModelingResources.getInstance(graph);
566 DiagramResource DIA = DiagramResource.getInstance(graph);
567 Layer0 L0 = Layer0.getInstance(graph);
568 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
570 if (p instanceof Resource) {
571 Resource element = (Resource) p;
572 if (graph.isInstanceOf(element, DIA.Element)) {
573 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
574 if (component != null) {
575 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
576 if (identifier != null) {
577 return Arrays.toString(createURIBasedL0Identifier(graph, component));
579 LOGGER.error("Component {} does not have GUID identifier!", component);
581 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
582 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
583 return graph.getURI(element).hashCode();
585 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
586 if (graph.hasStatement(element, L0.HasName))
587 return graph.getURI(element).hashCode();
592 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
595 } catch (DatabaseException e) {
596 throw new RuntimeDatabaseException(e);
601 } catch (DatabaseException e) {
602 LOGGER.error("Could not apply mappings", e);
603 throw new RuntimeDatabaseException(e);
609 static class RenderSVGContext {
611 Map<String,StringBuilder> documents = new HashMap<>();
613 public void append(String[] keys, String svgText) {
614 for(String key : keys) append(key, svgText);
617 public void append(String key, String svgText) {
618 StringBuilder builder = documents.get(key);
619 if(builder == null) {
620 builder = new StringBuilder();
621 documents.put(key, builder);
623 builder.append(svgText);
626 public void append(RenderSVGContext other) {
627 for(String key : other.documents.keySet()) {
628 append(key, other.get(key));
632 public String get(String key) {
633 StringBuilder builder = documents.get(key);
634 if(builder == null) return "";
635 else return builder.toString();
640 private static String renderSVG0(double width, double height, ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
642 // Get a DOMImplementation.
643 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
645 // Create an instance of org.w3c.dom.Document.
646 String svgNS = "http://www.w3.org/2000/svg";
647 Document document = domImpl.createDocument(svgNS, "svg", null);
649 // Create an instance of the SVG Generator.
650 SVGGraphics2D svgGenerator = new Generator(document);
652 RenderSVGContext result = new RenderSVGContext();
654 double[] matrix = new double[6];
657 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
658 if (selection != null) {
659 // This prevents workbench selection from being left over.
660 // Also prevents scene graph crap from being left on the screen.
661 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
662 selection.setSelection(0, d.getElements());
665 G2DSceneGraph sg = ctx.getSceneGraph();
667 G2DParentNode root = (G2DParentNode) sg.getRootNode();
669 // rtree is the actual content of the diagram
670 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
671 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
673 // get the bounds of the content
674 Rectangle2D content = rtreeBounds;
676 // To account for dynamic padding of selection rectangles (5 units + stroke width)
679 double scale = width < 0 || height < 0 ? 1.0 : Math.min((width - 2*offset) / content.getWidth(), (height - 2*offset) / content.getHeight());
681 AffineTransform tr = new AffineTransform();
682 tr.translate(offset, offset);
683 tr.scale(scale, scale);
684 tr.translate(-content.getX(), -content.getY());
685 tr.getMatrix(matrix);
686 //svgGenerator.translate(offset, offset);
687 //svgGenerator.scale(scale, scale);
688 // translate svgGenerator to the x and y coordinates of current content
689 //svgGenerator.translate(-content.getX(), -content.getY());
691 svgGenerator.setSVGCanvasSize(new Dimension((int)Math.ceil(scale * content.getWidth()) + 2*offset, (int)Math.ceil(scale * content.getHeight()) + 2*offset));
692 //svgGenerator.setClip(content);
694 result.append(MAIN_SECTION, "<g class=\"symbols\">");
695 result.append(SELECTION_SECTION, "<g class=\"selections\">");
696 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
698 KeyVisitor keyVisitor = new KeyVisitor();
699 sg.accept(keyVisitor);
701 Set<Object> keys = keyVisitor.getKeys();
703 Map<?, ?> mappings = mappingFunction.apply(keys);
705 IG2DNodeVisitor visitor = new PrintingVisitor(svgGenerator, result, mappings);
709 } catch (Throwable t) {
710 LOGGER.error("Problems rendering canvas context to SVG", t);
714 result.append(ALL_SECTIONS, "</g>");
716 StringBuilder res = new StringBuilder();
717 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
718 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(")\">");
719 res.append(result.get(MAIN_SECTION));
720 res.append(result.get(SELECTION_SECTION));
721 res.append(result.get(SELECTION_MASK_SECTION));
723 res.append("</svg>");
725 // System.err.println(" == FINAL RESULT == ");
726 // System.err.println(res.toString());
728 return res.toString();
734 private static class KeyVisitor implements IG2DNodeVisitor {
736 private Set<Object> keys = new HashSet<>();
739 public void enter(IG2DNode node) {
740 if (node instanceof SingleElementNode) {
741 Object key = ((SingleElementNode) node).getKey();
749 public void leave(IG2DNode node) {
753 public Set<Object> getKeys() {
758 private static class PrintingVisitor implements IG2DNodeVisitor {
762 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
764 private RenderSVGContext result;
765 private SVGGraphics2D svgGenerator;
767 private Map<?, ?> mappings;
769 public PrintingVisitor(SVGGraphics2D svgGenerator, RenderSVGContext result, Map<?, ?> mappings) {
770 this.result = result;
771 this.mappings = mappings;
772 this.svgGenerator = svgGenerator;
775 private String getKey(SingleElementNode node) {
777 if(node.getKey() != null) {
778 if (mappings.containsKey(node.getKey()))
779 key = mappings.get(node.getKey()).toString();
781 key = node.getKey().toString();
783 key = Long.toString(node.getId());
789 public void enter(IG2DNode node) {
791 RenderSVGContext parentBuilder = getParentBuilder(node);
794 if(node instanceof ConnectionNode) {
796 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
797 n.setIgnoreSelection(true);
800 String key = getKey((ConnectionNode) node);
801 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
802 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
803 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"" + OPACITY + "\" id=\"" + key + "\">");
805 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
806 String svg = printSVGDocument(doc);
807 parentBuilder.append(MAIN_SECTION, svg);
809 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
810 n.setIgnoreSelection(false);
813 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
814 svg = printSVGDocument(doc);
815 parentBuilder.append(SELECTION_SECTION, svg);
817 BasicStroke bs = new BasicStroke(10f);
819 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
820 n.setDynamicStroke(bs);
823 doc = renderSVGNode(svgGenerator, (IG2DNode)node);
824 svg = printSVGDocument(doc);
825 parentBuilder.append(SELECTION_MASK_SECTION, svg);
827 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
828 parentBuilder.append(SELECTION_SECTION, "\n</g>");
829 parentBuilder.append(MAIN_SECTION, "\n</g>");
831 } else if (isSelection0(node)) {
833 SelectionNode n = (SelectionNode)node;
834 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
835 if(parentSEN != null) {
837 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
839 String key = getKey(parentSEN);
841 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
843 String svg = printSVGDocument(doc);
844 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
845 parentBuilder2.append(SELECTION_SECTION, svg);
846 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
847 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key /*+ "\" transform=\"" + matrixString + "\"*/+ "\">");
848 Rectangle2D rect = n.getRect();
850 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
851 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"" + OPACITY + "\"");
852 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
853 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
854 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
856 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
859 } else if (node instanceof SelectionNode) {
861 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
862 String svg = printSVGDocument(doc);
863 parentBuilder.append(MAIN_SECTION, "<g>");
864 parentBuilder.append(MAIN_SECTION, svg);
865 parentBuilder.append(MAIN_SECTION, "\n</g>");
867 } else if (node instanceof SVGNode) {
868 SVGNode svg = (SVGNode)node;
869 AffineTransform at = svg.getTransform();
870 if (!at.isIdentity()) {
871 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
872 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
873 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
875 double[] ds = new double[6];
877 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
878 parentBuilder.append(MAIN_SECTION, "\n<g transform=\"" + m + "\">");
881 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
882 if (!at.isIdentity()) {
883 parentBuilder.append(MAIN_SECTION, "\n</g>");
885 } else if (node instanceof G2DParentNode) {
886 AffineTransform at = node.getTransform();
887 if(node instanceof SingleElementNode) {
888 SingleElementNode sen = (SingleElementNode)node;
889 String key = getKey(sen);
890 String typeClass = sen.getTypeClass();
891 String clazz = "definedElement";
892 if(typeClass != null && !typeClass.isEmpty())
893 clazz = clazz + " " + typeClass;
895 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
896 senBuilders.put(sen, new RenderSVGContext());
898 if(!at.isIdentity()) {
899 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
900 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
901 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
903 double[] ds = new double[6];
905 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
906 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
911 //enters.put(node, b.length());
915 private boolean isSelection0(IG2DNode node) {
917 if(node instanceof SelectionNode) {
918 SelectionNode sn = (SelectionNode)node;
919 return sn.getSelectionId() == 0;
926 private RenderSVGContext getParentBuilder(IG2DNode node) {
928 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
929 if(parentSEN instanceof G2DSceneGraph) return result;
931 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
932 if(parentBuilder == null) return result;
934 return parentBuilder;
939 public void leave(IG2DNode node) {
941 if(node instanceof ConnectionNode || node instanceof SVGNode) {
943 } else if (node instanceof G2DParentNode) {
945 RenderSVGContext parentBuilder = getParentBuilder(node);
947 if(node instanceof SingleElementNode) {
948 SingleElementNode sen = (SingleElementNode)node;
949 RenderSVGContext b = senBuilders.get(sen);
950 String content = b.get(MAIN_SECTION);
951 if(content.isEmpty()) {
952 if(sen.getKey() != null) {
954 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
958 Element doc = renderSVGNode(svgGenerator, (IG2DNode)node);
959 String svg = printSVGDocument(doc);
960 parentBuilder.append(MAIN_SECTION, svg);
963 parentBuilder.append(b);
967 AffineTransform at = node.getTransform();
968 if(!at.isIdentity()) {
969 parentBuilder.append(ALL_SECTIONS, "</g>");
971 if(node instanceof SingleElementNode) {
972 SingleElementNode sen = (SingleElementNode)node;
973 //if(sen.getKey() != null) {
974 parentBuilder.append(MAIN_SECTION, "</g>");