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.lang.ref.WeakReference;
21 import java.math.BigInteger;
24 import java.security.MessageDigest;
25 import java.security.NoSuchAlgorithmException;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.List;
32 import java.util.WeakHashMap;
34 import org.simantics.scenegraph.ExportableWidget.RasterOutputWidget;
35 import org.simantics.scenegraph.LoaderNode;
36 import org.simantics.scenegraph.ScenegraphUtils;
37 import org.simantics.scenegraph.g2d.G2DNode;
38 import org.simantics.scenegraph.utils.BufferedImage;
39 import org.simantics.scenegraph.utils.G2DUtils;
40 import org.simantics.scenegraph.utils.InitValueSupport;
41 import org.simantics.scenegraph.utils.MipMapBufferedImage;
42 import org.simantics.scenegraph.utils.MipMapVRamBufferedImage;
43 import org.simantics.scenegraph.utils.VRamBufferedImage;
44 import org.simantics.scl.runtime.function.Function1;
45 import org.simantics.scl.runtime.function.Function2;
46 import org.simantics.utils.threads.AWTThread;
48 import com.kitfox.svg.SVGCache;
49 import com.kitfox.svg.SVGDiagram;
50 import com.kitfox.svg.SVGElement;
51 import com.kitfox.svg.SVGException;
52 import com.kitfox.svg.SVGRoot;
53 import com.kitfox.svg.SVGUniverse;
54 import com.kitfox.svg.Text;
55 import com.kitfox.svg.Tspan;
56 import com.kitfox.svg.animation.AnimationElement;
59 public class SVGNode extends G2DNode implements InitValueSupport, LoaderNode {
61 private static final long serialVersionUID = 8508750881358776559L;
63 protected String data = null;
64 protected String defaultData = null;
65 protected Point targetSize = null;
66 protected Boolean useMipMap = true;
67 protected Rectangle2D bounds = null;
69 protected List<SVGNodeAssignment> assignments = new ArrayList<SVGNodeAssignment>();
71 protected transient BufferedImage buffer = null;
72 protected transient String documentCache = null;
73 protected transient SVGDiagram diagramCache = null;
74 protected transient String dataHash = null;
76 static transient Map<String, WeakReference<BufferedImage>> bufferCache = new HashMap<String, WeakReference<BufferedImage>>();
84 public void cleanup() {
88 public void setAssignments(List<SVGNodeAssignment> ass) {
90 assignments.addAll(ass);
93 public void cleanDiagramCache() {
94 SVGDiagram d = diagramCache;
97 SVGUniverse univ = SVGCache.getSVGUniverse();
98 if (univ.decRefCountAndClear(d.getXMLBase()) == 0) {
100 //System.out.println("cleared: " + d.getXMLBase());
105 static WeakHashMap<String, String> dataCache = new WeakHashMap<String, String>();
107 @PropertySetter("SVG")
109 public void setData(String data) {
110 String cached = dataCache.get(data);
111 if (cached == null) {
113 dataCache.put(data, data);
116 this.defaultData = cached;
119 @SyncField("targetSize")
120 public void setTargetSize(Point p) {
121 this.targetSize = p; // FIXME: Point doesn't serialize correctly for some reason
124 @SyncField("targetSize")
125 public void setTargetSize(int x, int y) {
126 this.targetSize = new Point(x, y); // FIXME: Point doesn't serialize correctly for some reason
129 @SyncField("useMipMap")
130 public void useMipMap(Boolean use) {
131 this.useMipMap = use;
134 @PropertySetter("Bounds")
136 public void setBounds(Rectangle2D bounds) {
137 this.bounds = bounds;
141 public Rectangle2D getBoundsInLocal() {
148 public void render(Graphics2D g2d) {
150 return; // Not initialized
152 if (!data.equals(documentCache) || diagramCache == null || buffer == null)
155 AffineTransform ot = null;
156 if (!transform.isIdentity()) {
157 ot = g2d.getTransform();
158 g2d.transform(transform);
165 g2d.setTransform(ot);
168 protected int dynamicHash() {
172 protected String parseSVG() {
176 SVGUniverse univ = SVGCache.getSVGUniverse();
178 Rectangle2D bbox = null;
179 synchronized (univ) {
180 // Relinquish reference to current element
181 if (diagramCache != null) {
182 univ.decRefCount(diagramCache.getXMLBase());
186 // Lets check for rootAssignment that contributes the whole SVG
187 SVGNodeAssignment rootAssignment = null;
188 if (!assignments.isEmpty()) {
189 for (SVGNodeAssignment ass : assignments) {
190 if (ass.attributeNameOrId.equals("$root")) {
191 rootAssignment = ass;
197 if (rootAssignment != null) {
198 dataBytes = rootAssignment.value.getBytes("UTF-8");
200 // NOTE: hard-coded to assume all SVG data is encoded in UTF-8
201 dataBytes = data.getBytes("UTF-8");
203 dataHash = digest(dataBytes, assignments, dynamicHash());
204 URI uri = univ.loadSVG(new ByteArrayInputStream(dataBytes), dataHash);
205 diagramCache = univ.getDiagram(uri, false);
207 if (diagramCache != null) {
208 univ.incRefCount(diagramCache.getXMLBase());
209 SVGRoot root = diagramCache.getRoot();
211 univ.decRefCount(diagramCache.getXMLBase());
212 diagramCache = univ.getDiagram(univ.loadSVG(BROKEN_SVG_DATA), false);
214 univ.incRefCount(diagramCache.getXMLBase());
215 bbox = (Rectangle2D) diagramCache.getRoot().getBoundingBox().clone();
217 bbox = root.getBoundingBox();
218 if (bbox.isEmpty()) {
219 // Lets check if this should be visible or not
220 Set<?> presentationAttributes = root.getPresentationAttributes();
221 if (!presentationAttributes.contains("display")) {
222 // TODO: fix this - How can one read values of attributes in SVG salamander???
223 univ.decRefCount(diagramCache.getXMLBase());
224 diagramCache = univ.getDiagram(univ.loadSVG(EMPTY_SVG_DATA), false);
226 univ.incRefCount(diagramCache.getXMLBase());
227 bbox = (Rectangle2D) root.getBoundingBox().clone();
229 bbox = new Rectangle2D.Double(0, 0, 0, 0);
232 if (applyAssignments(diagramCache, assignments)) {
233 bbox = (Rectangle2D) root.getBoundingBox().clone();
235 bbox = (Rectangle2D) bbox.clone();
240 bbox = new Rectangle2D.Double();
244 documentCache = data;
246 } catch (SVGException e) {
247 // This can only occur if diagramCache != null.
248 setBounds(diagramCache.getViewRect(new Rectangle2D.Double()));
249 univ.decRefCount(diagramCache.getXMLBase());
251 } catch (IOException e) {
258 protected boolean applyAssignments(SVGDiagram diagram, List<SVGNodeAssignment> assignments) throws SVGException {
259 if (assignments.isEmpty())
262 boolean changed = false;
264 for (SVGNodeAssignment ass : assignments) {
265 SVGElement e = diagram.getElement(ass.elementId);
267 if ("$text".equals(ass.attributeNameOrId)) {
268 if (e instanceof Tspan) {
270 if (ass.value.trim().isEmpty()) {
273 t.setText(ass.value);
275 SVGElement parent = t.getParent();
276 if (parent instanceof Text)
277 ((Text) parent).rebuild();
280 } else if (ass.attributeNameOrId.startsWith("#")) {
281 e.setAttribute(ass.attributeNameOrId.substring(1), AnimationElement.AT_CSS, ass.value);
284 e.setAttribute(ass.attributeNameOrId, AnimationElement.AT_AUTO, ass.value);
293 public static Rectangle2D getBounds(String data) {
294 return getBounds(data, 0);
297 public static Rectangle2D getBounds(String data, int dynamicHash) {
298 return getBounds(data, Collections.emptyList(), dynamicHash);
301 public static Rectangle2D getBounds(String data, List<SVGNodeAssignment> assignments, int dynamicHash) {
303 new Exception("null SVG data").printStackTrace();
307 SVGDiagram diagramCache = null;
309 // NOTE: hard-coded to assume all SVG data is encoded in UTF-8
310 byte[] dataBytes = data.getBytes("UTF-8");
311 String digest = digest(dataBytes, assignments, dynamicHash);
313 SVGUniverse univ = SVGCache.getSVGUniverse();
314 // TODO: this completely removes any parallel processing from the SVG loading which would be nice to have.
315 synchronized (univ) {
316 //System.out.println(Thread.currentThread() + ": LOADING SVG: " + digest);
317 URI uri = univ.loadSVG(new ByteArrayInputStream(dataBytes), digest);
318 diagramCache = univ.getDiagram(uri, false);
319 if (diagramCache != null) {
320 if (diagramCache.getRoot() == null) {
321 diagramCache = univ.getDiagram(univ.loadSVG(BROKEN_SVG_DATA));
322 } else if (diagramCache.getRoot().getBoundingBox().isEmpty()) {
323 diagramCache = univ.getDiagram(univ.loadSVG(EMPTY_SVG_DATA));
328 Rectangle2D rect = null;
329 if (diagramCache != null) {
330 SVGRoot root = diagramCache.getRoot();
331 Rectangle2D bbox = root.getBoundingBox();
332 rect = (Rectangle2D) bbox.clone();
334 rect = new Rectangle2D.Double();
337 } catch (SVGException e) {
338 return diagramCache.getViewRect(new Rectangle2D.Double());
339 } catch(IOException e) {
344 public static Rectangle2D getRealBounds(String data) {
345 return getRealBounds(data, Collections.emptyList(), 0);
348 public static Rectangle2D getRealBounds(String data, List<SVGNodeAssignment> assignments, int dynamicHash) {
350 new Exception("null SVG data").printStackTrace();
354 SVGDiagram diagramCache = null;
356 // NOTE: hard-coded to assume all SVG data is encoded in UTF-8
357 byte[] dataBytes = data.getBytes("UTF-8");
358 String digest = digest(dataBytes, assignments, dynamicHash);
360 SVGUniverse univ = SVGCache.getSVGUniverse();
361 // TODO: this completely removes any parallel processing from the SVG loading which would be nice to have.
362 synchronized (univ) {
363 //System.out.println(Thread.currentThread() + ": LOADING SVG: " + digest);
364 URI uri = univ.loadSVG(new ByteArrayInputStream(dataBytes), digest);
365 diagramCache = univ.getDiagram(uri, false);
366 if (diagramCache != null) {
367 SVGRoot root = diagramCache.getRoot();
368 if (root == null) return new Rectangle2D.Double();
369 return (Rectangle2D)root.getBoundingBox().clone();
372 } catch (SVGException e) {
373 return diagramCache.getViewRect(new Rectangle2D.Double());
374 } catch(IOException e) {
379 protected void initBuffer(Graphics2D g2d) {
380 if (!data.equals(documentCache) || diagramCache == null) {
381 dataHash = parseSVG();
382 if (diagramCache == null) {
383 System.err.println("UNABLE TO PARSE SVG:\n" + data);
388 if (buffer != null) {
391 diagramCache.setIgnoringClipHeuristic(true); // FIXME
392 if(bufferCache.containsKey(dataHash) && bufferCache.get(dataHash).get() != null) {
393 buffer = bufferCache.get(dataHash).get();
394 } else if(diagramCache.getViewRect().getWidth()==0 || diagramCache.getViewRect().getHeight()==0) {
396 } else if(useMipMap) {
397 if(G2DUtils.isAccelerated(g2d)) {
398 buffer = new MipMapVRamBufferedImage(diagramCache, bounds, targetSize);
400 buffer = new MipMapBufferedImage(diagramCache, bounds, targetSize);
402 bufferCache.put(dataHash, new WeakReference<BufferedImage>(buffer));
404 if(G2DUtils.isAccelerated(g2d)) {
405 buffer = new VRamBufferedImage(diagramCache, bounds, targetSize);
407 buffer = new BufferedImage(diagramCache, bounds, targetSize);
409 bufferCache.put(dataHash, new WeakReference<BufferedImage>(buffer));
413 public void setProperty(String field, Object value) {
414 if("data".equals(field)) {
415 // System.out.println("SVGNode data -> " + value);
416 this.data = (String)value;
417 } else if ("z".equals(field)) {
418 // System.out.println("SVGNode z -> " + value);
419 setZIndex((Integer)value);
420 } else if ("position".equals(field)) {
421 // System.out.println("SVGNode position -> " + value);
422 Point point = (Point)value;
423 setTransform(AffineTransform.getTranslateInstance(point.x, point.y));
424 // setPosition(point.x, point.y);
429 public void initValues() {
435 static WeakHashMap<String, String> digestCache = new WeakHashMap<String, String>();
437 static String digest(byte[] dataBytes, List<SVGNodeAssignment> assignments, int dynamicHash) {
439 MessageDigest md = MessageDigest.getInstance("MD5");
440 byte[] messageDigest = md.digest(dataBytes);
441 BigInteger number = new BigInteger(1, messageDigest);
442 String dataHash = number.toString(16) + (assignments != null ? assignments.hashCode() : 0) + 31 * dynamicHash;
443 String result = digestCache.get(dataHash);
446 digestCache.put(dataHash,dataHash);
449 } catch (NoSuchAlgorithmException e) {
451 throw new Error("MD5 digest must exist.");
455 static URL BROKEN_SVG_DATA = SVGNode.class.getResource("broken.svg");
456 static URL EMPTY_SVG_DATA = SVGNode.class.getResource("empty.svg");
459 public Function1<Object, Boolean> getPropertyFunction(String propertyName) {
460 return ScenegraphUtils.getMethodPropertyFunction(AWTThread.getThreadAccess(), this, propertyName);
464 public <T> T getProperty(String propertyName) {
469 public void setPropertyCallback(Function2<String, Object, Boolean> callback) {
472 public void synchronizeDocument(String document) {
476 public void synchronizeTransform(double[] data) {
477 this.setTransform(new AffineTransform(data));
480 public String getSVGText() {
481 String ret = data.replace("<svg", "<g").replaceAll("svg>", "g>");
482 //return diagramCache.toString();
483 //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>");