1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.g2d.diagram.participant;
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;
30 import java.util.Random;
32 import java.util.UUID;
33 import java.util.concurrent.ConcurrentHashMap;
34 import java.util.concurrent.ConcurrentMap;
35 import java.util.function.Consumer;
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;
103 * A diagram participant that keeps a diagram and its elements synchronized with
104 * the active canvas scene graph.
107 * Responsibilities include:
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>
119 * @author Tuukka Lehtonen
121 * @see ElementNodeBridge
123 public class ElementPainter extends AbstractDiagramParticipant implements CompositionListener, TransactionListener, ChildListener {
125 public static final Key KEY_SELECTION_PROVIDER = new KeyOf(ISelectionProvider.class);
127 public static final int SELECTION_PAINT_PRIORITY = 100;
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");
134 * Implement to customize the way a selection is visualized by
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);
142 private static final boolean DEBUG = false;
144 public static final int ELEMENT_PAINT_PRIORITY = 10;
147 ZOrderHandler zOrderHandler;
155 SingleElementNode diagramParent;
156 RTreeNode elementParent;
158 boolean paintSelectionFrames;
161 * Internally reused to avert constant reallocation.
163 private transient List<Relation> relations = new ArrayList<Relation>(4);
165 * Internally reused to avert constant reallocation.
167 private transient Set<IElement> relatedElements = new HashSet<IElement>(8);
169 public ElementPainter() {
173 public ElementPainter(boolean paintSelectionFrames) {
174 this.paintSelectionFrames = paintSelectionFrames;
178 public void addedToContext(ICanvasContext ctx) {
179 super.addedToContext(ctx);
180 if (zOrderHandler != null) {
181 zOrderHandler.addOrderListener(zOrderListener);
186 public void removedFromContext(ICanvasContext ctx) {
187 if (zOrderHandler != null) {
188 zOrderHandler.removeOrderListener(zOrderListener);
191 super.removedFromContext(ctx);
195 protected void onDiagramSet(IDiagram newValue, IDiagram oldValue) {
196 if (oldValue == newValue)
199 if (oldValue != null) {
200 for (IElement e : oldValue.getElements()) {
204 oldValue.removeCompositionListener(this);
205 oldValue.removeKeyHintListener(Hints.KEY_DIRTY, diagramHintListener);
206 oldValue.removeKeyHintListener(Hints.KEY_DISABLE_PAINTING, diagramHintListener);
208 ILayersEditor layers = oldValue.getHint(DiagramHints.KEY_LAYERS_EDITOR);
209 if (layers != null) {
210 layers.removeListener(layersListener);
213 for (TransactionContext tc : oldValue.getDiagramClass().getItemsByClass(TransactionContext.class)) {
214 tc.removeTransactionListener(oldValue, this);
218 if (newValue != null) {
219 for (IElement e : newValue.getElements()) {
220 addElement(e, false);
223 newValue.addCompositionListener(this);
224 newValue.addKeyHintListener(Hints.KEY_DISABLE_PAINTING, diagramHintListener);
225 newValue.addKeyHintListener(Hints.KEY_DIRTY, diagramHintListener);
227 ILayersEditor layers = newValue.getHint(DiagramHints.KEY_LAYERS_EDITOR);
228 if (layers != null) {
229 layers.addListener(layersListener);
232 for (TransactionContext tc : newValue.getDiagramClass().getItemsByClass(TransactionContext.class)) {
233 tc.addTransactionListener(newValue, this);
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);
249 public void cleanupSG() {
250 diagramParent.remove();
251 elementParent = null;
252 diagramParent = null;
255 public INode getDiagramElementParentNode() {
256 return elementParent;
259 // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
260 // Element z-order listening and update logic
261 // ------------------------------------------------------------------------
263 ZOrderListener zOrderListener = new ZOrderListener() {
265 public void orderChanged(IDiagram diagram) {
266 if (diagram == ElementPainter.this.diagram) {
267 updateZOrder(diagram, ElementHints.KEY_SG_NODE);
272 protected static void updateZOrder(IDiagram diagram, Key elementSgNodeKey) {
274 for (IElement e : diagram.getElements()) {
275 Node node = e.getHint(elementSgNodeKey);
276 if (node instanceof IG2DNode) {
277 ((IG2DNode) node).setZIndex(++zIndex);
282 // ------------------------------------------------------------------------
283 // Element z-order listening and update logic end
284 // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
287 // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
288 // Layer configuration change listening and reaction logic
289 // ------------------------------------------------------------------------
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();
299 public void layerRemoved(ILayer layer) {
303 public void layerDeactivated(ILayer layer) {
307 public void layerAdded(ILayer layer) {
311 public void layerActivated(ILayer layer) {
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);
323 public void ignoreVisibilityChanged(boolean value) {
328 protected void updateAllVisibility() {
329 // TODO: optimize, no node reinitialization
333 // ------------------------------------------------------------------------
334 // Layer configuration change listening and reaction logic
335 // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
338 // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
339 // Diagram/Element hint listeners
340 // ------------------------------------------------------------------------
342 class DiagramHintListener extends HintListenerAdapter {
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));
349 } else if (key == Hints.KEY_DIRTY) {
350 if (newValue == Hints.VALUE_Z_ORDER_CHANGED) {
351 diagram.removeHint(Hints.KEY_DIRTY);
354 System.out.println("Diagram z-order changed: " + diagram);
356 updateZOrder(diagram, ElementHints.KEY_SG_NODE);
362 private final DiagramHintListener diagramHintListener = new DiagramHintListener();
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.
369 * It does this by listening to {@link Hints#KEY_DIRTY} hint changes.
371 * @author Tuukka Lehtonen
373 class ElementHintListener implements IHintListener {
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");
382 IElement e = (IElement) sender;
383 e.removeHint(Hints.KEY_DIRTY);
386 System.out.println("Element is dirty: " + e);
388 updateSelfAndNeighbors(e, COMPLETE_UPDATE);
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);
404 public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {
408 private final ElementHintListener elementHintListener = new ElementHintListener();
410 private final Set<Transaction> activeTransactions = new HashSet<Transaction>();
413 public void transactionStarted(IDiagram d, Transaction t) {
414 activeTransactions.add(t);
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));
422 //System.out.println("COMPLETE_UPDATE(" + element + ")");
424 updateSelection(element);
427 Set<IElement> addRelatedElements(Set<IElement> elements) {
428 RelationshipHandler rh = diagram.getDiagramClass().getAtMostOneItemOfClass(RelationshipHandler.class);
430 relatedElements.clear();
431 for (IElement el : elements) {
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);
442 elements.addAll(relatedElements);
443 relatedElements.clear();
450 * @param updateCallback
452 protected void updateSelfAndNeighbors(IElement e, Consumer<IElement> updateCallback) {
453 // Slight optimization for cases that are known to be topologically
455 if (!isNotSelectionExpandable(e)) {
456 Set<IElement> single = Collections.singleton(e);
458 Set<IElement> expanded =
459 // Also update all elements somehow related to e.
461 // Get all topological neighbors and element self.
462 CollectionUtils.join(
464 TopologicalSelectionExpander.expandSelection(diagram, single)
467 // Perform the updates.
468 for (IElement el : expanded) {
469 updateCallback.accept(el);
472 updateCallback.accept(e);
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);
488 public void transactionFinished(IDiagram d, Transaction t) {
489 activeTransactions.remove(t);
492 boolean inDiagramTransaction() {
493 return !activeTransactions.isEmpty();
497 public void onElementAdded(IDiagram d, IElement e) {
499 System.out.println("EP.onElementAdded(" + d + ", " + e + ")");
501 if (inDiagramTransaction()) {
502 addElement(e, false);
508 public void onElementRemoved(IDiagram d, IElement e) {
510 System.out.println("EP.onElementRemoved(" + d + ", " + e + ")");
516 public void elementChildrenChanged(ChildEvent event) {
518 System.out.println("EP.elementChildrenChanged: " + event);
520 for (IElement removed : event.removed) {
521 removeElement(removed);
523 for (IElement added : event.added) {
524 addElement(added, false);
528 private final List<IElement> childrenTemp = new ArrayList<IElement>();
530 public void addElement(IElement e, boolean synchronizeSceneGraphNow) {
532 System.out.println("EP.addElement(now=" + synchronizeSceneGraphNow + ", " + e + ")");
534 e.addKeyHintListener(Hints.KEY_DIRTY, elementHintListener);
535 e.addKeyHintListener(ElementHints.KEY_VISIBLE_LAYERS, elementHintListener);
536 e.addKeyHintListener(ElementHints.KEY_FOCUS_LAYERS, elementHintListener);
538 ElementClass clazz = e.getElementClass();
539 G2DParentNode parentNode = elementParent;
540 Key sgKey = ElementHints.KEY_SG_NODE;
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;
553 boolean isConnection = e.getElementClass().containsClass(ConnectionHandler.class);
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);
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);
577 Children children = clazz.getAtMostOneItemOfClass(Children.class);
578 if (children != null) {
579 children.addChildListener(e, this);
581 childrenTemp.clear();
582 children.getChildren(e, childrenTemp);
583 //System.out.println("children: " + childrenTemp);
584 for (IElement child : childrenTemp) {
585 addElement(child, false);
587 childrenTemp.clear();
590 if (synchronizeSceneGraphNow)
591 updateElement(e, sgKey);
596 protected void removeElement(IElement e) {
598 System.out.println("EP.removeElement(" + e + ")");
600 e.removeKeyHintListener(Hints.KEY_DIRTY, elementHintListener);
601 e.removeKeyHintListener(ElementHints.KEY_VISIBLE_LAYERS, elementHintListener);
602 e.removeKeyHintListener(ElementHints.KEY_FOCUS_LAYERS, elementHintListener);
604 ElementClass clazz = e.getElementClass();
605 if (clazz.containsClass(Children.class)) {
606 Children children = clazz.getSingleItem(Children.class);
607 children.removeChildListener(e, this);
610 List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);
611 for (SceneGraph n : nodeHandlers) {
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);
629 * Invalidate the whole scene graph spatial structure. It will be rebuilt by
630 * RTreeNode when needed the next time.
632 private void setTreeDirty() {
633 elementParent.setDirty();
637 * Mark the specified node invalid with respect to the scene graph spatial
640 * @param node a scene graph node that has somehow changed
642 private void invalidateNode(INode node) {
643 // TODO: optimize rtree updates instead of killing the whole tree
644 elementParent.setDirty();
647 // ------------------------------------------------------------------------
648 // Diagram/Element hint listeners
649 // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
651 public void updateAll() {
653 System.out.println("EP.updateAll()");
655 Object task = BEGIN("EP.updateAll");
656 paintDiagram(elementParent, diagram, null);
662 public void update(IElement element) {
663 updateElement(element, ElementHints.KEY_SG_NODE);
670 * @param elementsToPaint
671 * elements to paint or null for all elements
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);
683 * @param elementsToPaint
684 * elements to paint or null for all elements
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);
691 Boolean disablePaint = diagram.getHint(Hints.KEY_DISABLE_PAINTING);
692 if (Boolean.TRUE.equals(disablePaint)) {
693 parent.removeNodes();
697 // Paint elementsToPaint in correct z-order from diagram.getElements()
698 List<IElement> elements = diagram.getSnapshot();
700 Set<SingleElementNode> tmp = new HashSet<SingleElementNode>();
702 for (int pass = 0; pass < 1; ++pass) {
703 for (IElement e : elements) {
704 if (elements != elementsToPaint && elementsToPaint != null)
705 if (!elementsToPaint.contains(e))
709 System.out.println("EP.paintDiagram(" + zIndex + ", " + e + ")");
711 SingleElementNode holder = updateElement(parent, e, elementSgNodeKey, false);
712 if (holder != null) {
714 holder.setZIndex(++zIndex);
719 // Hide unaccessed nodes (but don't remove)
720 for (IG2DNode node : parent.getNodes()) {
721 if (!tmp.contains(node)) {
722 ((SingleElementNode)node).setVisible(false);
727 public void updateElement(IElement e, Key elementSgNodeKey) {
728 updateElement(null, e, elementSgNodeKey, true);
732 * @param parent if <code>null</code> the scene graph node structure
733 * will not be created if it is missing
735 * @param elementSgNodeKey
736 * @param invalidateNode
738 public SingleElementNode updateElement(G2DParentNode parent, IElement e, Key elementSgNodeKey, boolean invalidateNode) {
740 System.out.println("EP.updateElement(" + e + ", " + elementSgNodeKey + ")");
741 Object task = BEGIN("EP.updateElement");
744 SingleElementNode holder = e.getHint(elementSgNodeKey);
745 if (holder == null && parent == null)
748 if (ElementUtils.isHidden(e))
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)) {
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()))
766 Composite composite = e.getHint(ElementHints.KEY_COMPOSITE);
768 if (holder == null) {
769 holder = parent.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);
770 e.setHint(elementSgNodeKey, holder);
772 holder.setComposite(composite);
773 holder.setVisible(true);
775 for (SceneGraph n : nodeHandlers) {
779 // Process decorators
780 if (decorators == null || decorators.isEmpty()) {
781 holder.removeNode("decorators");
783 G2DParentNode decoratorHolder = holder.getOrCreateNode("decorators", G2DParentNode.class);
784 decoratorHolder.removeNodes();
785 for (SceneGraph decorator : decorators) {
786 decorator.init(e, decoratorHolder);
791 invalidateNode(holder);
800 * @param elementsToUpdate to explicitly specify which elements to update
801 * the selection scene graph for, or <code>null</code> to update
804 public void updateSelections() {
805 Object task = BEGIN("EP.updateSelections");
808 if (!paintSelectionFrames)
810 if (selection == null)
813 boolean selectionsChanged = false;
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>();
821 for (Map.Entry<Integer, Set<IElement>> entry : selection.getSelections().entrySet()) {
822 Integer selectionId = entry.getKey();
823 Set<IElement> selectedElements = entry.getValue();
825 existingSelections.add(selectionId);
827 // System.out.println("SELECTION[" + selectionId + "]: " + selectedElements);
828 ElementNodeBridge bridge = getOrCreateSelectionMap(selectionId);
829 selectionNodes.clear();
830 selectionsChanged |= paintSelection(selectedElements, selectionId, selectionNodes, bridge);
832 // Remove selection nodes that were not referenced during the update.
833 // System.out.println("BRIDGE: " + bridge.toString());
834 // System.out.println("SELECTED: " + selectionNodes);
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);
843 G2DParentNode selectionsNode = getSelectionsNode(selectionId);
844 selectionLinks.clear();
845 getSelectedNodeReferences(selectionsNode, selectionLinks);
847 for (INode node : tmp) {
848 INode linkNode = selectionLinks.get(node.getParent());
849 if (linkNode != null) {
852 // System.out.println("REMOVED SELECTION: -> " + node);
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);
869 G2DParentNode selectionsNode = getSelectionsNode(selectionId);
870 selectionsNode.removeNodes();
874 // Make sure the view is refreshed after selection changes.
875 if (selectionsChanged) {
883 private G2DParentNode getSelectionsNode() {
884 G2DParentNode sels = NodeUtil.lookup(diagramParent, SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);
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);
893 private G2DParentNode getSelectionsNode(int selectionId) {
894 G2DParentNode selectionsNode = getSelectionsNode();
895 G2DParentNode s = selectionsNode.getOrCreateNode(String.valueOf(selectionId), G2DParentNode.class);
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();
904 result.put(n, (LinkNode) node);
910 public void updateSelection(IElement el) {
911 Object task = BEGIN("EP.updateSelection");
914 if (!paintSelectionFrames)
917 G2DParentNode elementNode = (G2DParentNode) el.getHint(ElementHints.KEY_SG_NODE);
918 if (elementNode == null)
921 boolean nodesUpdated = false;
923 for (Map.Entry<Integer, ElementNodeBridge> entry : selections.entrySet()) {
924 Integer selectionId = entry.getKey();
925 ElementNodeBridge bridge = entry.getValue();
926 Color color = getSelectionColor(selectionId);
928 G2DParentNode selectionNode = (G2DParentNode) bridge.getRight(el);
929 if (selectionNode == null)
932 if (NodeUtil.needSelectionPaint(elementNode))
933 paintSelectionFrame(elementNode, selectionNode, el, color);
938 // Make sure the view is refreshed after selection changes.
949 * @param selectionNodes for collecting all the "selection" nodes created or
950 * referenced by this method
954 public boolean paintSelection(Set<IElement> selection, int selectionId, Set<INode> selectionNodes, ElementNodeBridge bridge) {
956 boolean result = false;
957 Color color = getSelectionColor(selectionId);
958 G2DParentNode selectionsNode = getSelectionsNode(selectionId);
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);
975 // Mark this node selected in the scene graph "data area"
976 createSelectionReference(selectionsNode, elementNode);
978 if (NodeUtil.needSelectionPaint(elementNode))
979 paintSelectionFrame(en, selectionNode, e, color);
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);
989 // if (selection.isEmpty()) {
990 // Node pivotNode = (Node) parent.getNode("pivot");
991 // if (pivotNode != null)
992 // pivotNode.remove();
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);
1000 // parent.removeNode("pivot");
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);
1016 List<SelectionSpecification> ss = e.getElementClass().getItemsByClass(SelectionSpecification.class);
1017 if (!ss.isEmpty()) {
1018 G2DParentNode shapeholder = selectionNode.getOrCreateNode(getNodeId("outlines", e), G2DParentNode.class);
1020 for (SelectionSpecification es : ss) {
1021 Outline outline = (Outline) es.getAdapter(Outline.class);
1022 if (outline == null || outline.getElementShape(e) == null)
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));
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));
1042 Transform transform = (Transform) es.getAdapter(Transform.class);
1043 if (transform != null && transform.getTransform(e) != null)
1044 shapenode.setTransform(transform.getTransform(e));
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));
1055 List<SelectionOutline> shapeHandlers = e.getElementClass().getItemsByClass(SelectionOutline.class);
1056 if (!shapeHandlers.isEmpty()) {
1057 G2DParentNode shapeholder = selectionNode.getOrCreateNode(getNodeId("outlines", e), G2DParentNode.class);
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);
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);
1082 SelectionNode s = selectionNode.getOrCreateNode(getNodeId("shape", e), SelectionNode.class);
1083 s.init(selectionTransform, bounds, color);
1087 private void createSelectionReference(G2DParentNode selectionsNode, INode elementNode) {
1088 String id = NodeUtil.lookupId(elementNode);
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);
1099 private transient CharBuffer buf = CharBuffer.allocate(32);
1101 private String getNodeId(String prefix, Object first) {
1102 return getNodeId(prefix, first, null);
1105 private String getNodeId(String prefix, Object first, Object second) {
1109 if (first != null) {
1111 buf.append("" + first.hashCode());
1113 if (second != null) {
1115 buf.append("" + second.hashCode());
1117 buf.limit(buf.position());
1119 //System.out.println("node id: " + buf.toString());
1120 return buf.toString();
1124 * Get selection color for a selection Id
1125 * @param selectionId selection id
1126 * @return color for the id
1128 protected Color getSelectionColor(int selectionId) {
1129 if (selectionId == 0) {
1130 Color c = getHint(KEY_SELECTION_FRAME_COLOR);
1135 Color c = selectionColor.get(selectionId);
1137 Random r = new Random(selectionId);
1138 c = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat());
1139 selectionColor.put(selectionId, c);
1144 private transient ConcurrentMap<Integer, ElementNodeBridge> selections = new ConcurrentHashMap<Integer, ElementNodeBridge>();
1146 ElementNodeBridge getSelectionMap(int selectionId) {
1147 return selections.get(Integer.valueOf(selectionId));
1150 ElementNodeBridge getOrCreateSelectionMap(int selectionId) {
1151 Integer id = Integer.valueOf(selectionId);
1152 synchronized (selections) {
1153 ElementNodeBridge map = selections.get(id);
1157 selections.put(id, map = new ElementNodeBridge(id));
1162 private transient Map<Integer, Color> selectionColor = new HashMap<Integer, Color>();
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);
1168 private transient Point2D pivotPoint = new Point2D.Double();
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);
1176 @HintListener(Class=Selection.class, Field="SELECTION0")
1177 public void selectionRemoved(IHintObservable sender, Key key, Object oldValue) {
1178 //System.out.println("selection removed: " + oldValue);
1182 private static Object BEGIN(String name) {
1184 //return ThreadLog.BEGIN(name);
1189 private static void END(Object task) {
1191 //((Task) task).end();