]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.g2d/src/org/simantics/g2d/diagram/participant/ElementPainter.java
Fixed all line endings of the repository
[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.setTransferableProvider(new ElementTransferableProvider(getContext(), e));
561                 e.setHint(sgKey, holder);
562                 holder.setZIndex(parentNode.getNodeCount() + 1);
563             }
564
565         } else {
566
567             SingleElementNode holder = e.getHint(sgKey);
568             if (holder == null) {
569                 holder = parentNode.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);
570                 holder.setTransferableProvider(new ElementTransferableProvider(getContext(), e));
571                 e.setHint(sgKey, holder);
572                 holder.setZIndex(parentNode.getNodeCount() + 1);
573             }
574
575         }
576
577         Children children = clazz.getAtMostOneItemOfClass(Children.class);
578         if (children != null) {
579             children.addChildListener(e, this);
580
581             childrenTemp.clear();
582             children.getChildren(e, childrenTemp);
583             //System.out.println("children: " + childrenTemp);
584             for (IElement child : childrenTemp) {
585                 addElement(child, false);
586             }
587             childrenTemp.clear();
588         }
589
590         if (synchronizeSceneGraphNow)
591             updateElement(e, sgKey);
592
593         //setTreeDirty();
594     }
595
596     protected void removeElement(IElement e) {
597         if (DEBUG)
598             System.out.println("EP.removeElement(" + e + ")");
599
600         e.removeKeyHintListener(Hints.KEY_DIRTY, elementHintListener);
601         e.removeKeyHintListener(ElementHints.KEY_VISIBLE_LAYERS, elementHintListener);
602         e.removeKeyHintListener(ElementHints.KEY_FOCUS_LAYERS, elementHintListener);
603
604         ElementClass clazz = e.getElementClass();
605         if (clazz.containsClass(Children.class)) {
606             Children children = clazz.getSingleItem(Children.class);
607             children.removeChildListener(e, this);
608         }
609
610         List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);
611         for (SceneGraph n : nodeHandlers) {
612             n.cleanup(e);
613         }
614
615         // Remove all hints related to scene graph nodes to prevent leakage of
616         // scene graph resources.
617         Map<SceneGraphNodeKey, Object> sgHints = e.getHintsOfClass(SceneGraphNodeKey.class);
618         for (SceneGraphNodeKey sgKey : sgHints.keySet()) {
619             Node n = e.removeHint(sgKey);
620             if (n != null) {
621                 n.remove();
622             }
623         }
624
625         //setTreeDirty();
626     }
627
628     /**
629      * Invalidate the whole scene graph spatial structure. It will be rebuilt by
630      * RTreeNode when needed the next time.
631      */
632     private void setTreeDirty() {
633         elementParent.setDirty();
634     }
635
636     /**
637      * Mark the specified node invalid with respect to the scene graph spatial
638      * structure.
639      * 
640      * @param node a scene graph node that has somehow changed
641      */
642     private void invalidateNode(INode node) {
643         // TODO: optimize rtree updates instead of killing the whole tree
644         elementParent.setDirty();
645     }
646
647     // ------------------------------------------------------------------------
648     // Diagram/Element hint listeners
649     // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
650
651     public void updateAll() {
652         if (DEBUG)
653             System.out.println("EP.updateAll()");
654
655         Object task = BEGIN("EP.updateAll");
656         paintDiagram(elementParent, diagram, null);
657         updateSelections();
658         setTreeDirty();
659         END(task);
660     }
661
662     public void update(IElement element) {
663         updateElement(element, ElementHints.KEY_SG_NODE);
664     }
665
666     /**
667      *
668      * @param controlGC
669      * @param diagram
670      * @param elementsToPaint
671      *            elements to paint or null for all elements
672      */
673     public void paintDiagram(G2DParentNode parent, IDiagram diagram, Collection<IElement> elementsToPaint) {
674         Object task = BEGIN("EP.paintDiagram");
675         paintDiagram(parent, diagram, elementsToPaint, ElementHints.KEY_SG_NODE);
676         END(task);
677     }
678
679     /**
680      *
681      * @param controlGC
682      * @param diagram
683      * @param elementsToPaint
684      *            elements to paint or null for all elements
685      */
686     public void paintDiagram(G2DParentNode parent, IDiagram diagram, Collection<IElement> elementsToPaint, Key elementSgNodeKey) {
687         if(diagram == null) return;
688         ICanvasContext ctx = getContext();
689         assert (ctx != null);
690
691         Boolean disablePaint = diagram.getHint(Hints.KEY_DISABLE_PAINTING);
692         if (Boolean.TRUE.equals(disablePaint)) {
693             parent.removeNodes();
694             return;
695         }
696
697         // Paint elementsToPaint in correct z-order from diagram.getElements()
698         List<IElement> elements = diagram.getSnapshot();
699
700         Set<SingleElementNode> tmp = new HashSet<SingleElementNode>();
701         int zIndex = 0;
702         for (int pass = 0; pass < 1; ++pass) {
703             for (IElement e : elements) {
704                 if (elements != elementsToPaint && elementsToPaint != null)
705                     if (!elementsToPaint.contains(e))
706                         continue;
707
708                 if (DEBUG)
709                     System.out.println("EP.paintDiagram(" + zIndex + ", " + e + ")");
710
711                 SingleElementNode holder = updateElement(parent, e, elementSgNodeKey, false);
712                 if (holder != null) {
713                     tmp.add(holder);
714                     holder.setZIndex(++zIndex);
715                 }
716             }
717         }
718
719         // Hide unaccessed nodes (but don't remove)
720         for (IG2DNode node : parent.getNodes()) {
721             if (!tmp.contains(node)) {
722                 ((SingleElementNode)node).setVisible(false);
723             }
724         }
725     }
726
727     public void updateElement(IElement e, Key elementSgNodeKey) {
728         updateElement(null, e, elementSgNodeKey, true);
729     }
730
731     /**
732      * @param parent if <code>null</code> the scene graph node structure
733      *        will not be created if it is missing
734      * @param e
735      * @param elementSgNodeKey
736      * @param invalidateNode 
737      */
738     public SingleElementNode updateElement(G2DParentNode parent, IElement e, Key elementSgNodeKey, boolean invalidateNode) {
739         if (DEBUG)
740             System.out.println("EP.updateElement(" + e + ", " + elementSgNodeKey + ")");
741         Object task = BEGIN("EP.updateElement");
742
743         try {
744             SingleElementNode holder = e.getHint(elementSgNodeKey);
745             if (holder == null && parent == null)
746                 return null;
747
748             if (ElementUtils.isHidden(e))
749                 return null;
750
751 //            ElementClass ec = e.getElementClass();
752 //            ILayers layers = diagram.getHint(DiagramHints.KEY_LAYERS);
753 //            if (layers != null && !layers.getIgnoreVisibilitySettings()) {
754 //                ElementLayers el = ec.getAtMostOneItemOfClass(ElementLayers.class);
755 //                if (el != null && !el.isVisible(e, layers)) {
756 //                    return null;
757 //                }
758 //            }
759
760             // Update the node scene graph through SceneGraph handlers.
761             List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);
762             Collection<SceneGraph> decorators = e.getHint(ElementHints.KEY_DECORATORS);
763             if (nodeHandlers.isEmpty() && (decorators == null || decorators.isEmpty()))
764                 return null;
765
766             Composite composite = e.getHint(ElementHints.KEY_COMPOSITE);
767
768             if (holder == null) {
769                 holder = parent.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);
770                 e.setHint(elementSgNodeKey, holder);
771             }
772             holder.setComposite(composite);
773             holder.setVisible(true);
774
775             for (SceneGraph n : nodeHandlers) {
776                 n.init(e, holder);
777             }
778
779             // Process decorators
780             if (decorators == null || decorators.isEmpty()) {
781                 holder.removeNode("decorators");
782             } else {
783                 G2DParentNode decoratorHolder = holder.getOrCreateNode("decorators", G2DParentNode.class);
784                 decoratorHolder.removeNodes();
785                 for (SceneGraph decorator : decorators) {
786                     decorator.init(e, decoratorHolder);
787                 }
788             }
789
790             if (invalidateNode)
791                 invalidateNode(holder);
792
793             return holder;
794         } finally {
795             END(task);
796         }
797     }
798
799     /**
800      * @param elementsToUpdate to explicitly specify which elements to update
801      *        the selection scene graph for, or <code>null</code> to update
802      *        everything
803      */
804     public void updateSelections() {
805         Object task = BEGIN("EP.updateSelections");
806
807         try {
808             if (!paintSelectionFrames)
809                 return;
810             if (selection == null)
811                 return;
812
813             boolean selectionsChanged = false;
814
815             // Update and "touch" all selections.
816             Set<Integer> existingSelections = new HashSet<Integer>();
817             Set<INode> selectionNodes = new HashSet<INode>();
818             Set<INode> tmp = new HashSet<INode>();
819             Map<INode, LinkNode> selectionLinks = new HashMap<INode, LinkNode>();
820
821             for (Map.Entry<Integer, Set<IElement>> entry : selection.getSelections().entrySet()) {
822                 Integer selectionId = entry.getKey();
823                 Set<IElement> selectedElements = entry.getValue();
824
825                 existingSelections.add(selectionId);
826
827 //                System.out.println("SELECTION[" + selectionId + "]: " + selectedElements);
828                 ElementNodeBridge bridge = getOrCreateSelectionMap(selectionId);
829                 selectionNodes.clear();
830                 selectionsChanged |= paintSelection(selectedElements, selectionId, selectionNodes, bridge);
831
832                 // Remove selection nodes that were not referenced during the update.
833 //                System.out.println("BRIDGE: " + bridge.toString());
834 //                System.out.println("SELECTED: " + selectionNodes);
835                 tmp.clear();
836                 tmp.addAll(bridge.getRightSet());
837                 tmp.removeAll(selectionNodes);
838 //                System.out.println("REMOVED: " + tmp);
839 //                System.out.println("BRIDGE BEFORE: " + bridge);
840                 selectionsChanged |= bridge.retainAllRight(selectionNodes);
841 //                System.out.println("BRIDGE AFTER: " + bridge);
842
843                 G2DParentNode selectionsNode = getSelectionsNode(selectionId);
844                 selectionLinks.clear();
845                 getSelectedNodeReferences(selectionsNode, selectionLinks);
846
847                 for (INode node : tmp) {
848                     INode linkNode = selectionLinks.get(node.getParent());
849                     if (linkNode != null) {
850                         linkNode.remove();
851                     }
852 //                    System.out.println("REMOVED SELECTION: -> " + node);
853                     node.remove();
854                 }
855             }
856
857             for (Iterator<Map.Entry<Integer, ElementNodeBridge>> iterator = selections.entrySet().iterator(); iterator.hasNext();) {
858                 Map.Entry<Integer, ElementNodeBridge> entry = iterator.next();
859                 Integer selectionId = entry.getKey();
860                 if (!existingSelections.contains(selectionId)) {
861                     // Selection no longer exists.
862                     selectionsChanged = true;
863                     for (INode node : entry.getValue().getRightSet()) {
864 //                        System.out.println("REMOVED SELECTION: " + node);
865                         node.remove();
866                     }
867                     iterator.remove();
868
869                     G2DParentNode selectionsNode = getSelectionsNode(selectionId);
870                     selectionsNode.removeNodes();
871                 }
872             }
873
874             // Make sure the view is refreshed after selection changes.
875             if (selectionsChanged) {
876                 setDirty();
877             }
878         } finally {
879             END(task);
880         }
881     }
882
883     private G2DParentNode getSelectionsNode() {
884         G2DParentNode sels = NodeUtil.lookup(diagramParent, SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);
885         if (sels == null) {
886             DataNode data= NodeUtil.lookup(diagramParent, SceneGraphConstants.DATA_NODE_NAME, DataNode.class);
887             sels = data.addNode(SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);
888             sels.setLookupId(SceneGraphConstants.SELECTIONS_NODE_NAME);
889         }
890         return sels;
891     }
892
893     private G2DParentNode getSelectionsNode(int selectionId) {
894         G2DParentNode selectionsNode = getSelectionsNode();
895         G2DParentNode s = selectionsNode.getOrCreateNode(String.valueOf(selectionId), G2DParentNode.class);
896         return s;
897     }
898
899     private Map<INode, LinkNode> getSelectedNodeReferences(G2DParentNode selectionsNode, Map<INode, LinkNode> result) {
900         for (IG2DNode node : selectionsNode.getSortedNodes()) {
901             if (node instanceof LinkNode) {
902                 INode n = ((LinkNode) node).getDelegate();
903                 if (n != null)
904                     result.put(n, (LinkNode) node);
905             }
906         }
907         return result;
908     }
909
910     public void updateSelection(IElement el) {
911         Object task = BEGIN("EP.updateSelection");
912
913         try {
914             if (!paintSelectionFrames)
915                 return;
916
917             G2DParentNode elementNode = (G2DParentNode) el.getHint(ElementHints.KEY_SG_NODE);
918             if (elementNode == null)
919                 return;
920
921             boolean nodesUpdated = false;
922
923             for (Map.Entry<Integer, ElementNodeBridge> entry : selections.entrySet()) {
924                 Integer selectionId = entry.getKey();
925                 ElementNodeBridge bridge = entry.getValue();
926                 Color color = getSelectionColor(selectionId);
927
928                 G2DParentNode selectionNode = (G2DParentNode) bridge.getRight(el);
929                 if (selectionNode == null)
930                     continue;
931
932                 if (NodeUtil.needSelectionPaint(elementNode))
933                     paintSelectionFrame(elementNode, selectionNode, el, color);
934
935                 nodesUpdated = true;
936             }
937
938             // Make sure the view is refreshed after selection changes.
939             if (nodesUpdated)
940                 setDirty();
941         } finally {
942             END(task);
943         }
944     }
945
946     /**
947      * @param selection
948      * @param selectionId
949      * @param selectionNodes for collecting all the "selection" nodes created or
950      *        referenced by this method
951      * @param bridge
952      * @return
953      */
954     public boolean paintSelection(Set<IElement> selection, int selectionId, Set<INode> selectionNodes, ElementNodeBridge bridge) {
955
956         boolean result = false;
957         Color color = getSelectionColor(selectionId);
958         G2DParentNode selectionsNode = getSelectionsNode(selectionId);
959
960         for (IElement e : selection) {
961             Node elementNode = e.getHint(ElementHints.KEY_SG_NODE);
962 //            System.out.println("selectionNode: " + elementNode + " " + e);
963             if (elementNode instanceof G2DParentNode) {
964                 G2DParentNode en = (G2DParentNode) elementNode;
965                 G2DParentNode selectionNode = en.getOrCreateNode(NodeUtil.SELECTION_NODE_NAME, G2DParentNode.class);
966                 selectionNode.setZIndex(SELECTION_PAINT_PRIORITY);
967                 if (selectionNodes != null)
968                     selectionNodes.add(selectionNode);
969                 if (!bridge.containsLeft(e)) {
970                     //System.out.println("ADDED SELECTION: " + e + " -> " + selectionNode);
971                     bridge.map(e, selectionNode);
972                     result = true;
973                 }
974
975                 // Mark this node selected in the scene graph "data area"
976                 createSelectionReference(selectionsNode, elementNode);
977
978                 if (NodeUtil.needSelectionPaint(elementNode))
979                     paintSelectionFrame(en, selectionNode, e, color);
980
981             } else {
982                 if (elementNode != null) {
983                     // Cannot paint selection for unrecognized non-parenting node
984                     System.out.println("Cannot add selection child node for non-parent element node: " + elementNode);
985                 }
986             }
987         }
988
989 //        if (selection.isEmpty()) {
990 //            Node pivotNode = (Node) parent.getNode("pivot");
991 //            if (pivotNode != null)
992 //                pivotNode.remove();
993 //        } else {
994 //            Point2D pivot = ElementUtils.getElementBoundsCenter(selection, pivotPoint);
995 //            if (pivot != null) {
996 //                //System.out.println("painting pivot: " + pivot);
997 //                SelectionPivotNode pivotNode = parent.getOrCreateNode("pivot", SelectionPivotNode.class);
998 //                pivotNode.setPivot(pivot);
999 //            } else {
1000 //                parent.removeNode("pivot");
1001 //            }
1002 //        }
1003
1004         return result;
1005     }
1006
1007     public void paintSelectionFrame(G2DParentNode elementNode, G2DParentNode selectionNode, final IElement e, Color color) {
1008         // The element node already has the correct transform.
1009         AffineTransform selectionTransform = ElementUtils.getTransform(e);// no it doesnt ... new AffineTransform();
1010         Shape shape = ElementUtils.getElementShapeOrBounds(e);
1011         Rectangle2D bounds = shape.getBounds2D();
1012         //System.out.println("selection bounds: "+bounds);
1013         final double margin = 1;
1014         bounds.setFrame(bounds.getMinX() - margin, bounds.getMinY() - margin, bounds.getWidth() + 2*margin, bounds.getHeight() + 2*margin);
1015
1016         List<SelectionSpecification> ss = e.getElementClass().getItemsByClass(SelectionSpecification.class);
1017         if (!ss.isEmpty()) {
1018             G2DParentNode shapeholder = selectionNode.getOrCreateNode(getNodeId("outlines", e), G2DParentNode.class);
1019
1020             for (SelectionSpecification es : ss) {
1021                 Outline outline = (Outline) es.getAdapter(Outline.class);
1022                 if (outline == null || outline.getElementShape(e) == null)
1023                         continue;
1024                 ShapeNode shapenode = shapeholder.getOrCreateNode(getNodeId("outline", e, es), ShapeNode.class);
1025 //                shapenode.setShape(es.getSelectionShape(e));
1026 //                shapenode.setStroke(SELECTION_STROKE);
1027 //                shapenode.setScaleStroke(true);
1028 //                shapenode.setColor(color);
1029 //                shapenode.setTransform(selectionTransform);
1030 //                shapenode.setFill(false);
1031                 shapenode.setShape(outline.getElementShape(e));
1032                 StrokeSpec strokeSpec = (StrokeSpec) es.getAdapter(StrokeSpec.class);
1033                 if (strokeSpec != null && strokeSpec.getStroke(e) != null)
1034                         shapenode.setStroke(strokeSpec.getStroke(e));
1035                 
1036                 shapenode.setScaleStroke(false);
1037                 //shapenode.setColor(color);
1038                 OutlineColorSpec foregroundColor = (OutlineColorSpec) es.getAdapter(OutlineColorSpec.class);
1039                 if (foregroundColor != null && foregroundColor.getColor(e) != null)
1040                         shapenode.setColor(foregroundColor.getColor(e));
1041                 
1042                 Transform transform = (Transform) es.getAdapter(Transform.class);
1043                 if (transform != null && transform.getTransform(e) != null)
1044                         shapenode.setTransform(transform.getTransform(e));
1045                 
1046                 shapenode.setFill(false);
1047                 FillColor fillColor = (FillColor) es.getAdapter(FillColor.class);
1048                 if (fillColor != null && fillColor.getFillColor(e) != null)
1049                     shapenode.setFill(true);
1050 //                      shapenode.setColor(ColorUtil.withAlpha(backgroundColor.getColor(e), 192));
1051             }
1052             return;
1053         }
1054
1055         List<SelectionOutline> shapeHandlers = e.getElementClass().getItemsByClass(SelectionOutline.class);
1056         if (!shapeHandlers.isEmpty()) {
1057             G2DParentNode shapeholder = selectionNode.getOrCreateNode(getNodeId("outlines", e), G2DParentNode.class);
1058
1059             for (SelectionOutline es : shapeHandlers) {
1060                 ShapeNode shapenode = shapeholder.getOrCreateNode(getNodeId("outline", e, es), ShapeNode.class);
1061 //                shapenode.setShape(es.getSelectionShape(e));
1062 //                shapenode.setStroke(SELECTION_STROKE);
1063 //                shapenode.setScaleStroke(true);
1064 //                shapenode.setColor(color);
1065 //                shapenode.setTransform(selectionTransform);
1066 //                shapenode.setFill(false);
1067                 shapenode.setShape(es.getSelectionShape(e));
1068                 shapenode.setStroke(null);
1069                 shapenode.setScaleStroke(false);
1070                 //shapenode.setColor(color);
1071                 shapenode.setColor(ColorUtil.withAlpha(color, 192));
1072                 shapenode.setTransform(selectionTransform);
1073                 shapenode.setFill(true);
1074             }
1075             return;
1076         }
1077
1078         ISelectionProvider provider = this.getContext().getDefaultHintContext().getHint(KEY_SELECTION_PROVIDER);
1079         if (provider != null) {
1080             provider.init(e, selectionNode, getNodeId("shape", e), selectionTransform, bounds, color);
1081         } else {
1082             SelectionNode s = selectionNode.getOrCreateNode(getNodeId("shape", e), SelectionNode.class);
1083             s.init(selectionTransform, bounds, color);
1084         }
1085     }
1086
1087     private void createSelectionReference(G2DParentNode selectionsNode, INode elementNode) {
1088         String id = NodeUtil.lookupId(elementNode);
1089         String uuid = null;
1090         if (id == null)
1091             id = uuid = UUID.randomUUID().toString();
1092         NodeUtil.map(elementNode, id);
1093         LinkNode link = selectionsNode.getOrCreateNode(id, LinkNode.class);
1094         link.setDelegateId(id);
1095         link.setIgnoreDelegate(true);
1096         link.setLookupIdOwner(uuid != null);
1097     }
1098
1099     private transient CharBuffer buf = CharBuffer.allocate(32);
1100
1101     private String getNodeId(String prefix, Object first) {
1102         return getNodeId(prefix, first, null);
1103     }
1104
1105     private String getNodeId(String prefix, Object first, Object second) {
1106         buf.clear();
1107         if (prefix != null)
1108             buf.append(prefix);
1109         if (first != null) {
1110             buf.append('_');
1111             buf.append("" + first.hashCode());
1112         }
1113         if (second != null) {
1114             buf.append('_');
1115             buf.append("" + second.hashCode());
1116         }
1117         buf.limit(buf.position());
1118         buf.rewind();
1119         //System.out.println("node id: " + buf.toString());
1120         return buf.toString();
1121     }
1122
1123     /**
1124      * Get selection color for a selection Id
1125      * @param selectionId selection id
1126      * @return color for the id
1127      */
1128     protected Color getSelectionColor(int selectionId) {
1129         if (selectionId == 0) {
1130             Color c = getHint(KEY_SELECTION_FRAME_COLOR);
1131             if (c != null)
1132                 return c;
1133             return Color.BLACK;
1134         }
1135         Color c = selectionColor.get(selectionId);
1136         if (c == null) {
1137             Random r = new Random(selectionId);
1138             c = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat());
1139             selectionColor.put(selectionId, c);
1140         }
1141         return c;
1142     }
1143
1144     private transient ConcurrentMap<Integer, ElementNodeBridge> selections = new ConcurrentHashMap<Integer, ElementNodeBridge>();
1145
1146     ElementNodeBridge getSelectionMap(int selectionId) {
1147         return selections.get(Integer.valueOf(selectionId));
1148     }
1149
1150     ElementNodeBridge getOrCreateSelectionMap(int selectionId) {
1151         Integer id = Integer.valueOf(selectionId);
1152         synchronized (selections) {
1153             ElementNodeBridge map = selections.get(id);
1154             if (map != null)
1155                 return map;
1156
1157             selections.put(id, map = new ElementNodeBridge(id));
1158             return map;
1159         }
1160     }
1161
1162     private transient Map<Integer, Color>     selectionColor              = new HashMap<Integer, Color>();
1163
1164     private transient BasicStroke             SELECTION_STROKE            = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
1165             BasicStroke.JOIN_BEVEL, 10.0f,
1166             new float[] { 5.0f, 5.0f }, 0.0f);
1167
1168     private transient Point2D                 pivotPoint                  = new Point2D.Double();
1169
1170     @HintListener(Class=Selection.class, Field="SELECTION0")
1171     public void selectionChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
1172         //System.out.println("new selection: " + newValue);
1173         updateSelections();
1174     }
1175
1176     @HintListener(Class=Selection.class, Field="SELECTION0")
1177     public void selectionRemoved(IHintObservable sender, Key key, Object oldValue) {
1178         //System.out.println("selection removed: " + oldValue);
1179         updateSelections();
1180     }
1181
1182     private static Object BEGIN(String name) {
1183         if (DEBUG) {
1184             //return ThreadLog.BEGIN(name);
1185         }
1186         return null;
1187     }
1188
1189     private static void END(Object task) {
1190         if (DEBUG) {
1191             //((Task) task).end();
1192         }
1193     }
1194
1195 }