1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.scenegraph.g2d.nodes;
14 import java.awt.Graphics2D;
15 import java.awt.Point;
16 import java.awt.geom.AffineTransform;
17 import java.awt.geom.Rectangle2D;
18 import java.io.ByteArrayInputStream;
19 import java.io.IOException;
20 import java.io.StringReader;
21 import java.io.StringWriter;
22 import java.lang.ref.WeakReference;
23 import java.math.BigInteger;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
34 import java.util.WeakHashMap;
36 import javax.xml.parsers.DocumentBuilder;
37 import javax.xml.parsers.DocumentBuilderFactory;
38 import javax.xml.parsers.ParserConfigurationException;
39 import javax.xml.transform.Transformer;
40 import javax.xml.transform.TransformerFactory;
41 import javax.xml.transform.dom.DOMSource;
42 import javax.xml.transform.stream.StreamResult;
44 import org.simantics.scenegraph.ExportableWidget.RasterOutputWidget;
45 import org.simantics.scenegraph.LoaderNode;
46 import org.simantics.scenegraph.ScenegraphUtils;
47 import org.simantics.scenegraph.g2d.G2DNode;
48 import org.simantics.scenegraph.g2d.G2DRenderingHints;
49 import org.simantics.scenegraph.utils.BufferedImage;
50 import org.simantics.scenegraph.utils.G2DUtils;
51 import org.simantics.scenegraph.utils.InitValueSupport;
52 import org.simantics.scenegraph.utils.MipMapBufferedImage;
53 import org.simantics.scenegraph.utils.MipMapVRamBufferedImage;
54 import org.simantics.scenegraph.utils.SVGPassthruShape;
55 import org.simantics.scenegraph.utils.VRamBufferedImage;
56 import org.simantics.scl.runtime.function.Function1;
57 import org.simantics.scl.runtime.function.Function2;
58 import org.simantics.utils.threads.AWTThread;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.w3c.dom.Document;
62 import org.w3c.dom.Element;
63 import org.w3c.dom.NodeList;
64 import org.xml.sax.InputSource;
66 import com.kitfox.svg.RenderableElement;
67 import com.kitfox.svg.SVGCache;
68 import com.kitfox.svg.SVGDiagram;
69 import com.kitfox.svg.SVGElement;
70 import com.kitfox.svg.SVGException;
71 import com.kitfox.svg.SVGRoot;
72 import com.kitfox.svg.SVGUniverse;
73 import com.kitfox.svg.Text;
74 import com.kitfox.svg.Tspan;
75 import com.kitfox.svg.animation.AnimationElement;
78 public class SVGNode extends G2DNode implements InitValueSupport, LoaderNode {
80 private static final long serialVersionUID = 8508750881358776559L;
82 private static final Logger LOGGER = LoggerFactory.getLogger(SVGNode.class);
83 protected String data = null;
84 protected String defaultData = null;
85 protected Point targetSize = null;
86 protected Boolean useMipMap = true;
87 protected Rectangle2D bounds = null;
89 protected List<SVGNodeAssignment> assignments = new ArrayList<SVGNodeAssignment>();
91 protected transient BufferedImage buffer = null;
92 protected transient String documentCache = null;
93 protected transient SVGDiagram diagramCache = null;
94 protected transient String dataHash = null;
96 static transient Map<String, WeakReference<BufferedImage>> bufferCache = new HashMap<String, WeakReference<BufferedImage>>();
104 public void cleanup() {
108 public void setAssignments(List<SVGNodeAssignment> ass) {
110 assignments.addAll(ass);
113 public void cleanDiagramCache() {
114 SVGDiagram d = diagramCache;
118 SVGUniverse univ = SVGCache.getSVGUniverse();
119 if (univ.decRefCountAndClear(d.getXMLBase()) == 0) {
121 //System.out.println("cleared: " + d.getXMLBase());
126 static WeakHashMap<String, String> dataCache = new WeakHashMap<String, String>();
128 @PropertySetter("SVG")
130 public void setData(String data) {
131 String cached = dataCache.get(data);
132 if (cached == null) {
134 dataCache.put(data, data);
137 this.defaultData = cached;
141 @SyncField("targetSize")
142 public void setTargetSize(Point p) {
143 this.targetSize = p; // FIXME: Point doesn't serialize correctly for some reason
146 @SyncField("targetSize")
147 public void setTargetSize(int x, int y) {
148 this.targetSize = new Point(x, y); // FIXME: Point doesn't serialize correctly for some reason
151 @SyncField("useMipMap")
152 public void useMipMap(Boolean use) {
153 this.useMipMap = use;
156 @PropertySetter("Bounds")
158 public void setBounds(Rectangle2D bounds) {
159 this.bounds = bounds;
163 public Rectangle2D getBoundsInLocal() {
170 public void render(Graphics2D g2d) {
172 return; // Not initialized
174 AffineTransform ot = null;
175 if (!transform.isIdentity()) {
176 ot = g2d.getTransform();
177 g2d.transform(transform);
180 if (g2d.getRenderingHint(G2DRenderingHints.KEY_SVG_PASSTHRU) == Boolean.TRUE) {
181 SVGPassthruShape.resetG2D(g2d);
182 String svg = assignments.isEmpty() ? data : applyAssigments(data, assignments);
184 g2d.fill(new SVGPassthruShape(svg));
187 if (!data.equals(documentCache) || diagramCache == null || buffer == null)
195 g2d.setTransform(ot);
198 protected int dynamicHash() {
202 protected String parseSVG() {
206 SVGUniverse univ = SVGCache.getSVGUniverse();
208 Rectangle2D bbox = null;
209 synchronized (univ) {
210 // Relinquish reference to current element
211 if (diagramCache != null) {
212 univ.decRefCount(diagramCache.getXMLBase());
216 // Lets check for rootAssignment that contributes the whole SVG
217 SVGNodeAssignment rootAssignment = null;
218 if (!assignments.isEmpty()) {
219 for (SVGNodeAssignment ass : assignments) {
220 if (ass.attributeNameOrId.equals("$root")) {
221 rootAssignment = ass;
227 if (rootAssignment != null) {
228 dataBytes = rootAssignment.value.getBytes("UTF-8");
230 // NOTE: hard-coded to assume all SVG data is encoded in UTF-8
231 dataBytes = data.getBytes("UTF-8");
233 dataHash = digest(dataBytes, assignments, dynamicHash());
234 URI uri = univ.loadSVG(new ByteArrayInputStream(dataBytes), dataHash);
235 diagramCache = univ.getDiagram(uri, false);
237 if (diagramCache != null) {
238 univ.incRefCount(diagramCache.getXMLBase());
239 SVGRoot root = diagramCache.getRoot();
241 univ.decRefCount(diagramCache.getXMLBase());
242 diagramCache = univ.getDiagram(univ.loadSVG(BROKEN_SVG_DATA), false);
244 univ.incRefCount(diagramCache.getXMLBase());
245 bbox = (Rectangle2D) diagramCache.getRoot().getBoundingBox().clone();
247 bbox = root.getBoundingBox();
248 if (bbox.isEmpty()) {
249 // Lets check if this should be visible or not
250 Set<?> presentationAttributes = root.getPresentationAttributes();
251 if (!presentationAttributes.contains("display")) {
252 // TODO: fix this - How can one read values of attributes in SVG salamander???
253 univ.decRefCount(diagramCache.getXMLBase());
254 diagramCache = univ.getDiagram(univ.loadSVG(EMPTY_SVG_DATA), false);
256 univ.incRefCount(diagramCache.getXMLBase());
257 bbox = (Rectangle2D) root.getBoundingBox().clone();
259 bbox = new Rectangle2D.Double(0, 0, 0, 0);
262 if (applyAssignments(diagramCache, assignments)) {
263 bbox = (Rectangle2D) root.getBoundingBox().clone();
265 bbox = (Rectangle2D) bbox.clone();
270 bbox = new Rectangle2D.Double();
274 documentCache = data;
276 } catch (SVGException e) {
277 // This can only occur if diagramCache != null.
278 setBounds(diagramCache.getViewRect(new Rectangle2D.Double()));
279 univ.decRefCount(diagramCache.getXMLBase());
281 } catch (IOException e) {
288 private static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
290 dbf.setValidating(false);
292 dbf.setFeature("http://xml.org/sax/features/namespaces", false);
293 dbf.setFeature("http://xml.org/sax/features/validation", false);
294 dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
295 dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
296 } catch (ParserConfigurationException e) {
301 // Notice: Remember to change both implementations of applyAssigments when modifying the functionality.
302 protected static String applyAssigments(String svg, List<SVGNodeAssignment> assignments) {
304 DocumentBuilder db = dbf.newDocumentBuilder();
305 Document doc = db.parse(new InputSource(new StringReader(svg)));
307 NodeList entries = doc.getElementsByTagName("*");
308 for (int i=0; i<entries.getLength(); i++) {
309 Element element = (Element) entries.item(i);
310 if (element.hasAttribute("id")) {
311 element.setIdAttribute("id", true);
314 for (SVGNodeAssignment ass : assignments) {
315 Element e = doc.getElementById(ass.elementId);
317 if ("$text".equals(ass.attributeNameOrId)) {
318 if (e.getTagName().equals("tspan")) {
319 if (ass.value.trim().isEmpty()) {
320 e.setTextContent("-");
322 e.setTextContent(ass.value);
325 } else if (ass.attributeNameOrId.startsWith("#")) {
326 e.setAttribute(ass.attributeNameOrId.substring(1), ass.value);
328 e.setAttribute(ass.attributeNameOrId, ass.value);
331 LOGGER.warn("Element with id='" + ass.elementId + " was not found.");
335 DOMSource domSource = new DOMSource(doc);
336 StringWriter writer = new StringWriter();
337 StreamResult result = new StreamResult(writer);
338 TransformerFactory tf = TransformerFactory.newInstance();
339 Transformer transformer = tf.newTransformer();
340 transformer.transform(domSource, result);
341 return writer.toString();
343 } catch (Exception e) {
348 // Notice: Remember to change both implementations of applyAssigments when modifying the functionality.
349 protected boolean applyAssignments(SVGDiagram diagram, List<SVGNodeAssignment> assignments) throws SVGException {
350 if (assignments.isEmpty())
353 boolean changed = false;
355 // Without this elements are sometimes not found by id!
356 diagram.updateTime(0);
358 for (SVGNodeAssignment ass : assignments) {
359 SVGElement e = diagram.getElement(ass.elementId);
361 if ("$text".equals(ass.attributeNameOrId)) {
362 if (e instanceof Tspan) {
364 if (ass.value.trim().isEmpty()) {
367 t.setText(ass.value);
369 SVGElement parent = t.getParent();
370 if (parent instanceof Text)
371 ((Text) parent).rebuild();
374 } else if (ass.attributeNameOrId.startsWith("#")) {
375 e.setAttribute(ass.attributeNameOrId.substring(1), AnimationElement.AT_CSS, ass.value);
378 e.setAttribute(ass.attributeNameOrId, AnimationElement.AT_AUTO, ass.value);
384 // Without this the attribute values are not correctly reflected in rendering
385 diagram.updateTime(0);
390 public static Rectangle2D getBounds(String data) {
391 return getBounds(data, 0);
394 public static Rectangle2D getBounds(String data, int dynamicHash) {
395 return getBounds(data, Collections.emptyList(), dynamicHash);
398 public static Rectangle2D getBounds(String data, List<SVGNodeAssignment> assignments, int dynamicHash) {
400 new Exception("null SVG data").printStackTrace();
404 SVGDiagram diagramCache = null;
406 // NOTE: hard-coded to assume all SVG data is encoded in UTF-8
407 byte[] dataBytes = data.getBytes("UTF-8");
408 String digest = digest(dataBytes, assignments, dynamicHash);
410 SVGUniverse univ = SVGCache.getSVGUniverse();
411 // TODO: this completely removes any parallel processing from the SVG loading which would be nice to have.
412 synchronized (univ) {
413 //System.out.println(Thread.currentThread() + ": LOADING SVG: " + digest);
414 URI uri = univ.loadSVG(new ByteArrayInputStream(dataBytes), digest);
415 diagramCache = univ.getDiagram(uri, false);
416 if (diagramCache != null) {
417 if (diagramCache.getRoot() == null) {
418 diagramCache = univ.getDiagram(univ.loadSVG(BROKEN_SVG_DATA));
419 } else if (diagramCache.getRoot().getBoundingBox().isEmpty()) {
420 diagramCache = univ.getDiagram(univ.loadSVG(EMPTY_SVG_DATA));
425 Rectangle2D rect = null;
426 if (diagramCache != null) {
427 SVGRoot root = diagramCache.getRoot();
428 Rectangle2D bbox = root.getBoundingBox();
429 rect = (Rectangle2D) bbox.clone();
431 rect = new Rectangle2D.Double();
434 } catch (SVGException e) {
435 return diagramCache.getViewRect(new Rectangle2D.Double());
436 } catch(IOException e) {
441 public static Rectangle2D getRealBounds(String data) {
442 return getRealBounds(data, Collections.emptyList(), 0);
445 public static Rectangle2D getRealBounds(String data, List<SVGNodeAssignment> assignments, int dynamicHash) {
447 new Exception("null SVG data").printStackTrace();
451 SVGDiagram diagramCache = null;
453 // NOTE: hard-coded to assume all SVG data is encoded in UTF-8
454 byte[] dataBytes = data.getBytes("UTF-8");
455 String digest = digest(dataBytes, assignments, dynamicHash);
457 SVGUniverse univ = SVGCache.getSVGUniverse();
458 // TODO: this completely removes any parallel processing from the SVG loading which would be nice to have.
459 synchronized (univ) {
460 //System.out.println(Thread.currentThread() + ": LOADING SVG: " + digest);
461 URI uri = univ.loadSVG(new ByteArrayInputStream(dataBytes), digest);
462 diagramCache = univ.getDiagram(uri, false);
463 if (diagramCache != null) {
464 SVGRoot root = diagramCache.getRoot();
465 if (root == null) return new Rectangle2D.Double();
466 return (Rectangle2D)root.getBoundingBox().clone();
469 } catch (SVGException e) {
470 return diagramCache.getViewRect(new Rectangle2D.Double());
471 } catch(IOException e) {
476 protected void initBuffer(Graphics2D g2d) {
477 if (!data.equals(documentCache) || diagramCache == null) {
478 dataHash = parseSVG();
479 if (diagramCache == null) {
480 LOGGER.warn("UNABLE TO PARSE SVG:\n" + data);
485 if (buffer != null) {
488 diagramCache.setIgnoringClipHeuristic(true); // FIXME
489 if(bufferCache.containsKey(dataHash) && bufferCache.get(dataHash).get() != null) {
490 buffer = bufferCache.get(dataHash).get();
491 } else if(diagramCache.getViewRect().getWidth()==0 || diagramCache.getViewRect().getHeight()==0) {
493 } else if(useMipMap) {
494 if(G2DUtils.isAccelerated(g2d)) {
495 buffer = new MipMapVRamBufferedImage(diagramCache, bounds, targetSize);
497 buffer = new MipMapBufferedImage(diagramCache, bounds, targetSize);
499 bufferCache.put(dataHash, new WeakReference<BufferedImage>(buffer));
501 if(G2DUtils.isAccelerated(g2d)) {
502 buffer = new VRamBufferedImage(diagramCache, bounds, targetSize);
504 buffer = new BufferedImage(diagramCache, bounds, targetSize);
506 bufferCache.put(dataHash, new WeakReference<BufferedImage>(buffer));
510 public void setProperty(String field, Object value) {
511 if("data".equals(field)) {
512 // System.out.println("SVGNode data -> " + value);
513 this.data = (String)value;
514 } else if ("z".equals(field)) {
515 // System.out.println("SVGNode z -> " + value);
516 setZIndex((Integer)value);
517 } else if ("position".equals(field)) {
518 // System.out.println("SVGNode position -> " + value);
519 Point point = (Point)value;
520 setTransform(AffineTransform.getTranslateInstance(point.x, point.y));
521 // setPosition(point.x, point.y);
526 public void initValues() {
532 static WeakHashMap<String, String> digestCache = new WeakHashMap<String, String>();
534 static String digest(byte[] dataBytes, List<SVGNodeAssignment> assignments, int dynamicHash) {
536 MessageDigest md = MessageDigest.getInstance("MD5");
537 byte[] messageDigest = md.digest(dataBytes);
538 BigInteger number = new BigInteger(1, messageDigest);
539 String dataHash = number.toString(16) + (assignments != null ? assignments.hashCode() : 0) + 31 * dynamicHash;
540 String result = digestCache.get(dataHash);
543 digestCache.put(dataHash,dataHash);
546 } catch (NoSuchAlgorithmException e) {
548 throw new Error("MD5 digest must exist.");
552 static URL BROKEN_SVG_DATA = SVGNode.class.getResource("broken.svg");
553 static URL EMPTY_SVG_DATA = SVGNode.class.getResource("empty.svg");
556 public Function1<Object, Boolean> getPropertyFunction(String propertyName) {
557 return ScenegraphUtils.getMethodPropertyFunction(AWTThread.getThreadAccess(), this, propertyName);
561 public <T> T getProperty(String propertyName) {
566 public void setPropertyCallback(Function2<String, Object, Boolean> callback) {
569 public void synchronizeDocument(String document) {
573 public void synchronizeTransform(double[] data) {
574 this.setTransform(new AffineTransform(data));
577 public String getSVGText() {
578 String ret = data.replace("<svg", "<g").replaceAll("svg>", "g>");
579 //return diagramCache.toString();
580 //return data.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg xmlns=\"http://www.w3.org/2000/svg\" overflow=\"visible\" version=\"1.1\"", "<g").replaceAll("svg>", "/g>");
584 public Rectangle2D getElementBounds(String id) throws SVGException {
585 SVGElement e = diagramCache.getElement(id);
586 if (e instanceof RenderableElement) {
587 return ((RenderableElement)e).getBoundingBox();