Path: blob/master/src/java.desktop/share/classes/java/awt/ContainerOrderFocusTraversalPolicy.java
41152 views
/*1* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.awt;2627import java.io.Serial;28import java.util.ArrayList;29import java.util.List;3031import sun.util.logging.PlatformLogger;3233/**34* A FocusTraversalPolicy that determines traversal order based on the order35* of child Components in a Container. From a particular focus cycle root, the36* policy makes a pre-order traversal of the Component hierarchy, and traverses37* a Container's children according to the ordering of the array returned by38* {@code Container.getComponents()}. Portions of the hierarchy that are39* not visible and displayable will not be searched.40* <p>41* By default, ContainerOrderFocusTraversalPolicy implicitly transfers focus42* down-cycle. That is, during normal forward focus traversal, the Component43* traversed after a focus cycle root will be the focus-cycle-root's default44* Component to focus. This behavior can be disabled using the45* {@code setImplicitDownCycleTraversal} method.46* <p>47* By default, methods of this class will return a Component only if it is48* visible, displayable, enabled, and focusable. Subclasses can modify this49* behavior by overriding the {@code accept} method.50* <p>51* This policy takes into account <a52* href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus traversal53* policy providers</a>. When searching for first/last/next/previous Component,54* if a focus traversal policy provider is encountered, its focus traversal55* policy is used to perform the search operation.56*57* @author David Mendenhall58*59* @see Container#getComponents60* @since 1.461*/62public class ContainerOrderFocusTraversalPolicy extends FocusTraversalPolicy63implements java.io.Serializable64{65private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.ContainerOrderFocusTraversalPolicy");6667/**68* This constant is used when the forward focus traversal order is active.69*/70private final int FORWARD_TRAVERSAL = 0;7172/**73* This constant is used when the backward focus traversal order is active.74*/75private final int BACKWARD_TRAVERSAL = 1;7677/**78* Use serialVersionUID from JDK 1.4 for interoperability.79*/80@Serial81private static final long serialVersionUID = 486933713763926351L;8283/**84* Whether this {@code ContainerOrderFocusTraversalPolicy} transfers focus85* down-cycle implicitly.86*/87private boolean implicitDownCycleTraversal = true;8889/**90* Used by getComponentAfter and getComponentBefore for efficiency. In91* order to maintain compliance with the specification of92* FocusTraversalPolicy, if traversal wraps, we should invoke93* getFirstComponent or getLastComponent. These methods may be overriden in94* subclasses to behave in a non-generic way. However, in the generic case,95* these methods will simply return the first or last Components of the96* sorted list, respectively. Since getComponentAfter and97* getComponentBefore have already built the list before determining98* that they need to invoke getFirstComponent or getLastComponent, the99* list should be reused if possible.100*/101private transient Container cachedRoot;102private transient List<Component> cachedCycle;103104/**105* Constructs a {@code ContainerOrderFocusTraversalPolicy}.106*/107public ContainerOrderFocusTraversalPolicy() {}108109/*110* We suppose to use getFocusTraversalCycle & getComponentIndex methods in order111* to divide the policy into two parts:112* 1) Making the focus traversal cycle.113* 2) Traversing the cycle.114* The 1st point assumes producing a list of components representing the focus115* traversal cycle. The two methods mentioned above should implement this logic.116* The 2nd point assumes implementing the common concepts of operating on the117* cycle: traversing back and forth, retrieving the initial/default/first/last118* component. These concepts are described in the AWT Focus Spec and they are119* applied to the FocusTraversalPolicy in general.120* Thus, a descendant of this policy may wish to not reimplement the logic of121* the 2nd point but just override the implementation of the 1st one.122* A striking example of such a descendant is the javax.swing.SortingFocusTraversalPolicy.123*/124/*protected*/ private List<Component> getFocusTraversalCycle(Container aContainer) {125List<Component> cycle = new ArrayList<Component>();126enumerateCycle(aContainer, cycle);127return cycle;128}129/*protected*/ private int getComponentIndex(List<Component> cycle, Component aComponent) {130return cycle.indexOf(aComponent);131}132133private void enumerateCycle(Container container, List<Component> cycle) {134if (!(container.isVisible() && container.isDisplayable())) {135return;136}137138cycle.add(container);139140Component[] components = container.getComponents();141for (int i = 0; i < components.length; i++) {142Component comp = components[i];143if (comp instanceof Container) {144Container cont = (Container)comp;145146if (!cont.isFocusCycleRoot() && !cont.isFocusTraversalPolicyProvider()) {147enumerateCycle(cont, cycle);148continue;149}150}151cycle.add(comp);152}153}154155private Container getTopmostProvider(Container focusCycleRoot, Component aComponent) {156Container aCont = aComponent.getParent();157Container ftp = null;158while (aCont != focusCycleRoot && aCont != null) {159if (aCont.isFocusTraversalPolicyProvider()) {160ftp = aCont;161}162aCont = aCont.getParent();163}164if (aCont == null) {165return null;166}167return ftp;168}169170/*171* Checks if a new focus cycle takes place and returns a Component to traverse focus to.172* @param comp a possible focus cycle root or policy provider173* @param traversalDirection the direction of the traversal174* @return a Component to traverse focus to if {@code comp} is a root or provider175* and implicit down-cycle is set, otherwise {@code null}176*/177private Component getComponentDownCycle(Component comp, int traversalDirection) {178Component retComp = null;179180if (comp instanceof Container) {181Container cont = (Container)comp;182183if (cont.isFocusCycleRoot()) {184if (getImplicitDownCycleTraversal()) {185retComp = cont.getFocusTraversalPolicy().getDefaultComponent(cont);186187if (retComp != null && log.isLoggable(PlatformLogger.Level.FINE)) {188log.fine("### Transferred focus down-cycle to " + retComp +189" in the focus cycle root " + cont);190}191} else {192return null;193}194} else if (cont.isFocusTraversalPolicyProvider()) {195retComp = (traversalDirection == FORWARD_TRAVERSAL ?196cont.getFocusTraversalPolicy().getDefaultComponent(cont) :197cont.getFocusTraversalPolicy().getLastComponent(cont));198199if (retComp != null && log.isLoggable(PlatformLogger.Level.FINE)) {200log.fine("### Transferred focus to " + retComp + " in the FTP provider " + cont);201}202}203}204return retComp;205}206207/**208* Returns the Component that should receive the focus after aComponent.209* aContainer must be a focus cycle root of aComponent or a focus traversal policy provider.210* <p>211* By default, ContainerOrderFocusTraversalPolicy implicitly transfers212* focus down-cycle. That is, during normal forward focus traversal, the213* Component traversed after a focus cycle root will be the focus-cycle-214* root's default Component to focus. This behavior can be disabled using215* the {@code setImplicitDownCycleTraversal} method.216* <p>217* If aContainer is <a href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus218* traversal policy provider</a>, the focus is always transferred down-cycle.219*220* @param aContainer a focus cycle root of aComponent or a focus traversal policy provider221* @param aComponent a (possibly indirect) child of aContainer, or222* aContainer itself223* @return the Component that should receive the focus after aComponent, or224* null if no suitable Component can be found225* @throws IllegalArgumentException if aContainer is not a focus cycle226* root of aComponent or focus traversal policy provider, or if either aContainer or227* aComponent is null228*/229public Component getComponentAfter(Container aContainer, Component aComponent) {230if (log.isLoggable(PlatformLogger.Level.FINE)) {231log.fine("### Searching in " + aContainer + " for component after " + aComponent);232}233234if (aContainer == null || aComponent == null) {235throw new IllegalArgumentException("aContainer and aComponent cannot be null");236}237if (!aContainer.isFocusTraversalPolicyProvider() && !aContainer.isFocusCycleRoot()) {238throw new IllegalArgumentException("aContainer should be focus cycle root or focus traversal policy provider");239240} else if (aContainer.isFocusCycleRoot() && !aComponent.isFocusCycleRoot(aContainer)) {241throw new IllegalArgumentException("aContainer is not a focus cycle root of aComponent");242}243244synchronized(aContainer.getTreeLock()) {245246if (!(aContainer.isVisible() && aContainer.isDisplayable())) {247return null;248}249250// Before all the checks below we first see if it's an FTP provider or a focus cycle root.251// If it's the case just go down cycle (if it's set to "implicit").252Component comp = getComponentDownCycle(aComponent, FORWARD_TRAVERSAL);253// Check if aComponent is focus-cycle-root's default Component, i.e.254// focus cycle root & focus-cycle-root's default Component is same.255if (comp != null && comp != aComponent) {256return comp;257}258259// See if the component is inside of policy provider.260Container provider = getTopmostProvider(aContainer, aComponent);261if (provider != null) {262if (log.isLoggable(PlatformLogger.Level.FINE)) {263log.fine("### Asking FTP " + provider + " for component after " + aComponent);264}265266// FTP knows how to find component after the given. We don't.267FocusTraversalPolicy policy = provider.getFocusTraversalPolicy();268Component afterComp = policy.getComponentAfter(provider, aComponent);269270// Null result means that we overstepped the limit of the FTP's cycle.271// In that case we must quit the cycle, otherwise return the component found.272if (afterComp != null) {273if (log.isLoggable(PlatformLogger.Level.FINE)) {274log.fine("### FTP returned " + afterComp);275}276return afterComp;277}278aComponent = provider;279}280281List<Component> cycle = getFocusTraversalCycle(aContainer);282283if (log.isLoggable(PlatformLogger.Level.FINE)) {284log.fine("### Cycle is " + cycle + ", component is " + aComponent);285}286287int index = getComponentIndex(cycle, aComponent);288289if (index < 0) {290if (log.isLoggable(PlatformLogger.Level.FINE)) {291log.fine("### Didn't find component " + aComponent + " in a cycle " + aContainer);292}293return getFirstComponent(aContainer);294}295296for (index++; index < cycle.size(); index++) {297comp = cycle.get(index);298if (accept(comp)) {299return comp;300} else if ((comp = getComponentDownCycle(comp, FORWARD_TRAVERSAL)) != null) {301return comp;302}303}304305if (aContainer.isFocusCycleRoot()) {306this.cachedRoot = aContainer;307this.cachedCycle = cycle;308309comp = getFirstComponent(aContainer);310311this.cachedRoot = null;312this.cachedCycle = null;313314return comp;315}316}317return null;318}319320/**321* Returns the Component that should receive the focus before aComponent.322* aContainer must be a focus cycle root of aComponent or a <a323* href="doc-files/FocusSpec.html#FocusTraversalPolicyProviders">focus traversal policy324* provider</a>.325*326* @param aContainer a focus cycle root of aComponent or focus traversal policy provider327* @param aComponent a (possibly indirect) child of aContainer, or328* aContainer itself329* @return the Component that should receive the focus before aComponent,330* or null if no suitable Component can be found331* @throws IllegalArgumentException if aContainer is not a focus cycle332* root of aComponent or focus traversal policy provider, or if either aContainer or333* aComponent is null334*/335public Component getComponentBefore(Container aContainer, Component aComponent) {336if (aContainer == null || aComponent == null) {337throw new IllegalArgumentException("aContainer and aComponent cannot be null");338}339if (!aContainer.isFocusTraversalPolicyProvider() && !aContainer.isFocusCycleRoot()) {340throw new IllegalArgumentException("aContainer should be focus cycle root or focus traversal policy provider");341342} else if (aContainer.isFocusCycleRoot() && !aComponent.isFocusCycleRoot(aContainer)) {343throw new IllegalArgumentException("aContainer is not a focus cycle root of aComponent");344}345346synchronized(aContainer.getTreeLock()) {347348if (!(aContainer.isVisible() && aContainer.isDisplayable())) {349return null;350}351352// See if the component is inside of policy provider.353Container provider = getTopmostProvider(aContainer, aComponent);354if (provider != null) {355if (log.isLoggable(PlatformLogger.Level.FINE)) {356log.fine("### Asking FTP " + provider + " for component after " + aComponent);357}358359// FTP knows how to find component after the given. We don't.360FocusTraversalPolicy policy = provider.getFocusTraversalPolicy();361Component beforeComp = policy.getComponentBefore(provider, aComponent);362363// Null result means that we overstepped the limit of the FTP's cycle.364// In that case we must quit the cycle, otherwise return the component found.365if (beforeComp != null) {366if (log.isLoggable(PlatformLogger.Level.FINE)) {367log.fine("### FTP returned " + beforeComp);368}369return beforeComp;370}371aComponent = provider;372373// If the provider is traversable it's returned.374if (accept(aComponent)) {375return aComponent;376}377}378379List<Component> cycle = getFocusTraversalCycle(aContainer);380381if (log.isLoggable(PlatformLogger.Level.FINE)) {382log.fine("### Cycle is " + cycle + ", component is " + aComponent);383}384385int index = getComponentIndex(cycle, aComponent);386387if (index < 0) {388if (log.isLoggable(PlatformLogger.Level.FINE)) {389log.fine("### Didn't find component " + aComponent + " in a cycle " + aContainer);390}391return getLastComponent(aContainer);392}393394Component comp = null;395Component tryComp = null;396397for (index--; index>=0; index--) {398comp = cycle.get(index);399if (comp != aContainer && (tryComp = getComponentDownCycle(comp, BACKWARD_TRAVERSAL)) != null) {400return tryComp;401} else if (accept(comp)) {402return comp;403}404}405406if (aContainer.isFocusCycleRoot()) {407this.cachedRoot = aContainer;408this.cachedCycle = cycle;409410comp = getLastComponent(aContainer);411412this.cachedRoot = null;413this.cachedCycle = null;414415return comp;416}417}418return null;419}420421/**422* Returns the first Component in the traversal cycle. This method is used423* to determine the next Component to focus when traversal wraps in the424* forward direction.425*426* @param aContainer the focus cycle root or focus traversal policy provider whose first427* Component is to be returned428* @return the first Component in the traversal cycle of aContainer,429* or null if no suitable Component can be found430* @throws IllegalArgumentException if aContainer is null431*/432public Component getFirstComponent(Container aContainer) {433List<Component> cycle;434435if (log.isLoggable(PlatformLogger.Level.FINE)) {436log.fine("### Getting first component in " + aContainer);437}438if (aContainer == null) {439throw new IllegalArgumentException("aContainer cannot be null");440441}442443synchronized(aContainer.getTreeLock()) {444445if (!(aContainer.isVisible() && aContainer.isDisplayable())) {446return null;447}448449if (this.cachedRoot == aContainer) {450cycle = this.cachedCycle;451} else {452cycle = getFocusTraversalCycle(aContainer);453}454455if (cycle.size() == 0) {456if (log.isLoggable(PlatformLogger.Level.FINE)) {457log.fine("### Cycle is empty");458}459return null;460}461if (log.isLoggable(PlatformLogger.Level.FINE)) {462log.fine("### Cycle is " + cycle);463}464465for (Component comp : cycle) {466if (accept(comp)) {467return comp;468} else if (comp != aContainer &&469(comp = getComponentDownCycle(comp, FORWARD_TRAVERSAL)) != null)470{471return comp;472}473}474}475return null;476}477478/**479* Returns the last Component in the traversal cycle. This method is used480* to determine the next Component to focus when traversal wraps in the481* reverse direction.482*483* @param aContainer the focus cycle root or focus traversal policy provider whose last484* Component is to be returned485* @return the last Component in the traversal cycle of aContainer,486* or null if no suitable Component can be found487* @throws IllegalArgumentException if aContainer is null488*/489public Component getLastComponent(Container aContainer) {490List<Component> cycle;491if (log.isLoggable(PlatformLogger.Level.FINE)) {492log.fine("### Getting last component in " + aContainer);493}494495if (aContainer == null) {496throw new IllegalArgumentException("aContainer cannot be null");497}498499synchronized(aContainer.getTreeLock()) {500501if (!(aContainer.isVisible() && aContainer.isDisplayable())) {502return null;503}504505if (this.cachedRoot == aContainer) {506cycle = this.cachedCycle;507} else {508cycle = getFocusTraversalCycle(aContainer);509}510511if (cycle.size() == 0) {512if (log.isLoggable(PlatformLogger.Level.FINE)) {513log.fine("### Cycle is empty");514}515return null;516}517if (log.isLoggable(PlatformLogger.Level.FINE)) {518log.fine("### Cycle is " + cycle);519}520521for (int i= cycle.size() - 1; i >= 0; i--) {522Component comp = cycle.get(i);523if (accept(comp)) {524return comp;525} else if (comp instanceof Container && comp != aContainer) {526Container cont = (Container)comp;527if (cont.isFocusTraversalPolicyProvider()) {528Component retComp = cont.getFocusTraversalPolicy().getLastComponent(cont);529if (retComp != null) {530return retComp;531}532}533}534}535}536return null;537}538539/**540* Returns the default Component to focus. This Component will be the first541* to receive focus when traversing down into a new focus traversal cycle542* rooted at aContainer. The default implementation of this method543* returns the same Component as {@code getFirstComponent}.544*545* @param aContainer the focus cycle root or focus traversal policy provider whose default546* Component is to be returned547* @return the default Component in the traversal cycle of aContainer,548* or null if no suitable Component can be found549* @see #getFirstComponent550* @throws IllegalArgumentException if aContainer is null551*/552public Component getDefaultComponent(Container aContainer) {553return getFirstComponent(aContainer);554}555556/**557* Sets whether this ContainerOrderFocusTraversalPolicy transfers focus558* down-cycle implicitly. If {@code true}, during normal forward focus559* traversal, the Component traversed after a focus cycle root will be the560* focus-cycle-root's default Component to focus. If {@code false},561* the next Component in the focus traversal cycle rooted at the specified562* focus cycle root will be traversed instead. The default value for this563* property is {@code true}.564*565* @param implicitDownCycleTraversal whether this566* ContainerOrderFocusTraversalPolicy transfers focus down-cycle567* implicitly568* @see #getImplicitDownCycleTraversal569* @see #getFirstComponent570*/571public void setImplicitDownCycleTraversal(boolean implicitDownCycleTraversal) {572this.implicitDownCycleTraversal = implicitDownCycleTraversal;573}574575/**576* Returns whether this ContainerOrderFocusTraversalPolicy transfers focus577* down-cycle implicitly. If {@code true}, during normal forward focus578* traversal, the Component traversed after a focus cycle root will be the579* focus-cycle-root's default Component to focus. If {@code false},580* the next Component in the focus traversal cycle rooted at the specified581* focus cycle root will be traversed instead.582*583* @return whether this ContainerOrderFocusTraversalPolicy transfers focus584* down-cycle implicitly585* @see #setImplicitDownCycleTraversal586* @see #getFirstComponent587*/588public boolean getImplicitDownCycleTraversal() {589return implicitDownCycleTraversal;590}591592/**593* Determines whether a Component is an acceptable choice as the new594* focus owner. By default, this method will accept a Component if and595* only if it is visible, displayable, enabled, and focusable.596*597* @param aComponent the Component whose fitness as a focus owner is to598* be tested599* @return {@code true} if aComponent is visible, displayable,600* enabled, and focusable; {@code false} otherwise601*/602protected boolean accept(Component aComponent) {603if (!aComponent.canBeFocusOwner()) {604return false;605}606607// Verify that the Component is recursively enabled. Disabling a608// heavyweight Container disables its children, whereas disabling609// a lightweight Container does not.610if (!(aComponent instanceof Window)) {611for (Container enableTest = aComponent.getParent();612enableTest != null;613enableTest = enableTest.getParent())614{615if (!(enableTest.isEnabled() || enableTest.isLightweight())) {616return false;617}618if (enableTest instanceof Window) {619break;620}621}622}623624return true;625}626}627628629