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