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 public void refresh() {
126 * Util method for executing updates to scenegraph tree
127 * NOTE: You should really consider performance issues when using this
129 * @param r Runnable to be executed while rendering is not performed
131 public void syncExec(Runnable r) {
132 synchronized(treeLock) {
138 * Set rootpane for swing components. This is used as parent for the components created by ComponentNode.
140 * @param rootPane Component that is used as a parent for the swing component (This shouldn't be visible)
142 public void setRootPane(JComponent rootPane) {
143 synchronized (RepaintManager.class) {
144 RepaintManager old = RepaintManager.currentManager(rootPane);
145 old = findProperRepaintManager(old);
146 this.repaintManager = new G2DRepaintManager(rootPane.getClass(), old);
147 RepaintManager.setCurrentManager(repaintManager);
149 this.rootPane = rootPane;
153 * Set rootpane for swing components. This is used as parent for the components created by ComponentNode.
154 * Supports separate component that is responsible for repainting the scenegraph.
156 * @param rootPane Component that is used as a parent for the swing component (This shouldn't be visible)
157 * @param paintContext Component that is responsible for repainting the scenegraph
159 public void setRootPane(Container rootPane, Component paintContext) {
160 synchronized (RepaintManager.class) {
161 RepaintManager old = RepaintManager.currentManager(paintContext);
162 old = findProperRepaintManager(old);
163 this.repaintManager = new G2DRepaintManager(paintContext.getClass(), old);
164 RepaintManager.setCurrentManager(repaintManager);
166 this.rootPane = rootPane;
169 private RepaintManager findProperRepaintManager(RepaintManager old) {
170 while (old instanceof G2DRepaintManager) {
171 G2DRepaintManager g2drm = (G2DRepaintManager) old;
172 old = g2drm.getDelegate();
177 public G2DRepaintManager getRepaintManager() {
178 return repaintManager;
182 * Put the node to the remove queue
185 public void asyncRemoveNode(INode node) {
186 synchronized(nodesToRemove) {
187 // Prevent nodes from winding up twice on the nodesToRemove queue
188 if (nodesToRemoveSet.add(node)) {
189 nodesToRemove.add(node); // This is performed when called inside the render
195 * Perform the actual removal of the nodes in the nodesToRemove list
197 public void performCleanup() {
198 synchronized(nodesToRemove) {
199 while(nodesToRemove.size() > 0) {
200 INode node = nodesToRemove.removeFirst();
201 ParentNode<?> parent = node.getParent();
202 // This works around issue #2071
204 parent.removeNode(node);
206 if (!nodesToRemoveSet.isEmpty())
207 nodesToRemoveSet.clear();
212 public void cleanup() {
214 nodesToRemove.clear();
215 nodesToRemove = null;
216 nodesToRemoveSet.clear();
217 nodesToRemoveSet = null;
218 eventHandler.dispose();
220 eventDelegator.dispose();
221 eventDelegator = null;
224 public Container getRootPane() {
225 return (Container) this.rootPane;
229 public String toString() {
230 return super.toString() + " [root pane=" + rootPane + "]";
234 public ParentNode<?> getRootNode() {
235 // This is a root node!
239 // ILookupService implementation
241 private final Object lookupLock = new Object();
242 private final Map<String, INode> toNode = new HashMap<String, INode>();
243 private final Map<INode, String> toId = new HashMap<INode, String>();
245 transient Logger logger = Logger.getLogger(getClass().getName());
248 public INode map(String id, INode node) {
250 throw new NullPointerException("null id");
252 throw new NullPointerException("null node");
256 synchronized (lookupLock) {
257 oldNode = toNode.put(id, node);
258 oldId = toId.put(node, id);
260 // Keep the mapping a consistent bijection:
261 // If ID => INode mapping is removed, the INode => ID mappings must
264 if (oldNode != null && !oldNode.equals(node)) {
265 String removedId = toId.remove(oldNode);
266 if (!id.equals(removedId))
267 toNode.remove(removedId);
269 if (oldId != null && !oldId.equals(id)) {
270 INode removedNode = toNode.remove(oldId);
271 if (removedNode != node)
272 toId.remove(removedNode);
275 if (logger.isLoggable(Level.FINER))
276 logger.fine("map(" + id + ", " + node + ")");
277 if (oldNode != null || oldId != null) {
278 if (logger.isLoggable(Level.FINE)) {
279 logger.info("replaced mappings for ID " + oldId + " and node " + oldNode);
286 public INode unmap(String id) {
289 synchronized (lookupLock) {
290 node = toNode.remove(id);
293 mappedId = toId.remove(node);
295 if (logger.isLoggable(Level.FINER))
296 logger.fine("unmap(" + id + "): " + node);
297 if (mappedId != null && !mappedId.equals(id)) {
298 if (logger.isLoggable(Level.WARNING))
299 logger.log(Level.WARNING, "mapping was out-of-sync: " + id + " => " + node + " & " + mappedId + " => " + node, new Exception("trace"));
305 public String unmap(INode node) {
308 synchronized (lookupLock) {
309 id = toId.remove(node);
312 mappedNode = toNode.remove(id);
314 if (logger.isLoggable(Level.FINER))
315 logger.fine("unmap(" + node + "): " + id);
316 if (mappedNode != null && node != mappedNode) {
317 if (logger.isLoggable(Level.WARNING))
318 logger.log(Level.WARNING, "mapping was out-of-sync: " + node + " => " + id + " & " + id + " => " + mappedNode, new Exception("trace"));
324 public INode lookupNode(String id) {
325 synchronized (lookupLock) {
326 return toNode.get(id);
331 public String lookupId(INode node) {
332 synchronized (lookupLock) {
333 return toId.get(node);
337 public boolean isPending() {
338 return !pending.isEmpty();
341 synchronized public void increasePending(Object object) {
342 Integer ref = pending.get(object);
343 if (ref == null) pending.put(object, 1);
344 else pending.put(object, ref+1);
347 synchronized public void setPending(Object object) {
348 pending.put(object, 1);
351 synchronized public void clearPending(Object object) {
352 pending.remove(object);
355 synchronized public void decreasePending(Object object) {
356 Integer ref = pending.get(object);
359 //throw new IllegalStateException("Ref count in unregister was 0 for " + object);
361 if (ref > 1) pending.put(object, ref-1);
362 else if (ref==1) pending.remove(object);
365 //throw new IllegalStateException("Ref count in unregister was 0 for " + object);
369 synchronized public void setGlobalProperty(String key, Object value) {
370 globalProperties.put(key, value);
373 @SuppressWarnings("unchecked")
374 synchronized public <T> T getGlobalProperty(String key, T defaultValue) {
375 T t = (T)globalProperties.get(key);
376 if(t == null) return defaultValue;