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.scenegraph.utils;
14 import java.awt.AWTEvent;
15 import java.awt.Container;
16 import java.awt.event.MouseEvent;
17 import java.awt.event.MouseWheelEvent;
18 import java.awt.geom.AffineTransform;
19 import java.awt.geom.NoninvertibleTransformException;
20 import java.awt.geom.Point2D;
21 import java.awt.geom.Rectangle2D;
22 import java.io.PrintStream;
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.locks.Condition;
33 import java.util.concurrent.locks.Lock;
34 import java.util.concurrent.locks.ReentrantLock;
36 import org.simantics.scenegraph.IDynamicSelectionPainterNode;
37 import org.simantics.scenegraph.ILookupService;
38 import org.simantics.scenegraph.INode;
39 import org.simantics.scenegraph.INode.PropertySetter;
40 import org.simantics.scenegraph.ISelectionPainterNode;
41 import org.simantics.scenegraph.ParentNode;
42 import org.simantics.scenegraph.g2d.G2DParentNode;
43 import org.simantics.scenegraph.g2d.G2DSceneGraph;
44 import org.simantics.scenegraph.g2d.IG2DNode;
45 import org.simantics.scenegraph.g2d.events.EventDelegator;
46 import org.simantics.scenegraph.g2d.events.NodeEventHandler;
47 import org.simantics.scenegraph.g2d.events.SGMouseEvent;
48 import org.simantics.scenegraph.g2d.events.SGMouseWheelEvent;
49 import org.simantics.scenegraph.g2d.nodes.ConnectionNode;
50 import org.simantics.scenegraph.g2d.nodes.FlagNode;
51 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
52 import org.simantics.scl.runtime.function.Function1;
53 import org.simantics.scl.runtime.function.FunctionImpl1;
54 import org.simantics.utils.datastructures.Pair;
55 import org.simantics.utils.threads.IThreadWorkQueue;
58 * Utilities for debugging/printing the contents of a scenegraph.
60 * @author Tuukka Lehtonen
62 public final class NodeUtil {
67 public static interface Filter<T> {
68 public boolean accept(T t);
71 public static class PrefixFilter implements Filter<String> {
72 private final String prefix;
73 public PrefixFilter(String prefix) {
77 public boolean accept(String t) {
78 return t.startsWith(prefix);
83 * The name of the sibling-node that is used to represent that a node is selected.
85 public static final String SELECTION_NODE_NAME = "selection";
87 public static INode getNearestParentOfType(INode node, Class<?> clazz) {
88 ParentNode<?> parent = null;
90 parent = node.getParent();
94 if (clazz.isInstance(node))
99 public static INode getRootNode(INode node) {
100 ParentNode<?> parent = null;
102 parent = node.getParent();
109 public static G2DSceneGraph getRootNode(IG2DNode node) {
110 INode root = getRootNode((INode) node);
111 return (G2DSceneGraph) root;
114 public static G2DSceneGraph getPossibleRootNode(IG2DNode node) {
115 INode root = getRootNode((INode) node);
116 return (root instanceof G2DSceneGraph) ? (G2DSceneGraph) root : null;
120 * Method for seeking node from scenegraph by class
127 public static <T> T getNearestChildByClass(G2DParentNode parent, Class<T> clazz) {
128 return getNearestChildByClass(parent.getNodes(), clazz);
132 * Breadth-first-search implementation to be used by getNearestChildByClass method
139 @SuppressWarnings("unchecked")
140 public static <T> T getNearestChildByClass(Collection<IG2DNode> nodes, Class<T> clazz) {
141 Collection<IG2DNode> list = null;
142 for (IG2DNode n : nodes) {
143 if (clazz.isInstance(n)) {
145 } else if (n instanceof G2DParentNode) {
147 list = new ArrayList<IG2DNode>();
148 list.addAll(((G2DParentNode)n).getNodes());
151 if (list == null || list.isEmpty()) return null;
152 return getNearestChildByClass(list, clazz);
156 * Tries to look for a child node from the specified node with the specified
157 * ID. Returns <code>null</code> if the specified node is a not a
158 * {@link ParentNode}.
164 public static INode getChildById(INode node, String id) {
165 if (node instanceof ParentNode<?>) {
166 return ((ParentNode<?>) node).getNode(id);
172 * Looks for the first child node of the specified node based on 2D Z-order.
173 * The specified node must be a {@link G2DParentNode} for the method to
176 * @param node the node to get for the first child from
177 * @return <code>null</code> if the specified node is not a
178 * {@link G2DParentNode} or has no children.
180 public static INode getFirstChild(INode node) {
181 if (node instanceof G2DParentNode) {
182 G2DParentNode pn = (G2DParentNode) node;
183 IG2DNode[] sorted = pn.getSortedNodes();
184 if (sorted.length > 0)
191 * Returns a single child node of the specified node or <code>null</code> if
192 * there are more than one or zero children.
194 * @param node the node to get a possible single child from
195 * @return single child node or <code>null</code> if specified node has more
196 * than one or zero children
198 public static INode getPossibleChild(INode node) {
199 if (node instanceof ParentNode<?>) {
200 ParentNode<?> pn = (ParentNode<?>) node;
201 if (pn.getNodeCount() == 1)
202 return pn.getNodes().iterator().next();
208 * Counts the depth of the specified node in its scene graph node tree.
209 * Depth 1 equals root level.
211 * @param node the node for which to count a depth
212 * @return the depth of the node
214 public static int getDepth(INode node) {
216 ParentNode<?> parent = null;
218 parent = node.getParent();
226 private static final void printSceneGraph(PrintStream stream, int indentLevel, INode node, String id) {
227 for (int i = 0; i < indentLevel; ++i)
229 stream.print(node.getSimpleClassName());
231 String lookupId = tryLookupId(node);
232 if (lookupId != null) {
233 stream.print(" {" + id + ", lookupId = "+lookupId+"}");
235 stream.print(" {" + id + "}");
238 stream.println(node);
239 if (node instanceof G2DParentNode) {
240 G2DParentNode parentNode = (G2DParentNode) node;
241 for (String cid : parentNode.getSortedNodesById()) {
242 Object child = parentNode.getNode(cid);
243 if (child instanceof INode)
244 printSceneGraph(stream, indentLevel + 1, (INode) child, cid);
246 } else if (node instanceof ParentNode<?>) {
247 ParentNode<? extends INode> parentNode = (ParentNode<?>) node;
248 for (String cid : parentNode.getNodeIds()) {
249 INode child = parentNode.getNode(cid);
250 printSceneGraph(stream, indentLevel + 1, (INode) child);
255 public static final void printSceneGraph(PrintStream stream, int indentLevel, INode node) {
257 ParentNode<?> parent = node.getParent();
258 if (parent != null) {
259 Collection<String> ids = parent.getNodeIds();
260 for (String i : ids) {
261 INode n = parent.getNode(i);
268 printSceneGraph(stream, indentLevel, node, id);
271 public static final void printSceneGraph(int indentLevel, INode node) {
272 printSceneGraph(System.out, indentLevel, node);
275 public static final void printSceneGraph(INode node) {
276 printSceneGraph(System.out, 0, node);
279 public static interface NodeProcedure<T> {
280 T execute(INode node, String id);
284 * @param node the node to iterate possible children for
285 * @param procedure invoked for each child node, if returns a
286 * <code>non-null</code> value, the return value is collected into the result
288 * @return the list of collected children
290 public static final <T> List<T> forChildren(INode node, NodeProcedure<T> procedure) {
291 return forChildren(node, procedure, new ArrayList<T>());
295 * @param node the node to iterate possible children for
296 * @param procedure invoked for each child node, if returns a
297 * <code>non-null</code> value, the node is collected into the result
299 * @param result the result list into which selected children are collected
300 * or <code>null</code> to not collect
301 * @return the list of collected children or null if provided result list
302 * was <code>null</code>
304 public static final <T> List<T> forChildren(INode node, NodeProcedure<T> procedure, List<T> result) {
305 if (node instanceof ParentNode<?>) {
306 ParentNode<?> pn = (ParentNode<?>) node;
307 if (node instanceof G2DParentNode) {
308 G2DParentNode g2dpn = (G2DParentNode) node;
309 for (String id : g2dpn.getSortedNodesById()) {
310 INode n = pn.getNode(id);
311 T t = procedure.execute(n, id);
312 if (t != null && result != null)
316 for (String id : pn.getNodeIds()) {
317 INode n = pn.getNode(id);
318 T t = procedure.execute(n, id);
319 if (t != null && result != null)
327 public static final int countTreeNodes(INode node) {
329 if (node instanceof ParentNode<?>) {
330 ParentNode<? extends INode> pn = (ParentNode<?>) node;
331 Collection<? extends INode> ns = pn.getNodes();
333 result += countTreeNodes(n);
339 public static final void printTreeNodes(INode node, StringBuilder builder) {
340 printTreeNodes(node, 0, builder);
343 public static final void printTreeNodes(INode node, int indent, StringBuilder builder) {
344 for (int i = 0; i < indent; i++)
346 builder.append(node.toString() + "\n");
347 if (node instanceof ParentNode<?>) {
348 ParentNode<? extends INode> pn = (ParentNode<?>) node;
349 Collection<? extends INode> ns = pn.getNodes();
351 printTreeNodes(n, indent+2, builder);
356 public static final <T extends INode> Set<T> collectNodes(INode node, Class<T> clazz) {
357 Set<T> result = new HashSet<T>();
358 collectNodes(node, clazz, result);
362 @SuppressWarnings("unchecked")
363 public static final <T extends INode> void collectNodes(INode node, Class<T> clazz, Set<T> result) {
364 if (clazz.isInstance(node))
365 result.add((T) node);
366 if (node instanceof ParentNode<?>) {
367 ParentNode<? extends INode> pn = (ParentNode<?>) node;
368 Collection<? extends INode> ns = pn.getNodes();
370 collectNodes(n, clazz, result);
375 public static <T extends INode> T getSingleNode(INode node, Class<T> clazz) {
376 Set<T> all = collectNodes(node, clazz);
377 if(all.size() != 1) throw new RuntimeException("Expected exactly 1 instance of class " + clazz.getCanonicalName() + ", got " + all.size());
378 return (T)all.iterator().next();
381 public static final boolean hasChildren(INode node) {
382 if (node instanceof ParentNode<?>) {
383 ParentNode<?> pn = (ParentNode<?>) node;
384 return !pn.getNodes().isEmpty();
390 * Look for a single scene graph node by its ID in a path under a specified
393 * @param parent the parent node under which to start looking
394 * @param idPath the node ID path
395 * @return <code>null</code> if node was not found
396 * @throws ClassCastException if the found node was not of the expected type
399 @SuppressWarnings("unchecked")
400 public static <T extends INode> T findNodeById(INode parent, String... idPath) {
402 for (int i = 0;; ++i) {
403 if (i >= idPath.length)
405 if (n instanceof ParentNode<?>) {
406 n = ((ParentNode<?>) n).getNode(idPath[i]);
414 * Tries to find out whether a node is selected or not.
416 * DISCLAIMER: this is a hack for the current
417 * org.simantics.g2d.diagram.participant.ElementPainter implementation that
418 * will stop working if the implementation changes.
421 * @param ascendLimit the max. amount of steps towards parent nodes to take
422 * while looking for selection information
423 * @return <code>true</code> if evidence of selection is found
425 public static boolean isSelected(INode node, int ascendLimit) {
427 ParentNode<?> pn = null;
428 if (node instanceof ParentNode<?>) {
429 pn = (ParentNode<?>) node;
431 pn = node.getParent();
434 for (; pn != null && steps <= ascendLimit; pn = pn.getParent(), ++steps) {
435 INode child = pn.getNode(SELECTION_NODE_NAME);
442 public static Container findRootPane(INode node) {
443 G2DSceneGraph parent = findNearestParentNode(node, G2DSceneGraph.class);
446 return ((G2DSceneGraph) parent).getRootPane();
449 private static boolean isSelectionPainter(INode node) {
450 if (node instanceof ISelectionPainterNode) {
451 if (node instanceof IDynamicSelectionPainterNode)
452 return ((IDynamicSelectionPainterNode)node).showsSelection();
462 public static boolean needSelectionPaint(INode elementNode) {
463 // FIXME: there should be a cleaner way to implement this.
465 if (isSelectionPainter(elementNode)) {
466 // System.out.println("skipped selection painting for connection node child ISelectionPainterNode");
470 if (elementNode instanceof ConnectionNode) {
471 // System.out.println("connectionNode");
472 for (IG2DNode child : ((ConnectionNode) elementNode).getNodes()) {
473 // System.out.println(" child " + child);
474 if (isSelectionPainter(child)) {
475 // System.out.println("skipped selection painting for connection node child ISelectionPainterNode");
478 if (child instanceof SingleElementNode) {
479 for(IG2DNode child2 : ((SingleElementNode) child).getNodes()) {
480 // System.out.println(" child2 " + child2);
481 if (isSelectionPainter(child2)) {
482 // System.out.println("skipped selection painting for edge ISelectionPainterNode");
488 } else if (elementNode instanceof SingleElementNode) {
489 for (INode child : ((SingleElementNode) elementNode).getNodes()) {
490 if (isSelectionPainter(child))
498 private static final String SET_THREAD_CALLBACKS_NAME = "CGLIB$SET_THREAD_CALLBACKS"; // If this method is found, the class is enhanced by cglib, thus does not contain annotations
500 public static Method getSetterForProperty(String property, INode node) {
501 assert(node != null);
502 Class<?> cl = node.getClass();
505 boolean isEnhanced = false;
506 for(Method method : cl.getMethods()) {
507 if(method.isAnnotationPresent(PropertySetter.class)) {
508 PropertySetter ann = method.getAnnotation(PropertySetter.class);
509 if(ann.value().equals(property)) {
512 } else if(method.getName().equals(SET_THREAD_CALLBACKS_NAME) && method.getGenericParameterTypes().length == 1) {
513 // The class seems to be enhanced by cglib, hence annotations are not present. Check superclass for annotations..
515 cl = cl.getSuperclass();
516 break; // We are not going to find any annotations, stop loop and try with the parent class
519 if(!isEnhanced || cl == null) break;
525 * TODO: log exceptions for debug purposes
527 * @param property name of the property
528 * @param value can be null..
532 public static boolean setPropertyIfSupported(String property, Object value, INode node) {
533 Method setter = getSetterForProperty(property, node);
535 Class<?> pc[] = setter.getParameterTypes();
536 if(pc.length == 1 && (value == null || pc[0].isAssignableFrom(value.getClass()))) {
538 setter.invoke(node, value);
540 } catch (IllegalArgumentException e) {
541 // TODO Auto-generated catch block
543 } catch (IllegalAccessException e) {
544 // TODO Auto-generated catch block
546 } catch (InvocationTargetException e) {
547 // TODO Auto-generated catch block
548 e.getCause().printStackTrace();
553 System.err.println("Method " + setter.getName() + " expects " + pc[0].getCanonicalName() + " (got " + value.getClass().getCanonicalName() + ").");
562 public static INode findChildById(ParentNode<?> parent, String key) {
563 INode result = parent.getNode(key);
567 for (String entry : parent.getNodeIds()) {
568 if (entry.startsWith(key))
569 return parent.getNode(key);
572 for (INode node : parent.getNodes()) {
573 if (node instanceof ParentNode) {
574 result = findChildById((ParentNode<?>) node, key);
584 private static int getSegmentEnd(String suffix) {
586 for(pos=1;pos<suffix.length();++pos) {
587 char c = suffix.charAt(pos);
588 if(c == '/' || c == '#')
594 public static String decodeString(String string) {
598 public static INode browsePossible(INode node, String suffix) {
601 switch(suffix.charAt(0)) {
603 INode parent = node.getParent();
606 return browsePossible(parent, suffix.substring(1));
609 /*int segmentEnd = getSegmentEnd(suffix);
610 Variable property = getPossibleProperty(graph,
611 decodeString(suffix.substring(1, segmentEnd)));
614 return property.browsePossible(graph, suffix.substring(segmentEnd));*/
618 int segmentEnd = getSegmentEnd(suffix);
619 INode child = findChildById((ParentNode<?>)node, decodeString(suffix.substring(1, segmentEnd)));
622 return browsePossible(child, suffix.substring(segmentEnd));
629 public static Pair<INode, String> browsePossibleReference(INode node, String suffix) {
631 throw new RuntimeException("Did not find a reference.");
632 switch(suffix.charAt(0)) {
634 INode parent = node.getParent();
637 return browsePossibleReference(parent, suffix.substring(1));
640 return Pair.make(node, suffix.substring(1));
643 int segmentEnd = getSegmentEnd(suffix);
644 INode child = findChildById((ParentNode<?>)node, decodeString(suffix.substring(1, segmentEnd)));
647 return browsePossibleReference(child, suffix.substring(segmentEnd));
654 public static INode findChildByPrefix(G2DParentNode parent, String prefix) {
655 INode result = parent.getNode(prefix);
659 for (String entry : parent.getNodeIds()) {
660 if (entry.startsWith(prefix))
661 return parent.getNode(entry);
664 for (IG2DNode node : parent.getNodes()) {
665 if (node instanceof G2DParentNode) {
666 result = findChildByPrefix((G2DParentNode) node, prefix);
680 public static Collection<String> filterDirectChildIds(ParentNode<?> parent, String prefix) {
681 return filterDirectChildIds(parent, new PrefixFilter(prefix));
689 public static Collection<String> filterDirectChildIds(ParentNode<?> parent, Filter<String> childFilter) {
690 Collection<String> childIds = parent.getNodeIds();
691 ArrayList<String> result = new ArrayList<String>(childIds.size());
693 for (String id : childIds)
694 if (childFilter.accept(id))
705 public static Collection<INode> filterDirectChildren(ParentNode<?> parent, Filter<String> childFilter) {
706 Collection<String> childIds = parent.getNodeIds();
707 ArrayList<INode> result = new ArrayList<INode>(childIds.size());
709 for (String id : childIds)
710 if (childFilter.accept(id))
711 result.add( parent.getNode(id) );
718 * @return the lookup service for the specified node
719 * @throws UnsupportedOperationException if ILookupService is not available
721 public static ILookupService getLookupService(INode node) {
722 ParentNode<?> root = node.getRootNode();
723 if (!(root instanceof ILookupService))
724 throw new UnsupportedOperationException("ILookupService not supported by root node " + root + " attained from " + node);
725 return (ILookupService) root;
730 * @return <code>null</code> if lookup service is not available
732 public static ILookupService tryGetLookupService(INode node) {
733 ParentNode<?> root = node.getRootNode();
734 return root instanceof ILookupService ? (ILookupService) root : null;
740 * @return <code>null</code> if lookup failed, i.e. mapping does not exist
741 * @throws UnsupportedOperationException if lookup is not supported
742 * @see #getLookupService(INode)
743 * @see ILookupService
745 public static INode lookup(INode node, String id) {
746 ILookupService lookup = getLookupService(node);
747 return lookup.lookupNode(id);
753 * @return <code>null</code> if lookup not supported or lookup failed
754 * @see #tryGetLookupService(INode)
755 * @see ILookupService
757 public static INode tryLookup(INode node, String id) {
758 ILookupService lookup = tryGetLookupService(node);
759 return lookup != null ? lookup.lookupNode(id) : null;
766 * @return <code>null</code> if lookup failed, i.e. mapping does not exist
767 * @throws UnsupportedOperationException if lookup is not supported
768 * @throws ClassCastException if the found node cannot be cast to the
770 * @see #getLookupService(INode)
771 * @see ILookupService
773 public static <T> T lookup(INode node, String id, Class<T> clazz) {
774 ILookupService lookup = getLookupService(node);
775 INode found = lookup.lookupNode(id);
776 return found != null ? clazz.cast(found) : null;
782 * @return <code>null</code> if lookup not supported or lookup failed
783 * @see #tryGetLookupService(INode)
784 * @see ILookupService
786 public static <T> T tryLookup(INode node, String id, Class<T> clazz) {
787 ILookupService lookup = tryGetLookupService(node);
790 INode found = lookup.lookupNode(id);
791 return found != null ? clazz.cast(found) : null;
797 * @return <code>null</code> if lookup failed, i.e. mapping does not exist
798 * @throws UnsupportedOperationException if lookup is not supported
799 * @see #getLookupService(INode)
800 * @see ILookupService
802 public static String lookupId(INode node) {
803 ILookupService lookup = getLookupService(node);
804 return lookup.lookupId(node);
810 * @return <code>null</code> if lookup not supported or lookup failed
811 * @see #tryGetLookupService(INode)
812 * @see ILookupService
814 public static String tryLookupId(INode node) {
815 ILookupService lookup = tryGetLookupService(node);
816 return lookup != null ? lookup.lookupId(node) : null;
820 * Map the specified node to the specified ID in the {@link ILookupService}
821 * provided by the root node of the specified node.
825 * @throws UnsupportedOperationException if {@link ILookupService} is not
826 * available for the specified node
827 * @see #getLookupService(INode)
828 * @see ILookupService
830 public static void map(INode node, String id) {
831 getLookupService(node).map(id, node);
835 * Remove possible ILookupService mapping for the specified node.
837 * @param node the node to try to remove mappings for
838 * @return mapped ID or <code>null</code> if no mapping existed
839 * @throws UnsupportedOperationException if {@link ILookupService} is not
840 * available for the specified node
841 * @see ILookupService
842 * @see #getLookupService(INode)
844 public static String unmap(INode node) {
845 return getLookupService(node).unmap(node);
849 * Try to remove possible ILookupService mapping for the specified node.
851 * @param node the node to try to remove mappings for
852 * @return mapped ID or <code>null</code> if {@link ILookupService} is not
853 * supported or no mapping existed
854 * @see ILookupService
855 * @see #tryGetLookupService(INode)
857 public static String tryUnmap(INode node) {
858 ILookupService lookup = tryGetLookupService(node);
859 return lookup != null ? lookup.unmap(node) : null;
862 public static EventDelegator getEventDelegator(INode node) {
863 ParentNode<?> n = node.getRootNode();
864 if (n instanceof G2DSceneGraph) {
865 return ((G2DSceneGraph) n).getEventDelegator();
870 public static NodeEventHandler getNodeEventHandler(INode node) {
871 ParentNode<?> n = node.getRootNode();
872 return (n instanceof G2DSceneGraph) ? ((G2DSceneGraph) n).getEventHandler() : null;
873 // INodeEventHandlerProvider provider = findNearestParentNode(node, INodeEventHandlerProvider.class);
874 // return provider != null ? provider.getEventHandler() : null;
877 public static AWTEvent transformEvent(AWTEvent event, IG2DNode node) {
878 if (event instanceof MouseEvent) {
879 // Find node transform..
880 AffineTransform transform = getGlobalToLocalTransform(node, null);
881 if (transform == null) {
882 System.err.println("WARNING: Non-invertible transform for node: " + node);
885 MouseEvent me = (MouseEvent)event;
886 // Use double coordinates if available
887 Point2D p = new Point2D.Double((double)me.getX(), (double)me.getY());
888 transform.transform(p, p);
891 // Giving event.getSource() as a parameter for the new events will cause major delay for the event instantiation, hence dummy component is used
892 if (event instanceof MouseWheelEvent) {
893 e = new SGMouseWheelEvent(new DummyComponent(), me.getID(), me.getWhen(), me.getModifiers(), p.getX(), p.getY(), me.getClickCount(), me.isPopupTrigger(), ((MouseWheelEvent)me).getScrollType(), ((MouseWheelEvent)me).getScrollAmount(), ((MouseWheelEvent)me).getWheelRotation(), me);
895 e = new SGMouseEvent(new DummyComponent(), me.getID(), me.getWhen(), me.getModifiers(), p.getX(), p.getY(), me.getClickCount(), me.isPopupTrigger(), me.getButton(), me);
902 private static final boolean DEBUG_BOUNDS = false;
904 private static Rectangle2D getLocalBoundsImpl(INode node, Function1<INode, Boolean> filter, int indent) {
905 if (node instanceof IG2DNode) {
906 if (node instanceof G2DParentNode) {
907 G2DParentNode pNode = (G2DParentNode)node;
908 Iterator<IG2DNode> it = pNode.getNodes().iterator();
911 Rectangle2D bounds = null;
912 while (it.hasNext()) {
913 IG2DNode next = it.next();
914 if (filter != null && !filter.apply(next))
917 Rectangle2D bl = getLocalBoundsImpl(next, filter, indent+2);
920 for(int i=0;i<indent;i++) System.err.print(" ");
921 System.err.println("+getLocalBoundsImpl " + next + " => " + bl);
926 bounds = next.localToParent(bl.getFrame());
928 bounds.add(next.localToParent(bl));
934 for(int i=0;i<indent;i++) System.err.print(" ");
935 System.err.println("=getLocalBoundsImpl " + node + " => " + bounds);
940 Rectangle2D result = ((IG2DNode)node).getBoundsInLocal(true);
943 for(int i=0;i<indent;i++) System.err.print(" ");
944 System.err.println("=getLocalBoundsImpl " + node + " => " + result);
953 public static Rectangle2D getLocalBounds(INode node) {
954 return getLocalBoundsImpl(node, null, 0);
957 public static Rectangle2D getLocalBounds(INode node, final Set<INode> excluding) {
958 return getLocalBoundsImpl(node, new FunctionImpl1<INode, Boolean>() {
961 public Boolean apply(INode node) {
962 return !excluding.contains(node);
967 public static Rectangle2D getLocalBounds(INode node, final Class<?> excluding) {
968 return getLocalBoundsImpl(node, new FunctionImpl1<INode, Boolean>() {
971 public Boolean apply(INode node) {
972 return !excluding.isInstance(node);
977 public static Rectangle2D getLocalElementBounds(INode node) {
978 if(node instanceof ConnectionNode) {
979 return getLocalBounds(node);
980 } else if(node instanceof SingleElementNode) {
981 // For normal symbols
982 INode image = NodeUtil.findChildByPrefix((SingleElementNode)node, "composite_image");
984 // For generic text nodes
985 image = NodeUtil.findChildByPrefix((SingleElementNode) node, "text");
987 // For I/O table diagram flags (value of org.simantics.diagram.flag.FlagSceneGraph.VISUAL_ROOT)
988 image = NodeUtil.findChildByPrefix((SingleElementNode) node, "visual");
990 image = NodeUtil.getNearestChildByClass((SingleElementNode) node, FlagNode.class);
992 return getLocalElementBounds(image);
994 return getLocalBounds(node);
996 return getLocalBounds(node);
1000 public static <T> T findNearestParentNode(INode node, Class<T> ofClass) {
1001 ParentNode<?> parent = null;
1003 parent = node.getParent();
1006 if (ofClass.isInstance(parent))
1007 return ofClass.cast(parent);
1012 private static class PendingTester implements Runnable {
1014 private boolean pending = true;
1015 private final G2DSceneGraph sg;
1017 private final Lock pendingLock = new ReentrantLock();
1018 private final Condition pendingSet = pendingLock.newCondition();
1020 public PendingTester(G2DSceneGraph sg) {
1028 pending = sg.isPending();
1029 pendingSet.signalAll();
1031 pendingLock.unlock();
1035 public boolean isPending() {
1039 public void await() {
1043 pendingSet.await(10, TimeUnit.MILLISECONDS);
1044 } catch (InterruptedException e) {
1047 pendingLock.unlock();
1053 public static void waitPending(IThreadWorkQueue thread, G2DSceneGraph sg) {
1054 // Wait for 30s by default
1055 waitPending(thread, sg, 30000);
1059 * Synchronously waits until the the specified scene graph is no longer in
1062 * @param thread the thread to schedule pending checks into
1063 * @param sg the scene graph to wait upon
1065 public static void waitPending(IThreadWorkQueue thread, G2DSceneGraph sg, int timeoutMs) {
1066 PendingTester tester = new PendingTester(sg);
1067 long start = System.currentTimeMillis();
1068 while (tester.isPending()) {
1069 thread.asyncExec(tester);
1070 if (tester.isPending())
1072 long duration = System.currentTimeMillis() - start;
1073 if(duration > timeoutMs)
1074 throw new IllegalStateException("Timeout in resolving pending nodes.");
1078 public static void increasePending(INode node) {
1079 G2DSceneGraph sg = (G2DSceneGraph) node.getRootNode();
1081 sg.increasePending(node);
1084 public static void decreasePending(INode node) {
1085 G2DSceneGraph sg = (G2DSceneGraph) node.getRootNode();
1087 sg.decreasePending(node);
1092 public static AffineTransform getLocalToGlobalTransform(IG2DNode node, AffineTransform result) {
1093 result.setToIdentity();
1094 ParentNode<?> parent = node.getParent();
1095 while (parent != null) {
1096 result.preConcatenate(((IG2DNode) parent).getTransform());
1097 parent = parent.getParent();
1102 public static AffineTransform getLocalToGlobalTransform(IG2DNode node) {
1103 return getLocalToGlobalTransform(node, new AffineTransform());
1106 public static AffineTransform getGlobalToLocalTransform(IG2DNode node) throws NoninvertibleTransformException {
1107 AffineTransform transform = getLocalToGlobalTransform(node);
1112 public static AffineTransform getGlobalToLocalTransform(IG2DNode node, AffineTransform returnIfNonInvertible) {
1113 AffineTransform transform = getLocalToGlobalTransform(node);
1117 } catch (NoninvertibleTransformException e) {
1118 return returnIfNonInvertible;
1122 public static Point2D worldToLocal(IG2DNode local, Point2D pt, Point2D pt2) {
1123 AffineTransform at = getGlobalToLocalTransform(local, null);
1125 pt2.setLocation(pt);
1128 return at.transform(pt, pt2);
1131 public static Point2D localToWorld(IG2DNode local, Point2D pt, Point2D pt2) {
1132 AffineTransform at = getLocalToGlobalTransform(local);
1133 return at.transform(pt, pt2);
1136 public static String getNodeName(INode nn) {
1137 INode node = nn.getParent();
1138 ParentNode<?> pn = (ParentNode<?>) node;
1139 if (node instanceof G2DParentNode) {
1140 G2DParentNode g2dpn = (G2DParentNode) node;
1141 for (String id : g2dpn.getSortedNodesById())
1143 INode n = pn.getNode(id);
1153 * For asking whether specified parent node really is a parent of the
1154 * specified child node.
1159 * alleged child of parent
1160 * @return <code>true</code> if parent really is a parent of child
1162 public static boolean isParentOf(INode parent, INode child) {
1164 if (parent == child)
1166 child = child.getParent();