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