]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.g2d/src/org/simantics/g2d/diagram/participant/ElementPainter.java
Combination of Simantics-platform related changes and fixes for district
[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                 holder = parentNode.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);
571                 holder.setKey(e.getHint(ElementHints.KEY_OBJECT));
572                 holder.setTransferableProvider(new ElementTransferableProvider(getContext(), e));
573                 e.setHint(sgKey, holder);
574                 holder.setZIndex(parentNode.getNodeCount() + 1);
575             }
576
577         }
578
579         Children children = clazz.getAtMostOneItemOfClass(Children.class);
580         if (children != null) {
581             children.addChildListener(e, this);
582
583             childrenTemp.clear();
584             children.getChildren(e, childrenTemp);
585             //System.out.println("children: " + childrenTemp);
586             for (IElement child : childrenTemp) {
587                 addElement(child, false);
588             }
589             childrenTemp.clear();
590         }
591
592         if (synchronizeSceneGraphNow)
593             updateElement(e, sgKey);
594
595         //setTreeDirty();
596     }
597
598     protected void removeElement(IElement e) {
599         if (DEBUG)
600             System.out.println("EP.removeElement(" + e + ")");
601
602         e.removeKeyHintListener(Hints.KEY_DIRTY, elementHintListener);
603         e.removeKeyHintListener(ElementHints.KEY_VISIBLE_LAYERS, elementHintListener);
604         e.removeKeyHintListener(ElementHints.KEY_FOCUS_LAYERS, elementHintListener);
605
606         ElementClass clazz = e.getElementClass();
607         if (clazz.containsClass(Children.class)) {
608             Children children = clazz.getSingleItem(Children.class);
609             children.removeChildListener(e, this);
610         }
611
612         List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);
613         for (SceneGraph n : nodeHandlers) {
614             n.cleanup(e);
615         }
616
617         // Remove all hints related to scene graph nodes to prevent leakage of
618         // scene graph resources.
619         Map<SceneGraphNodeKey, Object> sgHints = e.getHintsOfClass(SceneGraphNodeKey.class);
620         for (SceneGraphNodeKey sgKey : sgHints.keySet()) {
621             Node n = e.removeHint(sgKey);
622             if (n != null) {
623                 n.remove();
624             }
625         }
626
627         //setTreeDirty();
628     }
629
630     /**
631      * Invalidate the whole scene graph spatial structure. It will be rebuilt by
632      * RTreeNode when needed the next time.
633      */
634     private void setTreeDirty() {
635         elementParent.setDirty();
636     }
637
638     /**
639      * Mark the specified node invalid with respect to the scene graph spatial
640      * structure.
641      * 
642      * @param node a scene graph node that has somehow changed
643      */
644     private void invalidateNode(INode node) {
645         // TODO: optimize rtree updates instead of killing the whole tree
646         elementParent.setDirty();
647     }
648
649     // ------------------------------------------------------------------------
650     // Diagram/Element hint listeners
651     // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
652
653     public void updateAll() {
654         if (DEBUG)
655             System.out.println("EP.updateAll()");
656
657         Object task = BEGIN("EP.updateAll");
658         paintDiagram(elementParent, diagram, null);
659         updateSelections();
660         setTreeDirty();
661         END(task);
662     }
663
664     public void update(IElement element) {
665         updateElement(element, ElementHints.KEY_SG_NODE);
666     }
667
668     /**
669      *
670      * @param controlGC
671      * @param diagram
672      * @param elementsToPaint
673      *            elements to paint or null for all elements
674      */
675     public void paintDiagram(G2DParentNode parent, IDiagram diagram, Collection<IElement> elementsToPaint) {
676         Object task = BEGIN("EP.paintDiagram");
677         paintDiagram(parent, diagram, elementsToPaint, ElementHints.KEY_SG_NODE);
678         END(task);
679     }
680
681     /**
682      *
683      * @param controlGC
684      * @param diagram
685      * @param elementsToPaint
686      *            elements to paint or null for all elements
687      */
688     public void paintDiagram(G2DParentNode parent, IDiagram diagram, Collection<IElement> elementsToPaint, Key elementSgNodeKey) {
689         if(diagram == null) return;
690         ICanvasContext ctx = getContext();
691         assert (ctx != null);
692
693         Boolean disablePaint = diagram.getHint(Hints.KEY_DISABLE_PAINTING);
694         if (Boolean.TRUE.equals(disablePaint)) {
695             parent.removeNodes();
696             return;
697         }
698
699         // Paint elementsToPaint in correct z-order from diagram.getElements()
700         List<IElement> elements = diagram.getSnapshot();
701
702         Set<SingleElementNode> tmp = new HashSet<SingleElementNode>();
703         int zIndex = 0;
704         for (int pass = 0; pass < 1; ++pass) {
705             for (IElement e : elements) {
706                 if (elements != elementsToPaint && elementsToPaint != null)
707                     if (!elementsToPaint.contains(e))
708                         continue;
709
710                 if (DEBUG)
711                     System.out.println("EP.paintDiagram(" + zIndex + ", " + e + ")");
712
713                 SingleElementNode holder = updateElement(parent, e, elementSgNodeKey, false);
714                 if (holder != null) {
715                     tmp.add(holder);
716                     holder.setZIndex(++zIndex);
717                 }
718             }
719         }
720
721         // Hide unaccessed nodes (but don't remove)
722         for (IG2DNode node : parent.getNodes()) {
723             if (!tmp.contains(node)) {
724                 ((SingleElementNode)node).setVisible(false);
725             }
726         }
727     }
728
729     public void updateElement(IElement e, Key elementSgNodeKey) {
730         updateElement(null, e, elementSgNodeKey, true);
731     }
732
733     /**
734      * @param parent if <code>null</code> the scene graph node structure
735      *        will not be created if it is missing
736      * @param e
737      * @param elementSgNodeKey
738      * @param invalidateNode 
739      */
740     public SingleElementNode updateElement(G2DParentNode parent, IElement e, Key elementSgNodeKey, boolean invalidateNode) {
741         if (DEBUG)
742             System.out.println("EP.updateElement(" + e + ", " + elementSgNodeKey + ")");
743         Object task = BEGIN("EP.updateElement");
744
745         try {
746             SingleElementNode holder = e.getHint(elementSgNodeKey);
747             if (holder == null && parent == null)
748                 return null;
749
750             if (ElementUtils.isHidden(e))
751                 return null;
752
753 //            ElementClass ec = e.getElementClass();
754 //            ILayers layers = diagram.getHint(DiagramHints.KEY_LAYERS);
755 //            if (layers != null && !layers.getIgnoreVisibilitySettings()) {
756 //                ElementLayers el = ec.getAtMostOneItemOfClass(ElementLayers.class);
757 //                if (el != null && !el.isVisible(e, layers)) {
758 //                    return null;
759 //                }
760 //            }
761
762             // Update the node scene graph through SceneGraph handlers.
763             List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);
764             Collection<SceneGraph> decorators = e.getHint(ElementHints.KEY_DECORATORS);
765             if (nodeHandlers.isEmpty() && (decorators == null || decorators.isEmpty()))
766                 return null;
767
768             Composite composite = e.getHint(ElementHints.KEY_COMPOSITE);
769
770             if (holder == null) {
771                 holder = parent.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);
772                 e.setHint(elementSgNodeKey, holder);
773             }
774             holder.setComposite(composite);
775             holder.setVisible(true);
776
777             for (SceneGraph n : nodeHandlers) {
778                 n.init(e, holder);
779             }
780
781             // Process decorators
782             if (decorators == null || decorators.isEmpty()) {
783                 holder.removeNode("decorators");
784             } else {
785                 G2DParentNode decoratorHolder = holder.getOrCreateNode("decorators", G2DParentNode.class);
786                 decoratorHolder.removeNodes();
787                 for (SceneGraph decorator : decorators) {
788                     decorator.init(e, decoratorHolder);
789                 }
790             }
791
792             if (invalidateNode)
793                 invalidateNode(holder);
794
795             return holder;
796         } finally {
797             END(task);
798         }
799     }
800
801     /**
802      * @param elementsToUpdate to explicitly specify which elements to update
803      *        the selection scene graph for, or <code>null</code> to update
804      *        everything
805      */
806     public void updateSelections() {
807         Object task = BEGIN("EP.updateSelections");
808
809         try {
810             if (!paintSelectionFrames)
811                 return;
812             if (selection == null)
813                 return;
814
815             boolean selectionsChanged = false;
816
817             // Update and "touch" all selections.
818             Set<Integer> existingSelections = new HashSet<Integer>();
819             Set<INode> selectionNodes = new HashSet<INode>();
820             Set<INode> tmp = new HashSet<INode>();
821             Map<INode, LinkNode> selectionLinks = new HashMap<INode, LinkNode>();
822
823             for (Map.Entry<Integer, Set<IElement>> entry : selection.getSelections().entrySet()) {
824                 Integer selectionId = entry.getKey();
825                 Set<IElement> selectedElements = entry.getValue();
826
827                 existingSelections.add(selectionId);
828
829 //                System.out.println("SELECTION[" + selectionId + "]: " + selectedElements);
830                 ElementNodeBridge bridge = getOrCreateSelectionMap(selectionId);
831                 selectionNodes.clear();
832                 selectionsChanged |= paintSelection(selectedElements, selectionId, selectionNodes, bridge);
833
834                 // Remove selection nodes that were not referenced during the update.
835 //                System.out.println("BRIDGE: " + bridge.toString());
836 //                System.out.println("SELECTED: " + selectionNodes);
837                 tmp.clear();
838                 tmp.addAll(bridge.getRightSet());
839                 tmp.removeAll(selectionNodes);
840 //                System.out.println("REMOVED: " + tmp);
841 //                System.out.println("BRIDGE BEFORE: " + bridge);
842                 selectionsChanged |= bridge.retainAllRight(selectionNodes);
843 //                System.out.println("BRIDGE AFTER: " + bridge);
844
845                 G2DParentNode selectionsNode = getSelectionsNode(selectionId);
846                 selectionLinks.clear();
847                 getSelectedNodeReferences(selectionsNode, selectionLinks);
848
849                 for (INode node : tmp) {
850                     INode linkNode = selectionLinks.get(node.getParent());
851                     if (linkNode != null) {
852                         linkNode.remove();
853                     }
854 //                    System.out.println("REMOVED SELECTION: -> " + node);
855                     node.remove();
856                 }
857             }
858
859             for (Iterator<Map.Entry<Integer, ElementNodeBridge>> iterator = selections.entrySet().iterator(); iterator.hasNext();) {
860                 Map.Entry<Integer, ElementNodeBridge> entry = iterator.next();
861                 Integer selectionId = entry.getKey();
862                 if (!existingSelections.contains(selectionId)) {
863                     // Selection no longer exists.
864                     selectionsChanged = true;
865                     for (INode node : entry.getValue().getRightSet()) {
866 //                        System.out.println("REMOVED SELECTION: " + node);
867                         node.remove();
868                     }
869                     iterator.remove();
870
871                     G2DParentNode selectionsNode = getSelectionsNode(selectionId);
872                     selectionsNode.removeNodes();
873                 }
874             }
875
876             // Make sure the view is refreshed after selection changes.
877             if (selectionsChanged) {
878                 setDirty();
879             }
880         } finally {
881             END(task);
882         }
883     }
884
885     private G2DParentNode getSelectionsNode() {
886         G2DParentNode sels = NodeUtil.lookup(diagramParent, SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);
887         if (sels == null) {
888             DataNode data= NodeUtil.lookup(diagramParent, SceneGraphConstants.DATA_NODE_NAME, DataNode.class);
889             sels = data.addNode(SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);
890             sels.setLookupId(SceneGraphConstants.SELECTIONS_NODE_NAME);
891         }
892         return sels;
893     }
894
895     private G2DParentNode getSelectionsNode(int selectionId) {
896         G2DParentNode selectionsNode = getSelectionsNode();
897         G2DParentNode s = selectionsNode.getOrCreateNode(String.valueOf(selectionId), G2DParentNode.class);
898         return s;
899     }
900
901     private Map<INode, LinkNode> getSelectedNodeReferences(G2DParentNode selectionsNode, Map<INode, LinkNode> result) {
902         for (IG2DNode node : selectionsNode.getSortedNodes()) {
903             if (node instanceof LinkNode) {
904                 INode n = ((LinkNode) node).getDelegate();
905                 if (n != null)
906                     result.put(n, (LinkNode) node);
907             }
908         }
909         return result;
910     }
911
912     public void updateSelection(IElement el) {
913         Object task = BEGIN("EP.updateSelection");
914
915         try {
916             if (!paintSelectionFrames)
917                 return;
918
919             G2DParentNode elementNode = (G2DParentNode) el.getHint(ElementHints.KEY_SG_NODE);
920             if (elementNode == null)
921                 return;
922
923             boolean nodesUpdated = false;
924
925             for (Map.Entry<Integer, ElementNodeBridge> entry : selections.entrySet()) {
926                 Integer selectionId = entry.getKey();
927                 ElementNodeBridge bridge = entry.getValue();
928                 Color color = getSelectionColor(selectionId);
929
930                 G2DParentNode selectionNode = (G2DParentNode) bridge.getRight(el);
931                 if (selectionNode == null)
932                     continue;
933
934                 if (NodeUtil.needSelectionPaint(elementNode))
935                     paintSelectionFrame(elementNode, selectionNode, el, color);
936
937                 nodesUpdated = true;
938             }
939
940             // Make sure the view is refreshed after selection changes.
941             if (nodesUpdated)
942                 setDirty();
943         } finally {
944             END(task);
945         }
946     }
947
948     /**
949      * @param selection
950      * @param selectionId
951      * @param selectionNodes for collecting all the "selection" nodes created or
952      *        referenced by this method
953      * @param bridge
954      * @return
955      */
956     public boolean paintSelection(Set<IElement> selection, int selectionId, Set<INode> selectionNodes, ElementNodeBridge bridge) {
957
958         boolean result = false;
959         Color color = getSelectionColor(selectionId);
960         G2DParentNode selectionsNode = getSelectionsNode(selectionId);
961
962         for (IElement e : selection) {
963             Node elementNode = e.getHint(ElementHints.KEY_SG_NODE);
964 //            System.out.println("selectionNode: " + elementNode + " " + e);
965             if (elementNode instanceof G2DParentNode) {
966                 G2DParentNode en = (G2DParentNode) elementNode;
967                 G2DParentNode selectionNode = en.getOrCreateNode(NodeUtil.SELECTION_NODE_NAME, G2DParentNode.class);
968                 selectionNode.setZIndex(SELECTION_PAINT_PRIORITY);
969                 if (selectionNodes != null)
970                     selectionNodes.add(selectionNode);
971                 if (!bridge.containsLeft(e)) {
972                     //System.out.println("ADDED SELECTION: " + e + " -> " + selectionNode);
973                     bridge.map(e, selectionNode);
974                     result = true;
975                 }
976
977                 // Mark this node selected in the scene graph "data area"
978                 createSelectionReference(selectionsNode, elementNode);
979
980                 if (NodeUtil.needSelectionPaint(elementNode))
981                     paintSelectionFrame(en, selectionNode, e, color);
982
983             } else {
984                 if (elementNode != null) {
985                     // Cannot paint selection for unrecognized non-parenting node
986                     System.out.println("Cannot add selection child node for non-parent element node: " + elementNode);
987                 }
988             }
989         }
990
991 //        if (selection.isEmpty()) {
992 //            Node pivotNode = (Node) parent.getNode("pivot");
993 //            if (pivotNode != null)
994 //                pivotNode.remove();
995 //        } else {
996 //            Point2D pivot = ElementUtils.getElementBoundsCenter(selection, pivotPoint);
997 //            if (pivot != null) {
998 //                //System.out.println("painting pivot: " + pivot);
999 //                SelectionPivotNode pivotNode = parent.getOrCreateNode("pivot", SelectionPivotNode.class);
1000 //                pivotNode.setPivot(pivot);
1001 //            } else {
1002 //                parent.removeNode("pivot");
1003 //            }
1004 //        }
1005
1006         return result;
1007     }
1008
1009     public void paintSelectionFrame(G2DParentNode elementNode, G2DParentNode selectionNode, final IElement e, Color color) {
1010         // The element node already has the correct transform.
1011         AffineTransform selectionTransform = ElementUtils.getTransform(e);// no it doesnt ... new AffineTransform();
1012         Shape shape = ElementUtils.getElementShapeOrBounds(e);
1013         Rectangle2D bounds = shape.getBounds2D();
1014         //System.out.println("selection bounds: "+bounds);
1015         final double marginX = 1 / selectionTransform.getScaleX();
1016         final double marginY = 1 / selectionTransform.getScaleY();
1017         bounds.setFrame(bounds.getMinX() - marginX, bounds.getMinY() - marginY, bounds.getWidth() + 2*marginX, bounds.getHeight() + 2*marginY);
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 }