1 package org.simantics.modeling;
3 import java.awt.BasicStroke;
4 import java.awt.Dimension;
5 import java.awt.RenderingHints;
6 import java.awt.RenderingHints.Key;
7 import java.awt.geom.AffineTransform;
8 import java.awt.geom.Rectangle2D;
9 import java.io.ByteArrayOutputStream;
10 import java.io.OutputStreamWriter;
11 import java.util.ArrayList;
12 import java.util.Arrays;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.List;
18 import java.util.Random;
20 import java.util.UUID;
21 import java.util.stream.Collectors;
23 import javax.xml.transform.OutputKeys;
24 import javax.xml.transform.Transformer;
25 import javax.xml.transform.TransformerFactory;
26 import javax.xml.transform.dom.DOMSource;
27 import javax.xml.transform.stream.StreamResult;
29 import org.apache.batik.dom.GenericDOMImplementation;
30 import org.apache.batik.svggen.SVGGeneratorContext;
31 import org.apache.batik.svggen.SVGGraphics2D;
32 import org.simantics.Simantics;
33 import org.simantics.datatypes.literal.GUID;
34 import org.simantics.db.ReadGraph;
35 import org.simantics.db.Resource;
36 import org.simantics.db.common.request.UnaryRead;
37 import org.simantics.db.exception.DatabaseException;
38 import org.simantics.db.exception.RuntimeDatabaseException;
39 import org.simantics.diagram.elements.DiagramNodeUtil;
40 import org.simantics.diagram.elements.TextGridNode;
41 import org.simantics.diagram.elements.TextNode;
42 import org.simantics.diagram.stubs.DiagramResource;
43 import org.simantics.g2d.canvas.ICanvasContext;
44 import org.simantics.g2d.diagram.DiagramHints;
45 import org.simantics.g2d.diagram.IDiagram;
46 import org.simantics.g2d.diagram.handler.DataElementMap;
47 import org.simantics.g2d.diagram.participant.Selection;
48 import org.simantics.g2d.element.IElement;
49 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
50 import org.simantics.g2d.utils.CanvasUtils;
51 import org.simantics.layer0.Layer0;
52 import org.simantics.scenegraph.INode;
53 import org.simantics.scenegraph.ParentNode;
54 import org.simantics.scenegraph.g2d.G2DParentNode;
55 import org.simantics.scenegraph.g2d.G2DRenderingHints;
56 import org.simantics.scenegraph.g2d.G2DSceneGraph;
57 import org.simantics.scenegraph.g2d.IG2DNode;
58 import org.simantics.scenegraph.g2d.IG2DNodeVisitor;
59 import org.simantics.scenegraph.g2d.events.command.Commands;
60 import org.simantics.scenegraph.g2d.nodes.BackgroundNode;
61 import org.simantics.scenegraph.g2d.nodes.BoundsNode;
62 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
63 import org.simantics.scenegraph.g2d.nodes.DataNode;
64 import org.simantics.scenegraph.g2d.nodes.DecorationSVGNode;
65 import org.simantics.scenegraph.g2d.nodes.NavigationNode;
66 import org.simantics.scenegraph.g2d.nodes.SVGNode;
67 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
68 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
69 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
70 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
71 import org.simantics.scenegraph.utils.NodeUtil;
72 import org.simantics.scl.runtime.function.Function1;
73 import org.simantics.trend.impl.ItemNode;
74 import org.simantics.utils.threads.ThreadUtils;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import org.w3c.dom.DOMImplementation;
78 import org.w3c.dom.Document;
79 import org.w3c.dom.Element;
80 import org.w3c.dom.NodeList;
82 public class SCLScenegraph {
84 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
86 private static final String MAIN_SECTION = "main";
87 private static final String SELECTION_SECTION = "selection";
88 private static final String SELECTION_MASK_SECTION = "selectionMask";
90 private static final String[] ALL_SECTIONS = { MAIN_SECTION, SELECTION_SECTION, SELECTION_MASK_SECTION };
93 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
94 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
98 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
102 public static String getNodeTransform(ICanvasContext ctx, String name) {
104 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
105 for (TextNode text : texts) {
106 String nodeName = NodeUtil.getNodeName(text);
107 if (nodeName.equals(name)) {
108 String transform = text.getTransform().toString();
112 return "No node found";
115 public static String getNodeText(ICanvasContext ctx, String name) {
117 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
118 for (TextNode text : texts) {
119 String nodeName = NodeUtil.getNodeName(text);
120 if (nodeName.equals(name)) {
121 String texti = text.getText();
125 return "No node found";
128 public static String getNodeCount(ICanvasContext ctx) {
129 G2DSceneGraph g2 = ctx.getSceneGraph();
130 int amount = NodeUtil.countTreeNodes(g2);
131 return "Node count: " + amount;
134 public static String getAllNodes (ICanvasContext ctx) {
136 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
137 int amount = g2.size() +1;
138 return "All nodes: " + amount;
141 public static String getBoundsNodes (ICanvasContext ctx) {
143 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
144 int amount = bn.size();
145 return "BoundsNodes: " + amount;
148 public static String getBackgroundNodes (ICanvasContext ctx) {
150 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
151 int amount = bg.size();
152 return "BackgroundNodes: " + amount;
155 public static String getDataNodes (ICanvasContext ctx) {
157 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
158 int amount = dn.size();
159 return "DataNodes: " + amount;
162 public static String getNavigationNodes (ICanvasContext ctx) {
164 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
165 int amount = g2.size();
166 return "NavigationNodes: " + amount;
169 public static String getParentNodes (ICanvasContext ctx) {
171 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
172 int amount = g2.size();
173 return "ParentNodes: " + amount;
176 public static String getDecorationNodes (ICanvasContext ctx) {
178 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
179 int amount = deco.size();
180 return "DecorationNodes: " + amount;
183 public static String getSingleElementNodes (ICanvasContext ctx) {
185 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
186 int amount = g2.size();
187 return "SingleElementNodes: " + amount;
190 public static String getConnectionNodes (ICanvasContext ctx) {
192 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
193 int amount = g2.size();
194 return "ConnectionNodes: " + amount;
197 public static String getTextNodes (ICanvasContext ctx) {
199 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
200 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
201 int amount = tn.size() + tgn.size();
202 return "TextNodes: " + amount;
205 public static String getItemNodes (ICanvasContext ctx) {
207 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
208 int amount = item.size();
209 return "ItemNodes: " + amount;
212 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
214 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
215 for (TextNode modulenode : textGridNodes) {
216 if (module.equals(modulenode.getText())) {
217 //System.out.println("Module what we were looking for: " + module);
218 //System.out.println("Modulenode: " + modulenode.getText());
220 ParentNode<?> parentnode = modulenode.getParent();
221 //System.out.println("Parentnode: " + parentnode);
223 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
224 for (TextNode valuenode : textnodes) {
225 if (previous_value.equals(valuenode.getText())) {
226 //System.out.println("Value what we were looking for: " + previous_value);
227 //System.out.println("Valuenode: " + valuenode.getText());
229 //valuenode.setEditMode(true);
230 valuenode.activateEdit(0, null, ctx);
231 valuenode.setText(new_value);
232 valuenode.fireTextEditingEnded();
234 //System.out.println("valuenode modified: " + valuenode);
235 return "Modified module " + module + " with value " + new_value;
238 return "Not found module : " + module;
241 return "No nodes in scenegraph!";
244 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
246 boolean module_founded = false;
247 boolean value_founded = false;
249 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
250 System.out.println("Total amount of nodes: " + g2.size() + 1);
252 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
253 Integer textGridNodeAmount = grid.size();
254 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
256 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
257 Integer textNodeAmount = grid.size();
258 System.out.println("Amount of TextNodes " + textNodeAmount);
260 for (TextNode node : texts) {
261 if (module.equals(node.getText())) {
262 module_founded = true;
263 System.out.println("Correct module " + module + " founded.");
265 if (value.equals(node.getText())) {
266 value_founded = true;
267 System.out.println("Correct value " + value + " founded.");
271 if (value_founded == true && module_founded == true) {
272 return "Found both correct module " + module + " and value " + value;
274 if (value_founded == false && module_founded == true) {
275 return "Found only correct module " + module + " but not value " + value;
277 if (value_founded == true && module_founded == false) {
278 return "Found only correct value " + value + " but not module " + module;
281 return "Didn't found either module " + module + " or value " + value;
285 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
287 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
289 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
291 final Collection<IElement> newSelection = new ArrayList<IElement>();
292 for (Resource module : modules) {
293 IElement element = dem.getElement(idiagram, module);
294 if (element != null) {
295 newSelection.add(element);
297 throw new DatabaseException("Could not find IElement for " + element);
301 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
304 if (source_ctx.isDisposed())
306 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
307 if (selection != null) {
308 // This prevents workbench selection from being left over.
309 // Also prevents scene graph crap from being left on the screen.
310 selection.setSelection(0, newSelection);
312 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
313 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
319 while(source_ctx.getEventQueue().size() > 0) {
322 } catch (InterruptedException e) {
323 throw new DatabaseException(e);
327 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
337 static class Generator extends SVGGraphics2D {
340 String newElementId = null;
341 ArrayList<Element> elements = new ArrayList<Element>();
343 public static final String svgNS = "http://www.w3.org/2000/svg";
345 public Generator(SVGGeneratorContext ctx, boolean joku) {
349 public Generator(Document document) {
354 public Element getRoot() {
355 Element root = super.getRoot();
356 for(Element e : elements) {
363 public void setRenderingHint(Key arg0, Object arg1) {
364 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
367 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
369 newElementId = arg1.toString();
371 newElementId = UUID.randomUUID().toString();
373 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
376 Element group = getDOMFactory().createElement(SVG_G_TAG);
377 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
378 group.setAttributeNS(null, "id", newElementId);
379 group.setAttributeNS(null, "class", arg1.toString());
384 super.setRenderingHint(arg0, arg1);
389 public static Element renderSVGNode(IG2DNode node) {
391 // Get a DOMImplementation.
392 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
394 // Create an instance of org.w3c.dom.Document.
395 String svgNS = "http://www.w3.org/2000/svg";
396 Document document = domImpl.createDocument(svgNS, "svg", null);
398 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
399 ctx.setComment(null);
401 // Create an instance of the SVG Generator.
402 SVGGraphics2D svgGenerator = new Generator(ctx, false);
406 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
407 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
408 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
410 node.render(svgGenerator);
412 } catch (Throwable t) {
413 LOGGER.error("Problems rendering scene graph to SVG", t);
416 return svgGenerator.getRoot();
419 public static String printSVGDocument(Element doce) {
421 StringBuilder result = new StringBuilder();
423 NodeList nl = doce.getChildNodes();
425 for(int i=0;i<nl.getLength();i++) {
427 ByteArrayOutputStream os = new ByteArrayOutputStream();
431 TransformerFactory tf = TransformerFactory.newInstance();
432 Transformer transformer = tf.newTransformer();
433 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
434 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
435 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
436 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
437 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
438 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
440 transformer.transform(new DOMSource(nl.item(i)),
441 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
446 } catch (Throwable t) {
447 LOGGER.error("Problems formatting SVGDocument to text.", t);
450 result.append(new String(os.toByteArray()));
454 return result.toString();
458 public static String renderSVG3(ICanvasContext ctx) {
459 return renderSVG0(ctx, p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2)));
465 * @throws DatabaseException
467 private static Object[] createURIBasedL0Identifier(ReadGraph graph, Resource component) throws DatabaseException {
468 String uri = graph.getPossibleURI(component);
469 int hashCode = uri.hashCode();
470 Random random = new Random(hashCode);
471 long l1 = random.nextLong();
472 long l2 = random.nextLong();
473 return new Object[] { l1, l2 };
477 * Default no-op mapper
479 private static final Function1<Set<?>, Map<?, ?>> mapper = p0 -> p0.stream().collect(Collectors.toMap(p1 -> p1, p2 -> p2));
481 public static String renderSVG(ICanvasContext ctx) {
482 return renderSVG0(ctx, mapper);
486 * Renders ICanvasContext into SVG by mapping the SVG id's into URI based
492 public static String renderSVGMapIdentifiers(ICanvasContext ctx) {
493 return renderSVG0(ctx, new Function1<Set<?>, Map<?, ?>>() {
496 public Map<?, ?> apply(Set<?> p0) {
498 return Simantics.getSession().syncRequest(new UnaryRead<Set<?>, Map<?, ?>>(p0) {
501 public Map<?, ?> perform(ReadGraph graph) throws DatabaseException {
502 ModelingResources MOD = ModelingResources.getInstance(graph);
503 DiagramResource DIA = DiagramResource.getInstance(graph);
504 Layer0 L0 = Layer0.getInstance(graph);
505 return parameter.stream().collect(Collectors.toMap(p -> p, p -> {
507 if (p instanceof Resource) {
508 Resource element = (Resource) p;
509 if (graph.isInstanceOf(element, DIA.Element)) {
510 Resource component = graph.getPossibleObject(element, MOD.ElementToComponent);
511 if (component != null) {
512 GUID identifier = graph.getPossibleRelatedValue(component, L0.identifier, GUID.BINDING);
513 if (identifier != null) {
514 return Arrays.toString(createURIBasedL0Identifier(graph, component));
516 LOGGER.error("Component {} does not have GUID identifier!", component);
518 } else if (graph.isInstanceOf(element, DIA.Connection) || graph.isInstanceOf(element, DIA.Terminal)) {
519 // Ok, lets create a hashcode for connections and terminals as they do not have identifiers
520 return graph.getURI(element).hashCode();
522 // Ok, lets create a hashcode or either return empty string in cases where no ID is required
523 if (graph.hasStatement(element, L0.HasName))
524 return graph.getURI(element).hashCode();
529 LOGGER.error("Parameter p {} is not resource but it is {}", p, p.getClass());
532 } catch (DatabaseException e) {
533 throw new RuntimeDatabaseException(e);
538 } catch (DatabaseException e) {
539 LOGGER.error("Could not apply mappings", e);
540 throw new RuntimeDatabaseException(e);
546 static class RenderSVGContext {
548 Map<String,StringBuilder> documents = new HashMap<>();
550 public void append(String[] keys, String svgText) {
551 for(String key : keys) append(key, svgText);
554 public void append(String key, String svgText) {
555 StringBuilder builder = documents.get(key);
556 if(builder == null) {
557 builder = new StringBuilder();
558 documents.put(key, builder);
560 builder.append(svgText);
563 public void append(RenderSVGContext other) {
564 for(String key : other.documents.keySet()) {
565 append(key, other.get(key));
569 public String get(String key) {
570 StringBuilder builder = documents.get(key);
571 if(builder == null) return "";
572 else return builder.toString();
577 private static String renderSVG0(ICanvasContext ctx, Function1<Set<?>, Map<?, ?>> mappingFunction) {
579 // Get a DOMImplementation.
580 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
582 // Create an instance of org.w3c.dom.Document.
583 String svgNS = "http://www.w3.org/2000/svg";
584 Document document = domImpl.createDocument(svgNS, "svg", null);
586 // Create an instance of the SVG Generator.
587 SVGGraphics2D svgGenerator = new Generator(document);
589 RenderSVGContext result = new RenderSVGContext();
593 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
594 if (selection != null) {
595 // This prevents workbench selection from being left over.
596 // Also prevents scene graph crap from being left on the screen.
597 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
598 selection.setSelection(0, d.getElements());
601 G2DSceneGraph sg = ctx.getSceneGraph();
602 G2DParentNode root = (G2DParentNode) sg.getRootNode();
604 // rtree is the actual content of the diagram
605 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
606 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
608 // nav is a node that has zooming functionalities
609 NavigationNode nav = NodeUtil.getNearestChildByClass(root, NavigationNode.class);
610 nav.setZoomEnabled(true);
612 // fit view with the contents of rtreeBounds
613 nav.zoomTo(rtreeBounds);
615 // get the bounds of the content
616 Rectangle2D content = NodeUtil.getLocalBounds(nav);
618 svgGenerator.scale(3,3);
620 // translate svgGenerator to the x and y coordinates of current content
621 svgGenerator.translate(-1 * content.getX(), (-1 * content.getY()));
623 Rectangle2D destination = new Rectangle2D.Double(0,0,1000,1000);
624 double sx = destination.getWidth() / content.getWidth();
625 double sy = destination.getHeight() / content.getHeight();
626 double scale = sx < sy ? sx : sy;
628 // Set svgCanvasSize to the given size parameters
629 svgGenerator.setSVGCanvasSize(new Dimension((int)(scale * content.getWidth()), (int)(scale * content.getHeight())));
630 svgGenerator.setClip(content);
632 double trX = -1 * content.getX();
633 double trY = -1 * content.getY();
636 if(!Double.isFinite(trX)) trX = 0;
637 if(!Double.isFinite(trY)) trY = 0;
639 result.append(MAIN_SECTION, "<g transform=\"translate(");
640 result.append(MAIN_SECTION, "" + trX);
641 result.append(MAIN_SECTION, ", ");
642 result.append(MAIN_SECTION, "" + trY);
643 result.append(MAIN_SECTION, ")\">");
645 result.append(SELECTION_SECTION, "<g class=\"selections\">");
647 result.append(SELECTION_MASK_SECTION, "<g class=\"selectionMasks\">");
649 KeyVisitor keyVisitor = new KeyVisitor();
650 sg.accept(keyVisitor);
652 Set<Object> keys = keyVisitor.getKeys();
654 Map<?, ?> mappings = mappingFunction.apply(keys);
656 IG2DNodeVisitor visitor = new PrintingVisitor(result, mappings);
660 } catch (Throwable t) {
661 LOGGER.error("Problems rendering canvas context to SVG", t);
665 result.append(SELECTION_SECTION, "</g>");
666 result.append(SELECTION_MASK_SECTION, "</g>");
667 result.append(MAIN_SECTION, "</g>");
669 StringBuilder res = new StringBuilder();
670 res.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\">");
671 res.append(result.get(MAIN_SECTION));
672 res.append(result.get(SELECTION_SECTION));
673 res.append(result.get(SELECTION_MASK_SECTION));
674 res.append(result.get("</svg>"));
676 // System.err.println(" == FINAL RESULT == ");
677 // System.err.println(res.toString());
679 return res.toString();
685 private static class KeyVisitor implements IG2DNodeVisitor {
687 private Set<Object> keys = new HashSet<>();
690 public void enter(IG2DNode node) {
691 if (node instanceof SingleElementNode) {
692 Object key = ((SingleElementNode) node).getKey();
700 public void leave(IG2DNode node) {
704 public Set<Object> getKeys() {
709 private static class PrintingVisitor implements IG2DNodeVisitor {
713 HashMap<SingleElementNode,RenderSVGContext> senBuilders = new HashMap<>();
715 private RenderSVGContext result;
717 private Map<?, ?> mappings;
719 public PrintingVisitor(RenderSVGContext result, Map<?, ?> mappings) {
720 this.result = result;
721 this.mappings = mappings;
724 private String getKey(SingleElementNode node) {
726 if (mappings.containsKey(node.getKey()))
727 key = mappings.get(node.getKey()).toString();
729 key = node.getKey().toString();
734 public void enter(IG2DNode node) {
736 RenderSVGContext parentBuilder = getParentBuilder(node);
739 if(node instanceof ConnectionNode) {
741 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
742 n.setIgnoreSelection(true);
745 String key = getKey((ConnectionNode) node);
746 parentBuilder.append(MAIN_SECTION, "\n<g class=\"connection\" id=\"" + key + "\">");
747 parentBuilder.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
748 parentBuilder.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" opacity=\"0.001\" id=\"" + key + "\">");
750 Element doc = renderSVGNode((IG2DNode)node);
751 String svg = printSVGDocument(doc);
752 parentBuilder.append(MAIN_SECTION, svg);
754 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
755 n.setIgnoreSelection(false);
758 doc = renderSVGNode((IG2DNode)node);
759 svg = printSVGDocument(doc);
760 parentBuilder.append(SELECTION_SECTION, svg);
762 BasicStroke bs = new BasicStroke(10f);
764 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
765 n.setDynamicStroke(bs);
768 doc = renderSVGNode((IG2DNode)node);
769 svg = printSVGDocument(doc);
770 parentBuilder.append(SELECTION_MASK_SECTION, svg);
772 parentBuilder.append(SELECTION_MASK_SECTION, "\n</g>");
773 parentBuilder.append(SELECTION_SECTION, "\n</g>");
774 parentBuilder.append(MAIN_SECTION, "\n</g>");
776 } else if (node instanceof SelectionNode) {
778 SelectionNode n = (SelectionNode)node;
779 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
780 if(parentSEN != null && parentSEN.getKey() != null) {
782 RenderSVGContext parentBuilder2 = getParentBuilder(parentSEN);
784 String key = getKey(parentSEN);
785 Element doc = renderSVGNode((IG2DNode)node);
786 String svg = printSVGDocument(doc);
787 parentBuilder2.append(SELECTION_SECTION, "\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
788 parentBuilder2.append(SELECTION_SECTION, svg);
789 parentBuilder2.append(SELECTION_SECTION, "\n</g>");
790 parentBuilder2.append(SELECTION_MASK_SECTION, "\n<g class=\"selectionMask\" id=\"" + key + "\">");
791 Rectangle2D rect = n.getRect();
793 if(rect.getHeight() == rect.getHeight() && rect.getWidth() == rect.getWidth()) {
794 parentBuilder2.append(SELECTION_MASK_SECTION,"<rect style=\"fill:#fff\" opacity=\"0.001\"");
795 parentBuilder2.append(SELECTION_MASK_SECTION," x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
796 parentBuilder2.append(SELECTION_MASK_SECTION," width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
797 parentBuilder2.append(SELECTION_MASK_SECTION,"></rect>");
799 parentBuilder2.append(SELECTION_MASK_SECTION,"\n</g>");
801 } else if (node instanceof SVGNode) {
802 SVGNode svg = (SVGNode)node;
803 parentBuilder.append(MAIN_SECTION, svg.getSVGText());
804 } else if (node instanceof G2DParentNode) {
805 AffineTransform at = node.getTransform();
806 if(node instanceof SingleElementNode) {
807 SingleElementNode sen = (SingleElementNode)node;
808 if(sen.getKey() != null) {
809 String key = getKey(sen);
810 String typeClass = sen.getTypeClass();
811 String clazz = "definedElement";
812 if(typeClass != null && !typeClass.isEmpty())
813 clazz = clazz + " " + typeClass;
815 parentBuilder.append(MAIN_SECTION, "\n<g class=\""+clazz+"\" id=\"" + key + "\">");
817 senBuilders.put(sen, new RenderSVGContext());
819 if(!at.isIdentity()) {
820 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
821 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
822 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
824 double[] ds = new double[6];
826 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
827 parentBuilder.append(ALL_SECTIONS, "\n<g transform=\"" + m + "\">");
832 //enters.put(node, b.length());
836 private RenderSVGContext getParentBuilder(IG2DNode node) {
838 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
839 if(parentSEN instanceof G2DSceneGraph) return result;
841 RenderSVGContext parentBuilder = senBuilders.get(parentSEN);
842 if(parentBuilder == null) return result;
844 return parentBuilder;
849 public void leave(IG2DNode node) {
851 if(node instanceof ConnectionNode || node instanceof SVGNode) {
853 } else if (node instanceof G2DParentNode) {
855 RenderSVGContext parentBuilder = getParentBuilder(node);
857 if(node instanceof SingleElementNode) {
858 SingleElementNode sen = (SingleElementNode)node;
859 RenderSVGContext b = senBuilders.get(sen);
860 String content = b.get(MAIN_SECTION);
861 if(content.isEmpty()) {
862 if(sen.getKey() != null) {
864 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
868 Element doc = renderSVGNode((IG2DNode)node);
869 String svg = printSVGDocument(doc);
870 parentBuilder.append(MAIN_SECTION, svg);
873 parentBuilder.append(b);
877 AffineTransform at = node.getTransform();
878 if(!at.isIdentity()) {
879 parentBuilder.append(ALL_SECTIONS, "</g>");
881 if(node instanceof SingleElementNode) {
882 SingleElementNode sen = (SingleElementNode)node;
883 if(sen.getKey() != null) {
884 parentBuilder.append(MAIN_SECTION, "</g>");