1 /*
   2  * Copyright (c) 2000, 2003, 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 package java.awt;
  26 
  27 import java.util.List;
  28 import java.util.ArrayList;
  29 import sun.util.logging.PlatformLogger;
  30 
  31 /**
  32  * A FocusTraversalPolicy that determines traversal order based on the order
  33  * of child Components in a Container. From a particular focus cycle root, the
  34  * policy makes a pre-order traversal of the Component hierarchy, and traverses
  35  * a Container's children according to the ordering of the array returned by
  36  * <code>Container.getComponents()</code>. Portions of the hierarchy that are
  37  * not visible and displayable will not be searched.
  38  * <p>
  39  * By default, ContainerOrderFocusTraversalPolicy implicitly transfers focus
  40  * down-cycle. That is, during normal forward focus traversal, the Component
  41  * traversed after a focus cycle root will be the focus-cycle-root's default
  42  * Component to focus. This behavior can be disabled using the
  43  * <code>setImplicitDownCycleTraversal</code> method.
  44  * <p>
  45  * By default, methods of this class with return a Component only if it is
  46  * visible, displayable, enabled, and focusable. Subclasses can modify this
  47  * behavior by overriding the <code>accept</code> method.
  48  * <p>
  49  * This policy takes into account <a
  50  * href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus traversal
  51  * policy providers</a>.  When searching for first/last/next/previous Component,
  52  * if a focus traversal policy provider is encountered, its focus traversal
  53  * policy is used to perform the search operation.
  54  *
  55  * @author David Mendenhall
  56  *
  57  * @see Container#getComponents
  58  * @since 1.4
  59  */
  60 public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy
  61     implements java.io.Serializable
  62 {
  63     private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.ContainerOrderFocusTraversalPolicy");
  64 
  65     final private int FORWARD_TRAVERSAL = 0;
  66     final private int BACKWARD_TRAVERSAL = 1;
  67 
  68     /*
  69      * JDK 1.4 serialVersionUID
  70      */
  71     private static final long serialVersionUID = 486933713763926351L;
  72 
  73     private boolean implicitDownCycleTraversal = true;
  74 
  75     /**
  76      * Used by getComponentAfter and getComponentBefore for efficiency. In
  77      * order to maintain compliance with the specification of
  78      * FocusTraversalPolicy, if traversal wraps, we should invoke
  79      * getFirstComponent or getLastComponent. These methods may be overriden in
  80      * subclasses to behave in a non-generic way. However, in the generic case,
  81      * these methods will simply return the first or last Components of the
  82      * sorted list, respectively. Since getComponentAfter and
  83      * getComponentBefore have already built the list before determining
  84      * that they need to invoke getFirstComponent or getLastComponent, the
  85      * list should be reused if possible.
  86      */
  87     transient private Container cachedRoot;
  88     transient private List cachedCycle;
  89 
  90     /*
  91      * We suppose to use getFocusTraversalCycle & getComponentIndex methods in order
  92      * to divide the policy into two parts:
  93      * 1) Making the focus traversal cycle.
  94      * 2) Traversing the cycle.
  95      * The 1st point assumes producing a list of components representing the focus
  96      * traversal cycle. The two methods mentioned above should implement this logic.
  97      * The 2nd point assumes implementing the common concepts of operating on the
  98      * cycle: traversing back and forth, retrieving the initial/default/first/last
  99      * component. These concepts are described in the AWT Focus Spec and they are
 100      * applied to the FocusTraversalPolicy in general.
 101      * Thus, a descendant of this policy may wish to not reimplement the logic of
 102      * the 2nd point but just override the implementation of the 1st one.
 103      * A striking example of such a descendant is the javax.swing.SortingFocusTraversalPolicy.
 104      */
 105     /*protected*/ private List<Component> getFocusTraversalCycle(Container aContainer) {
 106         List<Component> cycle = new ArrayList<Component>();
 107         enumerateCycle(aContainer, cycle);
 108         return cycle;
 109     }
 110     /*protected*/ private int getComponentIndex(List<Component> cycle, Component aComponent) {
 111         return cycle.indexOf(aComponent);
 112     }
 113 
 114     private void enumerateCycle(Container container, List cycle) {
 115         if (!(container.isVisible() && container.isDisplayable())) {
 116             return;
 117         }
 118 
 119         cycle.add(container);
 120 
 121         Component[] components = container.getComponents();
 122         for (int i = 0; i < components.length; i++) {
 123             Component comp = components[i];
 124             if (comp instanceof Container) {
 125                 Container cont = (Container)comp;
 126 
 127                 if (!cont.isFocusCycleRoot() && !cont.isFocusTraversalPolicyProvider()) {
 128                     enumerateCycle(cont, cycle);
 129                     continue;
 130                 }
 131             }
 132             cycle.add(comp);
 133         }
 134     }
 135 
 136     private Container getTopmostProvider(Container focusCycleRoot, Component aComponent) {
 137         Container aCont = aComponent.getParent();
 138         Container ftp = null;
 139         while (aCont  != focusCycleRoot && aCont != null) {
 140             if (aCont.isFocusTraversalPolicyProvider()) {
 141                 ftp = aCont;
 142             }
 143             aCont = aCont.getParent();
 144         }
 145         if (aCont == null) {
 146             return null;
 147         }
 148         return ftp;
 149     }
 150 
 151     /*
 152      * Checks if a new focus cycle takes place and returns a Component to traverse focus to.
 153      * @param comp a possible focus cycle root or policy provider
 154      * @param traversalDirection the direction of the traversal
 155      * @return a Component to traverse focus to if {@code comp} is a root or provider
 156      *         and implicit down-cycle is set, otherwise {@code null}
 157      */
 158     private Component getComponentDownCycle(Component comp, int traversalDirection) {
 159         Component retComp = null;
 160 
 161         if (comp instanceof Container) {
 162             Container cont = (Container)comp;
 163 
 164             if (cont.isFocusCycleRoot()) {
 165                 if (getImplicitDownCycleTraversal()) {
 166                     retComp = cont.getFocusTraversalPolicy().getDefaultComponent(cont);
 167 
 168                     if (retComp != null && log.isLoggable(PlatformLogger.FINE)) {
 169                         log.fine("### Transfered focus down-cycle to " + retComp +
 170                                  " in the focus cycle root " + cont);
 171                     }
 172                 } else {
 173                     return null;
 174                 }
 175             } else if (cont.isFocusTraversalPolicyProvider()) {
 176                 retComp = (traversalDirection == FORWARD_TRAVERSAL ?
 177                            cont.getFocusTraversalPolicy().getDefaultComponent(cont) :
 178                            cont.getFocusTraversalPolicy().getLastComponent(cont));
 179 
 180                 if (retComp != null && log.isLoggable(PlatformLogger.FINE)) {
 181                     log.fine("### Transfered focus to " + retComp + " in the FTP provider " + cont);
 182                 }
 183             }
 184         }
 185         return retComp;
 186     }
 187 
 188     /**
 189      * Returns the Component that should receive the focus after aComponent.
 190      * aContainer must be a focus cycle root of aComponent or a focus traversal policy provider.
 191      * <p>
 192      * By default, ContainerOrderFocusTraversalPolicy implicitly transfers
 193      * focus down-cycle. That is, during normal forward focus traversal, the
 194      * Component traversed after a focus cycle root will be the focus-cycle-
 195      * root's default Component to focus. This behavior can be disabled using
 196      * the <code>setImplicitDownCycleTraversal</code> method.
 197      * <p>
 198      * If aContainer is <a href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus
 199      * traversal policy provider</a>, the focus is always transferred down-cycle.
 200      *
 201      * @param aContainer a focus cycle root of aComponent or a focus traversal policy provider
 202      * @param aComponent a (possibly indirect) child of aContainer, or
 203      *        aContainer itself
 204      * @return the Component that should receive the focus after aComponent, or
 205      *         null if no suitable Component can be found
 206      * @throws IllegalArgumentException if aContainer is not a focus cycle
 207      *         root of aComponent or focus traversal policy provider, or if either aContainer or
 208      *         aComponent is null
 209      */
 210     public Component getComponentAfter(Container aContainer, Component aComponent) {
 211         if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Searching in " + aContainer + " for component after " + aComponent);
 212 
 213         if (aContainer == null || aComponent == null) {
 214             throw new IllegalArgumentException("aContainer and aComponent cannot be null");
 215         }
 216         if (!aContainer.isFocusTraversalPolicyProvider() && !aContainer.isFocusCycleRoot()) {
 217             throw new IllegalArgumentException("aContainer should be focus cycle root or focus traversal policy provider");
 218 
 219         } else if (aContainer.isFocusCycleRoot() && !aComponent.isFocusCycleRoot(aContainer)) {
 220             throw new IllegalArgumentException("aContainer is not a focus cycle root of aComponent");
 221         }
 222 
 223         synchronized(aContainer.getTreeLock()) {
 224 
 225             if (!(aContainer.isVisible() && aContainer.isDisplayable())) {
 226                 return null;
 227             }
 228 
 229             // Before all the ckecks below we first see if it's an FTP provider or a focus cycle root.
 230             // If it's the case just go down cycle (if it's set to "implicit").
 231             Component comp = getComponentDownCycle(aComponent, FORWARD_TRAVERSAL);
 232             if (comp != null) {
 233                 return comp;
 234             }
 235 
 236             // See if the component is inside of policy provider.
 237             Container provider = getTopmostProvider(aContainer, aComponent);
 238             if (provider != null) {
 239                 if (log.isLoggable(PlatformLogger.FINE)) {
 240                     log.fine("### Asking FTP " + provider + " for component after " + aComponent);
 241                 }
 242 
 243                 // FTP knows how to find component after the given. We don't.
 244                 FocusTraversalPolicy policy = provider.getFocusTraversalPolicy();
 245                 Component afterComp = policy.getComponentAfter(provider, aComponent);
 246 
 247                 // Null result means that we overstepped the limit of the FTP's cycle.
 248                 // In that case we must quit the cycle, otherwise return the component found.
 249                 if (afterComp != null) {
 250                     if (log.isLoggable(PlatformLogger.FINE)) log.fine("### FTP returned " + afterComp);
 251                     return afterComp;
 252                 }
 253                 aComponent = provider;
 254             }
 255 
 256             List<Component> cycle = getFocusTraversalCycle(aContainer);
 257 
 258             if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is " + cycle + ", component is " + aComponent);
 259 
 260             int index = getComponentIndex(cycle, aComponent);
 261 
 262             if (index < 0) {
 263                 if (log.isLoggable(PlatformLogger.FINE)) {
 264                     log.fine("### Didn't find component " + aComponent + " in a cycle " + aContainer);
 265                 }
 266                 return getFirstComponent(aContainer);
 267             }
 268 
 269             for (index++; index < cycle.size(); index++) {
 270                 comp = cycle.get(index);
 271                 if (accept(comp)) {
 272                     return comp;
 273                 } else if ((comp = getComponentDownCycle(comp, FORWARD_TRAVERSAL)) != null) {
 274                     return comp;
 275                 }
 276             }
 277 
 278             if (aContainer.isFocusCycleRoot()) {
 279                 this.cachedRoot = aContainer;
 280                 this.cachedCycle = cycle;
 281 
 282                 comp = getFirstComponent(aContainer);
 283 
 284                 this.cachedRoot = null;
 285                 this.cachedCycle = null;
 286 
 287                 return comp;
 288             }
 289         }
 290         return null;
 291     }
 292 
 293     /**
 294      * Returns the Component that should receive the focus before aComponent.
 295      * aContainer must be a focus cycle root of aComponent or a <a
 296      * href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus traversal policy
 297      * provider</a>.
 298      *
 299      * @param aContainer a focus cycle root of aComponent or focus traversal policy provider
 300      * @param aComponent a (possibly indirect) child of aContainer, or
 301      *        aContainer itself
 302      * @return the Component that should receive the focus before aComponent,
 303      *         or null if no suitable Component can be found
 304      * @throws IllegalArgumentException if aContainer is not a focus cycle
 305      *         root of aComponent or focus traversal policy provider, or if either aContainer or
 306      *         aComponent is null
 307      */
 308     public Component getComponentBefore(Container aContainer, Component aComponent) {
 309         if (aContainer == null || aComponent == null) {
 310             throw new IllegalArgumentException("aContainer and aComponent cannot be null");
 311         }
 312         if (!aContainer.isFocusTraversalPolicyProvider() && !aContainer.isFocusCycleRoot()) {
 313             throw new IllegalArgumentException("aContainer should be focus cycle root or focus traversal policy provider");
 314 
 315         } else if (aContainer.isFocusCycleRoot() && !aComponent.isFocusCycleRoot(aContainer)) {
 316             throw new IllegalArgumentException("aContainer is not a focus cycle root of aComponent");
 317         }
 318 
 319         synchronized(aContainer.getTreeLock()) {
 320 
 321             if (!(aContainer.isVisible() && aContainer.isDisplayable())) {
 322                 return null;
 323             }
 324 
 325             // See if the component is inside of policy provider.
 326             Container provider = getTopmostProvider(aContainer, aComponent);
 327             if (provider != null) {
 328                 if (log.isLoggable(PlatformLogger.FINE)) {
 329                     log.fine("### Asking FTP " + provider + " for component after " + aComponent);
 330                 }
 331 
 332                 // FTP knows how to find component after the given. We don't.
 333                 FocusTraversalPolicy policy = provider.getFocusTraversalPolicy();
 334                 Component beforeComp = policy.getComponentBefore(provider, aComponent);
 335 
 336                 // Null result means that we overstepped the limit of the FTP's cycle.
 337                 // In that case we must quit the cycle, otherwise return the component found.
 338                 if (beforeComp != null) {
 339                     if (log.isLoggable(PlatformLogger.FINE)) log.fine("### FTP returned " + beforeComp);
 340                     return beforeComp;
 341                 }
 342                 aComponent = provider;
 343 
 344                 // If the provider is traversable it's returned.
 345                 if (accept(aComponent)) {
 346                     return aComponent;
 347                 }
 348             }
 349 
 350             List<Component> cycle = getFocusTraversalCycle(aContainer);
 351 
 352             if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is " + cycle + ", component is " + aComponent);
 353 
 354             int index = getComponentIndex(cycle, aComponent);
 355 
 356             if (index < 0) {
 357                 if (log.isLoggable(PlatformLogger.FINE)) {
 358                     log.fine("### Didn't find component " + aComponent + " in a cycle " + aContainer);
 359                 }
 360                 return getLastComponent(aContainer);
 361             }
 362 
 363             Component comp = null;
 364             Component tryComp = null;
 365 
 366             for (index--; index>=0; index--) {
 367                 comp = cycle.get(index);
 368                 if (comp != aContainer && (tryComp = getComponentDownCycle(comp, BACKWARD_TRAVERSAL)) != null) {
 369                     return tryComp;
 370                 } else if (accept(comp)) {
 371                     return comp;
 372                 }
 373             }
 374 
 375             if (aContainer.isFocusCycleRoot()) {
 376                 this.cachedRoot = aContainer;
 377                 this.cachedCycle = cycle;
 378 
 379                 comp = getLastComponent(aContainer);
 380 
 381                 this.cachedRoot = null;
 382                 this.cachedCycle = null;
 383 
 384                 return comp;
 385             }
 386         }
 387         return null;
 388     }
 389 
 390     /**
 391      * Returns the first Component in the traversal cycle. This method is used
 392      * to determine the next Component to focus when traversal wraps in the
 393      * forward direction.
 394      *
 395      * @param aContainer the focus cycle root or focus traversal policy provider whose first
 396      *        Component is to be returned
 397      * @return the first Component in the traversal cycle of aContainer,
 398      *         or null if no suitable Component can be found
 399      * @throws IllegalArgumentException if aContainer is null
 400      */
 401     public Component getFirstComponent(Container aContainer) {
 402         List<Component> cycle;
 403 
 404         if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Getting first component in " + aContainer);
 405         if (aContainer == null) {
 406             throw new IllegalArgumentException("aContainer cannot be null");
 407 
 408         }
 409 
 410         synchronized(aContainer.getTreeLock()) {
 411 
 412             if (!(aContainer.isVisible() && aContainer.isDisplayable())) {
 413                 return null;
 414             }
 415 
 416             if (this.cachedRoot == aContainer) {
 417                 cycle = this.cachedCycle;
 418             } else {
 419                 cycle = getFocusTraversalCycle(aContainer);
 420             }
 421 
 422             if (cycle.size() == 0) {
 423                 if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is empty");
 424                 return null;
 425             }
 426             if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is " + cycle);
 427 
 428             for (Component comp : cycle) {
 429                 if (accept(comp)) {
 430                     return comp;
 431                 } else if (comp != aContainer &&
 432                            (comp = getComponentDownCycle(comp, FORWARD_TRAVERSAL)) != null)
 433                 {
 434                     return comp;
 435                 }
 436             }
 437         }
 438         return null;
 439     }
 440 
 441     /**
 442      * Returns the last Component in the traversal cycle. This method is used
 443      * to determine the next Component to focus when traversal wraps in the
 444      * reverse direction.
 445      *
 446      * @param aContainer the focus cycle root or focus traversal policy provider whose last
 447      *        Component is to be returned
 448      * @return the last Component in the traversal cycle of aContainer,
 449      *         or null if no suitable Component can be found
 450      * @throws IllegalArgumentException if aContainer is null
 451      */
 452     public Component getLastComponent(Container aContainer) {
 453         List<Component> cycle;
 454         if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Getting last component in " + aContainer);
 455 
 456         if (aContainer == null) {
 457             throw new IllegalArgumentException("aContainer cannot be null");
 458         }
 459 
 460         synchronized(aContainer.getTreeLock()) {
 461 
 462             if (!(aContainer.isVisible() && aContainer.isDisplayable())) {
 463                 return null;
 464             }
 465 
 466             if (this.cachedRoot == aContainer) {
 467                 cycle = this.cachedCycle;
 468             } else {
 469                 cycle = getFocusTraversalCycle(aContainer);
 470             }
 471 
 472             if (cycle.size() == 0) {
 473                 if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is empty");
 474                 return null;
 475             }
 476             if (log.isLoggable(PlatformLogger.FINE)) log.fine("### Cycle is " + cycle);
 477 
 478             for (int i= cycle.size() - 1; i >= 0; i--) {
 479                 Component comp = cycle.get(i);
 480                 if (accept(comp)) {
 481                     return comp;
 482                 } else if (comp instanceof Container && comp != aContainer) {
 483                     Container cont = (Container)comp;
 484                     if (cont.isFocusTraversalPolicyProvider()) {
 485                         return cont.getFocusTraversalPolicy().getLastComponent(cont);
 486                     }
 487                 }
 488             }
 489         }
 490         return null;
 491     }
 492 
 493     /**
 494      * Returns the default Component to focus. This Component will be the first
 495      * to receive focus when traversing down into a new focus traversal cycle
 496      * rooted at aContainer. The default implementation of this method
 497      * returns the same Component as <code>getFirstComponent</code>.
 498      *
 499      * @param aContainer the focus cycle root or focus traversal policy provider whose default
 500      *        Component is to be returned
 501      * @return the default Component in the traversal cycle of aContainer,
 502      *         or null if no suitable Component can be found
 503      * @see #getFirstComponent
 504      * @throws IllegalArgumentException if aContainer is null
 505      */
 506     public Component getDefaultComponent(Container aContainer) {
 507         return getFirstComponent(aContainer);
 508     }
 509 
 510     /**
 511      * Sets whether this ContainerOrderFocusTraversalPolicy transfers focus
 512      * down-cycle implicitly. If <code>true</code>, during normal forward focus
 513      * traversal, the Component traversed after a focus cycle root will be the
 514      * focus-cycle-root's default Component to focus. If <code>false</code>,
 515      * the next Component in the focus traversal cycle rooted at the specified
 516      * focus cycle root will be traversed instead. The default value for this
 517      * property is <code>true</code>.
 518      *
 519      * @param implicitDownCycleTraversal whether this
 520      *        ContainerOrderFocusTraversalPolicy transfers focus down-cycle
 521      *        implicitly
 522      * @see #getImplicitDownCycleTraversal
 523      * @see #getFirstComponent
 524      */
 525     public void setImplicitDownCycleTraversal(boolean implicitDownCycleTraversal) {
 526         this.implicitDownCycleTraversal = implicitDownCycleTraversal;
 527     }
 528 
 529     /**
 530      * Returns whether this ContainerOrderFocusTraversalPolicy transfers focus
 531      * down-cycle implicitly. If <code>true</code>, during normal forward focus
 532      * traversal, the Component traversed after a focus cycle root will be the
 533      * focus-cycle-root's default Component to focus. If <code>false</code>,
 534      * the next Component in the focus traversal cycle rooted at the specified
 535      * focus cycle root will be traversed instead.
 536      *
 537      * @return whether this ContainerOrderFocusTraversalPolicy transfers focus
 538      *         down-cycle implicitly
 539      * @see #setImplicitDownCycleTraversal
 540      * @see #getFirstComponent
 541      */
 542     public boolean getImplicitDownCycleTraversal() {
 543         return implicitDownCycleTraversal;
 544     }
 545 
 546     /**
 547      * Determines whether a Component is an acceptable choice as the new
 548      * focus owner. By default, this method will accept a Component if and
 549      * only if it is visible, displayable, enabled, and focusable.
 550      *
 551      * @param aComponent the Component whose fitness as a focus owner is to
 552      *        be tested
 553      * @return <code>true</code> if aComponent is visible, displayable,
 554      *         enabled, and focusable; <code>false</code> otherwise
 555      */
 556     protected boolean accept(Component aComponent) {
 557         if (!aComponent.canBeFocusOwner()) {
 558             return false;
 559         }
 560 
 561         // Verify that the Component is recursively enabled. Disabling a
 562         // heavyweight Container disables its children, whereas disabling
 563         // a lightweight Container does not.
 564         if (!(aComponent instanceof Window)) {
 565             for (Container enableTest = aComponent.getParent();
 566                  enableTest != null;
 567                  enableTest = enableTest.getParent())
 568             {
 569                 if (!(enableTest.isEnabled() || enableTest.isLightweight())) {
 570                     return false;
 571                 }
 572                 if (enableTest instanceof Window) {
 573                     break;
 574                 }
 575             }
 576         }
 577 
 578         return true;
 579     }
 580 }