1 /*
   2  * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javafx.scene;
  27 
  28 import com.sun.javafx.scene.traversal.ParentTraversalEngine;
  29 import javafx.beans.property.ObjectProperty;
  30 import javafx.beans.property.ReadOnlyBooleanProperty;
  31 import javafx.beans.property.ReadOnlyBooleanWrapper;
  32 import javafx.beans.property.SimpleObjectProperty;
  33 import javafx.beans.value.WritableValue;
  34 import javafx.collections.FXCollections;
  35 import javafx.collections.ListChangeListener.Change;
  36 import javafx.collections.ObservableList;
  37 import java.util.ArrayList;
  38 import java.util.HashSet;
  39 import java.util.List;
  40 import java.util.Set;
  41 
  42 import com.sun.javafx.util.TempState;
  43 import com.sun.javafx.util.Utils;
  44 import com.sun.javafx.collections.TrackableObservableList;
  45 import com.sun.javafx.collections.VetoableListDecorator;
  46 import com.sun.javafx.collections.annotations.ReturnsUnmodifiableCollection;
  47 import com.sun.javafx.css.Selector;
  48 import com.sun.javafx.css.StyleManager;
  49 import com.sun.javafx.geom.BaseBounds;
  50 import com.sun.javafx.geom.PickRay;
  51 import com.sun.javafx.geom.Point2D;
  52 import com.sun.javafx.geom.RectBounds;
  53 import com.sun.javafx.geom.transform.BaseTransform;
  54 import com.sun.javafx.geom.transform.NoninvertibleTransformException;
  55 import com.sun.javafx.jmx.MXNodeAlgorithm;
  56 import com.sun.javafx.jmx.MXNodeAlgorithmContext;
  57 import com.sun.javafx.scene.CssFlags;
  58 import com.sun.javafx.scene.DirtyBits;
  59 import com.sun.javafx.scene.input.PickResultChooser;
  60 import com.sun.javafx.sg.prism.NGGroup;
  61 import com.sun.javafx.sg.prism.NGNode;
  62 import com.sun.javafx.tk.Toolkit;
  63 import com.sun.javafx.scene.LayoutFlags;
  64 import javafx.stage.Window;
  65 
  66 /**
  67  * The base class for all nodes that have children in the scene graph.
  68  * <p>
  69  * This class handles all hierarchical scene graph operations, including adding/removing
  70  * child nodes, marking branches dirty for layout and rendering, picking,
  71  * bounds calculations, and executing the layout pass on each pulse.
  72  * <p>
  73  * There are two direct concrete Parent subclasses
  74  * <ul>
  75  * <li>{@link Group} effects and transforms to be applied to a collection of child nodes.</li>
  76  * <li>{@link javafx.scene.layout.Region} class for nodes that can be styled with CSS and layout children. </li>
  77  * </ul>
  78  *
  79  * @since JavaFX 2.0
  80  */
  81 public abstract class Parent extends Node {
  82     // package private for testing
  83     static final int DIRTY_CHILDREN_THRESHOLD = 10;
  84 
  85     // If set to true, generate a warning message whenever adding a node to a
  86     // parent if it is currently a child of another parent.
  87     private static final boolean warnOnAutoMove = PropertyHelper.getBooleanProperty("javafx.sg.warn");
  88 
  89     /**
  90      * Threshold when it's worth to populate list of removed children.
  91      */
  92     private static final int REMOVED_CHILDREN_THRESHOLD = 20;
  93 
  94     /**
  95      * Do not populate list of removed children when its number exceeds threshold,
  96      * but mark whole parent dirty.
  97      */
  98     private boolean removedChildrenOptimizationDisabled = false;
  99 
 100     /**
 101      * @treatAsPrivate implementation detail
 102      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
 103      */
 104     @Deprecated
 105     @Override public void impl_updatePeer() {
 106         super.impl_updatePeer();
 107         final NGGroup peer = impl_getPeer();
 108 
 109         if (Utils.assertionEnabled()) {
 110             List<NGNode> pgnodes = peer.getChildren();
 111             if (pgnodes.size() != pgChildrenSize) {
 112                 java.lang.System.err.println("*** pgnodes.size() [" + pgnodes.size() + "] != pgChildrenSize [" + pgChildrenSize + "]");
 113             }
 114         }
 115 
 116         if (impl_isDirty(DirtyBits.PARENT_CHILDREN)) {
 117             // Whether a permutation, or children having been added or
 118             // removed, we'll want to clear out the PG side starting
 119             // from startIdx. We know that everything up to but not
 120             // including startIdx is identical between the FX and PG
 121             // sides, so we only need to update the remaining portion.
 122             peer.clearFrom(startIdx);
 123             for (int idx = startIdx; idx < children.size(); idx++) {
 124                 peer.add(idx, children.get(idx).impl_getPeer());
 125             }
 126             if (removedChildrenOptimizationDisabled) {
 127                 peer.markDirty();
 128                 removedChildrenOptimizationDisabled = false;
 129             } else {
 130                 if (removed != null && !removed.isEmpty()) {
 131                     for(int i = 0; i < removed.size(); i++) {
 132                         peer.addToRemoved(removed.get(i).impl_getPeer());
 133                     }
 134                 }
 135             }
 136             if (removed != null) {
 137                 removed.clear();
 138             }
 139             pgChildrenSize = children.size();
 140             startIdx = pgChildrenSize;
 141         }
 142 
 143         if (Utils.assertionEnabled()) validatePG();
 144     }
 145 
 146 
 147     /***********************************************************************
 148      *                        Scenegraph Structure                         *
 149      *                                                                     *
 150      *  Functions and variables related to the scenegraph structure,       *
 151      *  modifying the structure, and walking the structure.                *
 152      *                                                                     *
 153      **********************************************************************/
 154 
 155     // Used to check for duplicate nodes
 156     private final Set<Node> childSet = new HashSet<Node>();
 157 
 158     // starting child index from which we need to send the children to the PGGroup
 159     private int startIdx = 0;
 160 
 161     // double of children in the PGGroup as of the last update
 162     private int pgChildrenSize = 0;
 163 
 164     void validatePG() {
 165         boolean assertionFailed = false;
 166         final NGGroup peer = impl_getPeer();
 167         List<NGNode> pgnodes = peer.getChildren();
 168         if (pgnodes.size() != children.size()) {
 169             java.lang.System.err.println("*** pgnodes.size validatePG() [" + pgnodes.size() + "] != children.size() [" + children.size() + "]");
 170             assertionFailed = true;
 171         } else {
 172             for (int idx = 0; idx < children.size(); idx++) {
 173                 Node n = children.get(idx);
 174                 if (n.getParent() != this) {
 175                     java.lang.System.err.println("*** this=" + this + " validatePG children[" + idx + "].parent= " + n.getParent());
 176                     assertionFailed = true;
 177                 }
 178                 if (n.impl_getPeer() != pgnodes.get(idx)) {
 179                     java.lang.System.err.println("*** pgnodes[" + idx + "] validatePG != children[" + idx + "]");
 180                     assertionFailed = true;
 181                 }
 182             }
 183         }
 184         if (assertionFailed) {
 185             throw new java.lang.AssertionError("validation of PGGroup children failed");
 186         }
 187 
 188     }
 189 
 190     void printSeq(String prefix, List<Node> nodes) {
 191         String str = prefix;
 192         for (Node nn : nodes) {
 193             str += nn + " ";
 194         }
 195         System.out.println(str);
 196     }
 197 
 198     // Variable used to indicate that the change to the children ObservableList is
 199     // a simple permutation as the result of a toFront or toBack operation.
 200     // We can avoid almost all of the processing of the on replace trigger in
 201     // this case.
 202     private boolean childrenTriggerPermutation = false;
 203 
 204     //accumulates all removed nodes between pulses, for dirty area calculation.
 205     private List<Node> removed;
 206 
 207     /**
 208      * A ObservableList of child {@code Node}s.
 209      * <p>
 210      * See the class documentation for {@link Node} for scene graph structure
 211      * restrictions on setting a {@link Parent}'s children ObservableList.
 212      * If these restrictions are violated by a change to the children ObservableList,
 213      * the change is ignored and the previous value of the child ObservableList is
 214      * restored.
 215      *
 216      * {@code <p>Throws AssignToBoundException} if the same node
 217      * appears in two different bound ObservableList.
 218      *
 219      * @defaultValue empty
 220      */
 221 
 222     // set to true if either childRemoved or childAdded returns
 223     // true. These functions will indicate whether the geom
 224     // bounds for the parent have changed
 225     private boolean geomChanged;
 226     private boolean childSetModified;
 227     private final ObservableList<Node> children = new VetoableListDecorator<Node>(new TrackableObservableList<Node>() {
 228 
 229 
 230         protected void onChanged(Change<Node> c) {
 231             // proceed with updating the scene graph
 232             unmodifiableManagedChildren = null;
 233             boolean relayout = false;
 234             if (childSetModified) {
 235                 while (c.next()) {
 236                     int from = c.getFrom();
 237                     int to = c.getTo();
 238                     for (int i = from; i < to; ++i) {
 239                         Node n = children.get(i);
 240                         if (n.getParent() != null && n.getParent() != Parent.this) {
 241                             if (warnOnAutoMove) {
 242                                 java.lang.System.err.println("WARNING added to a new parent without first removing it from its current");
 243                                 java.lang.System.err.println("    parent. It will be automatically removed from its current parent.");
 244                                 java.lang.System.err.println("    node=" + n + " oldparent= " + n.getParent() + " newparent=" + this);
 245                             }
 246                             n.getParent().children.remove(n);
 247                             if (warnOnAutoMove) {
 248                                 Thread.dumpStack();
 249                             }
 250                         }
 251                     }
 252 
 253                     List<Node> removed = c.getRemoved();
 254                     int removedSize = removed.size();
 255                     for (int i = 0; i < removedSize; ++i) {
 256                         final Node n = removed.get(i);
 257                         if (n.isManaged()) {
 258                             relayout = true;
 259                         }
 260                     }
 261 
 262                     // update the parent and scene for each new node
 263                     for (int i = from; i < to; ++i) {
 264                         Node node = children.get(i);
 265                         if (node.isManaged()) {
 266                             relayout = true;
 267                         }
 268                         node.setParent(Parent.this);
 269                         node.setScenes(getScene(), getSubScene());
 270                         // assert !node.boundsChanged;
 271                         if (node.isVisible()) {
 272                             geomChanged = true;
 273                             childIncluded(node);
 274                         }
 275                     }
 276                 }
 277 
 278                 // check to see if the number of children exceeds
 279                 // DIRTY_CHILDREN_THRESHOLD and dirtyChildren is null.
 280                 // If so, then we need to create dirtyChildren and
 281                 // populate it.
 282                 if (dirtyChildren == null && children.size() > DIRTY_CHILDREN_THRESHOLD) {
 283                     dirtyChildren
 284                             = new ArrayList<Node>(2 * DIRTY_CHILDREN_THRESHOLD);
 285                     // only bother populating children if geom has
 286                     // changed, otherwise there is no need
 287                     if (dirtyChildrenCount > 0) {
 288                         int size = children.size();
 289                         for (int i = 0; i < size; ++i) {
 290                             Node ch = children.get(i);
 291                             if (ch.isVisible() && ch.boundsChanged) {
 292                                 dirtyChildren.add(ch);
 293                             }
 294                         }
 295                     }
 296                 }
 297             } else {
 298                 // If childSet was not modified, we still need to check whether the permutation
 299                 // did change the layout
 300                 layout_loop:while (c.next()) {
 301                     List<Node> removed = c.getRemoved();
 302                     for (int i = 0, removedSize = removed.size(); i < removedSize; ++i) {
 303                         if (removed.get(i).isManaged()) {
 304                             relayout = true;
 305                             break layout_loop;
 306                         }
 307                     }
 308 
 309                     for (int i = c.getFrom(), to = c.getTo(); i < to; ++i) {
 310                         if (children.get(i).isManaged()) {
 311                             relayout = true;
 312                             break layout_loop;
 313                         }
 314                     }
 315                 }
 316             }
 317 
 318 
 319             //
 320             // Note that the styles of a child do not affect the parent or
 321             // its siblings. Thus, it is only necessary to reapply css to
 322             // the Node just added and not to this parent and all of its
 323             // children. So the following call to impl_reapplyCSS was moved
 324             // to Node.parentProperty. The original comment and code were
 325             // purposely left here as documentation should there be any
 326             // question about how the code used to work and why the change
 327             // was made.
 328             //
 329             // if children have changed then I need to reapply
 330             // CSS from this node on down
 331 //                impl_reapplyCSS();
 332             //
 333 
 334             // request layout if a Group subclass has overridden doLayout OR
 335             // if one of the new children needs layout, in which case need to ensure
 336             // the needsLayout flag is set all the way to the root so the next layout
 337             // pass will reach the child.
 338             if (relayout) {
 339                 requestLayout();
 340             }
 341 
 342             if (geomChanged) {
 343                 impl_geomChanged();
 344             }
 345 
 346             // Note the starting index at which we need to update the
 347             // PGGroup on the next update, and mark the children dirty
 348             c.reset();
 349             c.next();
 350             if (startIdx > c.getFrom()) {
 351                 startIdx = c.getFrom();
 352             }
 353 
 354             impl_markDirty(DirtyBits.PARENT_CHILDREN);
 355         }
 356 
 357     }) {
 358         @Override
 359         protected void onProposedChange(final List<Node> newNodes, int[] toBeRemoved) {
 360             final Scene scene = getScene();
 361             if (scene != null) {
 362                 Window w = scene.getWindow();
 363                 if (w != null && w.impl_getPeer() != null) {
 364                     Toolkit.getToolkit().checkFxUserThread();
 365                 }
 366             }
 367             geomChanged = false;
 368 
 369             long newLength = children.size() + newNodes.size();
 370             int removedLength = 0;
 371             for (int i = 0; i < toBeRemoved.length; i += 2) {
 372                 removedLength += toBeRemoved[i + 1] - toBeRemoved[i];
 373             }
 374             newLength -= removedLength;
 375 
 376             // If the childrenTriggerPermutation flag is set, then we know it
 377             // is a simple permutation and no further checking is needed.
 378             if (childrenTriggerPermutation) {
 379                 childSetModified = false;
 380                 return;
 381             }
 382 
 383             // If the childrenTriggerPermutation flag is not set, then we will
 384             // check to see whether any element in the ObservableList has changed,
 385             // or whether the new ObservableList is a permutation on the existing
 386             // ObservableList. Note that even if the childrenModified flag is false,
 387             // we still have to check for duplicates. If it is a simple
 388             // permutation, we can avoid checking for cycles or other parents.
 389             childSetModified = true;
 390             if (newLength == childSet.size()) {
 391                 childSetModified = false;
 392                 for (int i = newNodes.size() - 1; i >= 0; --i ) {
 393                     Node n = newNodes.get(i);
 394                     if (!childSet.contains(n)) {
 395                         childSetModified = true;
 396                         break;
 397                     }
 398                 }
 399             }
 400 
 401             // Enforce scene graph invariants, and check for structural errors.
 402             //
 403             // 1. If a child has been added to this parent more than once,
 404             // then it is an error
 405             //
 406             // 2. If a child is a target of a clip, then it is an error.
 407             //
 408             // 3. If a node would cause a cycle, then it is an error.
 409             //
 410             // 4. If a node is null
 411             //
 412             // Note that if a node is the child of another parent, we will
 413             // implicitly remove the node from its former Parent after first
 414             // checking for errors.
 415 
 416             // iterate over the nodes that were removed and remove them from
 417             // the hash set.
 418             for (int i = 0; i < toBeRemoved.length; i += 2) {
 419                 for (int j = toBeRemoved[i]; j < toBeRemoved[i + 1]; j++) {
 420                     childSet.remove(children.get(j));
 421                 }
 422             }
 423 
 424             try {
 425                 if (childSetModified) {
 426                     // check individual children before duplication test
 427                     // if done in this order, the exception is more specific
 428                     for (int i = newNodes.size() - 1; i >= 0; --i ) {
 429                         Node node = newNodes.get(i);
 430                         if (node == null) {
 431                             throw new NullPointerException(
 432                                     constructExceptionMessage(
 433                                         "child node is null", null));
 434                         }
 435                         if (node.getClipParent() != null) {
 436                             throw new IllegalArgumentException(
 437                                     constructExceptionMessage(
 438                                         "node already used as a clip", node));
 439                         }
 440                         if (wouldCreateCycle(Parent.this, node)) {
 441                             throw new IllegalArgumentException(
 442                                     constructExceptionMessage(
 443                                         "cycle detected", node));
 444                         }
 445                     }
 446                 }
 447 
 448                 childSet.addAll(newNodes);
 449                 if (childSet.size() != newLength) {
 450                     throw new IllegalArgumentException(
 451                             constructExceptionMessage(
 452                                 "duplicate children added", null));
 453                 }
 454             } catch (RuntimeException e) {
 455                 //Return children to it's original state
 456                 childSet.clear();
 457                 childSet.addAll(children);
 458 
 459                 // rethrow
 460                 throw e;
 461             }
 462 
 463             // Done with error checking
 464 
 465             if (!childSetModified) {
 466                 return;
 467             }
 468 
 469             // iterate over the nodes that were removed and clear their
 470             // parent and scene. Add to them also to removed list for further
 471             // dirty regions calculation.
 472             if (removed == null) {
 473                 removed = new ArrayList<Node>();
 474             }
 475             if (removed.size() + removedLength > REMOVED_CHILDREN_THRESHOLD || !impl_isTreeVisible()) {
 476                 //do not populate too many children in removed list
 477                 removedChildrenOptimizationDisabled = true;
 478             }
 479             for (int i = 0; i < toBeRemoved.length; i += 2) {
 480                 for (int j = toBeRemoved[i]; j < toBeRemoved[i + 1]; j++) {
 481                     Node old = children.get(j);
 482                     final Scene oldScene = old.getScene();
 483                     if (oldScene != null) {
 484                         oldScene.generateMouseExited(old);
 485                     }
 486                     if (dirtyChildren != null) {
 487                         dirtyChildren.remove(old);
 488                     }
 489                     if (old.isVisible()) {
 490                         geomChanged = true;
 491                         childExcluded(old);
 492                     }
 493                     if (old.getParent() == Parent.this) {
 494                         old.setParent(null);
 495                         old.setScenes(null, null);
 496                     }
 497                     if (!removedChildrenOptimizationDisabled) {
 498                         removed.add(old);
 499                     }
 500                 }
 501             }
 502         }
 503 
 504         private String constructExceptionMessage(
 505                 String cause, Node offendingNode) {
 506             final StringBuilder sb = new StringBuilder("Children: ");
 507             sb.append(cause);
 508             sb.append(": parent = ").append(Parent.this);
 509             if (offendingNode != null) {
 510                 sb.append(", node = ").append(offendingNode);
 511             }
 512 
 513             return sb.toString();
 514         }
 515     };
 516 
 517     /**
 518      * A constant reference to an unmodifiable view of the children, such that every time
 519      * we ask for an unmodifiable list of children, we don't actually create a new
 520      * collection and return it. The memory overhead is pretty lightweight compared
 521      * to all the garbage we would otherwise generate.
 522      */
 523     private final ObservableList<Node> unmodifiableChildren =
 524             FXCollections.unmodifiableObservableList(children);
 525 
 526     /**
 527      * A cached reference to the unmodifiable managed children of this Parent. This is
 528      * created whenever first asked for, and thrown away whenever children are added
 529      * or removed or when their managed state changes. This could be written
 530      * differently, such that this list is essentially a filtered copy of the
 531      * main children, but that additional overhead might not be worth it.
 532      */
 533     private List<Node> unmodifiableManagedChildren = null;
 534 
 535     /**
 536      * Gets the list of children of this {@code Parent}.
 537      *
 538      * <p>
 539      * See the class documentation for {@link Node} for scene graph structure
 540      * restrictions on setting a {@link Parent}'s children list.
 541      * If these restrictions are violated by a change to the list of children,
 542      * the change is ignored and the previous value of the children list is
 543      * restored. An {@link IllegalArgumentException} is thrown in this case.
 544      *
 545      * <p>
 546      * If this {@link Parent} node is attached to a {@link Scene} attached to a {@link Window}
 547      * that is showning ({@link javafx.stage.Window#isShowing()}), then its
 548      * list of children must only be modified on the JavaFX Application Thread.
 549      * An {@link IllegalStateException} is thrown if this restriction is
 550      * violated.
 551      *
 552      * <p>
 553      * Note to subclasses: if you override this method, you must return from
 554      * your implementation the result of calling this super method. The actual
 555      * list instance returned from any getChildren() implementation must be
 556      * the list owned and managed by this Parent. The only typical purpose
 557      * for overriding this method is to promote the method to be public.
 558      *
 559      * @return the list of children of this {@code Parent}.
 560      */
 561     protected ObservableList<Node> getChildren() {
 562         return children;
 563     }
 564 
 565     /**
 566      * Gets the list of children of this {@code Parent} as a read-only
 567      * list.
 568      *
 569      * @return read-only access to this parent's children ObservableList
 570      */
 571     @ReturnsUnmodifiableCollection
 572     public ObservableList<Node> getChildrenUnmodifiable() {
 573         return unmodifiableChildren;
 574     }
 575 
 576     /**
 577      * Gets the list of all managed children of this {@code Parent}.
 578      *
 579      * @param <E> the type of the children nodes
 580      * @return list of all managed children in this parent
 581      */
 582     @ReturnsUnmodifiableCollection
 583     protected <E extends Node> List<E> getManagedChildren() {
 584         if (unmodifiableManagedChildren == null) {
 585             unmodifiableManagedChildren = new ArrayList<Node>();
 586             for (int i=0, max=children.size(); i<max; i++) {
 587                 Node e = children.get(i);
 588                 if (e.isManaged()) {
 589                     unmodifiableManagedChildren.add(e);
 590                 }
 591             }
 592         }
 593         return (List<E>)unmodifiableManagedChildren;
 594     }
 595 
 596     /**
 597      * Called by Node whenever its managed state may have changed, this
 598      * method will cause the view of managed children to be updated
 599      * such that it properly includes or excludes this child.
 600      */
 601     final void managedChildChanged() {
 602         requestLayout();
 603         unmodifiableManagedChildren = null;
 604     }
 605 
 606     // implementation of Node.toFront function
 607     final void impl_toFront(Node node) {
 608         if (Utils.assertionEnabled()) {
 609             if (!childSet.contains(node)) {
 610                 throw new java.lang.AssertionError(
 611                         "specified node is not in the list of children");
 612             }
 613         }
 614 
 615         if (children.get(children.size() - 1) != node) {
 616             childrenTriggerPermutation = true;
 617             try {
 618                 children.remove(node);
 619                 children.add(node);
 620             } finally {
 621                 childrenTriggerPermutation = false;
 622             }
 623         }
 624     }
 625 
 626     // implementation of Node.toBack function
 627     final void impl_toBack(Node node) {
 628         if (Utils.assertionEnabled()) {
 629             if (!childSet.contains(node)) {
 630                 throw new java.lang.AssertionError(
 631                         "specified node is not in the list of children");
 632             }
 633         }
 634 
 635         if (children.get(0) != node) {
 636             childrenTriggerPermutation = true;
 637             try {
 638                 children.remove(node);
 639                 children.add(0, node);
 640             } finally {
 641                 childrenTriggerPermutation = false;
 642             }
 643         }
 644     }
 645 
 646     @Override
 647     void scenesChanged(final Scene newScene, final SubScene newSubScene,
 648                        final Scene oldScene, final SubScene oldSubScene) {
 649 
 650         if (oldScene != null && newScene == null) {
 651             // RT-34863 - clean up CSS cache when Parent is removed from scene-graph
 652             StyleManager.getInstance().forget(this);
 653         }
 654 
 655         for (int i=0; i<children.size(); i++) {
 656             children.get(i).setScenes(newScene, newSubScene);
 657         }
 658 
 659         final boolean awaitingLayout = layoutFlag != LayoutFlags.CLEAN;
 660 
 661         sceneRoot = (newSubScene != null && newSubScene.getRoot() == this) ||
 662                     (newScene != null && newScene.getRoot() == this);
 663         layoutRoot = !isManaged() || sceneRoot;
 664 
 665 
 666         if (awaitingLayout) {
 667             // If this node is dirty and the new scene or subScene is not null
 668             // then add this node to the new scene's dirty list
 669             if (newScene != null && layoutRoot) {
 670                 if (newSubScene != null) {
 671                     newSubScene.setDirtyLayout(this);
 672                 }
 673             }
 674         }
 675     }
 676 
 677     @Override
 678     void setDerivedDepthTest(boolean value) {
 679         super.setDerivedDepthTest(value);
 680 
 681         for (int i=0, max=children.size(); i<max; i++) {
 682             final Node node = children.get(i);
 683             node.computeDerivedDepthTest();
 684         }
 685     }
 686 
 687     /**
 688      * @treatAsPrivate implementation detail
 689      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
 690      */
 691     @Deprecated
 692     @Override protected void impl_pickNodeLocal(PickRay pickRay, PickResultChooser result) {
 693 
 694         double boundsDistance = impl_intersectsBounds(pickRay);
 695 
 696         if (!Double.isNaN(boundsDistance)) {
 697             for (int i = children.size()-1; i >= 0; i--) {
 698                 children.get(i).impl_pickNode(pickRay, result);
 699                 if (result.isClosed()) {
 700                     return;
 701                 }
 702             }
 703 
 704             if (isPickOnBounds()) {
 705                 result.offer(this, boundsDistance, PickResultChooser.computePoint(pickRay, boundsDistance));
 706             }
 707         }
 708     }
 709 
 710     @Override boolean isConnected() {
 711         return super.isConnected() || sceneRoot;
 712     }
 713 
 714     @Override public Node lookup(String selector) {
 715         Node n = super.lookup(selector);
 716         if (n == null) {
 717             for (int i=0, max=children.size(); i<max; i++) {
 718                 final Node node = children.get(i);
 719                 n = node.lookup(selector);
 720                 if (n != null) return n;
 721             }
 722         }
 723         return n;
 724     }
 725 
 726     /**
 727      * Please Note: This method should never create the results set,
 728      * let the Node class implementation do this!
 729      */
 730     @Override List<Node> lookupAll(Selector selector, List<Node> results) {
 731         results = super.lookupAll(selector, results);
 732         for (int i=0, max=children.size(); i<max; i++) {
 733             final Node node = children.get(i);
 734             results = node.lookupAll(selector, results);
 735         }
 736         return results;
 737     }
 738 
 739     /** @treatAsPrivate implementation detail */
 740     private javafx.beans.property.ObjectProperty<ParentTraversalEngine> impl_traversalEngine;
 741 
 742     /**
 743      * @treatAsPrivate implementation detail
 744      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
 745      */
 746     // SB-dependency: RT-21209 has been filed to track this
 747     @Deprecated
 748     public final void setImpl_traversalEngine(ParentTraversalEngine value) {
 749         impl_traversalEngineProperty().set(value);
 750     }
 751 
 752     /**
 753      * @treatAsPrivate implementation detail
 754      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
 755      */
 756     @Deprecated
 757     public final ParentTraversalEngine getImpl_traversalEngine() {
 758         return impl_traversalEngine == null ? null : impl_traversalEngine.get();
 759     }
 760 
 761     /**
 762      * @treatAsPrivate implementation detail
 763      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
 764      */
 765     @Deprecated
 766     public final ObjectProperty<ParentTraversalEngine> impl_traversalEngineProperty() {
 767         if (impl_traversalEngine == null) {
 768             impl_traversalEngine =
 769                     new SimpleObjectProperty<>(
 770                             this, "impl_traversalEngine");
 771         }
 772         return impl_traversalEngine;
 773     }
 774 
 775     /***********************************************************************
 776      *                               Layout                                *
 777      *                                                                     *
 778      *  Functions and variables related to the layout scheme used by       *
 779      *  JavaFX. Includes both public and private API.                      *
 780      *                                                                     *
 781      **********************************************************************/
 782     /**
 783      * Indicates that this Node and its subnodes requires a layout pass on
 784      * the next pulse.
 785      */
 786     private ReadOnlyBooleanWrapper needsLayout;
 787     LayoutFlags layoutFlag = LayoutFlags.CLEAN;
 788 
 789     protected final void setNeedsLayout(boolean value) {
 790         if (value) {
 791             markDirtyLayout(true);
 792         } else if (layoutFlag == LayoutFlags.NEEDS_LAYOUT) {
 793             boolean hasBranch = false;
 794             for (int i = 0, max = children.size(); i < max; i++) {
 795                 final Node child = children.get(i);
 796                 if (child instanceof Parent) {
 797                     if (((Parent)child).layoutFlag != LayoutFlags.CLEAN) {
 798                         hasBranch = true;
 799                         break;
 800                     }
 801 
 802                 }
 803             }
 804             setLayoutFlag(hasBranch ? LayoutFlags.DIRTY_BRANCH : LayoutFlags.CLEAN);
 805         }
 806     }
 807 
 808     public final boolean isNeedsLayout() {
 809         return layoutFlag == LayoutFlags.NEEDS_LAYOUT;
 810     }
 811 
 812     public final ReadOnlyBooleanProperty needsLayoutProperty() {
 813         if (needsLayout == null) {
 814             needsLayout = new ReadOnlyBooleanWrapper(this, "needsLayout", layoutFlag == LayoutFlags.NEEDS_LAYOUT);
 815         }
 816         return needsLayout;
 817     }
 818 
 819     /**
 820      * This package levelis used only by Node. It is set to true while
 821      * the layout() function is processing and set to false on the conclusion.
 822      * It is used by the Node to decide whether to perform CSS updates
 823      * synchronously or asynchronously.
 824      */
 825     boolean performingLayout = false;
 826 
 827     private boolean sizeCacheClear = true;
 828     private double prefWidthCache = -1;
 829     private double prefHeightCache = -1;
 830     private double minWidthCache = -1;
 831     private double minHeightCache = -1;
 832 
 833     void setLayoutFlag(LayoutFlags flag) {
 834         if (needsLayout != null) {
 835             needsLayout.set(flag == LayoutFlags.NEEDS_LAYOUT);
 836         }
 837         layoutFlag = flag;
 838     }
 839 
 840     private void markDirtyLayout(boolean local) {
 841         setLayoutFlag(LayoutFlags.NEEDS_LAYOUT);
 842         if (local || layoutRoot) {
 843             if (sceneRoot) {
 844                 Toolkit.getToolkit().requestNextPulse();
 845                 if (getSubScene() != null) {
 846                     getSubScene().setDirtyLayout(this);
 847                 }
 848             } else {
 849                 markDirtyLayoutBranch();
 850             }
 851         } else {
 852             requestParentLayout();
 853         }
 854     }
 855 
 856     /**
 857      * Requests a layout pass to be performed before the next scene is
 858      * rendered. This is batched up asynchronously to happen once per
 859      * "pulse", or frame of animation.
 860      * <p>
 861      * If this parent is either a layout root or unmanaged, then it will be
 862      * added directly to the scene's dirty layout list, otherwise requestParentLayout
 863      * will be invoked.
 864      * @since JavaFX 8.0
 865      */
 866     public void requestLayout() {
 867         clearSizeCache();
 868         markDirtyLayout(false);
 869     }
 870 
 871     /**
 872      * Requests a layout pass of the parent to be performed before the next scene is
 873      * rendered. This is batched up asynchronously to happen once per
 874      * "pulse", or frame of animation.
 875      * <p>
 876      * This may be used when the current parent have changed it's min/max/preferred width/height,
 877      * but doesn't know yet if the change will lead to it's actual size change. This will be determined
 878      * when it's parent recomputes the layout with the new hints.
 879      */
 880     protected final void requestParentLayout() {
 881         if (!layoutRoot) {
 882             final Parent parent = getParent();
 883             if (parent != null && !parent.performingLayout) {
 884                 parent.requestLayout();
 885             }
 886         }
 887 
 888     }
 889 
 890     void clearSizeCache() {
 891         if (sizeCacheClear) {
 892             return;
 893         }
 894         sizeCacheClear = true;
 895         prefWidthCache = -1;
 896         prefHeightCache = -1;
 897         minWidthCache = -1;
 898         minHeightCache = -1;
 899     }
 900 
 901     @Override public double prefWidth(double height) {
 902         if (height == -1) {
 903             if (prefWidthCache == -1) {
 904                 prefWidthCache = computePrefWidth(-1);
 905                 if (Double.isNaN(prefWidthCache) || prefWidthCache < 0) prefWidthCache = 0;
 906                 sizeCacheClear = false;
 907             }
 908             return prefWidthCache;
 909         } else {
 910             double result = computePrefWidth(height);
 911             return Double.isNaN(result) || result < 0 ? 0 : result;
 912         }
 913     }
 914 
 915     @Override public double prefHeight(double width) {
 916         if (width == -1) {
 917             if (prefHeightCache == -1) {
 918                 prefHeightCache = computePrefHeight(-1);
 919                 if (Double.isNaN(prefHeightCache) || prefHeightCache < 0) prefHeightCache = 0;
 920                 sizeCacheClear = false;
 921             }
 922             return prefHeightCache;
 923         } else {
 924             double result = computePrefHeight(width);
 925             return Double.isNaN(result) || result < 0 ? 0 : result;
 926         }
 927     }
 928 
 929     @Override public double minWidth(double height) {
 930         if (height == -1) {
 931             if (minWidthCache == -1) {
 932                 minWidthCache = computeMinWidth(-1);
 933                 if (Double.isNaN(minWidthCache) || minWidthCache < 0) minWidthCache = 0;
 934                 sizeCacheClear = false;
 935             }
 936             return minWidthCache;
 937         } else {
 938             double result = computeMinWidth(height);
 939             return Double.isNaN(result) || result < 0 ? 0 : result;
 940         }
 941     }
 942 
 943     @Override public double minHeight(double width) {
 944         if (width == -1) {
 945             if (minHeightCache == -1) {
 946                 minHeightCache = computeMinHeight(-1);
 947                 if (Double.isNaN(minHeightCache) || minHeightCache < 0) minHeightCache = 0;
 948                 sizeCacheClear = false;
 949             }
 950             return minHeightCache;
 951         } else {
 952             double result = computeMinHeight(width);
 953             return Double.isNaN(result) || result < 0 ? 0 : result;
 954         }
 955     }
 956 
 957     // PENDING_DOC_REVIEW
 958     /**
 959      * Calculates the preferred width of this {@code Parent}. The default
 960      * implementation calculates this width as the width of the area occupied
 961      * by its managed children when they are positioned at their
 962      * current positions at their preferred widths.
 963      *
 964      * @param height the height that should be used if preferred width depends
 965      *      on it
 966      * @return the calculated preferred width
 967      */
 968     protected double computePrefWidth(double height) {
 969         double minX = 0;
 970         double maxX = 0;
 971         for (int i=0, max=children.size(); i<max; i++) {
 972             Node node = children.get(i);
 973             if (node.isManaged()) {
 974                 final double x = node.getLayoutBounds().getMinX() + node.getLayoutX();
 975                 minX = Math.min(minX, x);
 976                 maxX = Math.max(maxX, x + boundedSize(node.prefWidth(-1), node.minWidth(-1), node.maxWidth(-1)));
 977             }
 978         }
 979         return maxX - minX;
 980     }
 981 
 982     // PENDING_DOC_REVIEW
 983     /**
 984      * Calculates the preferred height of this {@code Parent}. The default
 985      * implementation calculates this height as the height of the area occupied
 986      * by its managed children when they are positioned at their current
 987      * positions at their preferred heights.
 988      *
 989      * @param width the width that should be used if preferred height depends
 990      *      on it
 991      * @return the calculated preferred height
 992      */
 993     protected double computePrefHeight(double width) {
 994         double minY = 0;
 995         double maxY = 0;
 996         for (int i=0, max=children.size(); i<max; i++) {
 997             Node node = children.get(i);
 998             if (node.isManaged()) {
 999                 final double y = node.getLayoutBounds().getMinY() + node.getLayoutY();
1000                 minY = Math.min(minY, y);
1001                 maxY = Math.max(maxY, y + boundedSize(node.prefHeight(-1), node.minHeight(-1), node.maxHeight(-1)));
1002             }
1003         }
1004         return maxY - minY;
1005     }
1006 
1007     /**
1008      * Calculates the minimum width of this {@code Parent}. The default
1009      * implementation simply returns the pref width.
1010      *
1011      * @param height the height that should be used if min width depends
1012      *      on it
1013      * @return the calculated min width
1014      * @since JavaFX 2.1
1015      */
1016     protected double computeMinWidth(double height) {
1017         return prefWidth(height);
1018     }
1019 
1020     // PENDING_DOC_REVIEW
1021     /**
1022      * Calculates the min height of this {@code Parent}. The default
1023      * implementation simply returns the pref height;
1024      *
1025      * @param width the width that should be used if min height depends
1026      *      on it
1027      * @return the calculated min height
1028      * @since JavaFX 2.1
1029      */
1030     protected double computeMinHeight(double width) {
1031         return prefHeight(width);
1032     }
1033 
1034     /**
1035      * Calculates the baseline offset based on the first managed child. If there
1036      * is no such child, returns {@link Node#getBaselineOffset()}.
1037      *
1038      * @return baseline offset
1039      */
1040     @Override public double getBaselineOffset() {
1041         for (int i=0, max=children.size(); i<max; i++) {
1042             final Node child = children.get(i);
1043             if (child.isManaged()) {
1044                 double offset = child.getBaselineOffset();
1045                 if (offset == BASELINE_OFFSET_SAME_AS_HEIGHT) {
1046                     continue;
1047                 }
1048                 return child.getLayoutBounds().getMinY() + child.getLayoutY() + offset;
1049             }
1050         }
1051         return super.getBaselineOffset();
1052     }
1053 
1054     /**
1055      * Executes a top-down layout pass on the scene graph under this parent.
1056      * 
1057      * Calling this method while the Parent is doing layout is a no-op.
1058      */
1059     public final void layout() {
1060         switch(layoutFlag) {
1061             case CLEAN:
1062                 break;
1063             case NEEDS_LAYOUT:
1064                 if (performingLayout) {
1065                     /* This code is here mainly to avoid infinite loops as layout() is public and the call might be (indirectly) invoked accidentally
1066                      * while doing the layout.
1067                      * One example might be an invocation from Group layout bounds recalculation
1068                      *  (e.g. during the localToScene/localToParent calculation).
1069                      * The layout bounds will thus return layout bounds that are "old" (i.e. before the layout changes, that are just being done), 
1070                      * which is likely what the code would expect.
1071                      * The changes will invalidate the layout bounds again however, so the layout bounds query after layout pass will return correct answer.
1072                      */
1073                     break;
1074                 }
1075                 performingLayout = true;
1076                 layoutChildren();
1077                 // Intended fall-through
1078             case DIRTY_BRANCH:
1079                 for (int i = 0, max = children.size(); i < max; i++) {
1080                     final Node child = children.get(i);
1081                     if (child instanceof Parent) {
1082                         ((Parent)child).layout();
1083                     } else if (child instanceof SubScene) {
1084                         ((SubScene)child).layoutPass();
1085                     }
1086                 }
1087                 setLayoutFlag(LayoutFlags.CLEAN);
1088                 performingLayout = false;
1089                 break;
1090         }
1091     }
1092 
1093     /**
1094      * Invoked during the layout pass to layout the children in this
1095      * {@code Parent}. By default it will only set the size of managed,
1096      * resizable content to their preferred sizes and does not do any node
1097      * positioning.
1098      * <p>
1099      * Subclasses should override this function to layout content as needed.
1100      */
1101     protected void layoutChildren() {
1102         for (int i=0, max=children.size(); i<max; i++) {
1103             final Node node = children.get(i);
1104             if (node.isResizable() && node.isManaged()) {
1105                 node.autosize();
1106             }
1107         }
1108     }
1109 
1110     /**
1111      * This field is managed by the Scene, and set on any node which is the
1112      * root of a Scene.
1113      */
1114     private boolean sceneRoot = false;
1115 
1116     /**
1117      * Keeps track of whether this node is a layout root. This is updated
1118      * whenever the sceneRoot field changes, or whenever the managed
1119      * property changes.
1120      */
1121     boolean layoutRoot = false;
1122     @Override final void notifyManagedChanged() {
1123         layoutRoot = !isManaged() || sceneRoot;
1124     }
1125 
1126     final boolean isSceneRoot() {
1127         return sceneRoot;
1128     }
1129 
1130     /***********************************************************************
1131      *                                                                     *
1132      *                         Stylesheet Handling                         *
1133      *                                                                     *
1134      **********************************************************************/
1135 
1136 
1137     /**
1138      * A ObservableList of string URLs linking to the stylesheets to use with this scene's
1139      * contents. For additional information about using CSS with the
1140      * scene graph, see the <a href="doc-files/cssref.html">CSS Reference
1141      * Guide</a>.
1142      */
1143     private final ObservableList<String> stylesheets = new TrackableObservableList<String>() {
1144         @Override
1145         protected void onChanged(Change<String> c) {
1146             final Scene scene = getScene();
1147             if (scene != null) {
1148 
1149                 // Notify the StyleManager if stylesheets change. This Parent's
1150                 // styleManager will get recreated in impl_processCSS.
1151                 StyleManager.getInstance().stylesheetsChanged(Parent.this, c);
1152 
1153                 // RT-9784 - if stylesheet is removed, reset styled properties to
1154                 // their initial value.
1155                 c.reset();
1156                 while(c.next()) {
1157                     if (c.wasRemoved() == false) {
1158                         continue;
1159                     }
1160                     break; // no point in resetting more than once...
1161                 }
1162 
1163                 impl_reapplyCSS();
1164             }
1165         }
1166     };
1167 
1168     /**
1169      * Gets an observable list of string URLs linking to the stylesheets to use
1170      * with this Parent's contents. See {@link Scene#getStylesheets()} for details.
1171      * <p>For additional information about using CSS
1172      * with the scene graph, see the <a href="doc-files/cssref.html">CSS Reference
1173      * Guide</a>.</p>
1174      *
1175      * @return the list of stylesheets to use with this Parent
1176      * @since JavaFX 2.1
1177      */
1178     public final ObservableList<String> getStylesheets() { return stylesheets; }
1179 
1180     /**
1181      * This method recurses up the parent chain until parent is null. As the
1182      * stack unwinds, if the Parent has stylesheets, they are added to the
1183      * list.
1184      *
1185      * It is possible to override this method to stop the recursion. This allows
1186      * a Parent to have a set of stylesheets distinct from its Parent.
1187      *
1188      * @treatAsPrivate implementation detail
1189      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
1190      */
1191     @Deprecated // SB-dependency: RT-21247 has been filed to track this
1192     public /* Do not make this final! */ List<String> impl_getAllParentStylesheets() {
1193 
1194         List<String> list = null;
1195         final Parent myParent = getParent();
1196         if (myParent != null) {
1197 
1198             //
1199             // recurse so that stylesheets of Parents closest to the root are
1200             // added to the list first. The ensures that declarations for
1201             // stylesheets further down the tree (closer to the leaf) have
1202             // a higer ordinal in the cascade.
1203             //
1204             list = myParent.impl_getAllParentStylesheets();
1205         }
1206 
1207         if (stylesheets != null && stylesheets.isEmpty() == false) {
1208             if (list == null) {
1209                 list = new ArrayList<String>(stylesheets.size());
1210             }
1211             for (int n=0,nMax=stylesheets.size(); n<nMax; n++) {
1212                 list.add(stylesheets.get(n));
1213             }
1214         }
1215 
1216         return list;
1217 
1218     }
1219 
1220     /**
1221      * @treatAsPrivate implementation detail
1222      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
1223      */
1224     @Deprecated
1225     @Override protected void impl_processCSS(WritableValue<Boolean> unused) {
1226 
1227         // Nothing to do...
1228         if (cssFlag == CssFlags.CLEAN) return;
1229 
1230         // RT-29254 - If DIRTY_BRANCH, pass control to Node#processCSS. This avoids calling impl_processCSS on
1231         // this node and all of its children when css doesn't need updated, recalculated, or reapplied.
1232         if (cssFlag == CssFlags.DIRTY_BRANCH) {
1233             super.processCSS();
1234             return;
1235         }
1236 
1237         // Let the super implementation handle CSS for this node
1238         super.impl_processCSS(unused);
1239 
1240         // avoid the following call to children.toArray if there are no children
1241         if (children.isEmpty()) return;
1242 
1243         //
1244         // RT-33103
1245         //
1246         // It is possible for a child to be removed from children in the middle of
1247         // the following loop. Iterating over the children may result in an IndexOutOfBoundsException.
1248         // So a copy is made and the copy is iterated over.
1249         //
1250         // Note that we don't want the fail-fast feature of an iterator, not to mention the general iterator overhead.
1251         //
1252         final Node[] childArray = children.toArray(new Node[children.size()]);
1253 
1254         // For each child, process CSS
1255         for (int i=0; i<childArray.length; i++) {
1256 
1257             final Node child = childArray[i];
1258 
1259             //  If a child no longer has this as its parent, then it is skipped.
1260             final Parent childParent = child.getParent();
1261             if (childParent == null || childParent != this) continue;
1262 
1263             // If the parent styles are being updated, recalculated or
1264             // reapplied, then make sure the children get the same treatment.
1265             // Unless the child is already more dirty than this parent (RT-29074).
1266             if(CssFlags.UPDATE.compareTo(child.cssFlag) > 0) {
1267                 child.cssFlag = CssFlags.UPDATE;
1268             }
1269             child.impl_processCSS(unused);
1270         }
1271     }
1272 
1273     /***********************************************************************
1274      *                               Misc                                  *
1275      *                                                                     *
1276      *  Initialization and other functions                                 *
1277      *                                                                     *
1278      **********************************************************************/
1279 
1280 
1281     /**
1282      * Constructs a new {@code Parent}.
1283      */
1284     protected Parent() {
1285         layoutFlag = LayoutFlags.NEEDS_LAYOUT;
1286         setAccessibleRole(AccessibleRole.PARENT);
1287     }
1288 
1289     /**
1290      * @treatAsPrivate implementation detail
1291      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
1292      */
1293     @Deprecated
1294     @Override protected NGNode impl_createPeer() {
1295         return new NGGroup();
1296     }
1297 
1298     @Override
1299     void nodeResolvedOrientationChanged() {
1300         for (int i = 0, max = children.size(); i < max; ++i) {
1301             children.get(i).parentResolvedOrientationInvalidated();
1302         }
1303     }
1304 
1305     /***************************************************************************
1306      *                                                                         *
1307      *                         Bounds Computations                             *
1308      *                                                                         *
1309      *  This code originated in GroupBoundsHelper (part of javafx-sg-common)   *
1310      *  but has been ported here to the FX side since we cannot rely on the PG *
1311      *  side for computing the bounds (due to the decoupling of the two        *
1312      *  scenegraphs for threading and other purposes).                         *
1313      *                                                                         *
1314      *  Unfortunately, we cannot simply reuse GroupBoundsHelper without some  *
1315      *  major (and hacky) modification due to the fact that GroupBoundsHelper  *
1316      *  relies on PG state and we need to do similar things here that rely on  *
1317      *  core scenegraph state. Unfortunately, that means we made a port.       *
1318      *                                                                         *
1319      **************************************************************************/
1320 
1321     private BaseBounds tmp = new RectBounds();
1322 
1323     /**
1324      * The cached bounds for the Group. If the cachedBounds are invalid
1325      * then we have no history of what the bounds are, or were.
1326      */
1327     private BaseBounds cachedBounds = new RectBounds();
1328 
1329     /**
1330      * Indicates that the cachedBounds is invalid (or old) and need to be recomputed.
1331      * If cachedBoundsInvalid is true and dirtyChildrenCount is non-zero,
1332      * then when we recompute the cachedBounds we can consider the
1333      * values in cachedBounds to represent the last valid bounds for the group.
1334      * This is useful for several fast paths.
1335      */
1336     private boolean cachedBoundsInvalid;
1337 
1338     /**
1339      * The number of dirty children which bounds haven't been incorporated
1340      * into the cached bounds yet. Can be used even when dirtyChildren is null.
1341      */
1342     private int dirtyChildrenCount;
1343 
1344     /**
1345      * This set is used to track all of the children of this group which are
1346      * dirty. It is only used in cases where the number of children is > some
1347      * value (currently 10). For very wide trees, this can provide a very
1348      * important speed boost. For the sake of memory consumption, this is
1349      * null unless the number of children ever crosses the threshold where
1350      * it will be activated.
1351      */
1352     private ArrayList<Node> dirtyChildren;
1353 
1354     private Node top;
1355     private Node left;
1356     private Node bottom;
1357     private Node right;
1358     private Node near;
1359     private Node far;
1360 
1361     /**
1362      * @treatAsPrivate implementation detail
1363      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
1364      */
1365     @Deprecated
1366     @Override public BaseBounds impl_computeGeomBounds(BaseBounds bounds, BaseTransform tx) {
1367         // If we have no children, our bounds are invalid
1368         if (children.isEmpty()) {
1369             return bounds.makeEmpty();
1370         }
1371 
1372         if (tx.isTranslateOrIdentity()) {
1373             // this is a transform which is only doing translations, or nothing
1374             // at all (no scales, rotates, or shears)
1375             // so in this case we can easily use the cached bounds
1376             if (cachedBoundsInvalid) {
1377                 recomputeBounds();
1378 
1379                 if (dirtyChildren != null) {
1380                     dirtyChildren.clear();
1381                 }
1382                 cachedBoundsInvalid = false;
1383                 dirtyChildrenCount = 0;
1384             }
1385             if (!tx.isIdentity()) {
1386                 bounds = bounds.deriveWithNewBounds((float)(cachedBounds.getMinX() + tx.getMxt()),
1387                                  (float)(cachedBounds.getMinY() + tx.getMyt()),
1388                                  (float)(cachedBounds.getMinZ() + tx.getMzt()),
1389                                  (float)(cachedBounds.getMaxX() + tx.getMxt()),
1390                                  (float)(cachedBounds.getMaxY() + tx.getMyt()),
1391                                  (float)(cachedBounds.getMaxZ() + tx.getMzt()));
1392             } else {
1393                 bounds = bounds.deriveWithNewBounds(cachedBounds);
1394             }
1395 
1396             return bounds;
1397         } else {
1398             // there is a scale, shear, or rotation happening, so need to
1399             // do the full transform!
1400             double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE, minZ = Double.MAX_VALUE;
1401             double maxX = Double.MIN_VALUE, maxY = Double.MIN_VALUE, maxZ = Double.MIN_VALUE;
1402             boolean first = true;
1403             for (int i=0, max=children.size(); i<max; i++) {
1404                 final Node node = children.get(i);
1405                 if (node.isVisible()) {
1406                     bounds = getChildTransformedBounds(node, tx, bounds);
1407                     // if the bounds of the child are invalid, we don't want
1408                     // to use those in the remaining computations.
1409                     if (bounds.isEmpty()) continue;
1410                     if (first) {
1411                         minX = bounds.getMinX();
1412                         minY = bounds.getMinY();
1413                         minZ = bounds.getMinZ();
1414                         maxX = bounds.getMaxX();
1415                         maxY = bounds.getMaxY();
1416                         maxZ = bounds.getMaxZ();
1417                         first = false;
1418                     } else {
1419                         minX = Math.min(bounds.getMinX(), minX);
1420                         minY = Math.min(bounds.getMinY(), minY);
1421                         minZ = Math.min(bounds.getMinZ(), minZ);
1422                         maxX = Math.max(bounds.getMaxX(), maxX);
1423                         maxY = Math.max(bounds.getMaxY(), maxY);
1424                         maxZ = Math.max(bounds.getMaxZ(), maxZ);
1425                     }
1426                 }
1427             }
1428             // if "first" is still true, then we didn't have any children with
1429             // non-empty bounds and thus we must return an empty bounds,
1430             // otherwise we have non-empty bounds so go for it.
1431             if (first)
1432                 bounds.makeEmpty();
1433             else
1434                 bounds = bounds.deriveWithNewBounds((float)minX, (float)minY, (float)minZ,
1435                         (float)maxX, (float)maxY, (float)maxZ);
1436 
1437             return bounds;
1438         }
1439     }
1440 
1441     private void setChildDirty(final Node node, final boolean dirty) {
1442         if (node.boundsChanged == dirty) {
1443             return;
1444         }
1445 
1446         node.boundsChanged = dirty;
1447         if (dirty) {
1448             if (dirtyChildren != null) {
1449                 dirtyChildren.add(node);
1450             }
1451             ++dirtyChildrenCount;
1452         } else {
1453             if (dirtyChildren != null) {
1454                 dirtyChildren.remove(node);
1455             }
1456             --dirtyChildrenCount;
1457         }
1458     }
1459 
1460     private void childIncluded(final Node node) {
1461         // assert node.isVisible();
1462         cachedBoundsInvalid = true;
1463         setChildDirty(node, true);
1464     }
1465 
1466     // This is called when either the child is actually removed, OR IF IT IS
1467     // TOGGLED TO BE INVISIBLE. This is because in both cases it needs to be
1468     // cleared from the state which manages bounds.
1469     private void childExcluded(final Node node) {
1470         if (node == left) {
1471             left = null;
1472             cachedBoundsInvalid = true;
1473         }
1474         if (node == top) {
1475             top = null;
1476             cachedBoundsInvalid = true;
1477         }
1478         if (node == near) {
1479             near = null;
1480             cachedBoundsInvalid = true;
1481         }
1482         if (node == right) {
1483             right = null;
1484             cachedBoundsInvalid = true;
1485         }
1486         if (node == bottom) {
1487             bottom = null;
1488             cachedBoundsInvalid = true;
1489         }
1490         if (node == far) {
1491             far = null;
1492             cachedBoundsInvalid = true;
1493         }
1494 
1495         setChildDirty(node, false);
1496     }
1497 
1498     /**
1499      * Recomputes the bounds from scratch and saves the cached bounds.
1500      */
1501     private void recomputeBounds() {
1502         // fast path for case of no children
1503         if (children.isEmpty()) {
1504             cachedBounds.makeEmpty();
1505             return;
1506         }
1507 
1508         // fast path for case of 1 child
1509         if (children.size() == 1) {
1510             Node node = children.get(0);
1511             node.boundsChanged = false;
1512             if (node.isVisible()) {
1513                 cachedBounds = getChildTransformedBounds(node, BaseTransform.IDENTITY_TRANSFORM, cachedBounds);
1514                 top = left = bottom = right = near = far = node;
1515             } else {
1516                 cachedBounds.makeEmpty();
1517                 // no need to null edge nodes here, it was done in childExcluded
1518                 // top = left = bottom = right = near = far = null;
1519             }
1520             return;
1521         }
1522 
1523         if ((dirtyChildrenCount == 0) ||
1524                 !updateCachedBounds(dirtyChildren != null
1525                                         ? dirtyChildren : children,
1526                                     dirtyChildrenCount)) {
1527             // failed to update cached bounds, recreate them
1528             createCachedBounds(children);
1529         }
1530     }
1531 
1532     private final int LEFT_INVALID = 1;
1533     private final int TOP_INVALID = 1 << 1;
1534     private final int NEAR_INVALID = 1 << 2;
1535     private final int RIGHT_INVALID = 1 << 3;
1536     private final int BOTTOM_INVALID = 1 << 4;
1537     private final int FAR_INVALID = 1 << 5;
1538 
1539     private boolean updateCachedBounds(final List<Node> dirtyNodes,
1540                                        int remainingDirtyNodes) {
1541         // fast path for untransformed bounds calculation
1542         if (cachedBounds.isEmpty()) {
1543             createCachedBounds(dirtyNodes);
1544             return true;
1545         }
1546 
1547         int invalidEdges = 0;
1548 
1549         if ((left == null) || left.boundsChanged) {
1550             invalidEdges |= LEFT_INVALID;
1551         }
1552         if ((top == null) || top.boundsChanged) {
1553             invalidEdges |= TOP_INVALID;
1554         }
1555         if ((near == null) || near.boundsChanged) {
1556             invalidEdges |= NEAR_INVALID;
1557         }
1558         if ((right == null) || right.boundsChanged) {
1559             invalidEdges |= RIGHT_INVALID;
1560         }
1561         if ((bottom == null) || bottom.boundsChanged) {
1562             invalidEdges |= BOTTOM_INVALID;
1563         }
1564         if ((far == null) || far.boundsChanged) {
1565             invalidEdges |= FAR_INVALID;
1566         }
1567 
1568         // These indicate the bounds of the Group as computed by this
1569         // function
1570         float minX = cachedBounds.getMinX();
1571         float minY = cachedBounds.getMinY();
1572         float minZ = cachedBounds.getMinZ();
1573         float maxX = cachedBounds.getMaxX();
1574         float maxY = cachedBounds.getMaxY();
1575         float maxZ = cachedBounds.getMaxZ();
1576 
1577         // this checks the newly added nodes first, so if dirtyNodes is the
1578         // whole children list, we can end early
1579         for (int i = dirtyNodes.size() - 1; remainingDirtyNodes > 0; --i) {
1580             final Node node = dirtyNodes.get(i);
1581             if (node.boundsChanged) {
1582                 // assert node.isVisible();
1583                 node.boundsChanged = false;
1584                 --remainingDirtyNodes;
1585                 tmp = getChildTransformedBounds(node, BaseTransform.IDENTITY_TRANSFORM, tmp);
1586                 if (!tmp.isEmpty()) {
1587                     float tmpx = tmp.getMinX();
1588                     float tmpy = tmp.getMinY();
1589                     float tmpz = tmp.getMinZ();
1590                     float tmpx2 = tmp.getMaxX();
1591                     float tmpy2 = tmp.getMaxY();
1592                     float tmpz2 = tmp.getMaxZ();
1593 
1594                     // If this node forms an edge, then we will set it to be the
1595                     // node for this edge and update the min/max values
1596                     if (tmpx <= minX) {
1597                         minX = tmpx;
1598                         left = node;
1599                         invalidEdges &= ~LEFT_INVALID;
1600                     }
1601                     if (tmpy <= minY) {
1602                         minY = tmpy;
1603                         top = node;
1604                         invalidEdges &= ~TOP_INVALID;
1605                     }
1606                     if (tmpz <= minZ) {
1607                         minZ = tmpz;
1608                         near = node;
1609                         invalidEdges &= ~NEAR_INVALID;
1610                     }
1611                     if (tmpx2 >= maxX) {
1612                         maxX = tmpx2;
1613                         right = node;
1614                         invalidEdges &= ~RIGHT_INVALID;
1615                     }
1616                     if (tmpy2 >= maxY) {
1617                         maxY = tmpy2;
1618                         bottom = node;
1619                         invalidEdges &= ~BOTTOM_INVALID;
1620                     }
1621                     if (tmpz2 >= maxZ) {
1622                         maxZ = tmpz2;
1623                         far = node;
1624                         invalidEdges &= ~FAR_INVALID;
1625                     }
1626                 }
1627             }
1628         }
1629 
1630         if (invalidEdges != 0) {
1631             // failed to validate some edges
1632             return false;
1633         }
1634 
1635         cachedBounds = cachedBounds.deriveWithNewBounds(minX, minY, minZ,
1636                                                         maxX, maxY, maxZ);
1637         return true;
1638     }
1639 
1640     private void createCachedBounds(final List<Node> fromNodes) {
1641         // These indicate the bounds of the Group as computed by this function
1642         float minX, minY, minZ;
1643         float maxX, maxY, maxZ;
1644 
1645         final int nodeCount = fromNodes.size();
1646         int i;
1647 
1648         // handle first visible non-empty node
1649         for (i = 0; i < nodeCount; ++i) {
1650             final Node node = fromNodes.get(i);
1651             node.boundsChanged = false;
1652             if (node.isVisible()) {
1653                 tmp = node.getTransformedBounds(
1654                                tmp, BaseTransform.IDENTITY_TRANSFORM);
1655                 if (!tmp.isEmpty()) {
1656                     left = top = near = right = bottom = far = node;
1657                     break;
1658                 }
1659             }
1660         }
1661 
1662         if (i == nodeCount) {
1663             left = top = near = right = bottom = far = null;
1664             cachedBounds.makeEmpty();
1665             return;
1666         }
1667 
1668         minX = tmp.getMinX();
1669         minY = tmp.getMinY();
1670         minZ = tmp.getMinZ();
1671         maxX = tmp.getMaxX();
1672         maxY = tmp.getMaxY();
1673         maxZ = tmp.getMaxZ();
1674 
1675         // handle remaining visible non-empty nodes
1676         for (++i; i < nodeCount; ++i) {
1677             final Node node = fromNodes.get(i);
1678             node.boundsChanged = false;
1679             if (node.isVisible()) {
1680                 tmp = node.getTransformedBounds(
1681                                tmp, BaseTransform.IDENTITY_TRANSFORM);
1682                 if (!tmp.isEmpty()) {
1683                     final float tmpx = tmp.getMinX();
1684                     final float tmpy = tmp.getMinY();
1685                     final float tmpz = tmp.getMinZ();
1686                     final float tmpx2 = tmp.getMaxX();
1687                     final float tmpy2 = tmp.getMaxY();
1688                     final float tmpz2 = tmp.getMaxZ();
1689 
1690                     if (tmpx < minX) { minX = tmpx; left = node; }
1691                     if (tmpy < minY) { minY = tmpy; top = node; }
1692                     if (tmpz < minZ) { minZ = tmpz; near = node; }
1693                     if (tmpx2 > maxX) { maxX = tmpx2; right = node; }
1694                     if (tmpy2 > maxY) { maxY = tmpy2; bottom = node; }
1695                     if (tmpz2 > maxZ) { maxZ = tmpz2; far = node; }
1696                 }
1697             }
1698         }
1699 
1700         cachedBounds = cachedBounds.deriveWithNewBounds(minX, minY, minZ,
1701                                                         maxX, maxY, maxZ);
1702     }
1703 
1704     @Override protected void updateBounds() {
1705         for (int i=0, max=children.size(); i<max; i++) {
1706             children.get(i).updateBounds();
1707         }
1708         super.updateBounds();
1709     }
1710 
1711     // Note: this marks the currently processed child in terms of transformed bounds. In rare situations like
1712     // in RT-37879, it might happen that the child bounds will be marked as invalid. Due to optimizations,
1713     // the invalidation must *always* be propagated to the parent, because the parent with some transformation
1714     // calls child's getTransformedBounds non-idenitity transform and the child's transformed bounds are thus not validated.
1715     // This does not apply to the call itself however, because the call will yield the correct result even if something
1716     // was invalidated during the computation. We can safely ignore such invalidations from that Node in this case
1717     private Node currentlyProcessedChild;
1718 
1719     private BaseBounds getChildTransformedBounds(Node node, BaseTransform tx, BaseBounds bounds) {
1720         currentlyProcessedChild = node;
1721         bounds = node.getTransformedBounds(bounds, tx);
1722         currentlyProcessedChild = null;
1723         return bounds;
1724     }
1725 
1726     /**
1727      * Called by Node whenever its bounds have changed.
1728      */
1729     void childBoundsChanged(Node node) {
1730         // See comment above at "currentlyProcessedChild" field
1731         if (node == currentlyProcessedChild) {
1732             return;
1733         }
1734 
1735         cachedBoundsInvalid = true;
1736 
1737         // mark the node such that the parent knows that the child's bounds
1738         // are not in sync with this parent. In this way, when the bounds
1739         // need to be computed, we'll come back and figure out the new bounds
1740         // for all the children which have boundsChanged set to true
1741         setChildDirty(node, true);
1742 
1743         // go ahead and indicate that the geom has changed for this parent,
1744         // even though once we figure it all out it may be that the bounds
1745         // have not changed
1746         impl_geomChanged();
1747     }
1748 
1749     /**
1750      * Called by node whenever the visibility of the node changes.
1751      */
1752     void childVisibilityChanged(Node node) {
1753         if (node.isVisible()) {
1754             childIncluded(node);
1755         } else {
1756             childExcluded(node);
1757         }
1758 
1759         impl_geomChanged();
1760     }
1761 
1762     /**
1763      * @treatAsPrivate implementation detail
1764      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
1765      */
1766     @Deprecated
1767     @Override
1768     protected boolean impl_computeContains(double localX, double localY) {
1769         final Point2D tempPt = TempState.getInstance().point;
1770         for (int i=0, max=children.size(); i<max; i++) {
1771             final Node node = children.get(i);
1772             tempPt.x = (float)localX;
1773             tempPt.y = (float)localY;
1774             try {
1775                 node.parentToLocal(tempPt);
1776             } catch (NoninvertibleTransformException e) {
1777                 continue;
1778             }
1779             if (node.contains(tempPt.x, tempPt.y)) {
1780                 return true;
1781             }
1782         }
1783         return false;
1784     }
1785 
1786     /**
1787      * @treatAsPrivate implementation detail
1788      * @deprecated This is an internal API that is not intended for use and will be removed in the next version
1789      */
1790     @Deprecated
1791     public Object impl_processMXNode(MXNodeAlgorithm alg, MXNodeAlgorithmContext ctx) {
1792         return alg.processContainerNode(this, ctx);
1793     }
1794 
1795     @Override
1796     public Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) {
1797         switch (attribute) {
1798             case CHILDREN: return getChildrenUnmodifiable();
1799             default: return super.queryAccessibleAttribute(attribute, parameters);
1800         }
1801     }
1802 
1803     void releaseAccessible() {
1804         for (int i=0, max=children.size(); i<max; i++) {
1805             final Node node = children.get(i);
1806             node.releaseAccessible();
1807         }
1808         super.releaseAccessible();
1809     }
1810 
1811 }