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;
14 import java.awt.Component;
15 import java.awt.Container;
16 import java.awt.Graphics2D;
17 import java.util.ArrayDeque;
18 import java.util.Deque;
19 import java.util.HashMap;
20 import java.util.HashSet;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
26 import javax.swing.JComponent;
27 import javax.swing.RepaintManager;
29 import org.simantics.scenegraph.ILookupService;
30 import org.simantics.scenegraph.INode;
31 import org.simantics.scenegraph.LookupService;
32 import org.simantics.scenegraph.ParentNode;
33 import org.simantics.scenegraph.g2d.events.EventDelegator;
34 import org.simantics.scenegraph.g2d.events.INodeEventHandlerProvider;
35 import org.simantics.scenegraph.g2d.events.NodeEventHandler;
38 * The root node of a 2D scene graph.
40 * Implements {@link ILookupService} according to the reference implementation
41 * {@link LookupService}.
45 @SuppressWarnings("deprecation")
46 public class G2DSceneGraph extends G2DParentNode implements ILookupService, INodeEventHandlerProvider {
48 private static final long serialVersionUID = -7066146333849901429L;
50 public static final String IGNORE_FOCUS = "ignoreFocus";
52 protected transient Container rootPane = null;
53 // TODO: swing dependency in here might not be a good idea
55 // This variable is actually used in remote use, when rendering is not performed locally
56 private transient final Object treeLock = new Object();
58 private HashMap<Object, Integer> pending = new HashMap<Object, Integer>();
59 private HashMap<String, Object> globalProperties = new HashMap<String, Object>();
62 * For preventing duplicates on the nodesToRemove queue.
64 protected transient Set<INode> nodesToRemoveSet = new HashSet<INode>();
65 protected Deque<INode> nodesToRemove = new ArrayDeque<INode>();
67 private transient EventDelegator eventDelegator = new EventDelegator(this);
68 private transient NodeEventHandler eventHandler = new NodeEventHandler(this);
71 * The node that has input focus in the scene graph. The input node will
72 * receive key and command events.
74 private transient IG2DNode focusNode;
77 * The custom repaint manager of this scene graph.
79 private transient G2DRepaintManager repaintManager;
82 * Returns the event delegator, that is responsible for delegating events to nodes in the sg tree
84 * @return EventDelegator instance, always not null
86 public EventDelegator getEventDelegator() {
87 return eventDelegator;
91 * Returns the node event handler, that is responsible for delegating events
92 * to nodes in the sg tree.
94 * @return NodeEventHandler instance for this scene graph, always non-null
96 public NodeEventHandler getEventHandler() {
100 public void setFocusNode(IG2DNode focusNode) {
101 this.focusNode = focusNode;
104 public IG2DNode getFocusNode() {
109 public void render(Graphics2D g2d) {
111 Component rootPane = getRootPane();
112 if (rootPane != null)
113 g2d.setRenderingHint(G2DRenderingHints.KEY_COMPONENT, rootPane);
114 synchronized(treeLock) {
120 * Util method for executing updates to scenegraph tree
121 * NOTE: You should really consider performance issues when using this
123 * @param r Runnable to be executed while rendering is not performed
125 public void syncExec(Runnable r) {
126 synchronized(treeLock) {
132 * Set rootpane for swing components. This is used as parent for the components created by ComponentNode.
134 * @param rootPane Component that is used as a parent for the swing component (This shouldn't be visible)
136 public void setRootPane(JComponent rootPane) {
137 synchronized (RepaintManager.class) {
138 RepaintManager old = RepaintManager.currentManager(rootPane);
139 old = findProperRepaintManager(old);
140 this.repaintManager = new G2DRepaintManager(rootPane.getClass(), old);
141 RepaintManager.setCurrentManager(repaintManager);
143 this.rootPane = rootPane;
147 * Set rootpane for swing components. This is used as parent for the components created by ComponentNode.
148 * Supports separate component that is responsible for repainting the scenegraph.
150 * @param rootPane Component that is used as a parent for the swing component (This shouldn't be visible)
151 * @param paintContext Component that is responsible for repainting the scenegraph
153 public void setRootPane(Container rootPane, Component paintContext) {
154 synchronized (RepaintManager.class) {
155 RepaintManager old = RepaintManager.currentManager(paintContext);
156 old = findProperRepaintManager(old);
157 this.repaintManager = new G2DRepaintManager(paintContext.getClass(), old);
158 RepaintManager.setCurrentManager(repaintManager);
160 this.rootPane = rootPane;
161 eventHandler.setRootPane(rootPane);
164 private RepaintManager findProperRepaintManager(RepaintManager old) {
165 while (old instanceof G2DRepaintManager) {
166 G2DRepaintManager g2drm = (G2DRepaintManager) old;
167 old = g2drm.getDelegate();
172 public G2DRepaintManager getRepaintManager() {
173 return repaintManager;
177 * Put the node to the remove queue
180 public void asyncRemoveNode(INode node) {
181 synchronized(nodesToRemove) {
182 // Prevent nodes from winding up twice on the nodesToRemove queue
183 if (nodesToRemoveSet.add(node)) {
184 nodesToRemove.add(node); // This is performed when called inside the render
190 * Perform the actual removal of the nodes in the nodesToRemove list
192 public void performCleanup() {
193 synchronized(nodesToRemove) {
194 while(nodesToRemove.size() > 0) {
195 INode node = nodesToRemove.removeFirst();
196 ParentNode<?> parent = node.getParent();
197 // This works around issue #2071
199 parent.removeNode(node);
201 if (!nodesToRemoveSet.isEmpty())
202 nodesToRemoveSet.clear();
207 public void cleanup() {
209 nodesToRemove.clear();
210 nodesToRemove = null;
211 nodesToRemoveSet.clear();
212 nodesToRemoveSet = null;
213 eventHandler.dispose();
215 eventDelegator.dispose();
216 eventDelegator = null;
219 public Container getRootPane() {
220 return (Container) this.rootPane;
224 public String toString() {
225 return super.toString() + " [root pane=" + rootPane + "]";
229 public ParentNode<?> getRootNode() {
230 // This is a root node!
234 // ILookupService implementation
236 private final Object lookupLock = new Object();
237 private final Map<String, INode> toNode = new HashMap<String, INode>();
238 private final Map<INode, String> toId = new HashMap<INode, String>();
240 transient Logger logger = Logger.getLogger(getClass().getName());
243 public INode map(String id, INode node) {
245 throw new NullPointerException("null id");
247 throw new NullPointerException("null node");
251 synchronized (lookupLock) {
252 oldNode = toNode.put(id, node);
253 oldId = toId.put(node, id);
255 // Keep the mapping a consistent bijection:
256 // If ID => INode mapping is removed, the INode => ID mappings must
259 if (oldNode != null && !oldNode.equals(node)) {
260 String removedId = toId.remove(oldNode);
261 if (!id.equals(removedId))
262 toNode.remove(removedId);
264 if (oldId != null && !oldId.equals(id)) {
265 INode removedNode = toNode.remove(oldId);
266 if (removedNode != node)
267 toId.remove(removedNode);
270 if (logger.isLoggable(Level.FINER))
271 logger.fine("map(" + id + ", " + node + ")");
272 if (oldNode != null || oldId != null) {
273 if (logger.isLoggable(Level.FINE)) {
274 logger.info("replaced mappings for ID " + oldId + " and node " + oldNode);
281 public INode unmap(String id) {
284 synchronized (lookupLock) {
285 node = toNode.remove(id);
288 mappedId = toId.remove(node);
290 if (logger.isLoggable(Level.FINER))
291 logger.fine("unmap(" + id + "): " + node);
292 if (mappedId != null && !mappedId.equals(id)) {
293 if (logger.isLoggable(Level.WARNING))
294 logger.log(Level.WARNING, "mapping was out-of-sync: " + id + " => " + node + " & " + mappedId + " => " + node, new Exception("trace"));
300 public String unmap(INode node) {
303 synchronized (lookupLock) {
304 id = toId.remove(node);
307 mappedNode = toNode.remove(id);
309 if (logger.isLoggable(Level.FINER))
310 logger.fine("unmap(" + node + "): " + id);
311 if (mappedNode != null && node != mappedNode) {
312 if (logger.isLoggable(Level.WARNING))
313 logger.log(Level.WARNING, "mapping was out-of-sync: " + node + " => " + id + " & " + id + " => " + mappedNode, new Exception("trace"));
319 public INode lookupNode(String id) {
320 synchronized (lookupLock) {
321 return toNode.get(id);
326 public String lookupId(INode node) {
327 synchronized (lookupLock) {
328 return toId.get(node);
332 public boolean isPending() {
333 return !pending.isEmpty();
336 synchronized public void increasePending(Object object) {
337 Integer ref = pending.get(object);
338 if (ref == null) pending.put(object, 1);
339 else pending.put(object, ref+1);
342 synchronized public void setPending(Object object) {
343 pending.put(object, 1);
346 synchronized public void clearPending(Object object) {
347 pending.remove(object);
350 synchronized public void decreasePending(Object object) {
351 Integer ref = pending.get(object);
354 //throw new IllegalStateException("Ref count in unregister was 0 for " + object);
356 if (ref > 1) pending.put(object, ref-1);
357 else if (ref==1) pending.remove(object);
360 //throw new IllegalStateException("Ref count in unregister was 0 for " + object);
364 synchronized public void setGlobalProperty(String key, Object value) {
365 globalProperties.put(key, value);
368 @SuppressWarnings("unchecked")
369 synchronized public <T> T getGlobalProperty(String key, T defaultValue) {
370 T t = (T)globalProperties.get(key);
371 if(t == null) return defaultValue;