]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scenegraph/src/org/simantics/scenegraph/g2d/G2DSceneGraph.java
Trigger all drag start events from single place
[simantics/platform.git] / bundles / org.simantics.scenegraph / src / org / simantics / scenegraph / g2d / G2DSceneGraph.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.scenegraph.g2d;
13
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;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25
26 import javax.swing.JComponent;
27 import javax.swing.RepaintManager;
28
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;
36
37 /**
38  * The root node of a 2D scene graph.
39  * 
40  * Implements {@link ILookupService} according to the reference implementation
41  * {@link LookupService}.
42  * 
43  * @author J-P Laine
44  */
45 @SuppressWarnings("deprecation")
46 public class G2DSceneGraph extends G2DParentNode implements ILookupService, INodeEventHandlerProvider {
47
48     private static final long          serialVersionUID = -7066146333849901429L;
49     
50     public static final String        IGNORE_FOCUS = "ignoreFocus";
51
52     protected transient Container     rootPane         = null;
53     // TODO: swing dependency in here might not be a good idea
54
55     // This variable is actually used in remote use, when rendering is not performed locally
56     private transient final Object     treeLock         = new Object();
57
58     private HashMap<Object, Integer>   pending          = new HashMap<Object, Integer>();
59     private HashMap<String, Object>    globalProperties = new HashMap<String, Object>();
60
61     /**
62      * For preventing duplicates on the nodesToRemove queue.
63      */
64     protected transient Set<INode>     nodesToRemoveSet = new HashSet<INode>();
65     protected Deque<INode>             nodesToRemove    = new ArrayDeque<INode>();
66
67     private transient EventDelegator   eventDelegator   = new EventDelegator(this);
68     private transient NodeEventHandler eventHandler     = new NodeEventHandler(this);
69
70     /**
71      * The node that has input focus in the scene graph. The input node will
72      * receive key and command events.
73      */
74     private transient IG2DNode         focusNode;
75
76     /**
77      * The custom repaint manager of this scene graph.
78      */
79     private transient G2DRepaintManager repaintManager;
80
81     /**
82      * Returns the event delegator, that is responsible for delegating events to nodes in the sg tree
83      * 
84      * @return EventDelegator instance, always not null
85      */
86     public EventDelegator getEventDelegator() {
87         return eventDelegator;
88     }
89
90     /**
91      * Returns the node event handler, that is responsible for delegating events
92      * to nodes in the sg tree.
93      * 
94      * @return NodeEventHandler instance for this scene graph, always non-null
95      */
96     public NodeEventHandler getEventHandler() {
97         return eventHandler;
98     }
99
100     public void setFocusNode(IG2DNode focusNode) {
101         this.focusNode = focusNode;
102     }
103
104     public IG2DNode getFocusNode() {
105         return focusNode;
106     }
107
108     @Override
109     public void render(Graphics2D g2d) {
110         performCleanup();
111         Component rootPane = getRootPane();
112         if (rootPane != null)
113             g2d.setRenderingHint(G2DRenderingHints.KEY_COMPONENT, rootPane);
114         synchronized(treeLock) {
115             super.render(g2d);
116         }
117     }
118
119     /**
120      * Util method for executing updates to scenegraph tree
121      * NOTE: You should really consider performance issues when using this
122      * 
123      * @param r  Runnable to be executed while rendering is not performed
124      */
125     public void syncExec(Runnable r) {
126         synchronized(treeLock) {
127             r.run();
128         }
129     }
130
131     /**
132      * Set rootpane for swing components. This is used as parent for the components created by ComponentNode.
133      * 
134      * @param rootPane Component that is used as a parent for the swing component (This shouldn't be visible)
135      */
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);
142         }
143         this.rootPane = rootPane;
144     }
145
146     /**
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.
149      * 
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
152      */
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);
159         }
160         this.rootPane = rootPane;
161     }
162
163     private RepaintManager findProperRepaintManager(RepaintManager old) {
164         while (old instanceof G2DRepaintManager) {
165             G2DRepaintManager g2drm = (G2DRepaintManager) old;
166             old = g2drm.getDelegate();
167         }
168         return old;
169     }
170
171     public G2DRepaintManager getRepaintManager() {
172         return repaintManager;
173     }
174
175     /**
176      * Put the node to the remove queue
177      */
178     @Override
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
184             }
185         }
186     }
187
188     /**
189      * Perform the actual removal of the nodes in the nodesToRemove list
190      */
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
197                 if (parent != null)
198                     parent.removeNode(node);
199             }
200             if (!nodesToRemoveSet.isEmpty())
201                 nodesToRemoveSet.clear();
202         }
203     }
204
205     @Override
206     public void cleanup() {
207         super.cleanup();
208         nodesToRemove.clear();
209         nodesToRemove = null;
210         nodesToRemoveSet.clear();
211         nodesToRemoveSet = null;
212         eventHandler.dispose();
213         eventHandler = null;
214         eventDelegator.dispose();
215         eventDelegator = null;
216     }
217
218     public Container getRootPane() {
219         return (Container) this.rootPane;
220     }
221
222     @Override
223     public String toString() {
224         return super.toString() + " [root pane=" + rootPane + "]";
225     }
226
227     @Override
228     public ParentNode<?> getRootNode() {
229         // This is a root node!
230         return this;
231     }
232
233     // ILookupService implementation
234
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>();
238
239     transient Logger                 logger     = Logger.getLogger(getClass().getName());
240
241     @Override
242     public INode map(String id, INode node) {
243         if (id == null)
244             throw new NullPointerException("null id");
245         if (node == null)
246             throw new NullPointerException("null node");
247
248         INode oldNode;
249         String oldId;
250         synchronized (lookupLock) {
251             oldNode = toNode.put(id, node);
252             oldId = toId.put(node, id);
253
254             // Keep the mapping a consistent bijection:
255             // If ID => INode mapping is removed, the INode => ID mappings must
256             // removed also.
257
258             if (oldNode != null && !oldNode.equals(node)) {
259                 String removedId = toId.remove(oldNode);
260                 if (!id.equals(removedId))
261                     toNode.remove(removedId);
262             }
263             if (oldId != null && !oldId.equals(id)) {
264                 INode removedNode = toNode.remove(oldId);
265                 if (removedNode != node)
266                     toId.remove(removedNode);
267             }
268         }
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);
274             }
275         }
276         return oldNode;
277     }
278
279     @Override
280     public INode unmap(String id) {
281         INode node;
282         String mappedId;
283         synchronized (lookupLock) {
284             node = toNode.remove(id);
285             if (node == null)
286                 return null;
287             mappedId = toId.remove(node);
288         }
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"));
294         }
295         return node;
296     }
297
298     @Override
299     public String unmap(INode node) {
300         String id;
301         INode mappedNode;
302         synchronized (lookupLock) {
303             id = toId.remove(node);
304             if (node == null)
305                 return null;
306             mappedNode = toNode.remove(id);
307         }
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"));
313         }
314         return id;
315     }
316
317     @Override
318     public INode lookupNode(String id) {
319         synchronized (lookupLock) {
320             return toNode.get(id);
321         }
322     }
323
324     @Override
325     public String lookupId(INode node) {
326         synchronized (lookupLock) {
327             return toId.get(node);
328         }
329     }
330
331     public boolean isPending() {
332         return !pending.isEmpty();
333     }
334
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);
339     }
340
341     synchronized public void setPending(Object object) {
342         pending.put(object, 1);
343     }
344
345     synchronized public void clearPending(Object object) {
346         pending.remove(object);
347     }
348
349     synchronized public void decreasePending(Object object) {
350         Integer ref = pending.get(object);
351         if (ref == null) {
352             return;
353             //throw new IllegalStateException("Ref count in unregister was 0 for " + object);
354         }
355         if (ref > 1) pending.put(object, ref-1);
356         else if (ref==1) pending.remove(object);
357         else {
358             return;
359             //throw new IllegalStateException("Ref count in unregister was 0 for " + object);
360         }
361     }
362     
363     synchronized public void setGlobalProperty(String key, Object value) {
364         globalProperties.put(key, value);
365     }
366     
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;
371         return t;
372     }
373
374 }