1 /*
   2  * Copyright (c) 2000, 2017, 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.awt.event.FocusEvent;
  28 import java.awt.event.InputEvent;
  29 import java.awt.event.KeyEvent;
  30 import java.awt.event.WindowEvent;
  31 
  32 import java.awt.peer.KeyboardFocusManagerPeer;
  33 import java.awt.peer.LightweightPeer;
  34 
  35 import java.beans.PropertyChangeListener;
  36 import java.beans.PropertyChangeSupport;
  37 import java.beans.PropertyVetoException;
  38 import java.beans.VetoableChangeListener;
  39 import java.beans.VetoableChangeSupport;
  40 
  41 import java.lang.ref.WeakReference;
  42 
  43 import java.security.AccessController;
  44 import java.security.PrivilegedAction;
  45 
  46 import java.util.Collections;
  47 import java.util.HashSet;
  48 import java.util.Iterator;
  49 import java.util.LinkedList;
  50 import java.util.Set;
  51 import java.util.StringTokenizer;
  52 import java.util.WeakHashMap;
  53 
  54 import sun.util.logging.PlatformLogger;
  55 
  56 import sun.awt.AppContext;
  57 import sun.awt.SunToolkit;
  58 import sun.awt.KeyboardFocusManagerPeerProvider;
  59 import sun.awt.AWTAccessor;
  60 
  61 /**
  62  * The KeyboardFocusManager is responsible for managing the active and focused
  63  * Windows, and the current focus owner. The focus owner is defined as the
  64  * Component in an application that will typically receive all KeyEvents
  65  * generated by the user. The focused Window is the Window that is, or
  66  * contains, the focus owner. Only a Frame or a Dialog can be the active
  67  * Window. The native windowing system may denote the active Window or its
  68  * children with special decorations, such as a highlighted title bar. The
  69  * active Window is always either the focused Window, or the first Frame or
  70  * Dialog that is an owner of the focused Window.
  71  * <p>
  72  * The KeyboardFocusManager is both a centralized location for client code to
  73  * query for the focus owner and initiate focus changes, and an event
  74  * dispatcher for all FocusEvents, WindowEvents related to focus, and
  75  * KeyEvents.
  76  * <p>
  77  * Some browsers partition applets in different code bases into separate
  78  * contexts, and establish walls between these contexts. In such a scenario,
  79  * there will be one KeyboardFocusManager per context. Other browsers place all
  80  * applets into the same context, implying that there will be only a single,
  81  * global KeyboardFocusManager for all applets. This behavior is
  82  * implementation-dependent. Consult your browser's documentation for more
  83  * information. No matter how many contexts there may be, however, there can
  84  * never be more than one focus owner, focused Window, or active Window, per
  85  * ClassLoader.
  86  * <p>
  87  * Please see
  88  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
  89  * How to Use the Focus Subsystem</a>,
  90  * a section in <em>The Java Tutorial</em>, and the
  91  * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
  92  * for more information.
  93  *
  94  * @author David Mendenhall
  95  *
  96  * @see Window
  97  * @see Frame
  98  * @see Dialog
  99  * @see java.awt.event.FocusEvent
 100  * @see java.awt.event.WindowEvent
 101  * @see java.awt.event.KeyEvent
 102  * @since 1.4
 103  */
 104 public abstract class KeyboardFocusManager
 105     implements KeyEventDispatcher, KeyEventPostProcessor
 106 {
 107 
 108     // Shared focus engine logger
 109     private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.KeyboardFocusManager");
 110 
 111     static {
 112         /* ensure that the necessary native libraries are loaded */
 113         Toolkit.loadLibraries();
 114         if (!GraphicsEnvironment.isHeadless()) {
 115             initIDs();
 116         }
 117         AWTAccessor.setKeyboardFocusManagerAccessor(
 118             new AWTAccessor.KeyboardFocusManagerAccessor() {
 119                 public int shouldNativelyFocusHeavyweight(Component heavyweight,
 120                                                    Component descendant,
 121                                                    boolean temporary,
 122                                                    boolean focusedWindowChangeAllowed,
 123                                                    long time,
 124                                                    FocusEvent.Cause cause)
 125                 {
 126                     return KeyboardFocusManager.shouldNativelyFocusHeavyweight(
 127                         heavyweight, descendant, temporary, focusedWindowChangeAllowed, time, cause);
 128                 }
 129                 public boolean processSynchronousLightweightTransfer(Component heavyweight,
 130                                                               Component descendant,
 131                                                               boolean temporary,
 132                                                               boolean focusedWindowChangeAllowed,
 133                                                               long time)
 134                 {
 135                     return KeyboardFocusManager.processSynchronousLightweightTransfer(
 136                         heavyweight, descendant, temporary, focusedWindowChangeAllowed, time);
 137                 }
 138                 public void removeLastFocusRequest(Component heavyweight) {
 139                     KeyboardFocusManager.removeLastFocusRequest(heavyweight);
 140                 }
 141                 @Override
 142                 public Component getMostRecentFocusOwner(Window window) {
 143                     return KeyboardFocusManager.getMostRecentFocusOwner(window);
 144                 }
 145                 public void setMostRecentFocusOwner(Window window, Component component) {
 146                     KeyboardFocusManager.setMostRecentFocusOwner(window, component);
 147                 }
 148                 public KeyboardFocusManager getCurrentKeyboardFocusManager(AppContext ctx) {
 149                     return KeyboardFocusManager.getCurrentKeyboardFocusManager(ctx);
 150                 }
 151                 public Container getCurrentFocusCycleRoot() {
 152                     return KeyboardFocusManager.currentFocusCycleRoot;
 153                 }
 154             }
 155         );
 156     }
 157 
 158     transient KeyboardFocusManagerPeer peer;
 159 
 160     /**
 161      * Initialize JNI field and method IDs
 162      */
 163     private static native void initIDs();
 164 
 165     private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.KeyboardFocusManager");
 166 
 167     /**
 168      * The identifier for the Forward focus traversal keys.
 169      *
 170      * @see #setDefaultFocusTraversalKeys
 171      * @see #getDefaultFocusTraversalKeys
 172      * @see Component#setFocusTraversalKeys
 173      * @see Component#getFocusTraversalKeys
 174      */
 175     public static final int FORWARD_TRAVERSAL_KEYS = 0;
 176 
 177     /**
 178      * The identifier for the Backward focus traversal keys.
 179      *
 180      * @see #setDefaultFocusTraversalKeys
 181      * @see #getDefaultFocusTraversalKeys
 182      * @see Component#setFocusTraversalKeys
 183      * @see Component#getFocusTraversalKeys
 184      */
 185     public static final int BACKWARD_TRAVERSAL_KEYS = 1;
 186 
 187     /**
 188      * The identifier for the Up Cycle focus traversal keys.
 189      *
 190      * @see #setDefaultFocusTraversalKeys
 191      * @see #getDefaultFocusTraversalKeys
 192      * @see Component#setFocusTraversalKeys
 193      * @see Component#getFocusTraversalKeys
 194      */
 195     public static final int UP_CYCLE_TRAVERSAL_KEYS = 2;
 196 
 197     /**
 198      * The identifier for the Down Cycle focus traversal keys.
 199      *
 200      * @see #setDefaultFocusTraversalKeys
 201      * @see #getDefaultFocusTraversalKeys
 202      * @see Component#setFocusTraversalKeys
 203      * @see Component#getFocusTraversalKeys
 204      */
 205     public static final int DOWN_CYCLE_TRAVERSAL_KEYS = 3;
 206 
 207     static final int TRAVERSAL_KEY_LENGTH = DOWN_CYCLE_TRAVERSAL_KEYS + 1;
 208 
 209     /**
 210      * Returns the current KeyboardFocusManager instance for the calling
 211      * thread's context.
 212      *
 213      * @return this thread's context's KeyboardFocusManager
 214      * @see #setCurrentKeyboardFocusManager
 215      */
 216     public static KeyboardFocusManager getCurrentKeyboardFocusManager() {
 217         return getCurrentKeyboardFocusManager(AppContext.getAppContext());
 218     }
 219 
 220     static synchronized KeyboardFocusManager
 221         getCurrentKeyboardFocusManager(AppContext appcontext)
 222     {
 223         KeyboardFocusManager manager = (KeyboardFocusManager)
 224             appcontext.get(KeyboardFocusManager.class);
 225         if (manager == null) {
 226             manager = new DefaultKeyboardFocusManager();
 227             appcontext.put(KeyboardFocusManager.class, manager);
 228         }
 229         return manager;
 230     }
 231 
 232     /**
 233      * Sets the current KeyboardFocusManager instance for the calling thread's
 234      * context. If null is specified, then the current KeyboardFocusManager
 235      * is replaced with a new instance of DefaultKeyboardFocusManager.
 236      * <p>
 237      * If a SecurityManager is installed, the calling thread must be granted
 238      * the AWTPermission "replaceKeyboardFocusManager" in order to replace the
 239      * the current KeyboardFocusManager. If this permission is not granted,
 240      * this method will throw a SecurityException, and the current
 241      * KeyboardFocusManager will be unchanged.
 242      *
 243      * @param newManager the new KeyboardFocusManager for this thread's context
 244      * @see #getCurrentKeyboardFocusManager
 245      * @see DefaultKeyboardFocusManager
 246      * @throws SecurityException if the calling thread does not have permission
 247      *         to replace the current KeyboardFocusManager
 248      */
 249     public static void setCurrentKeyboardFocusManager(
 250         KeyboardFocusManager newManager) throws SecurityException
 251     {
 252         checkReplaceKFMPermission();
 253 
 254         KeyboardFocusManager oldManager = null;
 255 
 256         synchronized (KeyboardFocusManager.class) {
 257             AppContext appcontext = AppContext.getAppContext();
 258 
 259             if (newManager != null) {
 260                 oldManager = getCurrentKeyboardFocusManager(appcontext);
 261 
 262                 appcontext.put(KeyboardFocusManager.class, newManager);
 263             } else {
 264                 oldManager = getCurrentKeyboardFocusManager(appcontext);
 265                 appcontext.remove(KeyboardFocusManager.class);
 266             }
 267         }
 268 
 269         if (oldManager != null) {
 270             oldManager.firePropertyChange("managingFocus",
 271                                           Boolean.TRUE,
 272                                           Boolean.FALSE);
 273         }
 274         if (newManager != null) {
 275             newManager.firePropertyChange("managingFocus",
 276                                           Boolean.FALSE,
 277                                           Boolean.TRUE);
 278         }
 279     }
 280 
 281     /**
 282      * The Component in an application that will typically receive all
 283      * KeyEvents generated by the user.
 284      */
 285     private static Component focusOwner;
 286 
 287     /**
 288      * The Component in an application that will regain focus when an
 289      * outstanding temporary focus transfer has completed, or the focus owner,
 290      * if no outstanding temporary transfer exists.
 291      */
 292     private static Component permanentFocusOwner;
 293 
 294     /**
 295      * The Window which is, or contains, the focus owner.
 296      */
 297     private static Window focusedWindow;
 298 
 299     /**
 300      * Only a Frame or a Dialog can be the active Window. The native windowing
 301      * system may denote the active Window with a special decoration, such as a
 302      * highlighted title bar. The active Window is always either the focused
 303      * Window, or the first Frame or Dialog which is an owner of the focused
 304      * Window.
 305      */
 306     private static Window activeWindow;
 307 
 308     /**
 309      * The default FocusTraversalPolicy for all Windows that have no policy of
 310      * their own set. If those Windows have focus-cycle-root children that have
 311      * no keyboard-traversal policy of their own, then those children will also
 312      * inherit this policy (as will, recursively, their focus-cycle-root
 313      * children).
 314      */
 315     private FocusTraversalPolicy defaultPolicy =
 316         new DefaultFocusTraversalPolicy();
 317 
 318     /**
 319      * The bound property names of each focus traversal key.
 320      */
 321     private static final String[] defaultFocusTraversalKeyPropertyNames = {
 322         "forwardDefaultFocusTraversalKeys",
 323         "backwardDefaultFocusTraversalKeys",
 324         "upCycleDefaultFocusTraversalKeys",
 325         "downCycleDefaultFocusTraversalKeys"
 326     };
 327 
 328     /**
 329      * The default focus traversal keys. Each array of traversal keys will be
 330      * in effect on all Windows that have no such array of their own explicitly
 331      * set. Each array will also be inherited, recursively, by any child
 332      * Component of those Windows that has no such array of its own explicitly
 333      * set.
 334      */
 335     @SuppressWarnings({"unchecked", "rawtypes"})
 336     private Set<AWTKeyStroke>[] defaultFocusTraversalKeys = new Set[4];
 337 
 338     /**
 339      * The current focus cycle root. If the focus owner is itself a focus cycle
 340      * root, then it may be ambiguous as to which Components represent the next
 341      * and previous Components to focus during normal focus traversal. In that
 342      * case, the current focus cycle root is used to differentiate among the
 343      * possibilities.
 344      */
 345     private static Container currentFocusCycleRoot;
 346 
 347     /**
 348      * A description of any VetoableChangeListeners which have been registered.
 349      */
 350     private VetoableChangeSupport vetoableSupport;
 351 
 352     /**
 353      * A description of any PropertyChangeListeners which have been registered.
 354      */
 355     private PropertyChangeSupport changeSupport;
 356 
 357     /**
 358      * This KeyboardFocusManager's KeyEventDispatcher chain. The List does not
 359      * include this KeyboardFocusManager unless it was explicitly re-registered
 360      * via a call to {@code addKeyEventDispatcher}. If no other
 361      * KeyEventDispatchers are registered, this field may be null or refer to
 362      * a List of length 0.
 363      */
 364     private java.util.LinkedList<KeyEventDispatcher> keyEventDispatchers;
 365 
 366     /**
 367      * This KeyboardFocusManager's KeyEventPostProcessor chain. The List does
 368      * not include this KeyboardFocusManager unless it was explicitly
 369      * re-registered via a call to {@code addKeyEventPostProcessor}.
 370      * If no other KeyEventPostProcessors are registered, this field may be
 371      * null or refer to a List of length 0.
 372      */
 373     private java.util.LinkedList<KeyEventPostProcessor> keyEventPostProcessors;
 374 
 375     /**
 376      * Maps Windows to those Windows' most recent focus owners.
 377      */
 378     private static java.util.Map<Window, WeakReference<Component>> mostRecentFocusOwners = new WeakHashMap<>();
 379 
 380     /**
 381      * We cache the permission used to verify that the calling thread is
 382      * permitted to access the global focus state.
 383      */
 384     private static AWTPermission replaceKeyboardFocusManagerPermission;
 385 
 386     /*
 387      * SequencedEvent which is currently dispatched in AppContext.
 388      */
 389     transient SequencedEvent currentSequencedEvent = null;
 390 
 391     final void setCurrentSequencedEvent(SequencedEvent current) {
 392         synchronized (SequencedEvent.class) {
 393             assert(current == null || currentSequencedEvent == null);
 394             currentSequencedEvent = current;
 395         }
 396     }
 397 
 398     final SequencedEvent getCurrentSequencedEvent() {
 399         synchronized (SequencedEvent.class) {
 400             return currentSequencedEvent;
 401         }
 402     }
 403 
 404     static Set<AWTKeyStroke> initFocusTraversalKeysSet(String value, Set<AWTKeyStroke> targetSet) {
 405         StringTokenizer tokens = new StringTokenizer(value, ",");
 406         while (tokens.hasMoreTokens()) {
 407             targetSet.add(AWTKeyStroke.getAWTKeyStroke(tokens.nextToken()));
 408         }
 409         return (targetSet.isEmpty())
 410             ? Collections.emptySet()
 411             : Collections.unmodifiableSet(targetSet);
 412     }
 413 
 414     /**
 415      * Initializes a KeyboardFocusManager.
 416      */
 417     public KeyboardFocusManager() {
 418         @SuppressWarnings("deprecation")
 419         AWTKeyStroke[][] defaultFocusTraversalKeyStrokes = {
 420                 {
 421                         AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0, false),
 422                         AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,
 423                                 InputEvent.CTRL_DOWN_MASK |
 424                                         InputEvent.CTRL_MASK, false),
 425                 },
 426                 {
 427                         AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,
 428                                 InputEvent.SHIFT_DOWN_MASK |
 429                                         InputEvent.SHIFT_MASK, false),
 430                         AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,
 431                                 InputEvent.SHIFT_DOWN_MASK |
 432                                         InputEvent.SHIFT_MASK |
 433                                         InputEvent.CTRL_DOWN_MASK |
 434                                         InputEvent.CTRL_MASK,
 435                                 false),
 436                 },
 437                 {},
 438                 {},
 439         };
 440         for (int i = 0; i < TRAVERSAL_KEY_LENGTH; i++) {
 441             Set<AWTKeyStroke> work_set = new HashSet<>();
 442             for (int j = 0; j < defaultFocusTraversalKeyStrokes[i].length; j++) {
 443                 work_set.add(defaultFocusTraversalKeyStrokes[i][j]);
 444             }
 445             defaultFocusTraversalKeys[i] = (work_set.isEmpty())
 446                 ? Collections.emptySet()
 447                 : Collections.unmodifiableSet(work_set);
 448         }
 449         initPeer();
 450     }
 451 
 452     private void initPeer() {
 453         Toolkit tk = Toolkit.getDefaultToolkit();
 454         KeyboardFocusManagerPeerProvider peerProvider = (KeyboardFocusManagerPeerProvider)tk;
 455         peer = peerProvider.getKeyboardFocusManagerPeer();
 456     }
 457 
 458     /**
 459      * Returns the focus owner, if the focus owner is in the same context as
 460      * the calling thread. The focus owner is defined as the Component in an
 461      * application that will typically receive all KeyEvents generated by the
 462      * user. KeyEvents which map to the focus owner's focus traversal keys will
 463      * not be delivered if focus traversal keys are enabled for the focus
 464      * owner. In addition, KeyEventDispatchers may retarget or consume
 465      * KeyEvents before they reach the focus owner.
 466      *
 467      * @return the focus owner, or null if the focus owner is not a member of
 468      *         the calling thread's context
 469      * @see #getGlobalFocusOwner
 470      * @see #setGlobalFocusOwner
 471      */
 472     public Component getFocusOwner() {
 473         synchronized (KeyboardFocusManager.class) {
 474             if (focusOwner == null) {
 475                 return null;
 476             }
 477 
 478             return (focusOwner.appContext == AppContext.getAppContext())
 479                 ? focusOwner
 480                 : null;
 481         }
 482     }
 483 
 484     /**
 485      * Returns the focus owner, even if the calling thread is in a different
 486      * context than the focus owner. The focus owner is defined as the
 487      * Component in an application that will typically receive all KeyEvents
 488      * generated by the user. KeyEvents which map to the focus owner's focus
 489      * traversal keys will not be delivered if focus traversal keys are enabled
 490      * for the focus owner. In addition, KeyEventDispatchers may retarget or
 491      * consume KeyEvents before they reach the focus owner.
 492      * <p>
 493      * This method will throw a SecurityException if this KeyboardFocusManager
 494      * is not the current KeyboardFocusManager for the calling thread's
 495      * context.
 496      *
 497      * @return the focus owner
 498      * @see #getFocusOwner
 499      * @see #setGlobalFocusOwner
 500      * @throws SecurityException if this KeyboardFocusManager is not the
 501      *         current KeyboardFocusManager for the calling thread's context
 502      *         and if the calling thread does not have "replaceKeyboardFocusManager"
 503      *         permission
 504      */
 505     protected Component getGlobalFocusOwner() throws SecurityException {
 506         synchronized (KeyboardFocusManager.class) {
 507             checkKFMSecurity();
 508             return focusOwner;
 509         }
 510     }
 511 
 512     /**
 513      * Sets the focus owner. The operation will be cancelled if the Component
 514      * is not focusable. The focus owner is defined as the Component in an
 515      * application that will typically receive all KeyEvents generated by the
 516      * user. KeyEvents which map to the focus owner's focus traversal keys will
 517      * not be delivered if focus traversal keys are enabled for the focus
 518      * owner. In addition, KeyEventDispatchers may retarget or consume
 519      * KeyEvents before they reach the focus owner.
 520      * <p>
 521      * This method does not actually set the focus to the specified Component.
 522      * It merely stores the value to be subsequently returned by
 523      * {@code getFocusOwner()}. Use {@code Component.requestFocus()}
 524      * or {@code Component.requestFocusInWindow()} to change the focus
 525      * owner, subject to platform limitations.
 526      *
 527      * @param focusOwner the focus owner
 528      * @see #getFocusOwner
 529      * @see #getGlobalFocusOwner
 530      * @see Component#requestFocus()
 531      * @see Component#requestFocusInWindow()
 532      * @see Component#isFocusable
 533      * @throws SecurityException if this KeyboardFocusManager is not the
 534      *         current KeyboardFocusManager for the calling thread's context
 535      *         and if the calling thread does not have "replaceKeyboardFocusManager"
 536      *         permission
 537      */
 538     protected void setGlobalFocusOwner(Component focusOwner)
 539         throws SecurityException
 540     {
 541         Component oldFocusOwner = null;
 542         boolean shouldFire = false;
 543 
 544         if (focusOwner == null || focusOwner.isFocusable()) {
 545             synchronized (KeyboardFocusManager.class) {
 546                 checkKFMSecurity();
 547 
 548                 oldFocusOwner = getFocusOwner();
 549 
 550                 try {
 551                     fireVetoableChange("focusOwner", oldFocusOwner,
 552                                        focusOwner);
 553                 } catch (PropertyVetoException e) {
 554                     // rejected
 555                     return;
 556                 }
 557 
 558                 KeyboardFocusManager.focusOwner = focusOwner;
 559 
 560                 if (focusOwner != null &&
 561                     (getCurrentFocusCycleRoot() == null ||
 562                      !focusOwner.isFocusCycleRoot(getCurrentFocusCycleRoot())))
 563                 {
 564                     Container rootAncestor =
 565                         focusOwner.getFocusCycleRootAncestor();
 566                     if (rootAncestor == null && (focusOwner instanceof Window))
 567                     {
 568                         rootAncestor = (Container)focusOwner;
 569                     }
 570                     if (rootAncestor != null) {
 571                         setGlobalCurrentFocusCycleRootPriv(rootAncestor);
 572                     }
 573                 }
 574 
 575                 shouldFire = true;
 576             }
 577         }
 578 
 579         if (shouldFire) {
 580             firePropertyChange("focusOwner", oldFocusOwner, focusOwner);
 581         }
 582     }
 583 
 584     /**
 585      * Clears the focus owner at both the Java and native levels if the
 586      * focus owner exists and resides in the same context as the calling thread,
 587      * otherwise the method returns silently.
 588      * <p>
 589      * The focus owner component will receive a permanent FOCUS_LOST event.
 590      * After this operation completes, the native windowing system will discard
 591      * all user-generated KeyEvents until the user selects a new Component to
 592      * receive focus, or a Component is given focus explicitly via a call to
 593      * {@code requestFocus()}. This operation does not change the focused or
 594      * active Windows.
 595      *
 596      * @see Component#requestFocus()
 597      * @see java.awt.event.FocusEvent#FOCUS_LOST
 598      * @since 1.8
 599      */
 600     public void clearFocusOwner() {
 601         if (getFocusOwner() != null) {
 602             clearGlobalFocusOwner();
 603         }
 604     }
 605 
 606     /**
 607      * Clears the global focus owner at both the Java and native levels. If
 608      * there exists a focus owner, that Component will receive a permanent
 609      * FOCUS_LOST event. After this operation completes, the native windowing
 610      * system will discard all user-generated KeyEvents until the user selects
 611      * a new Component to receive focus, or a Component is given focus
 612      * explicitly via a call to {@code requestFocus()}. This operation
 613      * does not change the focused or active Windows.
 614      * <p>
 615      * If a SecurityManager is installed, the calling thread must be granted
 616      * the "replaceKeyboardFocusManager" AWTPermission. If this permission is
 617      * not granted, this method will throw a SecurityException, and the current
 618      * focus owner will not be cleared.
 619      * <p>
 620      * This method is intended to be used only by KeyboardFocusManager set as
 621      * current KeyboardFocusManager for the calling thread's context. It is not
 622      * for general client use.
 623      *
 624      * @see KeyboardFocusManager#clearFocusOwner
 625      * @see Component#requestFocus()
 626      * @see java.awt.event.FocusEvent#FOCUS_LOST
 627      * @throws SecurityException if the calling thread does not have
 628      *         "replaceKeyboardFocusManager" permission
 629      */
 630     public void clearGlobalFocusOwner()
 631         throws SecurityException
 632     {
 633         checkReplaceKFMPermission();
 634         if (!GraphicsEnvironment.isHeadless()) {
 635             // Toolkit must be fully initialized, otherwise
 636             // _clearGlobalFocusOwner will crash or throw an exception
 637             Toolkit.getDefaultToolkit();
 638 
 639             _clearGlobalFocusOwner();
 640         }
 641     }
 642     private void _clearGlobalFocusOwner() {
 643         Window activeWindow = markClearGlobalFocusOwner();
 644         peer.clearGlobalFocusOwner(activeWindow);
 645     }
 646 
 647     void clearGlobalFocusOwnerPriv() {
 648         AccessController.doPrivileged(new PrivilegedAction<Void>() {
 649             public Void run() {
 650                 clearGlobalFocusOwner();
 651                 return null;
 652             }
 653         });
 654     }
 655 
 656     Component getNativeFocusOwner() {
 657         return peer.getCurrentFocusOwner();
 658     }
 659 
 660     void setNativeFocusOwner(Component comp) {
 661         if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
 662             focusLog.finest("Calling peer {0} setCurrentFocusOwner for {1}",
 663                             String.valueOf(peer), String.valueOf(comp));
 664         }
 665         peer.setCurrentFocusOwner(comp);
 666     }
 667 
 668     Window getNativeFocusedWindow() {
 669         return peer.getCurrentFocusedWindow();
 670     }
 671 
 672     /**
 673      * Returns the permanent focus owner, if the permanent focus owner is in
 674      * the same context as the calling thread. The permanent focus owner is
 675      * defined as the last Component in an application to receive a permanent
 676      * FOCUS_GAINED event. The focus owner and permanent focus owner are
 677      * equivalent unless a temporary focus change is currently in effect. In
 678      * such a situation, the permanent focus owner will again be the focus
 679      * owner when the temporary focus change ends.
 680      *
 681      * @return the permanent focus owner, or null if the permanent focus owner
 682      *         is not a member of the calling thread's context
 683      * @see #getGlobalPermanentFocusOwner
 684      * @see #setGlobalPermanentFocusOwner
 685      */
 686     public Component getPermanentFocusOwner() {
 687         synchronized (KeyboardFocusManager.class) {
 688             if (permanentFocusOwner == null) {
 689                 return null;
 690             }
 691 
 692             return (permanentFocusOwner.appContext ==
 693                     AppContext.getAppContext())
 694                 ? permanentFocusOwner
 695                 : null;
 696         }
 697     }
 698 
 699     /**
 700      * Returns the permanent focus owner, even if the calling thread is in a
 701      * different context than the permanent focus owner. The permanent focus
 702      * owner is defined as the last Component in an application to receive a
 703      * permanent FOCUS_GAINED event. The focus owner and permanent focus owner
 704      * are equivalent unless a temporary focus change is currently in effect.
 705      * In such a situation, the permanent focus owner will again be the focus
 706      * owner when the temporary focus change ends.
 707      *
 708      * @return the permanent focus owner
 709      * @see #getPermanentFocusOwner
 710      * @see #setGlobalPermanentFocusOwner
 711      * @throws SecurityException if this KeyboardFocusManager is not the
 712      *         current KeyboardFocusManager for the calling thread's context
 713      *         and if the calling thread does not have "replaceKeyboardFocusManager"
 714      *         permission
 715      */
 716     protected Component getGlobalPermanentFocusOwner()
 717         throws SecurityException
 718     {
 719         synchronized (KeyboardFocusManager.class) {
 720             checkKFMSecurity();
 721             return permanentFocusOwner;
 722         }
 723     }
 724 
 725     /**
 726      * Sets the permanent focus owner. The operation will be cancelled if the
 727      * Component is not focusable. The permanent focus owner is defined as the
 728      * last Component in an application to receive a permanent FOCUS_GAINED
 729      * event. The focus owner and permanent focus owner are equivalent unless
 730      * a temporary focus change is currently in effect. In such a situation,
 731      * the permanent focus owner will again be the focus owner when the
 732      * temporary focus change ends.
 733      * <p>
 734      * This method does not actually set the focus to the specified Component.
 735      * It merely stores the value to be subsequently returned by
 736      * {@code getPermanentFocusOwner()}. Use
 737      * {@code Component.requestFocus()} or
 738      * {@code Component.requestFocusInWindow()} to change the focus owner,
 739      * subject to platform limitations.
 740      *
 741      * @param permanentFocusOwner the permanent focus owner
 742      * @see #getPermanentFocusOwner
 743      * @see #getGlobalPermanentFocusOwner
 744      * @see Component#requestFocus()
 745      * @see Component#requestFocusInWindow()
 746      * @see Component#isFocusable
 747      * @throws SecurityException if this KeyboardFocusManager is not the
 748      *         current KeyboardFocusManager for the calling thread's context
 749      *         and if the calling thread does not have "replaceKeyboardFocusManager"
 750      *         permission
 751      */
 752     protected void setGlobalPermanentFocusOwner(Component permanentFocusOwner)
 753         throws SecurityException
 754     {
 755         Component oldPermanentFocusOwner = null;
 756         boolean shouldFire = false;
 757 
 758         if (permanentFocusOwner == null || permanentFocusOwner.isFocusable()) {
 759             synchronized (KeyboardFocusManager.class) {
 760                 checkKFMSecurity();
 761 
 762                 oldPermanentFocusOwner = getPermanentFocusOwner();
 763 
 764                 try {
 765                     fireVetoableChange("permanentFocusOwner",
 766                                        oldPermanentFocusOwner,
 767                                        permanentFocusOwner);
 768                 } catch (PropertyVetoException e) {
 769                     // rejected
 770                     return;
 771                 }
 772 
 773                 KeyboardFocusManager.permanentFocusOwner = permanentFocusOwner;
 774 
 775                 KeyboardFocusManager.
 776                     setMostRecentFocusOwner(permanentFocusOwner);
 777 
 778                 shouldFire = true;
 779             }
 780         }
 781 
 782         if (shouldFire) {
 783             firePropertyChange("permanentFocusOwner", oldPermanentFocusOwner,
 784                                permanentFocusOwner);
 785         }
 786     }
 787 
 788     /**
 789      * Returns the focused Window, if the focused Window is in the same context
 790      * as the calling thread. The focused Window is the Window that is or
 791      * contains the focus owner.
 792      *
 793      * @return the focused Window, or null if the focused Window is not a
 794      *         member of the calling thread's context
 795      * @see #getGlobalFocusedWindow
 796      * @see #setGlobalFocusedWindow
 797      */
 798     public Window getFocusedWindow() {
 799         synchronized (KeyboardFocusManager.class) {
 800             if (focusedWindow == null) {
 801                 return null;
 802             }
 803 
 804             return (focusedWindow.appContext == AppContext.getAppContext())
 805                 ? focusedWindow
 806                 : null;
 807         }
 808     }
 809 
 810     /**
 811      * Returns the focused Window, even if the calling thread is in a different
 812      * context than the focused Window. The focused Window is the Window that
 813      * is or contains the focus owner.
 814      *
 815      * @return the focused Window
 816      * @see #getFocusedWindow
 817      * @see #setGlobalFocusedWindow
 818      * @throws SecurityException if this KeyboardFocusManager is not the
 819      *         current KeyboardFocusManager for the calling thread's context
 820      *         and if the calling thread does not have "replaceKeyboardFocusManager"
 821      *         permission
 822      */
 823     protected Window getGlobalFocusedWindow() throws SecurityException {
 824         synchronized (KeyboardFocusManager.class) {
 825             checkKFMSecurity();
 826             return focusedWindow;
 827         }
 828     }
 829 
 830     /**
 831      * Sets the focused Window. The focused Window is the Window that is or
 832      * contains the focus owner. The operation will be cancelled if the
 833      * specified Window to focus is not a focusable Window.
 834      * <p>
 835      * This method does not actually change the focused Window as far as the
 836      * native windowing system is concerned. It merely stores the value to be
 837      * subsequently returned by {@code getFocusedWindow()}. Use
 838      * {@code Component.requestFocus()} or
 839      * {@code Component.requestFocusInWindow()} to change the focused
 840      * Window, subject to platform limitations.
 841      *
 842      * @param focusedWindow the focused Window
 843      * @see #getFocusedWindow
 844      * @see #getGlobalFocusedWindow
 845      * @see Component#requestFocus()
 846      * @see Component#requestFocusInWindow()
 847      * @see Window#isFocusableWindow
 848      * @throws SecurityException if this KeyboardFocusManager is not the
 849      *         current KeyboardFocusManager for the calling thread's context
 850      *         and if the calling thread does not have "replaceKeyboardFocusManager"
 851      *         permission
 852      */
 853     protected void setGlobalFocusedWindow(Window focusedWindow)
 854         throws SecurityException
 855     {
 856         Window oldFocusedWindow = null;
 857         boolean shouldFire = false;
 858 
 859         if (focusedWindow == null || focusedWindow.isFocusableWindow()) {
 860             synchronized (KeyboardFocusManager.class) {
 861                 checkKFMSecurity();
 862 
 863                 oldFocusedWindow = getFocusedWindow();
 864 
 865                 try {
 866                     fireVetoableChange("focusedWindow", oldFocusedWindow,
 867                                        focusedWindow);
 868                 } catch (PropertyVetoException e) {
 869                     // rejected
 870                     return;
 871                 }
 872 
 873                 KeyboardFocusManager.focusedWindow = focusedWindow;
 874                 shouldFire = true;
 875             }
 876         }
 877 
 878         if (shouldFire) {
 879             firePropertyChange("focusedWindow", oldFocusedWindow,
 880                                focusedWindow);
 881         }
 882     }
 883 
 884     /**
 885      * Returns the active Window, if the active Window is in the same context
 886      * as the calling thread. Only a Frame or a Dialog can be the active
 887      * Window. The native windowing system may denote the active Window or its
 888      * children with special decorations, such as a highlighted title bar.
 889      * The active Window is always either the focused Window, or the first
 890      * Frame or Dialog that is an owner of the focused Window.
 891      *
 892      * @return the active Window, or null if the active Window is not a member
 893      *         of the calling thread's context
 894      * @see #getGlobalActiveWindow
 895      * @see #setGlobalActiveWindow
 896      */
 897     public Window getActiveWindow() {
 898         synchronized (KeyboardFocusManager.class) {
 899             if (activeWindow == null) {
 900                 return null;
 901             }
 902 
 903             return (activeWindow.appContext == AppContext.getAppContext())
 904                 ? activeWindow
 905                 : null;
 906         }
 907     }
 908 
 909     /**
 910      * Returns the active Window, even if the calling thread is in a different
 911      * context than the active Window. Only a Frame or a Dialog can be the
 912      * active Window. The native windowing system may denote the active Window
 913      * or its children with special decorations, such as a highlighted title
 914      * bar. The active Window is always either the focused Window, or the first
 915      * Frame or Dialog that is an owner of the focused Window.
 916      *
 917      * @return the active Window
 918      * @see #getActiveWindow
 919      * @see #setGlobalActiveWindow
 920      * @throws SecurityException if this KeyboardFocusManager is not the
 921      *         current KeyboardFocusManager for the calling thread's context
 922      *         and if the calling thread does not have "replaceKeyboardFocusManager"
 923      *         permission
 924      */
 925     protected Window getGlobalActiveWindow() throws SecurityException {
 926         synchronized (KeyboardFocusManager.class) {
 927             checkKFMSecurity();
 928             return activeWindow;
 929         }
 930     }
 931 
 932     /**
 933      * Sets the active Window. Only a Frame or a Dialog can be the active
 934      * Window. The native windowing system may denote the active Window or its
 935      * children with special decorations, such as a highlighted title bar. The
 936      * active Window is always either the focused Window, or the first Frame or
 937      * Dialog that is an owner of the focused Window.
 938      * <p>
 939      * This method does not actually change the active Window as far as the
 940      * native windowing system is concerned. It merely stores the value to be
 941      * subsequently returned by {@code getActiveWindow()}. Use
 942      * {@code Component.requestFocus()} or
 943      * {@code Component.requestFocusInWindow()} to change the active
 944      * Window, subject to platform limitations.
 945      *
 946      * @param activeWindow the active Window
 947      * @see #getActiveWindow
 948      * @see #getGlobalActiveWindow
 949      * @see Component#requestFocus()
 950      * @see Component#requestFocusInWindow()
 951      * @throws SecurityException if this KeyboardFocusManager is not the
 952      *         current KeyboardFocusManager for the calling thread's context
 953      *         and if the calling thread does not have "replaceKeyboardFocusManager"
 954      *         permission
 955      */
 956     protected void setGlobalActiveWindow(Window activeWindow)
 957         throws SecurityException
 958     {
 959         Window oldActiveWindow;
 960         synchronized (KeyboardFocusManager.class) {
 961             checkKFMSecurity();
 962 
 963             oldActiveWindow = getActiveWindow();
 964             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
 965                 focusLog.finer("Setting global active window to " + activeWindow + ", old active " + oldActiveWindow);
 966             }
 967 
 968             try {
 969                 fireVetoableChange("activeWindow", oldActiveWindow,
 970                                    activeWindow);
 971             } catch (PropertyVetoException e) {
 972                 // rejected
 973                 return;
 974             }
 975 
 976             KeyboardFocusManager.activeWindow = activeWindow;
 977         }
 978 
 979         firePropertyChange("activeWindow", oldActiveWindow, activeWindow);
 980     }
 981 
 982     /**
 983      * Returns the default FocusTraversalPolicy. Top-level components
 984      * use this value on their creation to initialize their own focus traversal
 985      * policy by explicit call to Container.setFocusTraversalPolicy.
 986      *
 987      * @return the default FocusTraversalPolicy. null will never be returned.
 988      * @see #setDefaultFocusTraversalPolicy
 989      * @see Container#setFocusTraversalPolicy
 990      * @see Container#getFocusTraversalPolicy
 991      */
 992     public synchronized FocusTraversalPolicy getDefaultFocusTraversalPolicy() {
 993         return defaultPolicy;
 994     }
 995 
 996     /**
 997      * Sets the default FocusTraversalPolicy. Top-level components
 998      * use this value on their creation to initialize their own focus traversal
 999      * policy by explicit call to Container.setFocusTraversalPolicy.
1000      * Note: this call doesn't affect already created components as they have
1001      * their policy initialized. Only new components will use this policy as
1002      * their default policy.
1003      *
1004      * @param defaultPolicy the new, default FocusTraversalPolicy
1005      * @see #getDefaultFocusTraversalPolicy
1006      * @see Container#setFocusTraversalPolicy
1007      * @see Container#getFocusTraversalPolicy
1008      * @throws IllegalArgumentException if defaultPolicy is null
1009      */
1010     public void setDefaultFocusTraversalPolicy(FocusTraversalPolicy
1011                                                defaultPolicy) {
1012         if (defaultPolicy == null) {
1013             throw new IllegalArgumentException("default focus traversal policy cannot be null");
1014         }
1015 
1016         FocusTraversalPolicy oldPolicy;
1017 
1018         synchronized (this) {
1019             oldPolicy = this.defaultPolicy;
1020             this.defaultPolicy = defaultPolicy;
1021         }
1022 
1023         firePropertyChange("defaultFocusTraversalPolicy", oldPolicy,
1024                            defaultPolicy);
1025     }
1026 
1027     /**
1028      * Sets the default focus traversal keys for a given traversal operation.
1029      * This traversal key {@code Set} will be in effect on all
1030      * {@code Window}s that have no such {@code Set} of
1031      * their own explicitly defined. This {@code Set} will also be
1032      * inherited, recursively, by any child {@code Component} of
1033      * those {@code Windows} that has
1034      * no such {@code Set} of its own explicitly defined.
1035      * <p>
1036      * The default values for the default focus traversal keys are
1037      * implementation-dependent. Sun recommends that all implementations for a
1038      * particular native platform use the same default values. The
1039      * recommendations for Windows and Unix are listed below. These
1040      * recommendations are used in the Sun AWT implementations.
1041      *
1042      * <table class="striped">
1043      * <caption style="display:none">Recommended default values for focus
1044      * traversal keys</caption>
1045      * <thead>
1046      * <tr>
1047      *    <th>Identifier</th>
1048      *    <th>Meaning</th>
1049      *    <th>Default</th>
1050      * </tr>
1051      * </thead>
1052      * <tbody>
1053      * <tr>
1054      *    <td>{@code KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS}</td>
1055      *    <td>Normal forward keyboard traversal</td>
1056      *    <td>{@code TAB} on {@code KEY_PRESSED},
1057      *        {@code CTRL-TAB} on {@code KEY_PRESSED}</td>
1058      * </tr>
1059      * <tr>
1060      *    <td>{@code KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS}</td>
1061      *    <td>Normal reverse keyboard traversal</td>
1062      *    <td>{@code SHIFT-TAB} on {@code KEY_PRESSED},
1063      *        {@code CTRL-SHIFT-TAB} on {@code KEY_PRESSED}</td>
1064      * </tr>
1065      * <tr>
1066      *    <td>{@code KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS}</td>
1067      *    <td>Go up one focus traversal cycle</td>
1068      *    <td>none</td>
1069      * </tr>
1070      * <tr>
1071      *    <td>{@code KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS}</td>
1072      *    <td>Go down one focus traversal cycle</td>
1073      *    <td>none</td>
1074      * </tr>
1075      * </tbody>
1076      * </table>
1077      *
1078      * To disable a traversal key, use an empty {@code Set};
1079      * {@code Collections.EMPTY_SET} is recommended.
1080      * <p>
1081      * Using the {@code AWTKeyStroke} API, client code can
1082      * specify on which of two
1083      * specific {@code KeyEvent}s, {@code KEY_PRESSED} or
1084      * {@code KEY_RELEASED}, the focus traversal operation will
1085      * occur. Regardless of which {@code KeyEvent} is specified,
1086      * however, all {@code KeyEvent}s related to the focus
1087      * traversal key, including the associated {@code KEY_TYPED}
1088      * event, will be consumed, and will not be dispatched
1089      * to any {@code Component}. It is a runtime error to
1090      * specify a {@code KEY_TYPED} event as
1091      * mapping to a focus traversal operation, or to map the same event to
1092      * multiple default focus traversal operations.
1093      * <p>
1094      * This method may throw a {@code ClassCastException} if any {@code Object}
1095      * in {@code keystrokes} is not an {@code AWTKeyStroke}.
1096      *
1097      * @param id one of
1098      *        {@code KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS},
1099      *        {@code KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS},
1100      *        {@code KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS}, or
1101      *        {@code KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS}
1102      * @param keystrokes the Set of {@code AWTKeyStroke}s for the
1103      *        specified operation
1104      * @see #getDefaultFocusTraversalKeys
1105      * @see Component#setFocusTraversalKeys
1106      * @see Component#getFocusTraversalKeys
1107      * @throws IllegalArgumentException if id is not one of
1108      *         {@code KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS},
1109      *         {@code KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS},
1110      *         {@code KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS}, or
1111      *         {@code KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS},
1112      *         or if keystrokes is {@code null},
1113      *         or if keystrokes contains {@code null},
1114      *         or if any keystroke
1115      *         represents a {@code KEY_TYPED} event,
1116      *         or if any keystroke already maps
1117      *         to another default focus traversal operation
1118      */
1119     public void
1120         setDefaultFocusTraversalKeys(int id,
1121                                      Set<? extends AWTKeyStroke> keystrokes)
1122     {
1123         if (id < 0 || id >= TRAVERSAL_KEY_LENGTH) {
1124             throw new IllegalArgumentException("invalid focus traversal key identifier");
1125         }
1126         if (keystrokes == null) {
1127             throw new IllegalArgumentException("cannot set null Set of default focus traversal keys");
1128         }
1129 
1130         Set<AWTKeyStroke> oldKeys;
1131 
1132         synchronized (this) {
1133             for (AWTKeyStroke keystroke : keystrokes) {
1134 
1135                 if (keystroke == null) {
1136                     throw new IllegalArgumentException("cannot set null focus traversal key");
1137                 }
1138 
1139                 if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
1140                     throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events");
1141                 }
1142 
1143                 // Check to see if key already maps to another traversal
1144                 // operation
1145                 for (int i = 0; i < TRAVERSAL_KEY_LENGTH; i++) {
1146                     if (i == id) {
1147                         continue;
1148                     }
1149 
1150                     if (defaultFocusTraversalKeys[i].contains(keystroke)) {
1151                         throw new IllegalArgumentException("focus traversal keys must be unique for a Component");
1152                     }
1153                 }
1154             }
1155 
1156             oldKeys = defaultFocusTraversalKeys[id];
1157             defaultFocusTraversalKeys[id] =
1158                 Collections.unmodifiableSet(new HashSet<>(keystrokes));
1159         }
1160 
1161         firePropertyChange(defaultFocusTraversalKeyPropertyNames[id],
1162                            oldKeys, keystrokes);
1163     }
1164 
1165     /**
1166      * Returns a Set of default focus traversal keys for a given traversal
1167      * operation. This traversal key Set will be in effect on all Windows that
1168      * have no such Set of their own explicitly defined. This Set will also be
1169      * inherited, recursively, by any child Component of those Windows that has
1170      * no such Set of its own explicitly defined. (See
1171      * {@code setDefaultFocusTraversalKeys} for a full description of each
1172      * operation.)
1173      *
1174      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
1175      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
1176      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
1177      *        KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
1178      * @return the {@code Set} of {@code AWTKeyStroke}s
1179      *         for the specified operation; the {@code Set}
1180      *         will be unmodifiable, and may be empty; {@code null}
1181      *         will never be returned
1182      * @see #setDefaultFocusTraversalKeys
1183      * @see Component#setFocusTraversalKeys
1184      * @see Component#getFocusTraversalKeys
1185      * @throws IllegalArgumentException if id is not one of
1186      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
1187      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
1188      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
1189      *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
1190      */
1191     public Set<AWTKeyStroke> getDefaultFocusTraversalKeys(int id) {
1192         if (id < 0 || id >= TRAVERSAL_KEY_LENGTH) {
1193             throw new IllegalArgumentException("invalid focus traversal key identifier");
1194         }
1195 
1196         // Okay to return Set directly because it is an unmodifiable view
1197         return defaultFocusTraversalKeys[id];
1198     }
1199 
1200     /**
1201      * Returns the current focus cycle root, if the current focus cycle root is
1202      * in the same context as the calling thread. If the focus owner is itself
1203      * a focus cycle root, then it may be ambiguous as to which Components
1204      * represent the next and previous Components to focus during normal focus
1205      * traversal. In that case, the current focus cycle root is used to
1206      * differentiate among the possibilities.
1207      * <p>
1208      * This method is intended to be used only by KeyboardFocusManagers and
1209      * focus implementations. It is not for general client use.
1210      *
1211      * @return the current focus cycle root, or null if the current focus cycle
1212      *         root is not a member of the calling thread's context
1213      * @see #getGlobalCurrentFocusCycleRoot
1214      * @see #setGlobalCurrentFocusCycleRoot
1215      */
1216     public Container getCurrentFocusCycleRoot() {
1217         synchronized (KeyboardFocusManager.class) {
1218             if (currentFocusCycleRoot == null) {
1219                 return null;
1220             }
1221 
1222             return (currentFocusCycleRoot.appContext ==
1223                     AppContext.getAppContext())
1224                 ? currentFocusCycleRoot
1225                 : null;
1226         }
1227     }
1228 
1229     /**
1230      * Returns the current focus cycle root, even if the calling thread is in a
1231      * different context than the current focus cycle root. If the focus owner
1232      * is itself a focus cycle root, then it may be ambiguous as to which
1233      * Components represent the next and previous Components to focus during
1234      * normal focus traversal. In that case, the current focus cycle root is
1235      * used to differentiate among the possibilities.
1236      *
1237      * @return the current focus cycle root, or null if the current focus cycle
1238      *         root is not a member of the calling thread's context
1239      * @see #getCurrentFocusCycleRoot
1240      * @see #setGlobalCurrentFocusCycleRoot
1241      * @throws SecurityException if this KeyboardFocusManager is not the
1242      *         current KeyboardFocusManager for the calling thread's context
1243      *         and if the calling thread does not have "replaceKeyboardFocusManager"
1244      *         permission
1245      */
1246     protected Container getGlobalCurrentFocusCycleRoot()
1247         throws SecurityException
1248     {
1249         synchronized (KeyboardFocusManager.class) {
1250             checkKFMSecurity();
1251             return currentFocusCycleRoot;
1252         }
1253     }
1254 
1255     /**
1256      * Sets the current focus cycle root. If the focus owner is itself a focus
1257      * cycle root, then it may be ambiguous as to which Components represent
1258      * the next and previous Components to focus during normal focus traversal.
1259      * In that case, the current focus cycle root is used to differentiate
1260      * among the possibilities.
1261      * <p>
1262      * If a SecurityManager is installed, the calling thread must be granted
1263      * the "replaceKeyboardFocusManager" AWTPermission. If this permission is
1264      * not granted, this method will throw a SecurityException, and the current
1265      * focus cycle root will not be changed.
1266      * <p>
1267      * This method is intended to be used only by KeyboardFocusManagers and
1268      * focus implementations. It is not for general client use.
1269      *
1270      * @param newFocusCycleRoot the new focus cycle root
1271      * @see #getCurrentFocusCycleRoot
1272      * @see #getGlobalCurrentFocusCycleRoot
1273      * @throws SecurityException if the calling thread does not have
1274      *         "replaceKeyboardFocusManager" permission
1275      */
1276     public void setGlobalCurrentFocusCycleRoot(Container newFocusCycleRoot)
1277         throws SecurityException
1278     {
1279         checkReplaceKFMPermission();
1280 
1281         Container oldFocusCycleRoot;
1282 
1283         synchronized (KeyboardFocusManager.class) {
1284             oldFocusCycleRoot  = getCurrentFocusCycleRoot();
1285             currentFocusCycleRoot = newFocusCycleRoot;
1286         }
1287 
1288         firePropertyChange("currentFocusCycleRoot", oldFocusCycleRoot,
1289                            newFocusCycleRoot);
1290     }
1291 
1292     void setGlobalCurrentFocusCycleRootPriv(final Container newFocusCycleRoot) {
1293         AccessController.doPrivileged(new PrivilegedAction<Void>() {
1294             public Void run() {
1295                 setGlobalCurrentFocusCycleRoot(newFocusCycleRoot);
1296                 return null;
1297             }
1298         });
1299     }
1300 
1301     /**
1302      * Adds a PropertyChangeListener to the listener list. The listener is
1303      * registered for all bound properties of this class, including the
1304      * following:
1305      * <ul>
1306      *    <li>whether the KeyboardFocusManager is currently managing focus
1307      *        for this application or applet's browser context
1308      *        ("managingFocus")</li>
1309      *    <li>the focus owner ("focusOwner")</li>
1310      *    <li>the permanent focus owner ("permanentFocusOwner")</li>
1311      *    <li>the focused Window ("focusedWindow")</li>
1312      *    <li>the active Window ("activeWindow")</li>
1313      *    <li>the default focus traversal policy
1314      *        ("defaultFocusTraversalPolicy")</li>
1315      *    <li>the Set of default FORWARD_TRAVERSAL_KEYS
1316      *        ("forwardDefaultFocusTraversalKeys")</li>
1317      *    <li>the Set of default BACKWARD_TRAVERSAL_KEYS
1318      *        ("backwardDefaultFocusTraversalKeys")</li>
1319      *    <li>the Set of default UP_CYCLE_TRAVERSAL_KEYS
1320      *        ("upCycleDefaultFocusTraversalKeys")</li>
1321      *    <li>the Set of default DOWN_CYCLE_TRAVERSAL_KEYS
1322      *        ("downCycleDefaultFocusTraversalKeys")</li>
1323      *    <li>the current focus cycle root ("currentFocusCycleRoot")</li>
1324      * </ul>
1325      * If listener is null, no exception is thrown and no action is performed.
1326      *
1327      * @param listener the PropertyChangeListener to be added
1328      * @see #removePropertyChangeListener
1329      * @see #getPropertyChangeListeners
1330      * @see #addPropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
1331      */
1332     public void addPropertyChangeListener(PropertyChangeListener listener) {
1333         if (listener != null) {
1334             synchronized (this) {
1335                 if (changeSupport == null) {
1336                     changeSupport = new PropertyChangeSupport(this);
1337                 }
1338                 changeSupport.addPropertyChangeListener(listener);
1339             }
1340         }
1341     }
1342 
1343     /**
1344      * Removes a PropertyChangeListener from the listener list. This method
1345      * should be used to remove the PropertyChangeListeners that were
1346      * registered for all bound properties of this class.
1347      * <p>
1348      * If listener is null, no exception is thrown and no action is performed.
1349      *
1350      * @param listener the PropertyChangeListener to be removed
1351      * @see #addPropertyChangeListener
1352      * @see #getPropertyChangeListeners
1353      * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
1354      */
1355     public void removePropertyChangeListener(PropertyChangeListener listener) {
1356         if (listener != null) {
1357             synchronized (this) {
1358                 if (changeSupport != null) {
1359                     changeSupport.removePropertyChangeListener(listener);
1360                 }
1361             }
1362         }
1363     }
1364 
1365     /**
1366      * Returns an array of all the property change listeners
1367      * registered on this keyboard focus manager.
1368      *
1369      * @return all of this keyboard focus manager's
1370      *         {@code PropertyChangeListener}s
1371      *         or an empty array if no property change
1372      *         listeners are currently registered
1373      *
1374      * @see #addPropertyChangeListener
1375      * @see #removePropertyChangeListener
1376      * @see #getPropertyChangeListeners(java.lang.String)
1377      * @since 1.4
1378      */
1379     public synchronized PropertyChangeListener[] getPropertyChangeListeners() {
1380         if (changeSupport == null) {
1381             changeSupport = new PropertyChangeSupport(this);
1382         }
1383         return changeSupport.getPropertyChangeListeners();
1384     }
1385 
1386     /**
1387      * Adds a PropertyChangeListener to the listener list for a specific
1388      * property. The specified property may be user-defined, or one of the
1389      * following:
1390      * <ul>
1391      *    <li>whether the KeyboardFocusManager is currently managing focus
1392      *        for this application or applet's browser context
1393      *        ("managingFocus")</li>
1394      *    <li>the focus owner ("focusOwner")</li>
1395      *    <li>the permanent focus owner ("permanentFocusOwner")</li>
1396      *    <li>the focused Window ("focusedWindow")</li>
1397      *    <li>the active Window ("activeWindow")</li>
1398      *    <li>the default focus traversal policy
1399      *        ("defaultFocusTraversalPolicy")</li>
1400      *    <li>the Set of default FORWARD_TRAVERSAL_KEYS
1401      *        ("forwardDefaultFocusTraversalKeys")</li>
1402      *    <li>the Set of default BACKWARD_TRAVERSAL_KEYS
1403      *        ("backwardDefaultFocusTraversalKeys")</li>
1404      *    <li>the Set of default UP_CYCLE_TRAVERSAL_KEYS
1405      *        ("upCycleDefaultFocusTraversalKeys")</li>
1406      *    <li>the Set of default DOWN_CYCLE_TRAVERSAL_KEYS
1407      *        ("downCycleDefaultFocusTraversalKeys")</li>
1408      *    <li>the current focus cycle root ("currentFocusCycleRoot")</li>
1409      * </ul>
1410      * If listener is null, no exception is thrown and no action is performed.
1411      *
1412      * @param propertyName one of the property names listed above
1413      * @param listener the PropertyChangeListener to be added
1414      * @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
1415      * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
1416      * @see #getPropertyChangeListeners(java.lang.String)
1417      */
1418     public void addPropertyChangeListener(String propertyName,
1419                                           PropertyChangeListener listener) {
1420         if (listener != null) {
1421             synchronized (this) {
1422                 if (changeSupport == null) {
1423                     changeSupport = new PropertyChangeSupport(this);
1424                 }
1425                 changeSupport.addPropertyChangeListener(propertyName,
1426                                                         listener);
1427             }
1428         }
1429     }
1430 
1431     /**
1432      * Removes a PropertyChangeListener from the listener list for a specific
1433      * property. This method should be used to remove PropertyChangeListeners
1434      * that were registered for a specific bound property.
1435      * <p>
1436      * If listener is null, no exception is thrown and no action is performed.
1437      *
1438      * @param propertyName a valid property name
1439      * @param listener the PropertyChangeListener to be removed
1440      * @see #addPropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
1441      * @see #getPropertyChangeListeners(java.lang.String)
1442      * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
1443      */
1444     public void removePropertyChangeListener(String propertyName,
1445                                              PropertyChangeListener listener) {
1446         if (listener != null) {
1447             synchronized (this) {
1448                 if (changeSupport != null) {
1449                     changeSupport.removePropertyChangeListener(propertyName,
1450                                                                listener);
1451                 }
1452             }
1453         }
1454     }
1455 
1456     /**
1457      * Returns an array of all the {@code PropertyChangeListener}s
1458      * associated with the named property.
1459      *
1460      * @param  propertyName the property name
1461      * @return all of the {@code PropertyChangeListener}s associated with
1462      *         the named property or an empty array if no such listeners have
1463      *         been added.
1464      *
1465      * @see #addPropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
1466      * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
1467      * @since 1.4
1468      */
1469     public synchronized PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
1470         if (changeSupport == null) {
1471             changeSupport = new PropertyChangeSupport(this);
1472         }
1473         return changeSupport.getPropertyChangeListeners(propertyName);
1474     }
1475 
1476     /**
1477      * Fires a PropertyChangeEvent in response to a change in a bound property.
1478      * The event will be delivered to all registered PropertyChangeListeners.
1479      * No event will be delivered if oldValue and newValue are the same.
1480      *
1481      * @param propertyName the name of the property that has changed
1482      * @param oldValue the property's previous value
1483      * @param newValue the property's new value
1484      */
1485     protected void firePropertyChange(String propertyName, Object oldValue,
1486                                       Object newValue)
1487     {
1488         if (oldValue == newValue) {
1489             return;
1490         }
1491         PropertyChangeSupport changeSupport = this.changeSupport;
1492         if (changeSupport != null) {
1493             changeSupport.firePropertyChange(propertyName, oldValue, newValue);
1494         }
1495     }
1496 
1497     /**
1498      * Adds a VetoableChangeListener to the listener list. The listener is
1499      * registered for all vetoable properties of this class, including the
1500      * following:
1501      * <ul>
1502      *    <li>the focus owner ("focusOwner")</li>
1503      *    <li>the permanent focus owner ("permanentFocusOwner")</li>
1504      *    <li>the focused Window ("focusedWindow")</li>
1505      *    <li>the active Window ("activeWindow")</li>
1506      * </ul>
1507      * If listener is null, no exception is thrown and no action is performed.
1508      *
1509      * @param listener the VetoableChangeListener to be added
1510      * @see #removeVetoableChangeListener
1511      * @see #getVetoableChangeListeners
1512      * @see #addVetoableChangeListener(java.lang.String,java.beans.VetoableChangeListener)
1513      */
1514     public void addVetoableChangeListener(VetoableChangeListener listener) {
1515         if (listener != null) {
1516             synchronized (this) {
1517                 if (vetoableSupport == null) {
1518                     vetoableSupport =
1519                         new VetoableChangeSupport(this);
1520                 }
1521                 vetoableSupport.addVetoableChangeListener(listener);
1522             }
1523         }
1524     }
1525 
1526     /**
1527      * Removes a VetoableChangeListener from the listener list. This method
1528      * should be used to remove the VetoableChangeListeners that were
1529      * registered for all vetoable properties of this class.
1530      * <p>
1531      * If listener is null, no exception is thrown and no action is performed.
1532      *
1533      * @param listener the VetoableChangeListener to be removed
1534      * @see #addVetoableChangeListener
1535      * @see #getVetoableChangeListeners
1536      * @see #removeVetoableChangeListener(java.lang.String,java.beans.VetoableChangeListener)
1537      */
1538     public void removeVetoableChangeListener(VetoableChangeListener listener) {
1539         if (listener != null) {
1540             synchronized (this) {
1541                 if (vetoableSupport != null) {
1542                     vetoableSupport.removeVetoableChangeListener(listener);
1543                 }
1544             }
1545         }
1546     }
1547 
1548     /**
1549      * Returns an array of all the vetoable change listeners
1550      * registered on this keyboard focus manager.
1551      *
1552      * @return all of this keyboard focus manager's
1553      *         {@code VetoableChangeListener}s
1554      *         or an empty array if no vetoable change
1555      *         listeners are currently registered
1556      *
1557      * @see #addVetoableChangeListener
1558      * @see #removeVetoableChangeListener
1559      * @see #getVetoableChangeListeners(java.lang.String)
1560      * @since 1.4
1561      */
1562     public synchronized VetoableChangeListener[] getVetoableChangeListeners() {
1563         if (vetoableSupport == null) {
1564             vetoableSupport = new VetoableChangeSupport(this);
1565         }
1566         return vetoableSupport.getVetoableChangeListeners();
1567     }
1568 
1569     /**
1570      * Adds a VetoableChangeListener to the listener list for a specific
1571      * property. The specified property may be user-defined, or one of the
1572      * following:
1573      * <ul>
1574      *    <li>the focus owner ("focusOwner")</li>
1575      *    <li>the permanent focus owner ("permanentFocusOwner")</li>
1576      *    <li>the focused Window ("focusedWindow")</li>
1577      *    <li>the active Window ("activeWindow")</li>
1578      * </ul>
1579      * If listener is null, no exception is thrown and no action is performed.
1580      *
1581      * @param propertyName one of the property names listed above
1582      * @param listener the VetoableChangeListener to be added
1583      * @see #addVetoableChangeListener(java.beans.VetoableChangeListener)
1584      * @see #removeVetoableChangeListener
1585      * @see #getVetoableChangeListeners
1586      */
1587     public void addVetoableChangeListener(String propertyName,
1588                                           VetoableChangeListener listener) {
1589         if (listener != null) {
1590             synchronized (this) {
1591                 if (vetoableSupport == null) {
1592                     vetoableSupport =
1593                         new VetoableChangeSupport(this);
1594                 }
1595                 vetoableSupport.addVetoableChangeListener(propertyName,
1596                                                           listener);
1597             }
1598         }
1599     }
1600 
1601     /**
1602      * Removes a VetoableChangeListener from the listener list for a specific
1603      * property. This method should be used to remove VetoableChangeListeners
1604      * that were registered for a specific bound property.
1605      * <p>
1606      * If listener is null, no exception is thrown and no action is performed.
1607      *
1608      * @param propertyName a valid property name
1609      * @param listener the VetoableChangeListener to be removed
1610      * @see #addVetoableChangeListener
1611      * @see #getVetoableChangeListeners
1612      * @see #removeVetoableChangeListener(java.beans.VetoableChangeListener)
1613      */
1614     public void removeVetoableChangeListener(String propertyName,
1615                                              VetoableChangeListener listener) {
1616         if (listener != null) {
1617             synchronized (this) {
1618                 if (vetoableSupport != null) {
1619                     vetoableSupport.removeVetoableChangeListener(propertyName,
1620                                                                  listener);
1621                 }
1622             }
1623         }
1624     }
1625 
1626     /**
1627      * Returns an array of all the {@code VetoableChangeListener}s
1628      * associated with the named property.
1629      *
1630      * @param  propertyName the property name
1631      * @return all of the {@code VetoableChangeListener}s associated with
1632      *         the named property or an empty array if no such listeners have
1633      *         been added.
1634      *
1635      * @see #addVetoableChangeListener(java.lang.String,java.beans.VetoableChangeListener)
1636      * @see #removeVetoableChangeListener(java.lang.String,java.beans.VetoableChangeListener)
1637      * @see #getVetoableChangeListeners
1638      * @since 1.4
1639      */
1640     public synchronized VetoableChangeListener[] getVetoableChangeListeners(String propertyName) {
1641         if (vetoableSupport == null) {
1642             vetoableSupport = new VetoableChangeSupport(this);
1643         }
1644         return vetoableSupport.getVetoableChangeListeners(propertyName);
1645     }
1646 
1647     /**
1648      * Fires a PropertyChangeEvent in response to a change in a vetoable
1649      * property. The event will be delivered to all registered
1650      * VetoableChangeListeners. If a VetoableChangeListener throws a
1651      * PropertyVetoException, a new event is fired reverting all
1652      * VetoableChangeListeners to the old value and the exception is then
1653      * rethrown. No event will be delivered if oldValue and newValue are the
1654      * same.
1655      *
1656      * @param propertyName the name of the property that has changed
1657      * @param oldValue the property's previous value
1658      * @param newValue the property's new value
1659      * @throws java.beans.PropertyVetoException if a
1660      *         {@code VetoableChangeListener} threw
1661      *         {@code PropertyVetoException}
1662      */
1663     protected void fireVetoableChange(String propertyName, Object oldValue,
1664                                       Object newValue)
1665         throws PropertyVetoException
1666     {
1667         if (oldValue == newValue) {
1668             return;
1669         }
1670         VetoableChangeSupport vetoableSupport =
1671             this.vetoableSupport;
1672         if (vetoableSupport != null) {
1673             vetoableSupport.fireVetoableChange(propertyName, oldValue,
1674                                                newValue);
1675         }
1676     }
1677 
1678     /**
1679      * Adds a KeyEventDispatcher to this KeyboardFocusManager's dispatcher
1680      * chain. This KeyboardFocusManager will request that each
1681      * KeyEventDispatcher dispatch KeyEvents generated by the user before
1682      * finally dispatching the KeyEvent itself. KeyEventDispatchers will be
1683      * notified in the order in which they were added. Notifications will halt
1684      * as soon as one KeyEventDispatcher returns {@code true} from its
1685      * {@code dispatchKeyEvent} method. There is no limit to the total
1686      * number of KeyEventDispatchers which can be added, nor to the number of
1687      * times which a particular KeyEventDispatcher instance can be added.
1688      * <p>
1689      * If a null dispatcher is specified, no action is taken and no exception
1690      * is thrown.
1691      * <p>
1692      * In a multithreaded application, {@link KeyEventDispatcher} behaves
1693      * the same as other AWT listeners.  See
1694      * <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1695      * >AWT Threading Issues</a> for more details.
1696      *
1697      * @param dispatcher the KeyEventDispatcher to add to the dispatcher chain
1698      * @see #removeKeyEventDispatcher
1699      */
1700     public void addKeyEventDispatcher(KeyEventDispatcher dispatcher) {
1701         if (dispatcher != null) {
1702             synchronized (this) {
1703                 if (keyEventDispatchers == null) {
1704                     keyEventDispatchers = new java.util.LinkedList<>();
1705                 }
1706                 keyEventDispatchers.add(dispatcher);
1707             }
1708         }
1709     }
1710 
1711     /**
1712      * Removes a KeyEventDispatcher which was previously added to this
1713      * KeyboardFocusManager's dispatcher chain. This KeyboardFocusManager
1714      * cannot itself be removed, unless it was explicitly re-registered via a
1715      * call to {@code addKeyEventDispatcher}.
1716      * <p>
1717      * If a null dispatcher is specified, if the specified dispatcher is not
1718      * in the dispatcher chain, or if this KeyboardFocusManager is specified
1719      * without having been explicitly re-registered, no action is taken and no
1720      * exception is thrown.
1721      * <p>
1722      * In a multithreaded application, {@link KeyEventDispatcher} behaves
1723      * the same as other AWT listeners.  See
1724      * <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1725      * >AWT Threading Issues</a> for more details.
1726      *
1727      * @param dispatcher the KeyEventDispatcher to remove from the dispatcher
1728      *        chain
1729      * @see #addKeyEventDispatcher
1730      */
1731     public void removeKeyEventDispatcher(KeyEventDispatcher dispatcher) {
1732         if (dispatcher != null) {
1733             synchronized (this) {
1734                 if (keyEventDispatchers != null) {
1735                     keyEventDispatchers.remove(dispatcher);
1736                 }
1737             }
1738         }
1739     }
1740 
1741     /**
1742      * Returns this KeyboardFocusManager's KeyEventDispatcher chain as a List.
1743      * The List will not include this KeyboardFocusManager unless it was
1744      * explicitly re-registered via a call to
1745      * {@code addKeyEventDispatcher}. If no other KeyEventDispatchers are
1746      * registered, implementations are free to return null or a List of length
1747      * 0. Client code should not assume one behavior over another, nor should
1748      * it assume that the behavior, once established, will not change.
1749      *
1750      * @return a possibly null or empty List of KeyEventDispatchers
1751      * @see #addKeyEventDispatcher
1752      * @see #removeKeyEventDispatcher
1753      */
1754     @SuppressWarnings("unchecked") // Cast of result of clone
1755     protected synchronized java.util.List<KeyEventDispatcher>
1756         getKeyEventDispatchers()
1757     {
1758         return (keyEventDispatchers != null)
1759             ? (java.util.List<KeyEventDispatcher>)keyEventDispatchers.clone()
1760             : null;
1761     }
1762 
1763     /**
1764      * Adds a KeyEventPostProcessor to this KeyboardFocusManager's post-
1765      * processor chain. After a KeyEvent has been dispatched to and handled by
1766      * its target, KeyboardFocusManager will request that each
1767      * KeyEventPostProcessor perform any necessary post-processing as part
1768      * of the KeyEvent's final resolution. KeyEventPostProcessors
1769      * will be notified in the order in which they were added; the current
1770      * KeyboardFocusManager will be notified last. Notifications will halt
1771      * as soon as one KeyEventPostProcessor returns {@code true} from its
1772      * {@code postProcessKeyEvent} method. There is no limit to the
1773      * total number of KeyEventPostProcessors that can be added, nor to the
1774      * number of times that a particular KeyEventPostProcessor instance can be
1775      * added.
1776      * <p>
1777      * If a null post-processor is specified, no action is taken and no
1778      * exception is thrown.
1779      * <p>
1780      * In a multithreaded application, {@link KeyEventPostProcessor} behaves
1781      * the same as other AWT listeners.  See
1782      * <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1783      * >AWT Threading Issues</a> for more details.
1784      *
1785      * @param processor the KeyEventPostProcessor to add to the post-processor
1786      *        chain
1787      * @see #removeKeyEventPostProcessor
1788      */
1789     public void addKeyEventPostProcessor(KeyEventPostProcessor processor) {
1790         if (processor != null) {
1791             synchronized (this) {
1792                 if (keyEventPostProcessors == null) {
1793                     keyEventPostProcessors = new java.util.LinkedList<>();
1794                 }
1795                 keyEventPostProcessors.add(processor);
1796             }
1797         }
1798     }
1799 
1800 
1801     /**
1802      * Removes a previously added KeyEventPostProcessor from this
1803      * KeyboardFocusManager's post-processor chain. This KeyboardFocusManager
1804      * cannot itself be entirely removed from the chain. Only additional
1805      * references added via {@code addKeyEventPostProcessor} can be
1806      * removed.
1807      * <p>
1808      * If a null post-processor is specified, if the specified post-processor
1809      * is not in the post-processor chain, or if this KeyboardFocusManager is
1810      * specified without having been explicitly added, no action is taken and
1811      * no exception is thrown.
1812      * <p>
1813      * In a multithreaded application, {@link KeyEventPostProcessor} behaves
1814      * the same as other AWT listeners.  See
1815      * <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1816      * >AWT Threading Issues</a> for more details.
1817      *
1818      * @param processor the KeyEventPostProcessor to remove from the post-
1819      *        processor chain
1820      * @see #addKeyEventPostProcessor
1821      */
1822     public void removeKeyEventPostProcessor(KeyEventPostProcessor processor) {
1823         if (processor != null) {
1824             synchronized (this) {
1825                 if (keyEventPostProcessors != null) {
1826                     keyEventPostProcessors.remove(processor);
1827                 }
1828             }
1829         }
1830     }
1831 
1832 
1833     /**
1834      * Returns this KeyboardFocusManager's KeyEventPostProcessor chain as a
1835      * List. The List will not include this KeyboardFocusManager unless it was
1836      * explicitly added via a call to {@code addKeyEventPostProcessor}. If
1837      * no KeyEventPostProcessors are registered, implementations are free to
1838      * return null or a List of length 0. Client code should not assume one
1839      * behavior over another, nor should it assume that the behavior, once
1840      * established, will not change.
1841      *
1842      * @return a possibly null or empty List of KeyEventPostProcessors
1843      * @see #addKeyEventPostProcessor
1844      * @see #removeKeyEventPostProcessor
1845      */
1846     @SuppressWarnings("unchecked") // Cast of result of clone
1847     protected java.util.List<KeyEventPostProcessor>
1848         getKeyEventPostProcessors()
1849     {
1850         return (keyEventPostProcessors != null)
1851             ? (java.util.List<KeyEventPostProcessor>)keyEventPostProcessors.clone()
1852             : null;
1853     }
1854 
1855 
1856 
1857     static void setMostRecentFocusOwner(Component component) {
1858         Component window = component;
1859         while (window != null && !(window instanceof Window)) {
1860             window = window.parent;
1861         }
1862         if (window != null) {
1863             setMostRecentFocusOwner((Window)window, component);
1864         }
1865     }
1866     static synchronized void setMostRecentFocusOwner(Window window,
1867                                                      Component component) {
1868         // ATTN: component has a strong reference to window via chain
1869         // of Component.parent fields.  Since WeakHasMap refers to its
1870         // values strongly, we need to break the strong link from the
1871         // value (component) back to its key (window).
1872         WeakReference<Component> weakValue = null;
1873         if (component != null) {
1874             weakValue = new WeakReference<>(component);
1875         }
1876         mostRecentFocusOwners.put(window, weakValue);
1877     }
1878     static void clearMostRecentFocusOwner(Component comp) {
1879         Container window;
1880 
1881         if (comp == null) {
1882             return;
1883         }
1884 
1885         synchronized (comp.getTreeLock()) {
1886             window = comp.getParent();
1887             while (window != null && !(window instanceof Window)) {
1888                 window = window.getParent();
1889             }
1890         }
1891 
1892         synchronized (KeyboardFocusManager.class) {
1893             if ((window != null)
1894                 && (getMostRecentFocusOwner((Window)window) == comp))
1895             {
1896                 setMostRecentFocusOwner((Window)window, null);
1897             }
1898             // Also clear temporary lost component stored in Window
1899             if (window != null) {
1900                 Window realWindow = (Window)window;
1901                 if (realWindow.getTemporaryLostComponent() == comp) {
1902                     realWindow.setTemporaryLostComponent(null);
1903                 }
1904             }
1905         }
1906     }
1907 
1908     /*
1909      * Please be careful changing this method! It is called from
1910      * javax.swing.JComponent.runInputVerifier() using reflection.
1911      */
1912     static synchronized Component getMostRecentFocusOwner(Window window) {
1913         WeakReference<Component> weakValue = mostRecentFocusOwners.get(window);
1914         return weakValue == null ? null : weakValue.get();
1915     }
1916 
1917     /**
1918      * This method is called by the AWT event dispatcher requesting that the
1919      * current KeyboardFocusManager dispatch the specified event on its behalf.
1920      * It is expected that all KeyboardFocusManagers will dispatch all
1921      * FocusEvents, all WindowEvents related to focus, and all KeyEvents.
1922      * These events should be dispatched based on the KeyboardFocusManager's
1923      * notion of the focus owner and the focused and active Windows, sometimes
1924      * overriding the source of the specified AWTEvent. Dispatching must be
1925      * done using {@code redispatchEvent} to prevent the AWT event
1926      * dispatcher from recursively requesting that the KeyboardFocusManager
1927      * dispatch the event again. If this method returns {@code false},
1928      * then the AWT event dispatcher will attempt to dispatch the event itself.
1929      *
1930      * @param e the AWTEvent to be dispatched
1931      * @return {@code true} if this method dispatched the event;
1932      *         {@code false} otherwise
1933      * @see #redispatchEvent
1934      * @see #dispatchKeyEvent
1935      */
1936     public abstract boolean dispatchEvent(AWTEvent e);
1937 
1938     /**
1939      * Redispatches an AWTEvent in such a way that the AWT event dispatcher
1940      * will not recursively request that the KeyboardFocusManager, or any
1941      * installed KeyEventDispatchers, dispatch the event again. Client
1942      * implementations of {@code dispatchEvent} and client-defined
1943      * KeyEventDispatchers must call {@code redispatchEvent(target, e)}
1944      * instead of {@code target.dispatchEvent(e)} to dispatch an event.
1945      * <p>
1946      * This method is intended to be used only by KeyboardFocusManagers and
1947      * KeyEventDispatchers. It is not for general client use.
1948      *
1949      * @param target the Component to which the event should be dispatched
1950      * @param e the event to dispatch
1951      * @see #dispatchEvent
1952      * @see KeyEventDispatcher
1953      */
1954     public final void redispatchEvent(Component target, AWTEvent e) {
1955         e.focusManagerIsDispatching = true;
1956         target.dispatchEvent(e);
1957         e.focusManagerIsDispatching = false;
1958     }
1959 
1960     /**
1961      * Typically this method will be called by {@code dispatchEvent} if no
1962      * other KeyEventDispatcher in the dispatcher chain dispatched the
1963      * KeyEvent, or if no other KeyEventDispatchers are registered. If an
1964      * implementation of this method returns {@code false},
1965      * {@code dispatchEvent} may try to dispatch the KeyEvent itself, or
1966      * may simply return {@code false}. If {@code true} is returned,
1967      * {@code dispatchEvent} should return {@code true} as well.
1968      *
1969      * @param e the KeyEvent which the current KeyboardFocusManager has
1970      *        requested that this KeyEventDispatcher dispatch
1971      * @return {@code true} if the KeyEvent was dispatched;
1972      *         {@code false} otherwise
1973      * @see #dispatchEvent
1974      */
1975     public abstract boolean dispatchKeyEvent(KeyEvent e);
1976 
1977     /**
1978      * This method will be called by {@code dispatchKeyEvent}.
1979      * By default, this method will handle any unconsumed KeyEvents that
1980      * map to an AWT {@code MenuShortcut} by consuming the event
1981      * and activating the shortcut.
1982      *
1983      * @param e the KeyEvent to post-process
1984      * @return {@code true} to indicate that no other
1985      *         KeyEventPostProcessor will be notified of the KeyEvent.
1986      * @see #dispatchKeyEvent
1987      * @see MenuShortcut
1988      */
1989     public abstract boolean postProcessKeyEvent(KeyEvent e);
1990 
1991     /**
1992      * This method initiates a focus traversal operation if and only if the
1993      * KeyEvent represents a focus traversal key for the specified
1994      * focusedComponent. It is expected that focusedComponent is the current
1995      * focus owner, although this need not be the case. If it is not,
1996      * focus traversal will nevertheless proceed as if focusedComponent
1997      * were the current focus owner.
1998      *
1999      * @param focusedComponent the Component that will be the basis for a focus
2000      *        traversal operation if the specified event represents a focus
2001      *        traversal key for the Component
2002      * @param e the event that may represent a focus traversal key
2003      */
2004     public abstract void processKeyEvent(Component focusedComponent,
2005                                          KeyEvent e);
2006 
2007     /**
2008      * Called by the AWT to notify the KeyboardFocusManager that it should
2009      * delay dispatching of KeyEvents until the specified Component becomes
2010      * the focus owner. If client code requests a focus change, and the AWT
2011      * determines that this request might be granted by the native windowing
2012      * system, then the AWT will call this method. It is the responsibility of
2013      * the KeyboardFocusManager to delay dispatching of KeyEvents with
2014      * timestamps later than the specified time stamp until the specified
2015      * Component receives a FOCUS_GAINED event, or the AWT cancels the delay
2016      * request by invoking {@code dequeueKeyEvents} or
2017      * {@code discardKeyEvents}.
2018      *
2019      * @param after timestamp of current event, or the current, system time if
2020      *        the current event has no timestamp, or the AWT cannot determine
2021      *        which event is currently being handled
2022      * @param untilFocused Component which should receive a FOCUS_GAINED event
2023      *        before any pending KeyEvents
2024      * @see #dequeueKeyEvents
2025      * @see #discardKeyEvents
2026      */
2027     protected abstract void enqueueKeyEvents(long after,
2028                                              Component untilFocused);
2029 
2030     /**
2031      * Called by the AWT to notify the KeyboardFocusManager that it should
2032      * cancel delayed dispatching of KeyEvents. All KeyEvents which were
2033      * enqueued because of a call to {@code enqueueKeyEvents} with the
2034      * same timestamp and Component should be released for normal dispatching
2035      * to the current focus owner. If the given timestamp is less than zero,
2036      * the outstanding enqueue request for the given Component with the <b>
2037      * oldest</b> timestamp (if any) should be cancelled.
2038      *
2039      * @param after the timestamp specified in the call to
2040      *        {@code enqueueKeyEvents}, or any value &lt; 0
2041      * @param untilFocused the Component specified in the call to
2042      *        {@code enqueueKeyEvents}
2043      * @see #enqueueKeyEvents
2044      * @see #discardKeyEvents
2045      */
2046     protected abstract void dequeueKeyEvents(long after,
2047                                              Component untilFocused);
2048 
2049     /**
2050      * Called by the AWT to notify the KeyboardFocusManager that it should
2051      * cancel delayed dispatching of KeyEvents. All KeyEvents which were
2052      * enqueued because of one or more calls to {@code enqueueKeyEvents}
2053      * with the same Component should be discarded.
2054      *
2055      * @param comp the Component specified in one or more calls to
2056      *        {@code enqueueKeyEvents}
2057      * @see #enqueueKeyEvents
2058      * @see #dequeueKeyEvents
2059      */
2060     protected abstract void discardKeyEvents(Component comp);
2061 
2062     /**
2063      * Focuses the Component after aComponent, typically based on a
2064      * FocusTraversalPolicy.
2065      *
2066      * @param aComponent the Component that is the basis for the focus
2067      *        traversal operation
2068      * @see FocusTraversalPolicy
2069      */
2070     public abstract void focusNextComponent(Component aComponent);
2071 
2072     /**
2073      * Focuses the Component before aComponent, typically based on a
2074      * FocusTraversalPolicy.
2075      *
2076      * @param aComponent the Component that is the basis for the focus
2077      *        traversal operation
2078      * @see FocusTraversalPolicy
2079      */
2080     public abstract void focusPreviousComponent(Component aComponent);
2081 
2082     /**
2083      * Moves the focus up one focus traversal cycle. Typically, the focus owner
2084      * is set to aComponent's focus cycle root, and the current focus cycle
2085      * root is set to the new focus owner's focus cycle root. If, however,
2086      * aComponent's focus cycle root is a Window, then typically the focus
2087      * owner is set to the Window's default Component to focus, and the current
2088      * focus cycle root is unchanged.
2089      *
2090      * @param aComponent the Component that is the basis for the focus
2091      *        traversal operation
2092      */
2093     public abstract void upFocusCycle(Component aComponent);
2094 
2095     /**
2096      * Moves the focus down one focus traversal cycle. Typically, if
2097      * aContainer is a focus cycle root, then the focus owner is set to
2098      * aContainer's default Component to focus, and the current focus cycle
2099      * root is set to aContainer. If aContainer is not a focus cycle root, then
2100      * no focus traversal operation occurs.
2101      *
2102      * @param aContainer the Container that is the basis for the focus
2103      *        traversal operation
2104      */
2105     public abstract void downFocusCycle(Container aContainer);
2106 
2107     /**
2108      * Focuses the Component after the current focus owner.
2109      */
2110     public final void focusNextComponent() {
2111         Component focusOwner = getFocusOwner();
2112         if (focusOwner != null) {
2113             focusNextComponent(focusOwner);
2114         }
2115     }
2116 
2117     /**
2118      * Focuses the Component before the current focus owner.
2119      */
2120     public final void focusPreviousComponent() {
2121         Component focusOwner = getFocusOwner();
2122         if (focusOwner != null) {
2123             focusPreviousComponent(focusOwner);
2124         }
2125     }
2126 
2127     /**
2128      * Moves the focus up one focus traversal cycle from the current focus
2129      * owner. Typically, the new focus owner is set to the current focus
2130      * owner's focus cycle root, and the current focus cycle root is set to the
2131      * new focus owner's focus cycle root. If, however, the current focus
2132      * owner's focus cycle root is a Window, then typically the focus owner is
2133      * set to the focus cycle root's default Component to focus, and the
2134      * current focus cycle root is unchanged.
2135      */
2136     public final void upFocusCycle() {
2137         Component focusOwner = getFocusOwner();
2138         if (focusOwner != null) {
2139             upFocusCycle(focusOwner);
2140         }
2141     }
2142 
2143     /**
2144      * Moves the focus down one focus traversal cycle from the current focus
2145      * owner, if and only if the current focus owner is a Container that is a
2146      * focus cycle root. Typically, the focus owner is set to the current focus
2147      * owner's default Component to focus, and the current focus cycle root is
2148      * set to the current focus owner. If the current focus owner is not a
2149      * Container that is a focus cycle root, then no focus traversal operation
2150      * occurs.
2151      */
2152     public final void downFocusCycle() {
2153         Component focusOwner = getFocusOwner();
2154         if (focusOwner instanceof Container) {
2155             downFocusCycle((Container)focusOwner);
2156         }
2157     }
2158 
2159     /**
2160      * Dumps the list of focus requests to stderr
2161      */
2162     void dumpRequests() {
2163         System.err.println(">>> Requests dump, time: " + System.currentTimeMillis());
2164         synchronized (heavyweightRequests) {
2165             for (HeavyweightFocusRequest req : heavyweightRequests) {
2166                 System.err.println(">>> Req: " + req);
2167             }
2168         }
2169         System.err.println("");
2170     }
2171 
2172     private static final class LightweightFocusRequest {
2173         final Component component;
2174         final boolean temporary;
2175         final FocusEvent.Cause cause;
2176 
2177         LightweightFocusRequest(Component component, boolean temporary, FocusEvent.Cause cause) {
2178             this.component = component;
2179             this.temporary = temporary;
2180             this.cause = cause;
2181         }
2182         public String toString() {
2183             return "LightweightFocusRequest[component=" + component +
2184                 ",temporary=" + temporary + ", cause=" + cause + "]";
2185         }
2186     }
2187 
2188     private static final class HeavyweightFocusRequest {
2189         final Component heavyweight;
2190         final LinkedList<LightweightFocusRequest> lightweightRequests;
2191 
2192         static final HeavyweightFocusRequest CLEAR_GLOBAL_FOCUS_OWNER =
2193             new HeavyweightFocusRequest();
2194 
2195         private HeavyweightFocusRequest() {
2196             heavyweight = null;
2197             lightweightRequests = null;
2198         }
2199 
2200         HeavyweightFocusRequest(Component heavyweight, Component descendant,
2201                                 boolean temporary, FocusEvent.Cause cause) {
2202             if (log.isLoggable(PlatformLogger.Level.FINE)) {
2203                 if (heavyweight == null) {
2204                     log.fine("Assertion (heavyweight != null) failed");
2205                 }
2206             }
2207 
2208             this.heavyweight = heavyweight;
2209             this.lightweightRequests = new LinkedList<LightweightFocusRequest>();
2210             addLightweightRequest(descendant, temporary, cause);
2211         }
2212         boolean addLightweightRequest(Component descendant,
2213                                       boolean temporary, FocusEvent.Cause cause) {
2214             if (log.isLoggable(PlatformLogger.Level.FINE)) {
2215                 if (this == HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER) {
2216                     log.fine("Assertion (this != HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER) failed");
2217                 }
2218                 if (descendant == null) {
2219                     log.fine("Assertion (descendant != null) failed");
2220                 }
2221             }
2222 
2223             Component lastDescendant = ((lightweightRequests.size() > 0)
2224                 ? lightweightRequests.getLast().component
2225                 : null);
2226 
2227             if (descendant != lastDescendant) {
2228                 // Not a duplicate request
2229                 lightweightRequests.add
2230                     (new LightweightFocusRequest(descendant, temporary, cause));
2231                 return true;
2232             } else {
2233                 return false;
2234             }
2235         }
2236 
2237         LightweightFocusRequest getFirstLightweightRequest() {
2238             if (this == CLEAR_GLOBAL_FOCUS_OWNER) {
2239                 return null;
2240             }
2241             return lightweightRequests.getFirst();
2242         }
2243         public String toString() {
2244             boolean first = true;
2245             String str = "HeavyweightFocusRequest[heavyweight=" + heavyweight +
2246                 ",lightweightRequests=";
2247             if (lightweightRequests == null) {
2248                 str += null;
2249             } else {
2250                 str += "[";
2251 
2252                 for (LightweightFocusRequest lwRequest : lightweightRequests) {
2253                     if (first) {
2254                         first = false;
2255                     } else {
2256                         str += ",";
2257                     }
2258                     str += lwRequest;
2259                 }
2260                 str += "]";
2261             }
2262             str += "]";
2263             return str;
2264         }
2265     }
2266 
2267     /*
2268      * heavyweightRequests is used as a monitor for synchronized changes of
2269      * currentLightweightRequests, clearingCurrentLightweightRequests and
2270      * newFocusOwner.
2271      */
2272     private static LinkedList<HeavyweightFocusRequest> heavyweightRequests =
2273         new LinkedList<HeavyweightFocusRequest>();
2274     private static LinkedList<LightweightFocusRequest> currentLightweightRequests;
2275     private static boolean clearingCurrentLightweightRequests;
2276     private static boolean allowSyncFocusRequests = true;
2277     private static Component newFocusOwner = null;
2278     private static volatile boolean disableRestoreFocus;
2279 
2280     static final int SNFH_FAILURE = 0;
2281     static final int SNFH_SUCCESS_HANDLED = 1;
2282     static final int SNFH_SUCCESS_PROCEED = 2;
2283 
2284     static boolean processSynchronousLightweightTransfer(Component heavyweight, Component descendant,
2285                                                   boolean temporary, boolean focusedWindowChangeAllowed,
2286                                                   long time)
2287     {
2288         Window parentWindow = SunToolkit.getContainingWindow(heavyweight);
2289         if (parentWindow == null || !parentWindow.syncLWRequests) {
2290             return false;
2291         }
2292         if (descendant == null) {
2293             // Focus transfers from a lightweight child back to the
2294             // heavyweight Container should be treated like lightweight
2295             // focus transfers.
2296             descendant = heavyweight;
2297         }
2298 
2299         KeyboardFocusManager manager = getCurrentKeyboardFocusManager(SunToolkit.targetToAppContext(descendant));
2300 
2301         FocusEvent currentFocusOwnerEvent = null;
2302         FocusEvent newFocusOwnerEvent = null;
2303         Component currentFocusOwner = manager.getGlobalFocusOwner();
2304 
2305         synchronized (heavyweightRequests) {
2306             HeavyweightFocusRequest hwFocusRequest = getLastHWRequest();
2307             if (hwFocusRequest == null &&
2308                 heavyweight == manager.getNativeFocusOwner() &&
2309                 allowSyncFocusRequests)
2310             {
2311 
2312                 if (descendant == currentFocusOwner) {
2313                     // Redundant request.
2314                     return true;
2315                 }
2316 
2317                 // 'heavyweight' owns the native focus and there are no pending
2318                 // requests. 'heavyweight' must be a Container and
2319                 // 'descendant' must not be the focus owner. Otherwise,
2320                 // we would never have gotten this far.
2321                 manager.enqueueKeyEvents(time, descendant);
2322 
2323                 hwFocusRequest =
2324                     new HeavyweightFocusRequest(heavyweight, descendant,
2325                                                 temporary, FocusEvent.Cause.UNKNOWN);
2326                 heavyweightRequests.add(hwFocusRequest);
2327 
2328                 if (currentFocusOwner != null) {
2329                     currentFocusOwnerEvent =
2330                         new FocusEvent(currentFocusOwner,
2331                                        FocusEvent.FOCUS_LOST,
2332                                        temporary, descendant);
2333                 }
2334                 newFocusOwnerEvent =
2335                     new FocusEvent(descendant, FocusEvent.FOCUS_GAINED,
2336                                    temporary, currentFocusOwner);
2337             }
2338         }
2339         boolean result = false;
2340         final boolean clearing = clearingCurrentLightweightRequests;
2341 
2342         Throwable caughtEx = null;
2343         try {
2344             clearingCurrentLightweightRequests = false;
2345             synchronized(Component.LOCK) {
2346 
2347                 if (currentFocusOwnerEvent != null && currentFocusOwner != null) {
2348                     ((AWTEvent) currentFocusOwnerEvent).isPosted = true;
2349                     caughtEx = dispatchAndCatchException(caughtEx, currentFocusOwner, currentFocusOwnerEvent);
2350                     result = true;
2351                 }
2352 
2353                 if (newFocusOwnerEvent != null && descendant != null) {
2354                     ((AWTEvent) newFocusOwnerEvent).isPosted = true;
2355                     caughtEx = dispatchAndCatchException(caughtEx, descendant, newFocusOwnerEvent);
2356                     result = true;
2357                 }
2358             }
2359         } finally {
2360             clearingCurrentLightweightRequests = clearing;
2361         }
2362         if (caughtEx instanceof RuntimeException) {
2363             throw (RuntimeException)caughtEx;
2364         } else if (caughtEx instanceof Error) {
2365             throw (Error)caughtEx;
2366         }
2367         return result;
2368     }
2369 
2370     /**
2371      * Indicates whether the native implementation should proceed with a
2372      * pending, native focus request. Before changing the focus at the native
2373      * level, the AWT implementation should always call this function for
2374      * permission. This function will reject the request if a duplicate request
2375      * preceded it, or if the specified heavyweight Component already owns the
2376      * focus and no native focus changes are pending. Otherwise, the request
2377      * will be approved and the focus request list will be updated so that,
2378      * if necessary, the proper descendant will be focused when the
2379      * corresponding FOCUS_GAINED event on the heavyweight is received.
2380      *
2381      * An implementation must ensure that calls to this method and native
2382      * focus changes are atomic. If this is not guaranteed, then the ordering
2383      * of the focus request list may be incorrect, leading to errors in the
2384      * type-ahead mechanism. Typically this is accomplished by only calling
2385      * this function from the native event pumping thread, or by holding a
2386      * global, native lock during invocation.
2387      */
2388     static int shouldNativelyFocusHeavyweight
2389         (Component heavyweight, Component descendant, boolean temporary,
2390          boolean focusedWindowChangeAllowed, long time, FocusEvent.Cause cause)
2391     {
2392         if (log.isLoggable(PlatformLogger.Level.FINE)) {
2393             if (heavyweight == null) {
2394                 log.fine("Assertion (heavyweight != null) failed");
2395             }
2396             if (time == 0) {
2397                 log.fine("Assertion (time != 0) failed");
2398             }
2399         }
2400 
2401         if (descendant == null) {
2402             // Focus transfers from a lightweight child back to the
2403             // heavyweight Container should be treated like lightweight
2404             // focus transfers.
2405             descendant = heavyweight;
2406         }
2407 
2408         KeyboardFocusManager manager =
2409             getCurrentKeyboardFocusManager(SunToolkit.targetToAppContext(descendant));
2410         KeyboardFocusManager thisManager = getCurrentKeyboardFocusManager();
2411         Component currentFocusOwner = thisManager.getGlobalFocusOwner();
2412         Component nativeFocusOwner = thisManager.getNativeFocusOwner();
2413         Window nativeFocusedWindow = thisManager.getNativeFocusedWindow();
2414         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
2415             focusLog.finer("SNFH for {0} in {1}",
2416                        String.valueOf(descendant), String.valueOf(heavyweight));
2417         }
2418         if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
2419             focusLog.finest("0. Current focus owner {0}",
2420                             String.valueOf(currentFocusOwner));
2421             focusLog.finest("0. Native focus owner {0}",
2422                             String.valueOf(nativeFocusOwner));
2423             focusLog.finest("0. Native focused window {0}",
2424                             String.valueOf(nativeFocusedWindow));
2425         }
2426         synchronized (heavyweightRequests) {
2427             HeavyweightFocusRequest hwFocusRequest = getLastHWRequest();
2428             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
2429                 focusLog.finest("Request {0}", String.valueOf(hwFocusRequest));
2430             }
2431             if (hwFocusRequest == null &&
2432                 heavyweight == nativeFocusOwner &&
2433                 heavyweight.getContainingWindow() == nativeFocusedWindow)
2434             {
2435                 if (descendant == currentFocusOwner) {
2436                     // Redundant request.
2437                     if (focusLog.isLoggable(PlatformLogger.Level.FINEST))
2438                         focusLog.finest("1. SNFH_FAILURE for {0}",
2439                                         String.valueOf(descendant));
2440                     return SNFH_FAILURE;
2441                 }
2442 
2443                 // 'heavyweight' owns the native focus and there are no pending
2444                 // requests. 'heavyweight' must be a Container and
2445                 // 'descendant' must not be the focus owner. Otherwise,
2446                 // we would never have gotten this far.
2447                 manager.enqueueKeyEvents(time, descendant);
2448 
2449                 hwFocusRequest =
2450                     new HeavyweightFocusRequest(heavyweight, descendant,
2451                                                 temporary, cause);
2452                 heavyweightRequests.add(hwFocusRequest);
2453 
2454                 if (currentFocusOwner != null) {
2455                     FocusEvent currentFocusOwnerEvent =
2456                         new FocusEvent(currentFocusOwner,
2457                                        FocusEvent.FOCUS_LOST,
2458                                        temporary, descendant, cause);
2459                     // Fix 5028014. Rolled out.
2460                     // SunToolkit.postPriorityEvent(currentFocusOwnerEvent);
2461                     SunToolkit.postEvent(currentFocusOwner.appContext,
2462                                          currentFocusOwnerEvent);
2463                 }
2464                 FocusEvent newFocusOwnerEvent =
2465                     new FocusEvent(descendant, FocusEvent.FOCUS_GAINED,
2466                                    temporary, currentFocusOwner, cause);
2467                 // Fix 5028014. Rolled out.
2468                 // SunToolkit.postPriorityEvent(newFocusOwnerEvent);
2469                 SunToolkit.postEvent(descendant.appContext, newFocusOwnerEvent);
2470 
2471                 if (focusLog.isLoggable(PlatformLogger.Level.FINEST))
2472                     focusLog.finest("2. SNFH_HANDLED for {0}", String.valueOf(descendant));
2473                 return SNFH_SUCCESS_HANDLED;
2474             } else if (hwFocusRequest != null &&
2475                        hwFocusRequest.heavyweight == heavyweight) {
2476                 // 'heavyweight' doesn't have the native focus right now, but
2477                 // if all pending requests were completed, it would. Add
2478                 // descendant to the heavyweight's list of pending
2479                 // lightweight focus transfers.
2480                 if (hwFocusRequest.addLightweightRequest(descendant,
2481                                                          temporary, cause)) {
2482                     manager.enqueueKeyEvents(time, descendant);
2483                 }
2484 
2485                 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
2486                     focusLog.finest("3. SNFH_HANDLED for lightweight" +
2487                                     descendant + " in " + heavyweight);
2488                 }
2489                 return SNFH_SUCCESS_HANDLED;
2490             } else {
2491                 if (!focusedWindowChangeAllowed) {
2492                     // For purposes of computing oldFocusedWindow, we should look at
2493                     // the second to last HeavyweightFocusRequest on the queue iff the
2494                     // last HeavyweightFocusRequest is CLEAR_GLOBAL_FOCUS_OWNER. If
2495                     // there is no second to last HeavyweightFocusRequest, null is an
2496                     // acceptable value.
2497                     if (hwFocusRequest ==
2498                         HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER)
2499                     {
2500                         int size = heavyweightRequests.size();
2501                         hwFocusRequest = (size >= 2)
2502                             ? heavyweightRequests.get(size - 2)
2503                             : null;
2504                     }
2505                     if (focusedWindowChanged(heavyweight,
2506                                              (hwFocusRequest != null)
2507                                              ? hwFocusRequest.heavyweight
2508                                              : nativeFocusedWindow)) {
2509                         if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
2510                             focusLog.finest("4. SNFH_FAILURE for " + descendant);
2511                         }
2512                         return SNFH_FAILURE;
2513                     }
2514                 }
2515 
2516                 manager.enqueueKeyEvents(time, descendant);
2517                 heavyweightRequests.add
2518                     (new HeavyweightFocusRequest(heavyweight, descendant,
2519                                                  temporary, cause));
2520                 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
2521                     focusLog.finest("5. SNFH_PROCEED for " + descendant);
2522                 }
2523                 return SNFH_SUCCESS_PROCEED;
2524             }
2525         }
2526     }
2527 
2528     /**
2529      * Returns the Window which will be active after processing this request,
2530      * or null if this is a duplicate request. The active Window is useful
2531      * because some native platforms do not support setting the native focus
2532      * owner to null. On these platforms, the obvious choice is to set the
2533      * focus owner to the focus proxy of the active Window.
2534      */
2535     static Window markClearGlobalFocusOwner() {
2536         // need to call this out of synchronized block to avoid possible deadlock
2537         // see 6454631.
2538         final Component nativeFocusedWindow =
2539                 getCurrentKeyboardFocusManager().getNativeFocusedWindow();
2540 
2541         synchronized (heavyweightRequests) {
2542             HeavyweightFocusRequest hwFocusRequest = getLastHWRequest();
2543             if (hwFocusRequest ==
2544                 HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER)
2545             {
2546                 // duplicate request
2547                 return null;
2548             }
2549 
2550             heavyweightRequests.add
2551                 (HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER);
2552 
2553             Component activeWindow = ((hwFocusRequest != null)
2554                 ? SunToolkit.getContainingWindow(hwFocusRequest.heavyweight)
2555                 : nativeFocusedWindow);
2556             while (activeWindow != null &&
2557                    !((activeWindow instanceof Frame) ||
2558                      (activeWindow instanceof Dialog)))
2559             {
2560                 activeWindow = activeWindow.getParent_NoClientCode();
2561             }
2562 
2563             return (Window) activeWindow;
2564         }
2565     }
2566     Component getCurrentWaitingRequest(Component parent) {
2567         synchronized (heavyweightRequests) {
2568             HeavyweightFocusRequest hwFocusRequest = getFirstHWRequest();
2569             if (hwFocusRequest != null) {
2570                 if (hwFocusRequest.heavyweight == parent) {
2571                     LightweightFocusRequest lwFocusRequest =
2572                         hwFocusRequest.lightweightRequests.getFirst();
2573                     if (lwFocusRequest != null) {
2574                         return lwFocusRequest.component;
2575                     }
2576                 }
2577             }
2578         }
2579         return null;
2580     }
2581 
2582     static boolean isAutoFocusTransferEnabled() {
2583         synchronized (heavyweightRequests) {
2584             return (heavyweightRequests.size() == 0)
2585                     && !disableRestoreFocus
2586                     && (null == currentLightweightRequests);
2587         }
2588     }
2589 
2590     static boolean isAutoFocusTransferEnabledFor(Component comp) {
2591         return isAutoFocusTransferEnabled() && comp.isAutoFocusTransferOnDisposal();
2592     }
2593 
2594     /*
2595      * Used to process exceptions in dispatching focus event (in focusLost/focusGained callbacks).
2596      * @param ex previously caught exception that may be processed right here, or null
2597      * @param comp the component to dispatch the event to
2598      * @param event the event to dispatch to the component
2599      */
2600     private static Throwable dispatchAndCatchException(Throwable ex, Component comp, FocusEvent event) {
2601         Throwable retEx = null;
2602         try {
2603             comp.dispatchEvent(event);
2604         } catch (RuntimeException re) {
2605             retEx = re;
2606         } catch (Error er) {
2607             retEx = er;
2608         }
2609         if (retEx != null) {
2610             if (ex != null) {
2611                 handleException(ex);
2612             }
2613             return retEx;
2614         }
2615         return ex;
2616     }
2617 
2618     private static void handleException(Throwable ex) {
2619         ex.printStackTrace();
2620     }
2621 
2622     static void processCurrentLightweightRequests() {
2623         KeyboardFocusManager manager = getCurrentKeyboardFocusManager();
2624         LinkedList<LightweightFocusRequest> localLightweightRequests = null;
2625 
2626         Component globalFocusOwner = manager.getGlobalFocusOwner();
2627         if ((globalFocusOwner != null) &&
2628             (globalFocusOwner.appContext != AppContext.getAppContext()))
2629         {
2630             // The current app context differs from the app context of a focus
2631             // owner (and all pending lightweight requests), so we do nothing
2632             // now and wait for a next event.
2633             return;
2634         }
2635 
2636         synchronized(heavyweightRequests) {
2637             if (currentLightweightRequests != null) {
2638                 clearingCurrentLightweightRequests = true;
2639                 disableRestoreFocus = true;
2640                 localLightweightRequests = currentLightweightRequests;
2641                 allowSyncFocusRequests = (localLightweightRequests.size() < 2);
2642                 currentLightweightRequests = null;
2643             } else {
2644                 // do nothing
2645                 return;
2646             }
2647         }
2648 
2649         Throwable caughtEx = null;
2650         try {
2651             if (localLightweightRequests != null) {
2652                 Component lastFocusOwner = null;
2653                 Component currentFocusOwner = null;
2654 
2655                 for (Iterator<KeyboardFocusManager.LightweightFocusRequest> iter = localLightweightRequests.iterator(); iter.hasNext(); ) {
2656 
2657                     currentFocusOwner = manager.getGlobalFocusOwner();
2658                     LightweightFocusRequest lwFocusRequest =
2659                         iter.next();
2660 
2661                     /*
2662                      * WARNING: This is based on DKFM's logic solely!
2663                      *
2664                      * We allow to trigger restoreFocus() in the dispatching process
2665                      * only if we have the last request to dispatch. If the last request
2666                      * fails, focus will be restored to either the component of the last
2667                      * previously succeeded request, or to the focus owner that was
2668                      * before this clearing process.
2669                      */
2670                     if (!iter.hasNext()) {
2671                         disableRestoreFocus = false;
2672                     }
2673 
2674                     FocusEvent currentFocusOwnerEvent = null;
2675                     /*
2676                      * We're not dispatching FOCUS_LOST while the current focus owner is null.
2677                      * But regardless of whether it's null or not, we're clearing ALL the local
2678                      * lw requests.
2679                      */
2680                     if (currentFocusOwner != null) {
2681                         currentFocusOwnerEvent = new FocusEvent(currentFocusOwner,
2682                                        FocusEvent.FOCUS_LOST,
2683                                        lwFocusRequest.temporary,
2684                                        lwFocusRequest.component, lwFocusRequest.cause);
2685                     }
2686                     FocusEvent newFocusOwnerEvent =
2687                         new FocusEvent(lwFocusRequest.component,
2688                                        FocusEvent.FOCUS_GAINED,
2689                                        lwFocusRequest.temporary,
2690                                        currentFocusOwner == null ? lastFocusOwner : currentFocusOwner,
2691                                        lwFocusRequest.cause);
2692 
2693                     if (currentFocusOwner != null) {
2694                         ((AWTEvent) currentFocusOwnerEvent).isPosted = true;
2695                         caughtEx = dispatchAndCatchException(caughtEx, currentFocusOwner, currentFocusOwnerEvent);
2696                     }
2697 
2698                     ((AWTEvent) newFocusOwnerEvent).isPosted = true;
2699                     caughtEx = dispatchAndCatchException(caughtEx, lwFocusRequest.component, newFocusOwnerEvent);
2700 
2701                     if (manager.getGlobalFocusOwner() == lwFocusRequest.component) {
2702                         lastFocusOwner = lwFocusRequest.component;
2703                     }
2704                 }
2705             }
2706         } finally {
2707             clearingCurrentLightweightRequests = false;
2708             disableRestoreFocus = false;
2709             localLightweightRequests = null;
2710             allowSyncFocusRequests = true;
2711         }
2712         if (caughtEx instanceof RuntimeException) {
2713             throw (RuntimeException)caughtEx;
2714         } else if (caughtEx instanceof Error) {
2715             throw (Error)caughtEx;
2716         }
2717     }
2718 
2719     static FocusEvent retargetUnexpectedFocusEvent(FocusEvent fe) {
2720         synchronized (heavyweightRequests) {
2721             // Any other case represents a failure condition which we did
2722             // not expect. We need to clearFocusRequestList() and patch up
2723             // the event as best as possible.
2724 
2725             if (removeFirstRequest()) {
2726                 return (FocusEvent)retargetFocusEvent(fe);
2727             }
2728 
2729             Component source = fe.getComponent();
2730             Component opposite = fe.getOppositeComponent();
2731             boolean temporary = false;
2732             if (fe.getID() == FocusEvent.FOCUS_LOST &&
2733                 (opposite == null || isTemporary(opposite, source)))
2734             {
2735                 temporary = true;
2736             }
2737             return new FocusEvent(source, fe.getID(), temporary, opposite,
2738                                         FocusEvent.Cause.UNEXPECTED);
2739         }
2740     }
2741 
2742     static FocusEvent retargetFocusGained(FocusEvent fe) {
2743         assert (fe.getID() == FocusEvent.FOCUS_GAINED);
2744 
2745         Component currentFocusOwner = getCurrentKeyboardFocusManager().
2746             getGlobalFocusOwner();
2747         Component source = fe.getComponent();
2748         Component opposite = fe.getOppositeComponent();
2749         Component nativeSource = getHeavyweight(source);
2750 
2751         synchronized (heavyweightRequests) {
2752             HeavyweightFocusRequest hwFocusRequest = getFirstHWRequest();
2753 
2754             if (hwFocusRequest == HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER)
2755             {
2756                 return retargetUnexpectedFocusEvent(fe);
2757             }
2758 
2759             if (source != null && nativeSource == null && hwFocusRequest != null) {
2760                 // if source w/o peer and
2761                 // if source is equal to first lightweight
2762                 // then we should correct source and nativeSource
2763                 if (source == hwFocusRequest.getFirstLightweightRequest().component)
2764                 {
2765                     source = hwFocusRequest.heavyweight;
2766                     nativeSource = source; // source is heavyweight itself
2767                 }
2768             }
2769             if (hwFocusRequest != null &&
2770                 nativeSource == hwFocusRequest.heavyweight)
2771             {
2772                 // Focus change as a result of a known call to requestFocus(),
2773                 // or known click on a peer focusable heavyweight Component.
2774 
2775                 heavyweightRequests.removeFirst();
2776 
2777                 LightweightFocusRequest lwFocusRequest =
2778                     hwFocusRequest.lightweightRequests.removeFirst();
2779 
2780                 Component newSource = lwFocusRequest.component;
2781                 if (currentFocusOwner != null) {
2782                     /*
2783                      * Since we receive FOCUS_GAINED when current focus
2784                      * owner is not null, corresponding FOCUS_LOST is supposed
2785                      * to be lost.  And so,  we keep new focus owner
2786                      * to determine synthetic FOCUS_LOST event which will be
2787                      * generated by KeyboardFocusManager for this FOCUS_GAINED.
2788                      *
2789                      * This code based on knowledge of
2790                      * DefaultKeyboardFocusManager's implementation and might
2791                      * be not applicable for another KeyboardFocusManager.
2792                      */
2793                     newFocusOwner = newSource;
2794                 }
2795 
2796                 boolean temporary = (opposite == null ||
2797                                      isTemporary(newSource, opposite))
2798                         ? false
2799                         : lwFocusRequest.temporary;
2800 
2801                 if (hwFocusRequest.lightweightRequests.size() > 0) {
2802                     currentLightweightRequests =
2803                         hwFocusRequest.lightweightRequests;
2804                     EventQueue.invokeLater(new Runnable() {
2805                             public void run() {
2806                                 processCurrentLightweightRequests();
2807                             }
2808                         });
2809                 }
2810 
2811                 // 'opposite' will be fixed by
2812                 // DefaultKeyboardFocusManager.realOppositeComponent
2813                 return new FocusEvent(newSource,
2814                                       FocusEvent.FOCUS_GAINED, temporary,
2815                                       opposite, lwFocusRequest.cause);
2816             }
2817 
2818             if (currentFocusOwner != null
2819                 && currentFocusOwner.getContainingWindow() == source
2820                 && (hwFocusRequest == null || source != hwFocusRequest.heavyweight))
2821             {
2822                 // Special case for FOCUS_GAINED in top-levels
2823                 // If it arrives as the result of activation we should skip it
2824                 // This event will not have appropriate request record and
2825                 // on arrival there will be already some focus owner set.
2826                 return new FocusEvent(currentFocusOwner, FocusEvent.FOCUS_GAINED, false,
2827                                             null, FocusEvent.Cause.ACTIVATION);
2828             }
2829 
2830             return retargetUnexpectedFocusEvent(fe);
2831         } // end synchronized(heavyweightRequests)
2832     }
2833 
2834     static FocusEvent retargetFocusLost(FocusEvent fe) {
2835         assert (fe.getID() == FocusEvent.FOCUS_LOST);
2836 
2837         Component currentFocusOwner = getCurrentKeyboardFocusManager().
2838             getGlobalFocusOwner();
2839         Component opposite = fe.getOppositeComponent();
2840         Component nativeOpposite = getHeavyweight(opposite);
2841 
2842         synchronized (heavyweightRequests) {
2843             HeavyweightFocusRequest hwFocusRequest = getFirstHWRequest();
2844 
2845             if (hwFocusRequest == HeavyweightFocusRequest.CLEAR_GLOBAL_FOCUS_OWNER)
2846             {
2847                 if (currentFocusOwner != null) {
2848                     // Call to KeyboardFocusManager.clearGlobalFocusOwner()
2849                     heavyweightRequests.removeFirst();
2850                     return new FocusEvent(currentFocusOwner,
2851                                                 FocusEvent.FOCUS_LOST, false, null,
2852                                                 FocusEvent.Cause.CLEAR_GLOBAL_FOCUS_OWNER);
2853                 }
2854 
2855                 // Otherwise, fall through to failure case below
2856 
2857             } else if (opposite == null)
2858             {
2859                 // Focus leaving application
2860                 if (currentFocusOwner != null) {
2861                     return new FocusEvent(currentFocusOwner,
2862                                                 FocusEvent.FOCUS_LOST,
2863                                                 true, null, FocusEvent.Cause.ACTIVATION);
2864                 } else {
2865                     return fe;
2866                 }
2867             } else if (hwFocusRequest != null &&
2868                        (nativeOpposite == hwFocusRequest.heavyweight ||
2869                         nativeOpposite == null &&
2870                         opposite == hwFocusRequest.getFirstLightweightRequest().component))
2871             {
2872                 if (currentFocusOwner == null) {
2873                     return fe;
2874                 }
2875                 // Focus change as a result of a known call to requestFocus(),
2876                 // or click on a peer focusable heavyweight Component.
2877                 // If a focus transfer is made across top-levels, then the
2878                 // FOCUS_LOST event is always temporary, and the FOCUS_GAINED
2879                 // event is always permanent. Otherwise, the stored temporary
2880                 // value is honored.
2881 
2882                 LightweightFocusRequest lwFocusRequest =
2883                     hwFocusRequest.lightweightRequests.getFirst();
2884 
2885                 boolean temporary = isTemporary(opposite, currentFocusOwner)
2886                     ? true
2887                     : lwFocusRequest.temporary;
2888 
2889                 return new FocusEvent(currentFocusOwner, FocusEvent.FOCUS_LOST,
2890                                             temporary, lwFocusRequest.component, lwFocusRequest.cause);
2891             } else if (focusedWindowChanged(opposite, currentFocusOwner)) {
2892                 // If top-level changed there might be no focus request in a list
2893                 // But we know the opposite, we now it is temporary - dispatch the event.
2894                 if (!fe.isTemporary() && currentFocusOwner != null) {
2895                     // Create copy of the event with only difference in temporary parameter.
2896                     fe = new FocusEvent(currentFocusOwner, FocusEvent.FOCUS_LOST,
2897                                               true, opposite, FocusEvent.Cause.ACTIVATION);
2898                 }
2899                 return fe;
2900             }
2901 
2902             return retargetUnexpectedFocusEvent(fe);
2903         }  // end synchronized(heavyweightRequests)
2904     }
2905 
2906     static AWTEvent retargetFocusEvent(AWTEvent event) {
2907         if (clearingCurrentLightweightRequests) {
2908             return event;
2909         }
2910 
2911         KeyboardFocusManager manager = getCurrentKeyboardFocusManager();
2912         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
2913             if (event instanceof FocusEvent || event instanceof WindowEvent) {
2914                 focusLog.finer(">>> {0}", String.valueOf(event));
2915             }
2916             if (focusLog.isLoggable(PlatformLogger.Level.FINER) && event instanceof KeyEvent) {
2917                 focusLog.finer("    focus owner is {0}",
2918                                String.valueOf(manager.getGlobalFocusOwner()));
2919                 focusLog.finer(">>> {0}", String.valueOf(event));
2920             }
2921         }
2922 
2923         synchronized(heavyweightRequests) {
2924             /*
2925              * This code handles FOCUS_LOST event which is generated by
2926              * DefaultKeyboardFocusManager for FOCUS_GAINED.
2927              *
2928              * This code based on knowledge of DefaultKeyboardFocusManager's
2929              * implementation and might be not applicable for another
2930              * KeyboardFocusManager.
2931              *
2932              * Fix for 4472032
2933              */
2934             if (newFocusOwner != null &&
2935                 event.getID() == FocusEvent.FOCUS_LOST)
2936             {
2937                 FocusEvent fe = (FocusEvent)event;
2938 
2939                 if (manager.getGlobalFocusOwner() == fe.getComponent() &&
2940                     fe.getOppositeComponent() == newFocusOwner)
2941                 {
2942                     newFocusOwner = null;
2943                     return event;
2944                 }
2945             }
2946         }
2947 
2948         processCurrentLightweightRequests();
2949 
2950         switch (event.getID()) {
2951             case FocusEvent.FOCUS_GAINED: {
2952                 event = retargetFocusGained((FocusEvent)event);
2953                 break;
2954             }
2955             case FocusEvent.FOCUS_LOST: {
2956                 event = retargetFocusLost((FocusEvent)event);
2957                 break;
2958             }
2959             default:
2960                 /* do nothing */
2961         }
2962         return event;
2963     }
2964 
2965     /**
2966      * Clears markers queue
2967      * This method is not intended to be overridden by KFM's.
2968      * Only DefaultKeyboardFocusManager can implement it.
2969      * @since 1.5
2970      */
2971     void clearMarkers() {
2972     }
2973 
2974     static boolean removeFirstRequest() {
2975         KeyboardFocusManager manager =
2976             KeyboardFocusManager.getCurrentKeyboardFocusManager();
2977 
2978         synchronized(heavyweightRequests) {
2979             HeavyweightFocusRequest hwFocusRequest = getFirstHWRequest();
2980 
2981             if (hwFocusRequest != null) {
2982                 heavyweightRequests.removeFirst();
2983                 if (hwFocusRequest.lightweightRequests != null) {
2984                     for (Iterator<KeyboardFocusManager.LightweightFocusRequest> lwIter = hwFocusRequest.lightweightRequests.
2985                              iterator();
2986                          lwIter.hasNext(); )
2987                     {
2988                         manager.dequeueKeyEvents
2989                             (-1, lwIter.next().
2990                              component);
2991                     }
2992                 }
2993             }
2994             // Fix for 4799136 - clear type-ahead markers if requests queue is empty
2995             // We do it here because this method is called only when problems happen
2996             if (heavyweightRequests.size() == 0) {
2997                 manager.clearMarkers();
2998             }
2999             return (heavyweightRequests.size() > 0);
3000         }
3001     }
3002     static void removeLastFocusRequest(Component heavyweight) {
3003         if (log.isLoggable(PlatformLogger.Level.FINE)) {
3004             if (heavyweight == null) {
3005                 log.fine("Assertion (heavyweight != null) failed");
3006             }
3007         }
3008 
3009         KeyboardFocusManager manager =
3010             KeyboardFocusManager.getCurrentKeyboardFocusManager();
3011         synchronized(heavyweightRequests) {
3012             HeavyweightFocusRequest hwFocusRequest = getLastHWRequest();
3013             if (hwFocusRequest != null &&
3014                 hwFocusRequest.heavyweight == heavyweight) {
3015                 heavyweightRequests.removeLast();
3016             }
3017             // Fix for 4799136 - clear type-ahead markers if requests queue is empty
3018             // We do it here because this method is called only when problems happen
3019             if (heavyweightRequests.size() == 0) {
3020                 manager.clearMarkers();
3021             }
3022         }
3023     }
3024 
3025     private static boolean focusedWindowChanged(Component to, Component from) {
3026         Window wto = SunToolkit.getContainingWindow(to);
3027         Window wfrom = SunToolkit.getContainingWindow(from);
3028         if (wto == null && wfrom == null) {
3029             return true;
3030         }
3031         if (wto == null) {
3032             return true;
3033         }
3034         if (wfrom == null) {
3035             return true;
3036         }
3037         return (wto != wfrom);
3038     }
3039 
3040     private static boolean isTemporary(Component to, Component from) {
3041         Window wto = SunToolkit.getContainingWindow(to);
3042         Window wfrom = SunToolkit.getContainingWindow(from);
3043         if (wto == null && wfrom == null) {
3044             return false;
3045         }
3046         if (wto == null) {
3047             return true;
3048         }
3049         if (wfrom == null) {
3050             return false;
3051         }
3052         return (wto != wfrom);
3053     }
3054 
3055     static Component getHeavyweight(Component comp) {
3056         if (comp == null || comp.peer == null) {
3057             return null;
3058         } else if (comp.peer instanceof LightweightPeer) {
3059             return comp.getNativeContainer();
3060         } else {
3061             return comp;
3062         }
3063     }
3064 
3065     // Accessor to private field isProxyActive of KeyEvent
3066     private static boolean isProxyActiveImpl(KeyEvent e) {
3067         return AWTAccessor.getKeyEventAccessor().isProxyActive(e);
3068     }
3069 
3070     // Returns the value of this KeyEvent's field isProxyActive
3071     static boolean isProxyActive(KeyEvent e) {
3072         if (!GraphicsEnvironment.isHeadless()) {
3073             return isProxyActiveImpl(e);
3074         } else {
3075             return false;
3076         }
3077     }
3078 
3079     private static HeavyweightFocusRequest getLastHWRequest() {
3080         synchronized(heavyweightRequests) {
3081             return (heavyweightRequests.size() > 0)
3082                 ? heavyweightRequests.getLast()
3083                 : null;
3084         }
3085     }
3086 
3087     private static HeavyweightFocusRequest getFirstHWRequest() {
3088         synchronized(heavyweightRequests) {
3089             return (heavyweightRequests.size() > 0)
3090                 ? heavyweightRequests.getFirst()
3091                 : null;
3092         }
3093     }
3094 
3095     private static void checkReplaceKFMPermission()
3096         throws SecurityException
3097     {
3098         SecurityManager security = System.getSecurityManager();
3099         if (security != null) {
3100             if (replaceKeyboardFocusManagerPermission == null) {
3101                 replaceKeyboardFocusManagerPermission =
3102                     new AWTPermission("replaceKeyboardFocusManager");
3103             }
3104             security.
3105                 checkPermission(replaceKeyboardFocusManagerPermission);
3106         }
3107     }
3108 
3109     // Checks if this KeyboardFocusManager instance is the current KFM,
3110     // or otherwise checks if the calling thread has "replaceKeyboardFocusManager"
3111     // permission. Here's the reasoning to do so:
3112     //
3113     // A system KFM instance (which is the current KFM by default) may have no
3114     // "replaceKFM" permission when a client code is on the call stack beneath,
3115     // but still it should be able to execute the methods protected by this check
3116     // due to the system KFM is trusted (and so it does like "privileged").
3117     //
3118     // If this KFM instance is not the current KFM but the client code has all
3119     // permissions we can't throw SecurityException because it would contradict
3120     // the security concepts. In this case the trusted client code is responsible
3121     // for calling the secured methods from KFM instance which is not current.
3122     private void checkKFMSecurity()
3123         throws SecurityException
3124     {
3125         if (this != getCurrentKeyboardFocusManager()) {
3126             checkReplaceKFMPermission();
3127         }
3128     }
3129 }