977f2be251388501e00d0f4a5a4996dab1d9c667
[simantics/platform.git] / bundles / org.simantics.g2d / src / org / simantics / g2d / diagram / participant / ElementPainter.java
1 /*******************************************************************************\r
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management\r
3  * in Industry THTH ry.\r
4  * All rights reserved. This program and the accompanying materials\r
5  * are made available under the terms of the Eclipse Public License v1.0\r
6  * which accompanies this distribution, and is available at\r
7  * http://www.eclipse.org/legal/epl-v10.html\r
8  *\r
9  * Contributors:\r
10  *     VTT Technical Research Centre of Finland - initial API and implementation\r
11  *******************************************************************************/\r
12 package org.simantics.g2d.diagram.participant;\r
13 \r
14 import java.awt.BasicStroke;\r
15 import java.awt.Color;\r
16 import java.awt.Composite;\r
17 import java.awt.Shape;\r
18 import java.awt.geom.AffineTransform;\r
19 import java.awt.geom.Point2D;\r
20 import java.awt.geom.Rectangle2D;\r
21 import java.nio.CharBuffer;\r
22 import java.util.ArrayList;\r
23 import java.util.Collection;\r
24 import java.util.Collections;\r
25 import java.util.HashMap;\r
26 import java.util.HashSet;\r
27 import java.util.Iterator;\r
28 import java.util.List;\r
29 import java.util.Map;\r
30 import java.util.Random;\r
31 import java.util.Set;\r
32 import java.util.UUID;\r
33 import java.util.concurrent.ConcurrentHashMap;\r
34 import java.util.concurrent.ConcurrentMap;\r
35 import java.util.function.Consumer;\r
36 \r
37 import org.simantics.g2d.canvas.Hints;\r
38 import org.simantics.g2d.canvas.ICanvasContext;\r
39 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;\r
40 import org.simantics.g2d.canvas.impl.DependencyReflection.Reference;\r
41 import org.simantics.g2d.canvas.impl.HintReflection.HintListener;\r
42 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGCleanup;\r
43 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;\r
44 import org.simantics.g2d.connection.handler.ConnectionHandler;\r
45 import org.simantics.g2d.diagram.DiagramHints;\r
46 import org.simantics.g2d.diagram.DiagramUtils;\r
47 import org.simantics.g2d.diagram.IDiagram;\r
48 import org.simantics.g2d.diagram.IDiagram.CompositionListener;\r
49 import org.simantics.g2d.diagram.handler.RelationshipHandler;\r
50 import org.simantics.g2d.diagram.handler.RelationshipHandler.Relation;\r
51 import org.simantics.g2d.diagram.handler.TransactionContext;\r
52 import org.simantics.g2d.diagram.handler.TransactionContext.Transaction;\r
53 import org.simantics.g2d.diagram.handler.TransactionContext.TransactionListener;\r
54 import org.simantics.g2d.element.ElementClass;\r
55 import org.simantics.g2d.element.ElementHints;\r
56 import org.simantics.g2d.element.ElementUtils;\r
57 import org.simantics.g2d.element.IElement;\r
58 import org.simantics.g2d.element.SceneGraphNodeKey;\r
59 import org.simantics.g2d.element.handler.BendsHandler;\r
60 import org.simantics.g2d.element.handler.Children;\r
61 import org.simantics.g2d.element.handler.Children.ChildEvent;\r
62 import org.simantics.g2d.element.handler.Children.ChildListener;\r
63 import org.simantics.g2d.element.handler.FillColor;\r
64 import org.simantics.g2d.element.handler.Outline;\r
65 import org.simantics.g2d.element.handler.OutlineColorSpec;\r
66 import org.simantics.g2d.element.handler.Parent;\r
67 import org.simantics.g2d.element.handler.SceneGraph;\r
68 import org.simantics.g2d.element.handler.SelectionOutline;\r
69 import org.simantics.g2d.element.handler.SelectionSpecification;\r
70 import org.simantics.g2d.element.handler.StrokeSpec;\r
71 import org.simantics.g2d.element.handler.TerminalTopology;\r
72 import org.simantics.g2d.element.handler.Transform;\r
73 import org.simantics.g2d.layers.ILayer;\r
74 import org.simantics.g2d.layers.ILayersEditor;\r
75 import org.simantics.g2d.layers.ILayersEditor.ILayersEditorListener;\r
76 import org.simantics.g2d.participant.TransformUtil;\r
77 import org.simantics.g2d.scenegraph.SceneGraphConstants;\r
78 import org.simantics.g2d.utils.ElementNodeBridge;\r
79 import org.simantics.g2d.utils.TopologicalSelectionExpander;\r
80 import org.simantics.scenegraph.INode;\r
81 import org.simantics.scenegraph.Node;\r
82 import org.simantics.scenegraph.g2d.G2DParentNode;\r
83 import org.simantics.scenegraph.g2d.G2DSceneGraph;\r
84 import org.simantics.scenegraph.g2d.IG2DNode;\r
85 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;\r
86 import org.simantics.scenegraph.g2d.nodes.DataNode;\r
87 import org.simantics.scenegraph.g2d.nodes.LinkNode;\r
88 import org.simantics.scenegraph.g2d.nodes.SelectionNode;\r
89 import org.simantics.scenegraph.g2d.nodes.ShapeNode;\r
90 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;\r
91 import org.simantics.scenegraph.g2d.nodes.UnboundedNode;\r
92 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;\r
93 import org.simantics.scenegraph.utils.ColorUtil;\r
94 import org.simantics.scenegraph.utils.NodeUtil;\r
95 import org.simantics.utils.datastructures.collections.CollectionUtils;\r
96 import org.simantics.utils.datastructures.hints.HintListenerAdapter;\r
97 import org.simantics.utils.datastructures.hints.IHintContext.Key;\r
98 import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;\r
99 import org.simantics.utils.datastructures.hints.IHintListener;\r
100 import org.simantics.utils.datastructures.hints.IHintObservable;\r
101 \r
102 /**\r
103  * A diagram participant that keeps a diagram and its elements synchronized with\r
104  * the active canvas scene graph.\r
105  * \r
106  * <p>\r
107  * Responsibilities include:\r
108  * <ul>\r
109  * <li>ensure that the scene graph contains a {@link SingleElementNode} instance\r
110  * for each diagram element</li>\r
111  * <li>ensure that the scene graph node order matches the diagram element order</li>\r
112  * <li>ensure that the scene graph contains a {@link SelectionNode} under the\r
113  * element instance nodes for each selected node. TODO: maybe try getting\r
114  * selection out of here into a different participant, but without cloning the\r
115  * entire listening/element<->scene graph updating infrastructure.</li>\r
116  * <li></li>\r
117  * </ul>\r
118  * \r
119  * @author Tuukka Lehtonen\r
120  * \r
121  * @see ElementNodeBridge\r
122  */\r
123 public class ElementPainter extends AbstractDiagramParticipant implements CompositionListener, TransactionListener, ChildListener {\r
124 \r
125     public static final Key      KEY_SELECTION_PROVIDER = new KeyOf(ISelectionProvider.class);\r
126 \r
127     public static final int SELECTION_PAINT_PRIORITY    = 100;\r
128 \r
129     public static final Key KEY_SELECTION_FRAME_COLOR   = new KeyOf(Color.class, "SELECTION_FRAME_COLOR");\r
130     public static final Key KEY_SELECTION_CONTENT_COLOR = new KeyOf(Color.class, "SELECTION_CONTENT_COLOR");\r
131 \r
132 \r
133     /**\r
134      * Implement to customize the way a selection is visualized by\r
135      * ElementPainter.\r
136      */\r
137     public static interface ISelectionProvider {\r
138         public void init(final IElement e, final G2DParentNode parentNode, final String nodeId,\r
139                 final AffineTransform transform, final Rectangle2D bounds, final Color color);\r
140     }\r
141 \r
142     private static final boolean DEBUG                  = false;\r
143 \r
144     public static final int      ELEMENT_PAINT_PRIORITY = 10;\r
145 \r
146     @Reference\r
147     ZOrderHandler zOrderHandler;\r
148 \r
149     @Dependency\r
150     TransformUtil util;\r
151 \r
152     @Dependency\r
153     Selection selection;\r
154 \r
155     SingleElementNode diagramParent;\r
156     RTreeNode elementParent;\r
157 \r
158     boolean paintSelectionFrames;\r
159 \r
160     /**\r
161      * Internally reused to avert constant reallocation.\r
162      */\r
163     private transient List<Relation> relations = new ArrayList<Relation>(4);\r
164     /**\r
165      * Internally reused to avert constant reallocation.\r
166      */\r
167     private transient Set<IElement> relatedElements = new HashSet<IElement>(8);\r
168 \r
169     public ElementPainter() {\r
170         this(true);\r
171     }\r
172 \r
173     public ElementPainter(boolean paintSelectionFrames) {\r
174         this.paintSelectionFrames = paintSelectionFrames;\r
175     }\r
176 \r
177     @Override\r
178     public void addedToContext(ICanvasContext ctx) {\r
179         super.addedToContext(ctx);\r
180         if (zOrderHandler != null) {\r
181             zOrderHandler.addOrderListener(zOrderListener);\r
182         }\r
183     }\r
184 \r
185     @Override\r
186     public void removedFromContext(ICanvasContext ctx) {\r
187         if (zOrderHandler != null) {\r
188             zOrderHandler.removeOrderListener(zOrderListener);\r
189         }\r
190         selections.clear();\r
191         super.removedFromContext(ctx);\r
192     }\r
193 \r
194     @Override\r
195     protected void onDiagramSet(IDiagram newValue, IDiagram oldValue) {\r
196         if (oldValue == newValue)\r
197             return;\r
198 \r
199         if (oldValue != null) {\r
200             for (IElement e : oldValue.getElements()) {\r
201                 removeElement(e);\r
202             }\r
203 \r
204             oldValue.removeCompositionListener(this);\r
205             oldValue.removeKeyHintListener(Hints.KEY_DIRTY, diagramHintListener);\r
206             oldValue.removeKeyHintListener(Hints.KEY_DISABLE_PAINTING, diagramHintListener);\r
207 \r
208             ILayersEditor layers = oldValue.getHint(DiagramHints.KEY_LAYERS_EDITOR);\r
209             if (layers != null) {\r
210                 layers.removeListener(layersListener);\r
211             }\r
212 \r
213             for (TransactionContext tc : oldValue.getDiagramClass().getItemsByClass(TransactionContext.class)) {\r
214                 tc.removeTransactionListener(oldValue, this);\r
215             }\r
216         }\r
217 \r
218         if (newValue != null) {\r
219             for (IElement e : newValue.getElements()) {\r
220                 addElement(e, false);\r
221             }\r
222 \r
223             newValue.addCompositionListener(this);\r
224             newValue.addKeyHintListener(Hints.KEY_DISABLE_PAINTING, diagramHintListener);\r
225             newValue.addKeyHintListener(Hints.KEY_DIRTY, diagramHintListener);\r
226 \r
227             ILayersEditor layers = newValue.getHint(DiagramHints.KEY_LAYERS_EDITOR);\r
228             if (layers != null) {\r
229                 layers.addListener(layersListener);\r
230             }\r
231 \r
232             for (TransactionContext tc : newValue.getDiagramClass().getItemsByClass(TransactionContext.class)) {\r
233                 tc.addTransactionListener(newValue, this);\r
234             }\r
235         }\r
236 \r
237         updateAll();\r
238     }\r
239 \r
240     @SGInit\r
241     public void initSG(G2DParentNode parent) {\r
242         diagramParent = parent.addNode("elements_"+Node.IDCOUNTER, UnboundedNode.class);\r
243         diagramParent.setZIndex(ELEMENT_PAINT_PRIORITY);\r
244         elementParent = diagramParent.addNode("spatialRoot", RTreeNode.class);\r
245         elementParent.setZIndex(0);\r
246     }\r
247 \r
248     @SGCleanup\r
249     public void cleanupSG() {\r
250         diagramParent.remove();\r
251         elementParent = null;\r
252         diagramParent = null;\r
253     }\r
254 \r
255     public INode getDiagramElementParentNode() {\r
256         return elementParent;\r
257     }\r
258 \r
259     // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\r
260     // Element z-order listening and update logic\r
261     // ------------------------------------------------------------------------\r
262 \r
263     ZOrderListener zOrderListener = new ZOrderListener() {\r
264         @Override\r
265         public void orderChanged(IDiagram diagram) {\r
266             if (diagram == ElementPainter.this.diagram) {\r
267                 updateZOrder(diagram, ElementHints.KEY_SG_NODE);\r
268             }\r
269         }\r
270     };\r
271 \r
272     protected static void updateZOrder(IDiagram diagram, Key elementSgNodeKey) {\r
273         int zIndex = 0;\r
274         for (IElement e : diagram.getElements()) {\r
275             Node node = e.getHint(elementSgNodeKey);\r
276             if (node instanceof IG2DNode) {\r
277                 ((IG2DNode) node).setZIndex(++zIndex);\r
278             }\r
279         }\r
280     }\r
281 \r
282     // ------------------------------------------------------------------------\r
283     // Element z-order listening and update logic end\r
284     // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r
285 \r
286 \r
287     // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\r
288     // Layer configuration change listening and reaction logic\r
289     // ------------------------------------------------------------------------\r
290 \r
291     ILayersEditorListener layersListener = new ILayersEditorListener() {\r
292         private void layersChanged() {\r
293             Object task = BEGIN("EP.layersChanged");\r
294             // Update visibility/focusability for each node only, do not reinitialize the graphics.\r
295             updateAllVisibility();\r
296             END(task);\r
297         }\r
298         @Override\r
299         public void layerRemoved(ILayer layer) {\r
300             layersChanged();\r
301         }\r
302         @Override\r
303         public void layerDeactivated(ILayer layer) {\r
304             layersChanged();\r
305         }\r
306         @Override\r
307         public void layerAdded(ILayer layer) {\r
308             layersChanged();\r
309         }\r
310         @Override\r
311         public void layerActivated(ILayer layer) {\r
312             layersChanged();\r
313         }\r
314         @Override\r
315         public void ignoreFocusChanged(boolean value) {\r
316                 ICanvasContext ctx = getContext();\r
317                 if(ctx == null) return;\r
318                 G2DSceneGraph sg = ctx.getSceneGraph();\r
319                 if(sg == null) return;\r
320                 sg.setGlobalProperty(G2DSceneGraph.IGNORE_FOCUS, value);\r
321         }\r
322         @Override\r
323         public void ignoreVisibilityChanged(boolean value) {\r
324             layersChanged();\r
325         }\r
326     };\r
327 \r
328     protected void updateAllVisibility() {\r
329         // TODO: optimize, no node reinitialization\r
330         updateAll();\r
331     }\r
332 \r
333     // ------------------------------------------------------------------------\r
334     // Layer configuration change listening and reaction logic\r
335     // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r
336 \r
337 \r
338     // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\r
339     // Diagram/Element hint listeners\r
340     // ------------------------------------------------------------------------\r
341 \r
342     class DiagramHintListener extends HintListenerAdapter {\r
343         @Override\r
344         public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
345             if (key == Hints.KEY_DISABLE_PAINTING) {\r
346                 if (diagramParent != null) {\r
347                     diagramParent.setVisible(!Boolean.TRUE.equals(newValue));\r
348                 }\r
349             } else if (key == Hints.KEY_DIRTY) {\r
350                 if (newValue == Hints.VALUE_Z_ORDER_CHANGED) {\r
351                     diagram.removeHint(Hints.KEY_DIRTY);\r
352 \r
353                     if (DEBUG)\r
354                         System.out.println("Diagram z-order changed: " + diagram);\r
355 \r
356                     updateZOrder(diagram, ElementHints.KEY_SG_NODE);\r
357                 }\r
358             }\r
359         }\r
360     };\r
361 \r
362     private final DiagramHintListener diagramHintListener = new DiagramHintListener();\r
363 \r
364     /**\r
365      * This element hint listener tries to ensure that diagram elements and the\r
366      * normal diagram scene graph stay in sync by listening to any changes\r
367      * occurring in elements, i.e. in their hints.\r
368      * \r
369      * It does this by listening to {@link Hints#KEY_DIRTY} hint changes.\r
370      * \r
371      * @author Tuukka Lehtonen\r
372      */\r
373     class ElementHintListener implements IHintListener {\r
374         @Override\r
375         public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
376             if (key == Hints.KEY_DIRTY) {\r
377                 if (newValue == Hints.VALUE_SG_DIRTY) {\r
378                     if (sender instanceof IElement) {\r
379                         assert getContext().getThreadAccess().currentThreadAccess();\r
380                         Object task = BEGIN("element dirty");\r
381 \r
382                         IElement e = (IElement) sender;\r
383                         e.removeHint(Hints.KEY_DIRTY);\r
384 \r
385                         if (DEBUG)\r
386                             System.out.println("Element is dirty: " + e);\r
387 \r
388                         updateSelfAndNeighbors(e, COMPLETE_UPDATE);\r
389                         END(task);\r
390                     }\r
391                 }\r
392             } else if (key == ElementHints.KEY_FOCUS_LAYERS || key == ElementHints.KEY_VISIBLE_LAYERS) {\r
393                 if (sender instanceof IElement) {\r
394                     assert getContext().getThreadAccess().currentThreadAccess();\r
395                     IElement e = (IElement) sender;\r
396                     Object task = BEGIN("layers changed: " + e);\r
397                     update(e);\r
398                     END(task);\r
399                 }\r
400             }\r
401         }\r
402 \r
403         @Override\r
404         public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {\r
405         }\r
406     }\r
407 \r
408     private final ElementHintListener elementHintListener = new ElementHintListener();\r
409 \r
410     private final Set<Transaction> activeTransactions = new HashSet<Transaction>();\r
411 \r
412     @Override\r
413     public void transactionStarted(IDiagram d, Transaction t) {\r
414         activeTransactions.add(t);\r
415     }\r
416 \r
417     Consumer<IElement> COMPLETE_UPDATE = element -> {\r
418         // Connections may need rerouting\r
419         if (element.getElementClass().containsClass(ConnectionHandler.class))\r
420             DiagramUtils.validateAndFix(diagram, Collections.singleton(element));\r
421 \r
422         //System.out.println("COMPLETE_UPDATE(" + element + ")");\r
423         update(element);\r
424         updateSelection(element);\r
425     };\r
426 \r
427     Set<IElement> addRelatedElements(Set<IElement> elements) {\r
428         RelationshipHandler rh = diagram.getDiagramClass().getAtMostOneItemOfClass(RelationshipHandler.class);\r
429         if (rh != null) {\r
430             relatedElements.clear();\r
431             for (IElement el : elements) {\r
432                 relations.clear();\r
433                 rh.getRelations(diagram, el, relations);\r
434                 for (Relation r : relations) {\r
435                     Object obj = r.getObject();\r
436                     if (obj instanceof IElement) {\r
437                         relatedElements.add((IElement) obj);\r
438                     }\r
439                 }\r
440                 relations.clear();\r
441             }\r
442             elements.addAll(relatedElements);\r
443             relatedElements.clear();\r
444         }\r
445         return elements;\r
446     }\r
447 \r
448     /**\r
449      * @param e\r
450      * @param updateCallback\r
451      */\r
452     protected void updateSelfAndNeighbors(IElement e, Consumer<IElement> updateCallback) {\r
453         // Slight optimization for cases that are known to be topologically\r
454         // non-expandable.\r
455         if (!isNotSelectionExpandable(e)) {\r
456             Set<IElement> single = Collections.singleton(e);\r
457 \r
458             Set<IElement> expanded =\r
459                 // Also update all elements somehow related to e.\r
460                 addRelatedElements(\r
461                         // Get all topological neighbors and element self.\r
462                         CollectionUtils.join(\r
463                                 single,\r
464                                 TopologicalSelectionExpander.expandSelection(diagram, single)\r
465                         )\r
466                 );\r
467             // Perform the updates.\r
468             for (IElement el : expanded) {\r
469                 updateCallback.accept(el);\r
470             }\r
471         } else {\r
472             updateCallback.accept(e);\r
473         }\r
474     }\r
475 \r
476     /**\r
477      * @param e\r
478      * @return\r
479      */\r
480     protected boolean isNotSelectionExpandable(IElement e) {\r
481         ElementClass ec = e.getElementClass();\r
482         return !ec.containsClass(ConnectionHandler.class)\r
483         && !ec.containsClass(BendsHandler.class)\r
484         && !ec.containsClass(TerminalTopology.class);\r
485     }\r
486 \r
487     @Override\r
488     public void transactionFinished(IDiagram d, Transaction t) {\r
489         activeTransactions.remove(t);\r
490     }\r
491 \r
492     boolean inDiagramTransaction() {\r
493         return !activeTransactions.isEmpty();\r
494     }\r
495 \r
496     @Override\r
497     public void onElementAdded(IDiagram d, IElement e) {\r
498         if (DEBUG)\r
499             System.out.println("EP.onElementAdded(" + d + ", " + e + ")");\r
500 \r
501         if (inDiagramTransaction()) {\r
502             addElement(e, false);\r
503         } else {\r
504             addElement(e, true);\r
505         }\r
506     }\r
507     @Override\r
508     public void onElementRemoved(IDiagram d, IElement e) {\r
509         if (DEBUG)\r
510             System.out.println("EP.onElementRemoved(" + d + ", " + e + ")");\r
511 \r
512         removeElement(e);\r
513     }\r
514 \r
515     @Override\r
516     public void elementChildrenChanged(ChildEvent event) {\r
517         if (DEBUG)\r
518             System.out.println("EP.elementChildrenChanged: " + event);\r
519 \r
520         for (IElement removed : event.removed) {\r
521             removeElement(removed);\r
522         }\r
523         for (IElement added : event.added) {\r
524             addElement(added, false);\r
525         }\r
526     }\r
527 \r
528     private final List<IElement> childrenTemp = new ArrayList<IElement>();\r
529 \r
530     public void addElement(IElement e, boolean synchronizeSceneGraphNow) {\r
531         if (DEBUG)\r
532             System.out.println("EP.addElement(now=" + synchronizeSceneGraphNow + ", " + e + ")");\r
533 \r
534         e.addKeyHintListener(Hints.KEY_DIRTY, elementHintListener);\r
535         e.addKeyHintListener(ElementHints.KEY_VISIBLE_LAYERS, elementHintListener);\r
536         e.addKeyHintListener(ElementHints.KEY_FOCUS_LAYERS, elementHintListener);\r
537 \r
538         ElementClass clazz = e.getElementClass();\r
539         G2DParentNode parentNode = elementParent;\r
540         Key sgKey = ElementHints.KEY_SG_NODE;\r
541 \r
542         Parent parent = clazz.getAtMostOneItemOfClass(Parent.class);\r
543         if (parent != null) {\r
544             IElement parentElement = parent.getParent(e);\r
545             if (parentElement != null) {\r
546                 SingleElementNode parentHolder = parentElement.getHint(sgKey);\r
547                 if (parentHolder != null) {\r
548                     parentNode = parentHolder;\r
549                 }\r
550             }\r
551         }\r
552 \r
553         boolean isConnection = e.getElementClass().containsClass(ConnectionHandler.class);\r
554 \r
555         if(isConnection) {\r
556 \r
557             ConnectionNode holder = e.getHint(sgKey);\r
558             if (holder == null) {\r
559                 holder = parentNode.addNode(ElementUtils.generateNodeId(e), ConnectionNode.class);\r
560                 e.setHint(sgKey, holder);\r
561                 holder.setZIndex(parentNode.getNodeCount() + 1);\r
562             }\r
563 \r
564         } else {\r
565 \r
566             SingleElementNode holder = e.getHint(sgKey);\r
567             if (holder == null) {\r
568                 holder = parentNode.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);\r
569                 e.setHint(sgKey, holder);\r
570                 holder.setZIndex(parentNode.getNodeCount() + 1);\r
571             }\r
572 \r
573         }\r
574 \r
575         Children children = clazz.getAtMostOneItemOfClass(Children.class);\r
576         if (children != null) {\r
577             children.addChildListener(e, this);\r
578 \r
579             childrenTemp.clear();\r
580             children.getChildren(e, childrenTemp);\r
581             //System.out.println("children: " + childrenTemp);\r
582             for (IElement child : childrenTemp) {\r
583                 addElement(child, false);\r
584             }\r
585             childrenTemp.clear();\r
586         }\r
587 \r
588         if (synchronizeSceneGraphNow)\r
589             updateElement(e, sgKey);\r
590 \r
591         //setTreeDirty();\r
592     }\r
593 \r
594     protected void removeElement(IElement e) {\r
595         if (DEBUG)\r
596             System.out.println("EP.removeElement(" + e + ")");\r
597 \r
598         e.removeKeyHintListener(Hints.KEY_DIRTY, elementHintListener);\r
599         e.removeKeyHintListener(ElementHints.KEY_VISIBLE_LAYERS, elementHintListener);\r
600         e.removeKeyHintListener(ElementHints.KEY_FOCUS_LAYERS, elementHintListener);\r
601 \r
602         ElementClass clazz = e.getElementClass();\r
603         if (clazz.containsClass(Children.class)) {\r
604             Children children = clazz.getSingleItem(Children.class);\r
605             children.removeChildListener(e, this);\r
606         }\r
607 \r
608         List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);\r
609         for (SceneGraph n : nodeHandlers) {\r
610             n.cleanup(e);\r
611         }\r
612 \r
613         // Remove all hints related to scene graph nodes to prevent leakage of\r
614         // scene graph resources.\r
615         Map<SceneGraphNodeKey, Object> sgHints = e.getHintsOfClass(SceneGraphNodeKey.class);\r
616         for (SceneGraphNodeKey sgKey : sgHints.keySet()) {\r
617             Node n = e.removeHint(sgKey);\r
618             if (n != null) {\r
619                 n.remove();\r
620             }\r
621         }\r
622 \r
623         //setTreeDirty();\r
624     }\r
625 \r
626     /**\r
627      * Invalidate the whole scene graph spatial structure. It will be rebuilt by\r
628      * RTreeNode when needed the next time.\r
629      */\r
630     private void setTreeDirty() {\r
631         elementParent.setDirty();\r
632     }\r
633 \r
634     /**\r
635      * Mark the specified node invalid with respect to the scene graph spatial\r
636      * structure.\r
637      * \r
638      * @param node a scene graph node that has somehow changed\r
639      */\r
640     private void invalidateNode(INode node) {\r
641         // TODO: optimize rtree updates instead of killing the whole tree\r
642         elementParent.setDirty();\r
643     }\r
644 \r
645     // ------------------------------------------------------------------------\r
646     // Diagram/Element hint listeners\r
647     // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\r
648 \r
649     public void updateAll() {\r
650         if (DEBUG)\r
651             System.out.println("EP.updateAll()");\r
652 \r
653         Object task = BEGIN("EP.updateAll");\r
654         paintDiagram(elementParent, diagram, null);\r
655         updateSelections();\r
656         setTreeDirty();\r
657         END(task);\r
658     }\r
659 \r
660     public void update(IElement element) {\r
661         updateElement(element, ElementHints.KEY_SG_NODE);\r
662     }\r
663 \r
664     /**\r
665      *\r
666      * @param controlGC\r
667      * @param diagram\r
668      * @param elementsToPaint\r
669      *            elements to paint or null for all elements\r
670      */\r
671     public void paintDiagram(G2DParentNode parent, IDiagram diagram, Collection<IElement> elementsToPaint) {\r
672         Object task = BEGIN("EP.paintDiagram");\r
673         paintDiagram(parent, diagram, elementsToPaint, ElementHints.KEY_SG_NODE);\r
674         END(task);\r
675     }\r
676 \r
677     /**\r
678      *\r
679      * @param controlGC\r
680      * @param diagram\r
681      * @param elementsToPaint\r
682      *            elements to paint or null for all elements\r
683      */\r
684     public void paintDiagram(G2DParentNode parent, IDiagram diagram, Collection<IElement> elementsToPaint, Key elementSgNodeKey) {\r
685         if(diagram == null) return;\r
686         ICanvasContext ctx = getContext();\r
687         assert (ctx != null);\r
688 \r
689         Boolean disablePaint = diagram.getHint(Hints.KEY_DISABLE_PAINTING);\r
690         if (Boolean.TRUE.equals(disablePaint)) {\r
691             parent.removeNodes();\r
692             return;\r
693         }\r
694 \r
695         // Paint elementsToPaint in correct z-order from diagram.getElements()\r
696         List<IElement> elements = diagram.getSnapshot();\r
697 \r
698         Set<SingleElementNode> tmp = new HashSet<SingleElementNode>();\r
699         int zIndex = 0;\r
700         for (int pass = 0; pass < 1; ++pass) {\r
701             for (IElement e : elements) {\r
702                 if (elements != elementsToPaint && elementsToPaint != null)\r
703                     if (!elementsToPaint.contains(e))\r
704                         continue;\r
705 \r
706                 if (DEBUG)\r
707                     System.out.println("EP.paintDiagram(" + zIndex + ", " + e + ")");\r
708 \r
709                 SingleElementNode holder = updateElement(parent, e, elementSgNodeKey, false);\r
710                 if (holder != null) {\r
711                     tmp.add(holder);\r
712                     holder.setZIndex(++zIndex);\r
713                 }\r
714             }\r
715         }\r
716 \r
717         // Hide unaccessed nodes (but don't remove)\r
718         for (IG2DNode node : parent.getNodes()) {\r
719             if (!tmp.contains(node)) {\r
720                 ((SingleElementNode)node).setVisible(false);\r
721             }\r
722         }\r
723     }\r
724 \r
725     public void updateElement(IElement e, Key elementSgNodeKey) {\r
726         updateElement(null, e, elementSgNodeKey, true);\r
727     }\r
728 \r
729     /**\r
730      * @param parent if <code>null</code> the scene graph node structure\r
731      *        will not be created if it is missing\r
732      * @param e\r
733      * @param elementSgNodeKey\r
734      * @param invalidateNode \r
735      */\r
736     public SingleElementNode updateElement(G2DParentNode parent, IElement e, Key elementSgNodeKey, boolean invalidateNode) {\r
737         if (DEBUG)\r
738             System.out.println("EP.updateElement(" + e + ", " + elementSgNodeKey + ")");\r
739         Object task = BEGIN("EP.updateElement");\r
740 \r
741         try {\r
742             SingleElementNode holder = e.getHint(elementSgNodeKey);\r
743             if (holder == null && parent == null)\r
744                 return null;\r
745 \r
746             if (ElementUtils.isHidden(e))\r
747                 return null;\r
748 \r
749 //            ElementClass ec = e.getElementClass();\r
750 //            ILayers layers = diagram.getHint(DiagramHints.KEY_LAYERS);\r
751 //            if (layers != null && !layers.getIgnoreVisibilitySettings()) {\r
752 //                ElementLayers el = ec.getAtMostOneItemOfClass(ElementLayers.class);\r
753 //                if (el != null && !el.isVisible(e, layers)) {\r
754 //                    return null;\r
755 //                }\r
756 //            }\r
757 \r
758             // Update the node scene graph through SceneGraph handlers.\r
759             List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);\r
760             Collection<SceneGraph> decorators = e.getHint(ElementHints.KEY_DECORATORS);\r
761             if (nodeHandlers.isEmpty() && (decorators == null || decorators.isEmpty()))\r
762                 return null;\r
763 \r
764             Composite composite = e.getHint(ElementHints.KEY_COMPOSITE);\r
765 \r
766             if (holder == null) {\r
767                 holder = parent.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);\r
768                 e.setHint(elementSgNodeKey, holder);\r
769             }\r
770             holder.setComposite(composite);\r
771             holder.setVisible(true);\r
772 \r
773             for (SceneGraph n : nodeHandlers) {\r
774                 n.init(e, holder);\r
775             }\r
776 \r
777             // Process decorators\r
778             if (decorators == null || decorators.isEmpty()) {\r
779                 holder.removeNode("decorators");\r
780             } else {\r
781                 G2DParentNode decoratorHolder = holder.getOrCreateNode("decorators", G2DParentNode.class);\r
782                 decoratorHolder.removeNodes();\r
783                 for (SceneGraph decorator : decorators) {\r
784                     decorator.init(e, decoratorHolder);\r
785                 }\r
786             }\r
787 \r
788             if (invalidateNode)\r
789                 invalidateNode(holder);\r
790 \r
791             return holder;\r
792         } finally {\r
793             END(task);\r
794         }\r
795     }\r
796 \r
797     /**\r
798      * @param elementsToUpdate to explicitly specify which elements to update\r
799      *        the selection scene graph for, or <code>null</code> to update\r
800      *        everything\r
801      */\r
802     public void updateSelections() {\r
803         Object task = BEGIN("EP.updateSelections");\r
804 \r
805         try {\r
806             if (!paintSelectionFrames)\r
807                 return;\r
808             if (selection == null)\r
809                 return;\r
810 \r
811             boolean selectionsChanged = false;\r
812 \r
813             // Update and "touch" all selections.\r
814             Set<Integer> existingSelections = new HashSet<Integer>();\r
815             Set<INode> selectionNodes = new HashSet<INode>();\r
816             Set<INode> tmp = new HashSet<INode>();\r
817             Map<INode, LinkNode> selectionLinks = new HashMap<INode, LinkNode>();\r
818 \r
819             for (Map.Entry<Integer, Set<IElement>> entry : selection.getSelections().entrySet()) {\r
820                 Integer selectionId = entry.getKey();\r
821                 Set<IElement> selectedElements = entry.getValue();\r
822 \r
823                 existingSelections.add(selectionId);\r
824 \r
825 //                System.out.println("SELECTION[" + selectionId + "]: " + selectedElements);\r
826                 ElementNodeBridge bridge = getOrCreateSelectionMap(selectionId);\r
827                 selectionNodes.clear();\r
828                 selectionsChanged |= paintSelection(selectedElements, selectionId, selectionNodes, bridge);\r
829 \r
830                 // Remove selection nodes that were not referenced during the update.\r
831 //                System.out.println("BRIDGE: " + bridge.toString());\r
832 //                System.out.println("SELECTED: " + selectionNodes);\r
833                 tmp.clear();\r
834                 tmp.addAll(bridge.getRightSet());\r
835                 tmp.removeAll(selectionNodes);\r
836 //                System.out.println("REMOVED: " + tmp);\r
837 //                System.out.println("BRIDGE BEFORE: " + bridge);\r
838                 selectionsChanged |= bridge.retainAllRight(selectionNodes);\r
839 //                System.out.println("BRIDGE AFTER: " + bridge);\r
840 \r
841                 G2DParentNode selectionsNode = getSelectionsNode(selectionId);\r
842                 selectionLinks.clear();\r
843                 getSelectedNodeReferences(selectionsNode, selectionLinks);\r
844 \r
845                 for (INode node : tmp) {\r
846                     INode linkNode = selectionLinks.get(node.getParent());\r
847                     if (linkNode != null) {\r
848                         linkNode.remove();\r
849                     }\r
850 //                    System.out.println("REMOVED SELECTION: -> " + node);\r
851                     node.remove();\r
852                 }\r
853             }\r
854 \r
855             for (Iterator<Map.Entry<Integer, ElementNodeBridge>> iterator = selections.entrySet().iterator(); iterator.hasNext();) {\r
856                 Map.Entry<Integer, ElementNodeBridge> entry = iterator.next();\r
857                 Integer selectionId = entry.getKey();\r
858                 if (!existingSelections.contains(selectionId)) {\r
859                     // Selection no longer exists.\r
860                     selectionsChanged = true;\r
861                     for (INode node : entry.getValue().getRightSet()) {\r
862 //                        System.out.println("REMOVED SELECTION: " + node);\r
863                         node.remove();\r
864                     }\r
865                     iterator.remove();\r
866 \r
867                     G2DParentNode selectionsNode = getSelectionsNode(selectionId);\r
868                     selectionsNode.removeNodes();\r
869                 }\r
870             }\r
871 \r
872             // Make sure the view is refreshed after selection changes.\r
873             if (selectionsChanged) {\r
874                 setDirty();\r
875             }\r
876         } finally {\r
877             END(task);\r
878         }\r
879     }\r
880 \r
881     private G2DParentNode getSelectionsNode() {\r
882         G2DParentNode sels = NodeUtil.lookup(diagramParent, SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);\r
883         if (sels == null) {\r
884             DataNode data= NodeUtil.lookup(diagramParent, SceneGraphConstants.DATA_NODE_NAME, DataNode.class);\r
885             sels = data.addNode(SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);\r
886             sels.setLookupId(SceneGraphConstants.SELECTIONS_NODE_NAME);\r
887         }\r
888         return sels;\r
889     }\r
890 \r
891     private G2DParentNode getSelectionsNode(int selectionId) {\r
892         G2DParentNode selectionsNode = getSelectionsNode();\r
893         G2DParentNode s = selectionsNode.getOrCreateNode(String.valueOf(selectionId), G2DParentNode.class);\r
894         return s;\r
895     }\r
896 \r
897     private Map<INode, LinkNode> getSelectedNodeReferences(G2DParentNode selectionsNode, Map<INode, LinkNode> result) {\r
898         for (IG2DNode node : selectionsNode.getSortedNodes()) {\r
899             if (node instanceof LinkNode) {\r
900                 INode n = ((LinkNode) node).getDelegate();\r
901                 if (n != null)\r
902                     result.put(n, (LinkNode) node);\r
903             }\r
904         }\r
905         return result;\r
906     }\r
907 \r
908     public void updateSelection(IElement el) {\r
909         Object task = BEGIN("EP.updateSelection");\r
910 \r
911         try {\r
912             if (!paintSelectionFrames)\r
913                 return;\r
914 \r
915             G2DParentNode elementNode = (G2DParentNode) el.getHint(ElementHints.KEY_SG_NODE);\r
916             if (elementNode == null)\r
917                 return;\r
918 \r
919             boolean nodesUpdated = false;\r
920 \r
921             for (Map.Entry<Integer, ElementNodeBridge> entry : selections.entrySet()) {\r
922                 Integer selectionId = entry.getKey();\r
923                 ElementNodeBridge bridge = entry.getValue();\r
924                 Color color = getSelectionColor(selectionId);\r
925 \r
926                 G2DParentNode selectionNode = (G2DParentNode) bridge.getRight(el);\r
927                 if (selectionNode == null)\r
928                     continue;\r
929 \r
930                 if (NodeUtil.needSelectionPaint(elementNode))\r
931                     paintSelectionFrame(elementNode, selectionNode, el, color);\r
932 \r
933                 nodesUpdated = true;\r
934             }\r
935 \r
936             // Make sure the view is refreshed after selection changes.\r
937             if (nodesUpdated)\r
938                 setDirty();\r
939         } finally {\r
940             END(task);\r
941         }\r
942     }\r
943 \r
944     /**\r
945      * @param selection\r
946      * @param selectionId\r
947      * @param selectionNodes for collecting all the "selection" nodes created or\r
948      *        referenced by this method\r
949      * @param bridge\r
950      * @return\r
951      */\r
952     public boolean paintSelection(Set<IElement> selection, int selectionId, Set<INode> selectionNodes, ElementNodeBridge bridge) {\r
953 \r
954         boolean result = false;\r
955         Color color = getSelectionColor(selectionId);\r
956         G2DParentNode selectionsNode = getSelectionsNode(selectionId);\r
957 \r
958         for (IElement e : selection) {\r
959             Node elementNode = e.getHint(ElementHints.KEY_SG_NODE);\r
960 //            System.out.println("selectionNode: " + elementNode + " " + e);\r
961             if (elementNode instanceof G2DParentNode) {\r
962                 G2DParentNode en = (G2DParentNode) elementNode;\r
963                 G2DParentNode selectionNode = en.getOrCreateNode(NodeUtil.SELECTION_NODE_NAME, G2DParentNode.class);\r
964                 selectionNode.setZIndex(SELECTION_PAINT_PRIORITY);\r
965                 if (selectionNodes != null)\r
966                     selectionNodes.add(selectionNode);\r
967                 if (!bridge.containsLeft(e)) {\r
968                     //System.out.println("ADDED SELECTION: " + e + " -> " + selectionNode);\r
969                     bridge.map(e, selectionNode);\r
970                     result = true;\r
971                 }\r
972 \r
973                 // Mark this node selected in the scene graph "data area"\r
974                 createSelectionReference(selectionsNode, elementNode);\r
975 \r
976                 if (NodeUtil.needSelectionPaint(elementNode))\r
977                     paintSelectionFrame(en, selectionNode, e, color);\r
978 \r
979             } else {\r
980                 if (elementNode != null) {\r
981                     // Cannot paint selection for unrecognized non-parenting node\r
982                     System.out.println("Cannot add selection child node for non-parent element node: " + elementNode);\r
983                 }\r
984             }\r
985         }\r
986 \r
987 //        if (selection.isEmpty()) {\r
988 //            Node pivotNode = (Node) parent.getNode("pivot");\r
989 //            if (pivotNode != null)\r
990 //                pivotNode.remove();\r
991 //        } else {\r
992 //            Point2D pivot = ElementUtils.getElementBoundsCenter(selection, pivotPoint);\r
993 //            if (pivot != null) {\r
994 //                //System.out.println("painting pivot: " + pivot);\r
995 //                SelectionPivotNode pivotNode = parent.getOrCreateNode("pivot", SelectionPivotNode.class);\r
996 //                pivotNode.setPivot(pivot);\r
997 //            } else {\r
998 //                parent.removeNode("pivot");\r
999 //            }\r
1000 //        }\r
1001 \r
1002         return result;\r
1003     }\r
1004 \r
1005     public void paintSelectionFrame(G2DParentNode elementNode, G2DParentNode selectionNode, final IElement e, Color color) {\r
1006         // The element node already has the correct transform.\r
1007         AffineTransform selectionTransform = ElementUtils.getTransform(e);// no it doesnt ... new AffineTransform();\r
1008         Shape shape = ElementUtils.getElementShapeOrBounds(e);\r
1009         Rectangle2D bounds = shape.getBounds2D();\r
1010         //System.out.println("selection bounds: "+bounds);\r
1011         final double margin = 1;\r
1012         bounds.setFrame(bounds.getMinX() - margin, bounds.getMinY() - margin, bounds.getWidth() + 2*margin, bounds.getHeight() + 2*margin);\r
1013 \r
1014         List<SelectionSpecification> ss = e.getElementClass().getItemsByClass(SelectionSpecification.class);\r
1015         if (!ss.isEmpty()) {\r
1016             G2DParentNode shapeholder = selectionNode.getOrCreateNode(getNodeId("outlines", e), G2DParentNode.class);\r
1017 \r
1018             for (SelectionSpecification es : ss) {\r
1019                 Outline outline = (Outline) es.getAdapter(Outline.class);\r
1020                 if (outline == null || outline.getElementShape(e) == null)\r
1021                         continue;\r
1022                 ShapeNode shapenode = shapeholder.getOrCreateNode(getNodeId("outline", e, es), ShapeNode.class);\r
1023 //                shapenode.setShape(es.getSelectionShape(e));\r
1024 //                shapenode.setStroke(SELECTION_STROKE);\r
1025 //                shapenode.setScaleStroke(true);\r
1026 //                shapenode.setColor(color);\r
1027 //                shapenode.setTransform(selectionTransform);\r
1028 //                shapenode.setFill(false);\r
1029                 shapenode.setShape(outline.getElementShape(e));\r
1030                 StrokeSpec strokeSpec = (StrokeSpec) es.getAdapter(StrokeSpec.class);\r
1031                 if (strokeSpec != null && strokeSpec.getStroke(e) != null)\r
1032                         shapenode.setStroke(strokeSpec.getStroke(e));\r
1033                 \r
1034                 shapenode.setScaleStroke(false);\r
1035                 //shapenode.setColor(color);\r
1036                 OutlineColorSpec foregroundColor = (OutlineColorSpec) es.getAdapter(OutlineColorSpec.class);\r
1037                 if (foregroundColor != null && foregroundColor.getColor(e) != null)\r
1038                         shapenode.setColor(foregroundColor.getColor(e));\r
1039                 \r
1040                 Transform transform = (Transform) es.getAdapter(Transform.class);\r
1041                 if (transform != null && transform.getTransform(e) != null)\r
1042                         shapenode.setTransform(transform.getTransform(e));\r
1043                 \r
1044                 shapenode.setFill(false);\r
1045                 FillColor fillColor = (FillColor) es.getAdapter(FillColor.class);\r
1046                 if (fillColor != null && fillColor.getFillColor(e) != null)\r
1047                     shapenode.setFill(true);\r
1048 //                      shapenode.setColor(ColorUtil.withAlpha(backgroundColor.getColor(e), 192));\r
1049             }\r
1050             return;\r
1051         }\r
1052 \r
1053         List<SelectionOutline> shapeHandlers = e.getElementClass().getItemsByClass(SelectionOutline.class);\r
1054         if (!shapeHandlers.isEmpty()) {\r
1055             G2DParentNode shapeholder = selectionNode.getOrCreateNode(getNodeId("outlines", e), G2DParentNode.class);\r
1056 \r
1057             for (SelectionOutline es : shapeHandlers) {\r
1058                 ShapeNode shapenode = shapeholder.getOrCreateNode(getNodeId("outline", e, es), ShapeNode.class);\r
1059 //                shapenode.setShape(es.getSelectionShape(e));\r
1060 //                shapenode.setStroke(SELECTION_STROKE);\r
1061 //                shapenode.setScaleStroke(true);\r
1062 //                shapenode.setColor(color);\r
1063 //                shapenode.setTransform(selectionTransform);\r
1064 //                shapenode.setFill(false);\r
1065                 shapenode.setShape(es.getSelectionShape(e));\r
1066                 shapenode.setStroke(null);\r
1067                 shapenode.setScaleStroke(false);\r
1068                 //shapenode.setColor(color);\r
1069                 shapenode.setColor(ColorUtil.withAlpha(color, 192));\r
1070                 shapenode.setTransform(selectionTransform);\r
1071                 shapenode.setFill(true);\r
1072             }\r
1073             return;\r
1074         }\r
1075 \r
1076         ISelectionProvider provider = this.getContext().getDefaultHintContext().getHint(KEY_SELECTION_PROVIDER);\r
1077         if (provider != null) {\r
1078             provider.init(e, selectionNode, getNodeId("shape", e), selectionTransform, bounds, color);\r
1079         } else {\r
1080             SelectionNode s = selectionNode.getOrCreateNode(getNodeId("shape", e), SelectionNode.class);\r
1081             s.init(selectionTransform, bounds, color);\r
1082         }\r
1083     }\r
1084 \r
1085     private void createSelectionReference(G2DParentNode selectionsNode, INode elementNode) {\r
1086         String id = NodeUtil.lookupId(elementNode);\r
1087         String uuid = null;\r
1088         if (id == null)\r
1089             id = uuid = UUID.randomUUID().toString();\r
1090         NodeUtil.map(elementNode, id);\r
1091         LinkNode link = selectionsNode.getOrCreateNode(id, LinkNode.class);\r
1092         link.setDelegateId(id);\r
1093         link.setIgnoreDelegate(true);\r
1094         link.setLookupIdOwner(uuid != null);\r
1095     }\r
1096 \r
1097     private transient CharBuffer buf = CharBuffer.allocate(32);\r
1098 \r
1099     private String getNodeId(String prefix, Object first) {\r
1100         return getNodeId(prefix, first, null);\r
1101     }\r
1102 \r
1103     private String getNodeId(String prefix, Object first, Object second) {\r
1104         buf.clear();\r
1105         if (prefix != null)\r
1106             buf.append(prefix);\r
1107         if (first != null) {\r
1108             buf.append('_');\r
1109             buf.append("" + first.hashCode());\r
1110         }\r
1111         if (second != null) {\r
1112             buf.append('_');\r
1113             buf.append("" + second.hashCode());\r
1114         }\r
1115         buf.limit(buf.position());\r
1116         buf.rewind();\r
1117         //System.out.println("node id: " + buf.toString());\r
1118         return buf.toString();\r
1119     }\r
1120 \r
1121     /**\r
1122      * Get selection color for a selection Id\r
1123      * @param selectionId selection id\r
1124      * @return color for the id\r
1125      */\r
1126     protected Color getSelectionColor(int selectionId) {\r
1127         if (selectionId == 0) {\r
1128             Color c = getHint(KEY_SELECTION_FRAME_COLOR);\r
1129             if (c != null)\r
1130                 return c;\r
1131             return Color.BLACK;\r
1132         }\r
1133         Color c = selectionColor.get(selectionId);\r
1134         if (c == null) {\r
1135             Random r = new Random(selectionId);\r
1136             c = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat());\r
1137             selectionColor.put(selectionId, c);\r
1138         }\r
1139         return c;\r
1140     }\r
1141 \r
1142     private transient ConcurrentMap<Integer, ElementNodeBridge> selections = new ConcurrentHashMap<Integer, ElementNodeBridge>();\r
1143 \r
1144     ElementNodeBridge getSelectionMap(int selectionId) {\r
1145         return selections.get(Integer.valueOf(selectionId));\r
1146     }\r
1147 \r
1148     ElementNodeBridge getOrCreateSelectionMap(int selectionId) {\r
1149         Integer id = Integer.valueOf(selectionId);\r
1150         synchronized (selections) {\r
1151             ElementNodeBridge map = selections.get(id);\r
1152             if (map != null)\r
1153                 return map;\r
1154 \r
1155             selections.put(id, map = new ElementNodeBridge(id));\r
1156             return map;\r
1157         }\r
1158     }\r
1159 \r
1160     private transient Map<Integer, Color>     selectionColor              = new HashMap<Integer, Color>();\r
1161 \r
1162     private transient BasicStroke             SELECTION_STROKE            = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,\r
1163             BasicStroke.JOIN_BEVEL, 10.0f,\r
1164             new float[] { 5.0f, 5.0f }, 0.0f);\r
1165 \r
1166     private transient Point2D                 pivotPoint                  = new Point2D.Double();\r
1167 \r
1168     @HintListener(Class=Selection.class, Field="SELECTION0")\r
1169     public void selectionChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {\r
1170         //System.out.println("new selection: " + newValue);\r
1171         updateSelections();\r
1172     }\r
1173 \r
1174     @HintListener(Class=Selection.class, Field="SELECTION0")\r
1175     public void selectionRemoved(IHintObservable sender, Key key, Object oldValue) {\r
1176         //System.out.println("selection removed: " + oldValue);\r
1177         updateSelections();\r
1178     }\r
1179 \r
1180     private static Object BEGIN(String name) {\r
1181         if (DEBUG) {\r
1182             //return ThreadLog.BEGIN(name);\r
1183         }\r
1184         return null;\r
1185     }\r
1186 \r
1187     private static void END(Object task) {\r
1188         if (DEBUG) {\r
1189             //((Task) task).end();\r
1190         }\r
1191     }\r
1192 \r
1193 }\r