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