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;
163 private RepaintManager findProperRepaintManager(RepaintManager old) {
164 while (old instanceof G2DRepaintManager) {
165 G2DRepaintManager g2drm = (G2DRepaintManager) old;
166 old = g2drm.getDelegate();
171 public G2DRepaintManager getRepaintManager() {
172 return repaintManager;
176 * Put the node to the remove queue
179 public void asyncRemoveNode(INode node) {
180 synchronized(nodesToRemove) {
181 // Prevent nodes from winding up twice on the nodesToRemove queue
182 if (nodesToRemoveSet.add(node)) {
183 nodesToRemove.add(node); // This is performed when called inside the render
189 * Perform the actual removal of the nodes in the nodesToRemove list
191 public void performCleanup() {
192 synchronized(nodesToRemove) {
193 while(nodesToRemove.size() > 0) {
194 INode node = nodesToRemove.removeFirst();
195 ParentNode<?> parent = node.getParent();
196 // This works around issue #2071
198 parent.removeNode(node);
200 if (!nodesToRemoveSet.isEmpty())
201 nodesToRemoveSet.clear();
206 public void cleanup() {
208 nodesToRemove.clear();
209 nodesToRemove = null;
210 nodesToRemoveSet.clear();
211 nodesToRemoveSet = null;
212 eventHandler.dispose();
214 eventDelegator.dispose();
215 eventDelegator = null;
218 public Container getRootPane() {
219 return (Container) this.rootPane;
223 public String toString() {
224 return super.toString() + " [root pane=" + rootPane + "]";
228 public ParentNode<?> getRootNode() {
229 // This is a root node!
233 // ILookupService implementation
235 private final Object lookupLock = new Object();
236 private final Map<String, INode> toNode = new HashMap<String, INode>();
237 private final Map<INode, String> toId = new HashMap<INode, String>();
239 transient Logger logger = Logger.getLogger(getClass().getName());
242 public INode map(String id, INode node) {
244 throw new NullPointerException("null id");
246 throw new NullPointerException("null node");
250 synchronized (lookupLock) {
251 oldNode = toNode.put(id, node);
252 oldId = toId.put(node, id);
254 // Keep the mapping a consistent bijection:
255 // If ID => INode mapping is removed, the INode => ID mappings must
258 if (oldNode != null && !oldNode.equals(node)) {
259 String removedId = toId.remove(oldNode);
260 if (!id.equals(removedId))
261 toNode.remove(removedId);
263 if (oldId != null && !oldId.equals(id)) {
264 INode removedNode = toNode.remove(oldId);
265 if (removedNode != node)
266 toId.remove(removedNode);
269 if (logger.isLoggable(Level.FINER))
270 logger.fine("map(" + id + ", " + node + ")");
271 if (oldNode != null || oldId != null) {
272 if (logger.isLoggable(Level.FINE)) {
273 logger.info("replaced mappings for ID " + oldId + " and node " + oldNode);
280 public INode unmap(String id) {
283 synchronized (lookupLock) {
284 node = toNode.remove(id);
287 mappedId = toId.remove(node);
289 if (logger.isLoggable(Level.FINER))
290 logger.fine("unmap(" + id + "): " + node);
291 if (mappedId != null && !mappedId.equals(id)) {
292 if (logger.isLoggable(Level.WARNING))
293 logger.log(Level.WARNING, "mapping was out-of-sync: " + id + " => " + node + " & " + mappedId + " => " + node, new Exception("trace"));
299 public String unmap(INode node) {
302 synchronized (lookupLock) {
303 id = toId.remove(node);
306 mappedNode = toNode.remove(id);
308 if (logger.isLoggable(Level.FINER))
309 logger.fine("unmap(" + node + "): " + id);
310 if (mappedNode != null && node != mappedNode) {
311 if (logger.isLoggable(Level.WARNING))
312 logger.log(Level.WARNING, "mapping was out-of-sync: " + node + " => " + id + " & " + id + " => " + mappedNode, new Exception("trace"));
318 public INode lookupNode(String id) {
319 synchronized (lookupLock) {
320 return toNode.get(id);
325 public String lookupId(INode node) {
326 synchronized (lookupLock) {
327 return toId.get(node);
331 public boolean isPending() {
332 return !pending.isEmpty();
335 synchronized public void increasePending(Object object) {
336 Integer ref = pending.get(object);
337 if (ref == null) pending.put(object, 1);
338 else pending.put(object, ref+1);
341 synchronized public void setPending(Object object) {
342 pending.put(object, 1);
345 synchronized public void clearPending(Object object) {
346 pending.remove(object);
349 synchronized public void decreasePending(Object object) {
350 Integer ref = pending.get(object);
353 //throw new IllegalStateException("Ref count in unregister was 0 for " + object);
355 if (ref > 1) pending.put(object, ref-1);
356 else if (ref==1) pending.remove(object);
359 //throw new IllegalStateException("Ref count in unregister was 0 for " + object);
363 synchronized public void setGlobalProperty(String key, Object value) {
364 globalProperties.put(key, value);
367 @SuppressWarnings("unchecked")
368 synchronized public <T> T getGlobalProperty(String key, T defaultValue) {
369 T t = (T)globalProperties.get(key);
370 if(t == null) return defaultValue;