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.Collection;
13 import java.util.HashMap;
14 import java.util.List;
16 import java.util.UUID;
18 import javax.xml.transform.OutputKeys;
19 import javax.xml.transform.Transformer;
20 import javax.xml.transform.TransformerFactory;
21 import javax.xml.transform.dom.DOMSource;
22 import javax.xml.transform.stream.StreamResult;
24 import org.apache.batik.dom.GenericDOMImplementation;
25 import org.apache.batik.svggen.SVGGeneratorContext;
26 import org.apache.batik.svggen.SVGGraphics2D;
27 import org.simantics.db.Resource;
28 import org.simantics.db.exception.DatabaseException;
29 import org.simantics.diagram.elements.DiagramNodeUtil;
30 import org.simantics.diagram.elements.TextGridNode;
31 import org.simantics.diagram.elements.TextNode;
32 import org.simantics.g2d.canvas.ICanvasContext;
33 import org.simantics.g2d.diagram.DiagramHints;
34 import org.simantics.g2d.diagram.IDiagram;
35 import org.simantics.g2d.diagram.handler.DataElementMap;
36 import org.simantics.g2d.diagram.participant.Selection;
37 import org.simantics.g2d.element.IElement;
38 import org.simantics.g2d.scenegraph.ICanvasSceneGraphProvider;
39 import org.simantics.g2d.utils.CanvasUtils;
40 import org.simantics.scenegraph.INode;
41 import org.simantics.scenegraph.ParentNode;
42 import org.simantics.scenegraph.g2d.G2DParentNode;
43 import org.simantics.scenegraph.g2d.G2DRenderingHints;
44 import org.simantics.scenegraph.g2d.G2DSceneGraph;
45 import org.simantics.scenegraph.g2d.IG2DNode;
46 import org.simantics.scenegraph.g2d.IG2DNodeVisitor;
47 import org.simantics.scenegraph.g2d.events.command.Commands;
48 import org.simantics.scenegraph.g2d.nodes.BackgroundNode;
49 import org.simantics.scenegraph.g2d.nodes.BoundsNode;
50 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
51 import org.simantics.scenegraph.g2d.nodes.DataNode;
52 import org.simantics.scenegraph.g2d.nodes.DecorationSVGNode;
53 import org.simantics.scenegraph.g2d.nodes.NavigationNode;
54 import org.simantics.scenegraph.g2d.nodes.SVGNode;
55 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
56 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
57 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphNode;
58 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
59 import org.simantics.scenegraph.utils.NodeUtil;
60 import org.simantics.trend.impl.ItemNode;
61 import org.simantics.utils.threads.ThreadUtils;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import org.w3c.dom.DOMImplementation;
65 import org.w3c.dom.Document;
66 import org.w3c.dom.Element;
67 import org.w3c.dom.NodeList;
69 public class SCLScenegraph {
71 private static final Logger LOGGER = LoggerFactory.getLogger(SCLScenegraph.class);
73 public static ICanvasSceneGraphProvider getICanvasSceneGraphProvider(Resource model, Resource diagram, String diagramRVI) throws DatabaseException, InterruptedException {
74 ICanvasSceneGraphProvider provider = DiagramNodeUtil.loadSceneGraphProvider(model, diagram, diagramRVI);
78 public static void disposeSceneGraphProvider(ICanvasSceneGraphProvider provider) {
82 public static String getNodeTransform(ICanvasContext ctx, String name) {
84 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
85 for (TextNode text : texts) {
86 String nodeName = NodeUtil.getNodeName(text);
87 if (nodeName.equals(name)) {
88 String transform = text.getTransform().toString();
92 return "No node found";
95 public static String getNodeText(ICanvasContext ctx, String name) {
97 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
98 for (TextNode text : texts) {
99 String nodeName = NodeUtil.getNodeName(text);
100 if (nodeName.equals(name)) {
101 String texti = text.getText();
105 return "No node found";
108 public static String getNodeCount(ICanvasContext ctx) {
109 G2DSceneGraph g2 = ctx.getSceneGraph();
110 int amount = NodeUtil.countTreeNodes(g2);
111 return "Node count: " + amount;
114 public static String getAllNodes (ICanvasContext ctx) {
116 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
117 int amount = g2.size() +1;
118 return "All nodes: " + amount;
121 public static String getBoundsNodes (ICanvasContext ctx) {
123 Set<BoundsNode> bn = NodeUtil.collectNodes(ctx.getSceneGraph(), BoundsNode.class);
124 int amount = bn.size();
125 return "BoundsNodes: " + amount;
128 public static String getBackgroundNodes (ICanvasContext ctx) {
130 Set<BackgroundNode> bg = NodeUtil.collectNodes(ctx.getSceneGraph(), BackgroundNode.class);
131 int amount = bg.size();
132 return "BackgroundNodes: " + amount;
135 public static String getDataNodes (ICanvasContext ctx) {
137 Set<DataNode> dn = NodeUtil.collectNodes(ctx.getSceneGraph(), DataNode.class);
138 int amount = dn.size();
139 return "DataNodes: " + amount;
142 public static String getNavigationNodes (ICanvasContext ctx) {
144 Set<NavigationNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), NavigationNode.class);
145 int amount = g2.size();
146 return "NavigationNodes: " + amount;
149 public static String getParentNodes (ICanvasContext ctx) {
151 Set<G2DParentNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DParentNode.class);
152 int amount = g2.size();
153 return "ParentNodes: " + amount;
156 public static String getDecorationNodes (ICanvasContext ctx) {
158 Set<DecorationSVGNode> deco = NodeUtil.collectNodes(ctx.getSceneGraph(), DecorationSVGNode.class);
159 int amount = deco.size();
160 return "DecorationNodes: " + amount;
163 public static String getSingleElementNodes (ICanvasContext ctx) {
165 Set<SingleElementNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), SingleElementNode.class);
166 int amount = g2.size();
167 return "SingleElementNodes: " + amount;
170 public static String getConnectionNodes (ICanvasContext ctx) {
172 Set<ConnectionNode> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), ConnectionNode.class);
173 int amount = g2.size();
174 return "ConnectionNodes: " + amount;
177 public static String getTextNodes (ICanvasContext ctx) {
179 Set<TextNode> tn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
180 Set<TextGridNode> tgn = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
181 int amount = tn.size() + tgn.size();
182 return "TextNodes: " + amount;
185 public static String getItemNodes (ICanvasContext ctx) {
187 Set<ItemNode> item = NodeUtil.collectNodes(ctx.getSceneGraph(), ItemNode.class);
188 int amount = item.size();
189 return "ItemNodes: " + amount;
192 public static String editNodeText (ICanvasContext ctx, String module, String previous_value, String new_value) {
194 Set<TextNode> textGridNodes = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
195 for (TextNode modulenode : textGridNodes) {
196 if (module.equals(modulenode.getText())) {
197 //System.out.println("Module what we were looking for: " + module);
198 //System.out.println("Modulenode: " + modulenode.getText());
200 ParentNode<?> parentnode = modulenode.getParent();
201 //System.out.println("Parentnode: " + parentnode);
203 Collection<TextNode> textnodes = (Collection<TextNode>) parentnode.getNodes();
204 for (TextNode valuenode : textnodes) {
205 if (previous_value.equals(valuenode.getText())) {
206 //System.out.println("Value what we were looking for: " + previous_value);
207 //System.out.println("Valuenode: " + valuenode.getText());
209 //valuenode.setEditMode(true);
210 valuenode.activateEdit(0, null, ctx);
211 valuenode.setText(new_value);
212 valuenode.fireTextEditingEnded();
214 //System.out.println("valuenode modified: " + valuenode);
215 return "Modified module " + module + " with value " + new_value;
218 return "Not found module : " + module;
221 return "No nodes in scenegraph!";
224 public static String sceneGraphTest (ICanvasContext ctx, String module, String value) {
226 boolean module_founded = false;
227 boolean value_founded = false;
229 Set<G2DSceneGraph> g2 = NodeUtil.collectNodes(ctx.getSceneGraph(), G2DSceneGraph.class);
230 System.out.println("Total amount of nodes: " + g2.size() + 1);
232 Set<TextGridNode> grid = NodeUtil.collectNodes(ctx.getSceneGraph(), TextGridNode.class);
233 Integer textGridNodeAmount = grid.size();
234 System.out.println("Amount of TextGridNodes " + textGridNodeAmount);
236 Set<TextNode> texts = NodeUtil.collectNodes(ctx.getSceneGraph(), TextNode.class);
237 Integer textNodeAmount = grid.size();
238 System.out.println("Amount of TextNodes " + textNodeAmount);
240 for (TextNode node : texts) {
241 if (module.equals(node.getText())) {
242 module_founded = true;
243 System.out.println("Correct module " + module + " founded.");
245 if (value.equals(node.getText())) {
246 value_founded = true;
247 System.out.println("Correct value " + value + " founded.");
251 if (value_founded == true && module_founded == true) {
252 return "Found both correct module " + module + " and value " + value;
254 if (value_founded == false && module_founded == true) {
255 return "Found only correct module " + module + " but not value " + value;
257 if (value_founded == true && module_founded == false) {
258 return "Found only correct value " + value + " but not module " + module;
261 return "Didn't found either module " + module + " or value " + value;
265 public static boolean copyPaste (final ICanvasContext source_ctx, final ICanvasContext target_ctx, List<Resource> modules) throws DatabaseException {
267 IDiagram idiagram = source_ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
269 DataElementMap dem = idiagram.getDiagramClass().getAtMostOneItemOfClass(DataElementMap.class);
271 final Collection<IElement> newSelection = new ArrayList<IElement>();
272 for (Resource module : modules) {
273 IElement element = dem.getElement(idiagram, module);
274 if (element != null) {
275 newSelection.add(element);
277 throw new DatabaseException("Could not find IElement for " + element);
281 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
284 if (source_ctx.isDisposed())
286 Selection selection = source_ctx.getAtMostOneItemOfClass(Selection.class);
287 if (selection != null) {
288 // This prevents workbench selection from being left over.
289 // Also prevents scene graph crap from being left on the screen.
290 selection.setSelection(0, newSelection);
292 CanvasUtils.sendCommand(source_ctx, Commands.COPY);
293 CanvasUtils.sendCommand(target_ctx, Commands.PASTE);
299 while(source_ctx.getEventQueue().size() > 0) {
302 } catch (InterruptedException e) {
303 throw new DatabaseException(e);
307 ThreadUtils.syncExec(source_ctx.getThreadAccess(), new Runnable() {
317 static class Generator extends SVGGraphics2D {
320 String newElementId = null;
321 ArrayList<Element> elements = new ArrayList<Element>();
323 public static final String svgNS = "http://www.w3.org/2000/svg";
325 public Generator(SVGGeneratorContext ctx, boolean joku) {
329 public Generator(Document document) {
334 public Element getRoot() {
335 Element root = super.getRoot();
336 for(Element e : elements) {
343 public void setRenderingHint(Key arg0, Object arg1) {
344 if(G2DRenderingHints.KEY_BEGIN_ELEMENT == arg0) {
347 if(G2DRenderingHints.KEY_ELEMENT_ID == arg0) {
349 newElementId = arg1.toString();
351 newElementId = UUID.randomUUID().toString();
353 if(G2DRenderingHints.KEY_END_ELEMENT == arg0) {
356 Element group = getDOMFactory().createElement(SVG_G_TAG);
357 //Element group = getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
358 group.setAttributeNS(null, "id", newElementId);
359 group.setAttributeNS(null, "class", arg1.toString());
364 super.setRenderingHint(arg0, arg1);
369 public static Element renderSVGNode(IG2DNode node) {
371 // Get a DOMImplementation.
372 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
374 // Create an instance of org.w3c.dom.Document.
375 String svgNS = "http://www.w3.org/2000/svg";
376 Document document = domImpl.createDocument(svgNS, "svg", null);
378 SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
379 ctx.setComment(null);
381 // Create an instance of the SVG Generator.
382 SVGGraphics2D svgGenerator = new Generator(ctx, false);
386 svgGenerator.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
387 svgGenerator.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
388 svgGenerator.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
390 node.render(svgGenerator);
392 } catch (Throwable t) {
393 LOGGER.error("Problems rendering scene graph to SVG", t);
396 return svgGenerator.getRoot();
399 public static String printSVGDocument(Element doce) {
401 StringBuilder result = new StringBuilder();
403 NodeList nl = doce.getChildNodes();
405 for(int i=0;i<nl.getLength();i++) {
407 ByteArrayOutputStream os = new ByteArrayOutputStream();
411 TransformerFactory tf = TransformerFactory.newInstance();
412 Transformer transformer = tf.newTransformer();
413 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
414 transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
415 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
416 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
417 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
418 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
420 transformer.transform(new DOMSource(nl.item(i)),
421 new StreamResult(new OutputStreamWriter(os, "UTF-8")));
426 } catch (Throwable t) {
427 LOGGER.error("Problems formatting SVGDocument to text.", t);
430 result.append(new String(os.toByteArray()));
434 return result.toString();
438 public static String renderSVG(ICanvasContext ctx) {
440 // Get a DOMImplementation.
441 DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
443 // Create an instance of org.w3c.dom.Document.
444 String svgNS = "http://www.w3.org/2000/svg";
445 Document document = domImpl.createDocument(svgNS, "svg", null);
447 // Create an instance of the SVG Generator.
448 SVGGraphics2D svgGenerator = new Generator(document);
450 StringBuilder result = new StringBuilder();
454 Selection selection = ctx.getAtMostOneItemOfClass(Selection.class);
455 if (selection != null) {
456 // This prevents workbench selection from being left over.
457 // Also prevents scene graph crap from being left on the screen.
458 IDiagram d = ctx.getDefaultHintContext().getHint(DiagramHints.KEY_DIAGRAM);
459 selection.setSelection(0, d.getElements());
462 G2DSceneGraph sg = ctx.getSceneGraph();
463 G2DParentNode root = (G2DParentNode) sg.getRootNode();
465 // rtree is the actual content of the diagram
466 RTreeNode rtree = NodeUtil.getNearestChildByClass(root, RTreeNode.class);
467 Rectangle2D rtreeBounds = NodeUtil.getLocalBounds(rtree);
469 // nav is a node that has zooming functionalities
470 NavigationNode nav = NodeUtil.getNearestChildByClass(root, NavigationNode.class);
471 nav.setZoomEnabled(true);
473 // fit view with the contents of rtreeBounds
474 nav.zoomTo(rtreeBounds);
476 // get the bounds of the content
477 Rectangle2D content = NodeUtil.getLocalBounds(nav);
479 svgGenerator.scale(3,3);
481 // translate svgGenerator to the x and y coordinates of current content
482 svgGenerator.translate(-1 * content.getX(), (-1 * content.getY()));
484 Rectangle2D destination = new Rectangle2D.Double(0,0,1000,1000);
485 double sx = destination.getWidth() / content.getWidth();
486 double sy = destination.getHeight() / content.getHeight();
487 double scale = sx < sy ? sx : sy;
489 // Set svgCanvasSize to the given size parameters
490 svgGenerator.setSVGCanvasSize(new Dimension((int)(scale * content.getWidth()), (int)(scale * content.getHeight())));
491 svgGenerator.setClip(content);
493 double trX = -1 * content.getX();
494 double trY = -1 * content.getY();
496 result.append("<svg width=\"100%\" height=\"100%\" stroke=\"black\"><g transform=\"translate(").append(trX).append(' ').append(trY).append(")\">");
498 IG2DNodeVisitor visitor = new IG2DNodeVisitor() {
502 HashMap<SingleElementNode,StringBuilder> senBuilders = new HashMap<>();
505 public void enter(IG2DNode node) {
507 StringBuilder parentBuilder = getParentBuilder(node);
510 if(node instanceof ConnectionNode) {
512 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
513 n.setIgnoreSelection(true);
516 String key = ((ConnectionNode)node).getKey().toString();
518 parentBuilder.append("\n<g class=\"connection\" id=\"" + key + "\">");
519 Element doc = renderSVGNode((IG2DNode)node);
520 String svg = printSVGDocument(doc);
521 parentBuilder.append(svg);
523 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
524 n.setIgnoreSelection(false);
527 parentBuilder.append("\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
528 doc = renderSVGNode((IG2DNode)node);
529 svg = printSVGDocument(doc);
530 parentBuilder.append(svg);
531 parentBuilder.append("\n</g>");
533 BasicStroke bs = new BasicStroke(5f);
535 for(RouteGraphNode n : NodeUtil.collectNodes(node, RouteGraphNode.class)) {
536 n.setDynamicStroke(bs);
539 parentBuilder.append("\n<g class=\"selectionMask\" opacity=\"0.001\" id=\"" + key + "\">");
540 doc = renderSVGNode((IG2DNode)node);
541 svg = printSVGDocument(doc);
542 parentBuilder.append(svg);
543 parentBuilder.append("\n</g>");
545 parentBuilder.append("\n</g>");
547 } else if (node instanceof SelectionNode) {
549 SelectionNode n = (SelectionNode)node;
550 SingleElementNode parentSEN = (SingleElementNode)NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
551 if(parentSEN != null && parentSEN.getKey() != null) {
553 StringBuilder parentBuilder2 = getParentBuilder(parentSEN);
555 String key = parentSEN.getKey().toString();
556 Element doc = renderSVGNode((IG2DNode)node);
557 String svg = printSVGDocument(doc);
558 parentBuilder2.append("\n<g style=\"visibility:hidden\" class=\"selection\" id=\"" + key + "\">");
559 parentBuilder2.append(svg);
560 parentBuilder2.append("\n</g>");
561 parentBuilder2.append("\n<g class=\"selectionMask\" id=\"" + key + "\">");
562 Rectangle2D rect = n.getRect();
563 parentBuilder2.append("<rect style=\"fill:#fff\" opacity=\"0.001\"");
564 parentBuilder2.append(" x=\"" + rect.getX() + "\" y=\"" + rect.getY() + "\"");
565 parentBuilder2.append(" width=\"" + rect.getWidth() + "\" height=\"" + rect.getHeight() + "\"");
566 parentBuilder2.append("></rect>");
567 parentBuilder2.append("\n</g>");
569 } else if (node instanceof SVGNode) {
570 SVGNode svg = (SVGNode)node;
571 parentBuilder.append(svg.getSVGText());
572 } else if (node instanceof G2DParentNode) {
573 AffineTransform at = node.getTransform();
574 if(node instanceof SingleElementNode) {
575 SingleElementNode sen = (SingleElementNode)node;
576 if(sen.getKey() != null) {
577 String key = sen.getKey().toString();
578 parentBuilder.append("\n<g class=\"definedElement\" id=\"" + key + "\">");
580 senBuilders.put(sen, new StringBuilder());
582 if(!at.isIdentity()) {
583 if(at.getScaleX() == 1.0 && at.getScaleY() == 1.0 && at.getShearX() == 0.0 && at.getShearY() == 0.0) {
584 String m = "translate(" + at.getTranslateX() + " " + at.getTranslateY() + ")";
585 parentBuilder.append("\n<g transform=\"" + m + "\">");
587 double[] ds = new double[6];
589 String m = "matrix(" + ds[0] + " " + ds[1] + " " + ds[2] + " " + ds[3] + " " + ds[4] + " " + ds[5] + ")";
590 parentBuilder.append("\n<g transform=\"" + m + "\">");
595 //enters.put(node, b.length());
599 private StringBuilder getParentBuilder(IG2DNode node) {
601 INode parentSEN = NodeUtil.getNearestParentOfType(node, SingleElementNode.class);
602 if(parentSEN instanceof G2DSceneGraph) return result;
604 StringBuilder parentBuilder = senBuilders.get(parentSEN);
605 if(parentBuilder == null) return result;
607 return parentBuilder;
612 public void leave(IG2DNode node) {
614 if(node instanceof ConnectionNode || node instanceof SVGNode) {
616 } else if (node instanceof G2DParentNode) {
618 StringBuilder parentBuilder = getParentBuilder(node);
620 if(node instanceof SingleElementNode) {
621 SingleElementNode sen = (SingleElementNode)node;
622 // if(sen.getKey() != null) {
623 StringBuilder b = senBuilders.get(sen);
624 String content = b.toString();
625 if(content.isEmpty()) {
626 if(sen.getKey() != null) {
628 for(SelectionNode n : NodeUtil.collectNodes(node, SelectionNode.class)) {
632 Element doc = renderSVGNode((IG2DNode)node);
633 String svg = printSVGDocument(doc);
634 parentBuilder.append(svg);
637 parentBuilder.append(content);
643 AffineTransform at = node.getTransform();
644 if(!at.isIdentity()) {
645 parentBuilder.append("</g>");
647 if(node instanceof SingleElementNode) {
648 SingleElementNode sen = (SingleElementNode)node;
649 if(sen.getKey() != null) {
650 parentBuilder.append("</g>");
660 } catch (Throwable t) {
661 LOGGER.error("Problems rendering canvas context to SVG", t);
664 result.append("</g></svg>");
665 //System.err.println(" == FINAL RESULT == ");
666 //System.err.println(b);
667 return result.toString();