1 /*******************************************************************************
2 * Copyright (c) 2007, 2018 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 * Semantum Oy - GitLab issue #66
12 *******************************************************************************/
13 package org.simantics.g2d.diagram.participant;
15 import java.awt.BasicStroke;
16 import java.awt.Color;
17 import java.awt.Composite;
18 import java.awt.Shape;
19 import java.awt.geom.AffineTransform;
20 import java.awt.geom.Point2D;
21 import java.awt.geom.Rectangle2D;
22 import java.nio.CharBuffer;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.Random;
33 import java.util.UUID;
34 import java.util.concurrent.ConcurrentHashMap;
35 import java.util.concurrent.ConcurrentMap;
36 import java.util.function.Consumer;
38 import org.simantics.g2d.canvas.Hints;
39 import org.simantics.g2d.canvas.ICanvasContext;
40 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
41 import org.simantics.g2d.canvas.impl.DependencyReflection.Reference;
42 import org.simantics.g2d.canvas.impl.HintReflection.HintListener;
43 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGCleanup;
44 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
45 import org.simantics.g2d.connection.handler.ConnectionHandler;
46 import org.simantics.g2d.diagram.DiagramHints;
47 import org.simantics.g2d.diagram.DiagramUtils;
48 import org.simantics.g2d.diagram.IDiagram;
49 import org.simantics.g2d.diagram.IDiagram.CompositionListener;
50 import org.simantics.g2d.diagram.handler.RelationshipHandler;
51 import org.simantics.g2d.diagram.handler.RelationshipHandler.Relation;
52 import org.simantics.g2d.diagram.handler.TransactionContext;
53 import org.simantics.g2d.diagram.handler.TransactionContext.Transaction;
54 import org.simantics.g2d.diagram.handler.TransactionContext.TransactionListener;
55 import org.simantics.g2d.element.ElementClass;
56 import org.simantics.g2d.element.ElementHints;
57 import org.simantics.g2d.element.ElementUtils;
58 import org.simantics.g2d.element.IElement;
59 import org.simantics.g2d.element.SceneGraphNodeKey;
60 import org.simantics.g2d.element.handler.BendsHandler;
61 import org.simantics.g2d.element.handler.Children;
62 import org.simantics.g2d.element.handler.Children.ChildEvent;
63 import org.simantics.g2d.element.handler.Children.ChildListener;
64 import org.simantics.g2d.element.handler.FillColor;
65 import org.simantics.g2d.element.handler.Outline;
66 import org.simantics.g2d.element.handler.OutlineColorSpec;
67 import org.simantics.g2d.element.handler.Parent;
68 import org.simantics.g2d.element.handler.SceneGraph;
69 import org.simantics.g2d.element.handler.SelectionOutline;
70 import org.simantics.g2d.element.handler.SelectionSpecification;
71 import org.simantics.g2d.element.handler.StrokeSpec;
72 import org.simantics.g2d.element.handler.TerminalTopology;
73 import org.simantics.g2d.element.handler.Transform;
74 import org.simantics.g2d.layers.ILayer;
75 import org.simantics.g2d.layers.ILayersEditor;
76 import org.simantics.g2d.layers.ILayersEditor.ILayersEditorListener;
77 import org.simantics.g2d.participant.TransformUtil;
78 import org.simantics.g2d.scenegraph.SceneGraphConstants;
79 import org.simantics.g2d.utils.ElementNodeBridge;
80 import org.simantics.g2d.utils.TopologicalSelectionExpander;
81 import org.simantics.scenegraph.INode;
82 import org.simantics.scenegraph.Node;
83 import org.simantics.scenegraph.g2d.G2DParentNode;
84 import org.simantics.scenegraph.g2d.G2DSceneGraph;
85 import org.simantics.scenegraph.g2d.IG2DNode;
86 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
87 import org.simantics.scenegraph.g2d.nodes.DataNode;
88 import org.simantics.scenegraph.g2d.nodes.LinkNode;
89 import org.simantics.scenegraph.g2d.nodes.SelectionNode;
90 import org.simantics.scenegraph.g2d.nodes.ShapeNode;
91 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
92 import org.simantics.scenegraph.g2d.nodes.UnboundedNode;
93 import org.simantics.scenegraph.g2d.nodes.spatial.RTreeNode;
94 import org.simantics.scenegraph.utils.ColorUtil;
95 import org.simantics.scenegraph.utils.GeometryUtils;
96 import org.simantics.scenegraph.utils.NodeUtil;
97 import org.simantics.utils.datastructures.collections.CollectionUtils;
98 import org.simantics.utils.datastructures.hints.HintListenerAdapter;
99 import org.simantics.utils.datastructures.hints.IHintContext.Key;
100 import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;
101 import org.simantics.utils.datastructures.hints.IHintListener;
102 import org.simantics.utils.datastructures.hints.IHintObservable;
105 * A diagram participant that keeps a diagram and its elements synchronized with
106 * the active canvas scene graph.
109 * Responsibilities include:
111 * <li>ensure that the scene graph contains a {@link SingleElementNode} instance
112 * for each diagram element</li>
113 * <li>ensure that the scene graph node order matches the diagram element order</li>
114 * <li>ensure that the scene graph contains a {@link SelectionNode} under the
115 * element instance nodes for each selected node. TODO: maybe try getting
116 * selection out of here into a different participant, but without cloning the
117 * entire listening/element<->scene graph updating infrastructure.</li>
121 * @author Tuukka Lehtonen
123 * @see ElementNodeBridge
125 public class ElementPainter extends AbstractDiagramParticipant implements CompositionListener, TransactionListener, ChildListener {
127 public static final Key KEY_SELECTION_PROVIDER = new KeyOf(ISelectionProvider.class);
129 public static final int SELECTION_PAINT_PRIORITY = 100;
131 public static final Key KEY_SELECTION_FRAME_COLOR = new KeyOf(Color.class, "SELECTION_FRAME_COLOR");
132 public static final Key KEY_SELECTION_CONTENT_COLOR = new KeyOf(Color.class, "SELECTION_CONTENT_COLOR");
136 * Implement to customize the way a selection is visualized by
139 public static interface ISelectionProvider {
140 public void init(int selectionId, final IElement e, final G2DParentNode parentNode, final String nodeId,
141 final AffineTransform transform, final Rectangle2D bounds, final Color color);
144 private static final boolean DEBUG = false;
145 private static final boolean NODE_TO_ELEMENT_MAPPING = true;
147 public static final int ELEMENT_PAINT_PRIORITY = 10;
150 ZOrderHandler zOrderHandler;
158 SingleElementNode diagramParent;
159 RTreeNode elementParent;
161 boolean paintSelectionFrames;
164 * Internally reused to avert constant reallocation.
166 private transient List<Relation> relations = new ArrayList<Relation>(4);
168 * Internally reused to avert constant reallocation.
170 private transient Set<IElement> relatedElements = new HashSet<IElement>(8);
172 public ElementPainter() {
176 public ElementPainter(boolean paintSelectionFrames) {
177 this.paintSelectionFrames = paintSelectionFrames;
181 public void addedToContext(ICanvasContext ctx) {
182 super.addedToContext(ctx);
183 if (zOrderHandler != null) {
184 zOrderHandler.addOrderListener(zOrderListener);
189 public void removedFromContext(ICanvasContext ctx) {
190 if (zOrderHandler != null) {
191 zOrderHandler.removeOrderListener(zOrderListener);
194 super.removedFromContext(ctx);
198 protected void onDiagramSet(IDiagram newValue, IDiagram oldValue) {
199 if (oldValue == newValue)
202 if (oldValue != null) {
203 Map<INode, IElement> nodeToElementMap = oldValue.removeHint(DiagramHints.NODE_TO_ELEMENT_MAP);
204 for (IElement e : oldValue.getElements()) {
205 removeElement(oldValue, e, nodeToElementMap);
208 oldValue.removeCompositionListener(this);
209 oldValue.removeKeyHintListener(Hints.KEY_DIRTY, diagramHintListener);
210 oldValue.removeKeyHintListener(Hints.KEY_DISABLE_PAINTING, diagramHintListener);
212 ILayersEditor layers = oldValue.getHint(DiagramHints.KEY_LAYERS_EDITOR);
213 if (layers != null) {
214 layers.removeListener(layersListener);
217 for (TransactionContext tc : oldValue.getDiagramClass().getItemsByClass(TransactionContext.class)) {
218 tc.removeTransactionListener(oldValue, this);
222 if (newValue != null) {
223 diagram.removeHint(DiagramHints.NODE_TO_ELEMENT_MAP);
224 Map<INode, IElement> nodeElementMap = NODE_TO_ELEMENT_MAPPING ? new HashMap<>() : null;
225 if (nodeElementMap != null)
226 diagram.setHint(DiagramHints.NODE_TO_ELEMENT_MAP, nodeElementMap);
228 for (IElement e : newValue.getElements()) {
229 addElement(newValue, e, false, nodeElementMap);
232 newValue.addCompositionListener(this);
233 newValue.addKeyHintListener(Hints.KEY_DISABLE_PAINTING, diagramHintListener);
234 newValue.addKeyHintListener(Hints.KEY_DIRTY, diagramHintListener);
236 ILayersEditor layers = newValue.getHint(DiagramHints.KEY_LAYERS_EDITOR);
237 if (layers != null) {
238 layers.addListener(layersListener);
241 for (TransactionContext tc : newValue.getDiagramClass().getItemsByClass(TransactionContext.class)) {
242 tc.addTransactionListener(newValue, this);
250 public void initSG(G2DParentNode parent) {
251 diagramParent = parent.addNode("elements_"+Node.IDCOUNTER, UnboundedNode.class);
252 diagramParent.setZIndex(ELEMENT_PAINT_PRIORITY);
253 elementParent = diagramParent.addNode(SceneGraphConstants.SPATIAL_ROOT_NODE_NAME, RTreeNode.class);
254 elementParent.setLookupId(SceneGraphConstants.SPATIAL_ROOT_NODE_ID);
255 elementParent.setZIndex(0);
259 public void cleanupSG() {
260 diagramParent.remove();
261 elementParent = null;
262 diagramParent = null;
265 public INode getDiagramElementParentNode() {
266 return elementParent;
269 // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
270 // Element z-order listening and update logic
271 // ------------------------------------------------------------------------
273 ZOrderListener zOrderListener = new ZOrderListener() {
275 public void orderChanged(IDiagram diagram) {
276 if (diagram == ElementPainter.this.diagram) {
277 updateZOrder(diagram, ElementHints.KEY_SG_NODE);
282 protected static void updateZOrder(IDiagram diagram, Key elementSgNodeKey) {
284 for (IElement e : diagram.getElements()) {
285 Node node = e.getHint(elementSgNodeKey);
286 if (node instanceof IG2DNode) {
287 ((IG2DNode) node).setZIndex(++zIndex);
292 // ------------------------------------------------------------------------
293 // Element z-order listening and update logic end
294 // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
297 // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
298 // Layer configuration change listening and reaction logic
299 // ------------------------------------------------------------------------
301 ILayersEditorListener layersListener = new ILayersEditorListener() {
302 private void layersChanged() {
303 Object task = BEGIN("EP.layersChanged");
304 // Update visibility/focusability for each node only, do not reinitialize the graphics.
305 updateAllVisibility();
309 public void layerRemoved(ILayer layer) {
313 public void layerDeactivated(ILayer layer) {
317 public void layerAdded(ILayer layer) {
321 public void layerActivated(ILayer layer) {
325 public void ignoreFocusChanged(boolean value) {
326 ICanvasContext ctx = getContext();
327 if(ctx == null) return;
328 G2DSceneGraph sg = ctx.getSceneGraph();
329 if(sg == null) return;
330 sg.setGlobalProperty(G2DSceneGraph.IGNORE_FOCUS, value);
333 public void ignoreVisibilityChanged(boolean value) {
338 protected void updateAllVisibility() {
339 // TODO: optimize, no node reinitialization
343 // ------------------------------------------------------------------------
344 // Layer configuration change listening and reaction logic
345 // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
348 // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
349 // Diagram/Element hint listeners
350 // ------------------------------------------------------------------------
352 class DiagramHintListener extends HintListenerAdapter {
354 public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
355 if (key == Hints.KEY_DISABLE_PAINTING) {
356 if (diagramParent != null) {
357 diagramParent.setVisible(!Boolean.TRUE.equals(newValue));
359 } else if (key == Hints.KEY_DIRTY) {
360 if (newValue == Hints.VALUE_Z_ORDER_CHANGED) {
361 diagram.removeHint(Hints.KEY_DIRTY);
364 System.out.println("Diagram z-order changed: " + diagram);
366 updateZOrder(diagram, ElementHints.KEY_SG_NODE);
372 private final DiagramHintListener diagramHintListener = new DiagramHintListener();
375 * This element hint listener tries to ensure that diagram elements and the
376 * normal diagram scene graph stay in sync by listening to any changes
377 * occurring in elements, i.e. in their hints.
379 * It does this by listening to {@link Hints#KEY_DIRTY} hint changes.
381 * @author Tuukka Lehtonen
383 class ElementHintListener implements IHintListener {
385 public void hintChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
386 if (key == Hints.KEY_DIRTY) {
387 if (newValue == Hints.VALUE_SG_DIRTY) {
388 if (sender instanceof IElement) {
389 assert getContext().getThreadAccess().currentThreadAccess();
390 Object task = BEGIN("element dirty");
392 IElement e = (IElement) sender;
393 e.removeHint(Hints.KEY_DIRTY);
396 System.out.println("Element is dirty: " + e);
398 updateSelfAndNeighbors(e, COMPLETE_UPDATE);
402 } else if (key == ElementHints.KEY_FOCUS_LAYERS || key == ElementHints.KEY_VISIBLE_LAYERS) {
403 if (sender instanceof IElement) {
404 assert getContext().getThreadAccess().currentThreadAccess();
405 IElement e = (IElement) sender;
406 Object task = BEGIN("layers changed: " + e);
414 public void hintRemoved(IHintObservable sender, Key key, Object oldValue) {
418 private final ElementHintListener elementHintListener = new ElementHintListener();
420 private final Set<Transaction> activeTransactions = new HashSet<Transaction>();
423 public void transactionStarted(IDiagram d, Transaction t) {
424 activeTransactions.add(t);
427 Consumer<IElement> COMPLETE_UPDATE = element -> {
428 // Connections may need rerouting
429 if (element.getElementClass().containsClass(ConnectionHandler.class))
430 DiagramUtils.validateAndFix(diagram, Collections.singleton(element));
432 //System.out.println("COMPLETE_UPDATE(" + element + ")");
434 updateSelection(element);
437 Set<IElement> addRelatedElements(Set<IElement> elements) {
438 RelationshipHandler rh = diagram.getDiagramClass().getAtMostOneItemOfClass(RelationshipHandler.class);
440 relatedElements.clear();
441 for (IElement el : elements) {
443 rh.getRelations(diagram, el, relations);
444 for (Relation r : relations) {
445 Object obj = r.getObject();
446 if (obj instanceof IElement) {
447 relatedElements.add((IElement) obj);
452 elements.addAll(relatedElements);
453 relatedElements.clear();
460 * @param updateCallback
462 protected void updateSelfAndNeighbors(IElement e, Consumer<IElement> updateCallback) {
463 // Slight optimization for cases that are known to be topologically
465 if (!isNotSelectionExpandable(e)) {
466 Set<IElement> single = Collections.singleton(e);
468 Set<IElement> expanded =
469 // Also update all elements somehow related to e.
471 // Get all topological neighbors and element self.
472 CollectionUtils.join(
474 TopologicalSelectionExpander.expandSelection(diagram, single)
477 // Perform the updates.
478 for (IElement el : expanded) {
479 updateCallback.accept(el);
482 updateCallback.accept(e);
490 protected boolean isNotSelectionExpandable(IElement e) {
491 ElementClass ec = e.getElementClass();
492 return !ec.containsClass(ConnectionHandler.class)
493 && !ec.containsClass(BendsHandler.class)
494 && !ec.containsClass(TerminalTopology.class);
498 public void transactionFinished(IDiagram d, Transaction t) {
499 activeTransactions.remove(t);
502 boolean inDiagramTransaction() {
503 return !activeTransactions.isEmpty();
507 public void onElementAdded(IDiagram d, IElement e) {
509 System.out.println("EP.onElementAdded(" + d + ", " + e + ")");
511 Map<INode, IElement> nodeElementMap = diagram.getHint(DiagramHints.NODE_TO_ELEMENT_MAP);
512 if (inDiagramTransaction()) {
513 addElement(d, e, false, nodeElementMap);
515 addElement(d, e, true, nodeElementMap);
519 public void onElementRemoved(IDiagram d, IElement e) {
521 System.out.println("EP.onElementRemoved(" + d + ", " + e + ")");
523 removeElement(d, e, diagram.getHint(DiagramHints.NODE_TO_ELEMENT_MAP));
527 public void elementChildrenChanged(ChildEvent event) {
529 System.out.println("EP.elementChildrenChanged: " + event);
531 Map<INode, IElement> nodeElementMap = diagram.getHint(DiagramHints.NODE_TO_ELEMENT_MAP);
533 for (IElement removed : event.removed) {
534 removeElement(diagram, removed, nodeElementMap);
536 for (IElement added : event.added) {
537 addElement(diagram, added, false, nodeElementMap);
541 private final List<IElement> childrenTemp = new ArrayList<IElement>();
543 public void addElement(IDiagram d, IElement e, boolean synchronizeSceneGraphNow, Map<INode, IElement> nodeElementMap) {
545 System.out.println("EP.addElement(now=" + synchronizeSceneGraphNow + ", " + e + ")");
547 e.addKeyHintListener(Hints.KEY_DIRTY, elementHintListener);
548 e.addKeyHintListener(ElementHints.KEY_VISIBLE_LAYERS, elementHintListener);
549 e.addKeyHintListener(ElementHints.KEY_FOCUS_LAYERS, elementHintListener);
551 ElementClass clazz = e.getElementClass();
552 G2DParentNode parentNode = elementParent;
553 Key sgKey = ElementHints.KEY_SG_NODE;
555 Parent parent = clazz.getAtMostOneItemOfClass(Parent.class);
556 if (parent != null) {
557 IElement parentElement = parent.getParent(e);
558 if (parentElement != null) {
559 SingleElementNode parentHolder = parentElement.getHint(sgKey);
560 if (parentHolder != null) {
561 parentNode = parentHolder;
566 boolean isConnection = e.getElementClass().containsClass(ConnectionHandler.class);
570 ConnectionNode holder = e.getHint(sgKey);
571 if (holder == null) {
572 holder = parentNode.addNode(ElementUtils.generateNodeId(e), ConnectionNode.class);
573 holder.setKey(e.getHint(ElementHints.KEY_OBJECT));
574 holder.setTypeClass(e.getHint(ElementHints.KEY_TYPE_CLASS));
575 holder.setTransferableProvider(new ElementTransferableProvider(getContext(), e));
576 e.setHint(sgKey, holder);
577 holder.setZIndex(parentNode.getNodeCount() + 1);
578 if (nodeElementMap != null)
579 nodeElementMap.put(holder, e);
584 SingleElementNode holder = e.getHint(sgKey);
585 if (holder == null) {
586 holder = parentNode.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);
587 holder.setKey(e.getHint(ElementHints.KEY_OBJECT));
588 holder.setTypeClass(e.getHint(ElementHints.KEY_TYPE_CLASS));
589 holder.setTransferableProvider(new ElementTransferableProvider(getContext(), e));
590 e.setHint(sgKey, holder);
591 holder.setZIndex(parentNode.getNodeCount() + 1);
592 if (nodeElementMap != null)
593 nodeElementMap.put(holder, e);
598 Children children = clazz.getAtMostOneItemOfClass(Children.class);
599 if (children != null) {
600 children.addChildListener(e, this);
602 childrenTemp.clear();
603 children.getChildren(e, childrenTemp);
604 //System.out.println("children: " + childrenTemp);
605 for (IElement child : childrenTemp) {
606 addElement(d, child, false, nodeElementMap);
608 childrenTemp.clear();
611 if (synchronizeSceneGraphNow)
612 updateElement(e, sgKey);
617 protected void removeElement(IDiagram d, IElement e, Map<INode, IElement> nodeElementMap) {
619 System.out.println("EP.removeElement(" + e + ")");
621 e.removeKeyHintListener(Hints.KEY_DIRTY, elementHintListener);
622 e.removeKeyHintListener(ElementHints.KEY_VISIBLE_LAYERS, elementHintListener);
623 e.removeKeyHintListener(ElementHints.KEY_FOCUS_LAYERS, elementHintListener);
625 ElementClass clazz = e.getElementClass();
626 if (clazz.containsClass(Children.class)) {
627 Children children = clazz.getSingleItem(Children.class);
628 children.removeChildListener(e, this);
631 List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);
632 for (SceneGraph n : nodeHandlers) {
636 // Remove all hints related to scene graph nodes to prevent leakage of
637 // scene graph resources.
638 Map<SceneGraphNodeKey, Object> sgHints = e.getHintsOfClass(SceneGraphNodeKey.class);
639 for (SceneGraphNodeKey sgKey : sgHints.keySet()) {
640 Node n = e.removeHint(sgKey);
643 if (nodeElementMap != null)
644 nodeElementMap.remove(n);
652 * Invalidate the whole scene graph spatial structure. It will be rebuilt by
653 * RTreeNode when needed the next time.
655 private void setTreeDirty() {
656 elementParent.setDirty();
660 * Mark the specified node invalid with respect to the scene graph spatial
663 * @param node a scene graph node that has somehow changed
665 private void invalidateNode(INode node) {
666 // TODO: optimize rtree updates instead of killing the whole tree
667 elementParent.setDirty();
670 // ------------------------------------------------------------------------
671 // Diagram/Element hint listeners
672 // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
674 public void updateAll() {
676 System.out.println("EP.updateAll()");
678 Object task = BEGIN("EP.updateAll");
679 paintDiagram(elementParent, diagram, null);
685 public void update(IElement element) {
686 updateElement(element, ElementHints.KEY_SG_NODE);
693 * @param elementsToPaint
694 * elements to paint or null for all elements
696 public void paintDiagram(G2DParentNode parent, IDiagram diagram, Collection<IElement> elementsToPaint) {
697 Object task = BEGIN("EP.paintDiagram");
698 paintDiagram(parent, diagram, elementsToPaint, ElementHints.KEY_SG_NODE);
706 * @param elementsToPaint
707 * elements to paint or null for all elements
709 public void paintDiagram(G2DParentNode parent, IDiagram diagram, Collection<IElement> elementsToPaint, Key elementSgNodeKey) {
710 if(diagram == null) return;
711 ICanvasContext ctx = getContext();
712 assert (ctx != null);
714 Boolean disablePaint = diagram.getHint(Hints.KEY_DISABLE_PAINTING);
715 if (Boolean.TRUE.equals(disablePaint)) {
716 parent.removeNodes();
720 // Paint elementsToPaint in correct z-order from diagram.getElements()
721 List<IElement> elements = diagram.getSnapshot();
723 Set<SingleElementNode> tmp = new HashSet<SingleElementNode>();
725 for (int pass = 0; pass < 1; ++pass) {
726 for (IElement e : elements) {
727 if (elements != elementsToPaint && elementsToPaint != null)
728 if (!elementsToPaint.contains(e))
732 System.out.println("EP.paintDiagram(" + zIndex + ", " + e + ")");
734 SingleElementNode holder = updateElement(parent, e, elementSgNodeKey, false);
735 if (holder != null) {
737 holder.setZIndex(++zIndex);
742 // Hide unaccessed nodes (but don't remove)
743 for (IG2DNode node : parent.getNodes()) {
744 if (!tmp.contains(node)) {
745 ((SingleElementNode)node).setVisible(false);
750 public void updateElement(IElement e, Key elementSgNodeKey) {
751 updateElement(null, e, elementSgNodeKey, true);
755 * @param parent if <code>null</code> the scene graph node structure
756 * will not be created if it is missing
758 * @param elementSgNodeKey
759 * @param invalidateNode
761 public SingleElementNode updateElement(G2DParentNode parent, IElement e, Key elementSgNodeKey, boolean invalidateNode) {
763 System.out.println("EP.updateElement(" + e + ", " + elementSgNodeKey + ")");
764 Object task = BEGIN("EP.updateElement");
767 SingleElementNode holder = e.getHint(elementSgNodeKey);
768 if (holder == null && parent == null)
771 if (ElementUtils.isHidden(e))
774 // ElementClass ec = e.getElementClass();
775 // ILayers layers = diagram.getHint(DiagramHints.KEY_LAYERS);
776 // if (layers != null && !layers.getIgnoreVisibilitySettings()) {
777 // ElementLayers el = ec.getAtMostOneItemOfClass(ElementLayers.class);
778 // if (el != null && !el.isVisible(e, layers)) {
783 // Update the node scene graph through SceneGraph handlers.
784 List<SceneGraph> nodeHandlers = e.getElementClass().getItemsByClass(SceneGraph.class);
785 Collection<SceneGraph> decorators = e.getHint(ElementHints.KEY_DECORATORS);
786 if (nodeHandlers.isEmpty() && (decorators == null || decorators.isEmpty()))
789 Composite composite = e.getHint(ElementHints.KEY_COMPOSITE);
791 if (holder == null) {
792 holder = parent.addNode(ElementUtils.generateNodeId(e), SingleElementNode.class);
793 e.setHint(elementSgNodeKey, holder);
795 holder.setComposite(composite);
796 holder.setVisible(true);
798 for (SceneGraph n : nodeHandlers) {
802 // Process decorators
803 if (decorators == null || decorators.isEmpty()) {
804 holder.removeNode("decorators");
806 G2DParentNode decoratorHolder = holder.getOrCreateNode("decorators", G2DParentNode.class);
807 decoratorHolder.removeNodes();
808 for (SceneGraph decorator : decorators) {
809 decorator.init(e, decoratorHolder);
814 invalidateNode(holder);
823 * @param elementsToUpdate to explicitly specify which elements to update
824 * the selection scene graph for, or <code>null</code> to update
827 public void updateSelections() {
828 Object task = BEGIN("EP.updateSelections");
831 if (!paintSelectionFrames)
833 if (selection == null)
836 boolean selectionsChanged = false;
838 // Update and "touch" all selections.
839 Set<Integer> existingSelections = new HashSet<Integer>();
840 Set<INode> selectionNodes = new HashSet<INode>();
841 Set<INode> tmp = new HashSet<INode>();
842 Map<INode, LinkNode> selectionLinks = new HashMap<INode, LinkNode>();
844 for (Map.Entry<Integer, Set<IElement>> entry : selection.getSelections().entrySet()) {
845 Integer selectionId = entry.getKey();
846 Set<IElement> selectedElements = entry.getValue();
848 existingSelections.add(selectionId);
850 // System.out.println("SELECTION[" + selectionId + "]: " + selectedElements);
851 ElementNodeBridge bridge = getOrCreateSelectionMap(selectionId);
852 selectionNodes.clear();
853 selectionsChanged |= paintSelection(selectedElements, selectionId, selectionNodes, bridge);
855 // Remove selection nodes that were not referenced during the update.
856 // System.out.println("BRIDGE: " + bridge.toString());
857 // System.out.println("SELECTED: " + selectionNodes);
859 tmp.addAll(bridge.getRightSet());
860 tmp.removeAll(selectionNodes);
861 // System.out.println("REMOVED: " + tmp);
862 // System.out.println("BRIDGE BEFORE: " + bridge);
863 selectionsChanged |= bridge.retainAllRight(selectionNodes);
864 // System.out.println("BRIDGE AFTER: " + bridge);
866 G2DParentNode selectionsNode = getSelectionsNode(selectionId);
867 selectionLinks.clear();
868 getSelectedNodeReferences(selectionsNode, selectionLinks);
870 for (INode node : tmp) {
871 INode linkNode = selectionLinks.get(node.getParent());
872 if (linkNode != null) {
875 // System.out.println("REMOVED SELECTION: -> " + node);
880 for (Iterator<Map.Entry<Integer, ElementNodeBridge>> iterator = selections.entrySet().iterator(); iterator.hasNext();) {
881 Map.Entry<Integer, ElementNodeBridge> entry = iterator.next();
882 Integer selectionId = entry.getKey();
883 if (!existingSelections.contains(selectionId)) {
884 // Selection no longer exists.
885 selectionsChanged = true;
886 for (INode node : entry.getValue().getRightSet()) {
887 // System.out.println("REMOVED SELECTION: " + node);
892 G2DParentNode selectionsNode = getSelectionsNode(selectionId);
893 selectionsNode.removeNodes();
897 // Make sure the view is refreshed after selection changes.
898 if (selectionsChanged) {
906 private G2DParentNode getSelectionsNode() {
907 G2DParentNode sels = NodeUtil.lookup(diagramParent, SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);
909 DataNode data= NodeUtil.lookup(diagramParent, SceneGraphConstants.DATA_NODE_NAME, DataNode.class);
910 sels = data.addNode(SceneGraphConstants.SELECTIONS_NODE_NAME, G2DParentNode.class);
911 sels.setLookupId(SceneGraphConstants.SELECTIONS_NODE_NAME);
916 private G2DParentNode getSelectionsNode(int selectionId) {
917 G2DParentNode selectionsNode = getSelectionsNode();
918 G2DParentNode s = selectionsNode.getOrCreateNode(String.valueOf(selectionId), G2DParentNode.class);
922 private Map<INode, LinkNode> getSelectedNodeReferences(G2DParentNode selectionsNode, Map<INode, LinkNode> result) {
923 for (IG2DNode node : selectionsNode.getSortedNodes()) {
924 if (node instanceof LinkNode) {
925 INode n = ((LinkNode) node).getDelegate();
927 result.put(n, (LinkNode) node);
933 public void updateSelection(IElement el) {
934 Object task = BEGIN("EP.updateSelection");
937 if (!paintSelectionFrames)
940 G2DParentNode elementNode = (G2DParentNode) el.getHint(ElementHints.KEY_SG_NODE);
941 if (elementNode == null)
944 boolean nodesUpdated = false;
946 for (Map.Entry<Integer, ElementNodeBridge> entry : selections.entrySet()) {
947 Integer selectionId = entry.getKey();
948 ElementNodeBridge bridge = entry.getValue();
949 Color color = getSelectionColor(selectionId);
951 G2DParentNode selectionNode = (G2DParentNode) bridge.getRight(el);
952 if (selectionNode == null)
955 if (NodeUtil.needSelectionPaint(elementNode))
956 paintSelectionFrame(selectionId, elementNode, selectionNode, el, color);
961 // Make sure the view is refreshed after selection changes.
972 * @param selectionNodes for collecting all the "selection" nodes created or
973 * referenced by this method
977 public boolean paintSelection(Set<IElement> selection, int selectionId, Set<INode> selectionNodes, ElementNodeBridge bridge) {
979 boolean result = false;
980 Color color = getSelectionColor(selectionId);
981 G2DParentNode selectionsNode = getSelectionsNode(selectionId);
983 for (IElement e : selection) {
984 Node elementNode = e.getHint(ElementHints.KEY_SG_NODE);
985 // System.out.println("selectionNode: " + elementNode + " " + e);
986 if (elementNode instanceof G2DParentNode) {
987 G2DParentNode en = (G2DParentNode) elementNode;
988 G2DParentNode selectionNode = en.getOrCreateNode(NodeUtil.SELECTION_NODE_NAME, G2DParentNode.class);
989 selectionNode.setZIndex(SELECTION_PAINT_PRIORITY);
990 if (selectionNodes != null)
991 selectionNodes.add(selectionNode);
992 if (!bridge.containsLeft(e)) {
993 //System.out.println("ADDED SELECTION: " + e + " -> " + selectionNode);
994 bridge.map(e, selectionNode);
998 // Mark this node selected in the scene graph "data area"
999 createSelectionReference(selectionsNode, elementNode);
1001 if (NodeUtil.needSelectionPaint(elementNode))
1002 paintSelectionFrame(selectionId, en, selectionNode, e, color);
1005 if (elementNode != null) {
1006 // Cannot paint selection for unrecognized non-parenting node
1007 System.out.println("Cannot add selection child node for non-parent element node: " + elementNode);
1012 // if (selection.isEmpty()) {
1013 // Node pivotNode = (Node) parent.getNode("pivot");
1014 // if (pivotNode != null)
1015 // pivotNode.remove();
1017 // Point2D pivot = ElementUtils.getElementBoundsCenter(selection, pivotPoint);
1018 // if (pivot != null) {
1019 // //System.out.println("painting pivot: " + pivot);
1020 // SelectionPivotNode pivotNode = parent.getOrCreateNode("pivot", SelectionPivotNode.class);
1021 // pivotNode.setPivot(pivot);
1023 // parent.removeNode("pivot");
1030 public void paintSelectionFrame(int selectionId, G2DParentNode elementNode, G2DParentNode selectionNode, final IElement e, Color color) {
1031 // The element node already has the correct transform.
1032 AffineTransform selectionTransform = ElementUtils.getTransform(e);// no it doesnt ... new AffineTransform();
1033 Shape shape = ElementUtils.getElementShapeOrBounds(e);
1034 Rectangle2D bounds = shape.getBounds2D();
1035 //System.out.println("selection bounds: "+bounds);
1037 Point2D scale = GeometryUtils.getScale2D(selectionTransform);
1038 final double marginX = Math.abs(scale.getX()) > 1e-10 ? 1 / scale.getX() : 1;
1039 final double marginY = Math.abs(scale.getY()) > 1e-10 ? 1 / scale.getY() : 1;
1041 bounds.setFrame(bounds.getMinX() - marginX, bounds.getMinY() - marginY, bounds.getWidth() + 2*marginX, bounds.getHeight() + 2*marginY);
1043 List<SelectionSpecification> ss = e.getElementClass().getItemsByClass(SelectionSpecification.class);
1044 if (!ss.isEmpty()) {
1045 G2DParentNode shapeholder = selectionNode.getOrCreateNode(getNodeId("outlines", e), G2DParentNode.class);
1047 for (SelectionSpecification es : ss) {
1048 Outline outline = (Outline) es.getAdapter(Outline.class);
1049 if (outline == null || outline.getElementShape(e) == null)
1051 ShapeNode shapenode = shapeholder.getOrCreateNode(getNodeId("outline", e, es), ShapeNode.class);
1052 // shapenode.setShape(es.getSelectionShape(e));
1053 // shapenode.setStroke(SELECTION_STROKE);
1054 // shapenode.setScaleStroke(true);
1055 // shapenode.setColor(color);
1056 // shapenode.setTransform(selectionTransform);
1057 // shapenode.setFill(false);
1058 shapenode.setShape(outline.getElementShape(e));
1059 StrokeSpec strokeSpec = (StrokeSpec) es.getAdapter(StrokeSpec.class);
1060 if (strokeSpec != null && strokeSpec.getStroke(e) != null)
1061 shapenode.setStroke(strokeSpec.getStroke(e));
1063 shapenode.setScaleStroke(false);
1064 //shapenode.setColor(color);
1065 OutlineColorSpec foregroundColor = (OutlineColorSpec) es.getAdapter(OutlineColorSpec.class);
1066 if (foregroundColor != null && foregroundColor.getColor(e) != null)
1067 shapenode.setColor(foregroundColor.getColor(e));
1069 Transform transform = (Transform) es.getAdapter(Transform.class);
1070 if (transform != null && transform.getTransform(e) != null)
1071 shapenode.setTransform(transform.getTransform(e));
1073 shapenode.setFill(false);
1074 FillColor fillColor = (FillColor) es.getAdapter(FillColor.class);
1075 if (fillColor != null && fillColor.getFillColor(e) != null)
1076 shapenode.setFill(true);
1077 // shapenode.setColor(ColorUtil.withAlpha(backgroundColor.getColor(e), 192));
1082 List<SelectionOutline> shapeHandlers = e.getElementClass().getItemsByClass(SelectionOutline.class);
1083 if (!shapeHandlers.isEmpty()) {
1084 G2DParentNode shapeholder = selectionNode.getOrCreateNode(getNodeId("outlines", e), G2DParentNode.class);
1086 for (SelectionOutline es : shapeHandlers) {
1087 ShapeNode shapenode = shapeholder.getOrCreateNode(getNodeId("outline", e, es), ShapeNode.class);
1088 // shapenode.setShape(es.getSelectionShape(e));
1089 // shapenode.setStroke(SELECTION_STROKE);
1090 // shapenode.setScaleStroke(true);
1091 // shapenode.setColor(color);
1092 // shapenode.setTransform(selectionTransform);
1093 // shapenode.setFill(false);
1094 shapenode.setShape(es.getSelectionShape(e));
1095 shapenode.setStroke(null);
1096 shapenode.setScaleStroke(false);
1097 //shapenode.setColor(color);
1098 shapenode.setColor(ColorUtil.withAlpha(color, 192));
1099 shapenode.setTransform(selectionTransform);
1100 shapenode.setFill(true);
1105 ISelectionProvider provider = this.getContext().getDefaultHintContext().getHint(KEY_SELECTION_PROVIDER);
1106 if (provider != null) {
1107 provider.init(selectionId, e, selectionNode, getNodeId("shape", e), selectionTransform, bounds, color);
1109 SelectionNode s = selectionNode.getOrCreateNode(getNodeId("shape", e), SelectionNode.class);
1110 s.init(selectionId, selectionTransform, bounds, color);
1111 Double paddingFactor = diagram.getHint(DiagramHints.SELECTION_PADDING_SCALE_FACTOR);
1112 if (paddingFactor != null)
1113 s.setPaddingFactor(paddingFactor);
1117 private void createSelectionReference(G2DParentNode selectionsNode, INode elementNode) {
1118 String id = NodeUtil.lookupId(elementNode);
1121 id = uuid = UUID.randomUUID().toString();
1122 NodeUtil.map(elementNode, id);
1123 LinkNode link = selectionsNode.getOrCreateNode(id, LinkNode.class);
1124 link.setDelegateId(id);
1125 link.setIgnoreDelegate(true);
1126 link.setLookupIdOwner(uuid != null);
1129 private transient CharBuffer buf = CharBuffer.allocate(32);
1131 private String getNodeId(String prefix, Object first) {
1132 return getNodeId(prefix, first, null);
1135 private String getNodeId(String prefix, Object first, Object second) {
1139 if (first != null) {
1141 buf.append("" + first.hashCode());
1143 if (second != null) {
1145 buf.append("" + second.hashCode());
1147 buf.limit(buf.position());
1149 //System.out.println("node id: " + buf.toString());
1150 return buf.toString();
1154 * Get selection color for a selection Id
1155 * @param selectionId selection id
1156 * @return color for the id
1158 protected Color getSelectionColor(int selectionId) {
1159 if (selectionId == 0) {
1160 Color c = getHint(KEY_SELECTION_FRAME_COLOR);
1165 Color c = selectionColor.get(selectionId);
1167 Random r = new Random(selectionId);
1168 c = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat());
1169 selectionColor.put(selectionId, c);
1174 private transient ConcurrentMap<Integer, ElementNodeBridge> selections = new ConcurrentHashMap<Integer, ElementNodeBridge>();
1176 ElementNodeBridge getSelectionMap(int selectionId) {
1177 return selections.get(Integer.valueOf(selectionId));
1180 ElementNodeBridge getOrCreateSelectionMap(int selectionId) {
1181 Integer id = Integer.valueOf(selectionId);
1182 synchronized (selections) {
1183 ElementNodeBridge map = selections.get(id);
1187 selections.put(id, map = new ElementNodeBridge(id));
1192 private transient Map<Integer, Color> selectionColor = new HashMap<Integer, Color>();
1194 private transient BasicStroke SELECTION_STROKE = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,
1195 BasicStroke.JOIN_BEVEL, 10.0f,
1196 new float[] { 5.0f, 5.0f }, 0.0f);
1198 private transient Point2D pivotPoint = new Point2D.Double();
1200 @HintListener(Class=Selection.class, Field="SELECTION0")
1201 public void selectionChanged(IHintObservable sender, Key key, Object oldValue, Object newValue) {
1202 //System.out.println("new selection: " + newValue);
1206 @HintListener(Class=Selection.class, Field="SELECTION0")
1207 public void selectionRemoved(IHintObservable sender, Key key, Object oldValue) {
1208 //System.out.println("selection removed: " + oldValue);
1212 private static Object BEGIN(String name) {
1214 //return ThreadLog.BEGIN(name);
1219 private static void END(Object task) {
1221 //((Task) task).end();