1 /*
   2  * Copyright (c) 2000, 2016, 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.KeyEvent;
  29 import java.awt.event.WindowEvent;
  30 import java.awt.peer.ComponentPeer;
  31 import java.awt.peer.LightweightPeer;
  32 import java.lang.ref.WeakReference;
  33 import java.util.LinkedList;
  34 import java.util.Iterator;
  35 import java.util.ListIterator;
  36 import java.util.Set;
  37 
  38 import sun.util.logging.PlatformLogger;
  39 
  40 import sun.awt.AppContext;
  41 import sun.awt.SunToolkit;
  42 import sun.awt.AWTAccessor;
  43 import sun.awt.TimedWindowEvent;
  44 
  45 /**
  46  * The default KeyboardFocusManager for AWT applications. Focus traversal is
  47  * done in response to a Component's focus traversal keys, and using a
  48  * Container's FocusTraversalPolicy.
  49  * <p>
  50  * Please see
  51  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
  52  * How to Use the Focus Subsystem</a>,
  53  * a section in <em>The Java Tutorial</em>, and the
  54  * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
  55  * for more information.
  56  *
  57  * @author David Mendenhall
  58  *
  59  * @see FocusTraversalPolicy
  60  * @see Component#setFocusTraversalKeys
  61  * @see Component#getFocusTraversalKeys
  62  * @since 1.4
  63  */
  64 public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
  65     private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.DefaultKeyboardFocusManager");
  66 
  67     // null weak references to not create too many objects
  68     private static final WeakReference<Window> NULL_WINDOW_WR =
  69         new WeakReference<Window>(null);
  70     private static final WeakReference<Component> NULL_COMPONENT_WR =
  71         new WeakReference<Component>(null);
  72     private WeakReference<Window> realOppositeWindowWR = NULL_WINDOW_WR;
  73     private WeakReference<Component> realOppositeComponentWR = NULL_COMPONENT_WR;
  74     private int inSendMessage;
  75     private LinkedList<KeyEvent> enqueuedKeyEvents = new LinkedList<KeyEvent>();
  76     private LinkedList<TypeAheadMarker> typeAheadMarkers = new LinkedList<TypeAheadMarker>();
  77     private boolean consumeNextKeyTyped;
  78     private Component restoreFocusTo;
  79 
  80     static {
  81         AWTAccessor.setDefaultKeyboardFocusManagerAccessor(
  82             new AWTAccessor.DefaultKeyboardFocusManagerAccessor() {
  83                 public void consumeNextKeyTyped(DefaultKeyboardFocusManager dkfm, KeyEvent e) {
  84                     dkfm.consumeNextKeyTyped(e);
  85                 }
  86             });
  87     }
  88 
  89     private static class TypeAheadMarker {
  90         long after;
  91         Component untilFocused;
  92 
  93         TypeAheadMarker(long after, Component untilFocused) {
  94             this.after = after;
  95             this.untilFocused = untilFocused;
  96         }
  97         /**
  98          * Returns string representation of the marker
  99          */
 100         public String toString() {
 101             return ">>> Marker after " + after + " on " + untilFocused;
 102         }
 103     }
 104 
 105     private Window getOwningFrameDialog(Window window) {
 106         while (window != null && !(window instanceof Frame ||
 107                                    window instanceof Dialog)) {
 108             window = (Window)window.getParent();
 109         }
 110         return window;
 111     }
 112 
 113     /*
 114      * This series of restoreFocus methods is used for recovering from a
 115      * rejected focus or activation change. Rejections typically occur when
 116      * the user attempts to focus a non-focusable Component or Window.
 117      */
 118     private void restoreFocus(FocusEvent fe, Window newFocusedWindow) {
 119         Component realOppositeComponent = this.realOppositeComponentWR.get();
 120         Component vetoedComponent = fe.getComponent();
 121 
 122         if (newFocusedWindow != null && restoreFocus(newFocusedWindow,
 123                                                      vetoedComponent, false))
 124         {
 125         } else if (realOppositeComponent != null &&
 126                    doRestoreFocus(realOppositeComponent, vetoedComponent, false)) {
 127         } else if (fe.getOppositeComponent() != null &&
 128                    doRestoreFocus(fe.getOppositeComponent(), vetoedComponent, false)) {
 129         } else {
 130             clearGlobalFocusOwnerPriv();
 131         }
 132     }
 133     private void restoreFocus(WindowEvent we) {
 134         Window realOppositeWindow = this.realOppositeWindowWR.get();
 135         if (realOppositeWindow != null
 136             && restoreFocus(realOppositeWindow, null, false))
 137         {
 138             // do nothing, everything is done in restoreFocus()
 139         } else if (we.getOppositeWindow() != null &&
 140                    restoreFocus(we.getOppositeWindow(), null, false))
 141         {
 142             // do nothing, everything is done in restoreFocus()
 143         } else {
 144             clearGlobalFocusOwnerPriv();
 145         }
 146     }
 147     private boolean restoreFocus(Window aWindow, Component vetoedComponent,
 148                                  boolean clearOnFailure) {
 149         restoreFocusTo = null;
 150         Component toFocus =
 151             KeyboardFocusManager.getMostRecentFocusOwner(aWindow);
 152 
 153         if (toFocus != null && toFocus != vetoedComponent) {
 154             if (getHeavyweight(aWindow) != getNativeFocusOwner()) {
 155                 // cannot restore focus synchronously
 156                 if (!toFocus.isShowing() || !toFocus.canBeFocusOwner()) {
 157                     toFocus = toFocus.getNextFocusCandidate();
 158                 }
 159                 if (toFocus != null && toFocus != vetoedComponent) {
 160                     if (!toFocus.requestFocus(false,
 161                                                    FocusEvent.Cause.ROLLBACK)) {
 162                         restoreFocusTo = toFocus;
 163                     }
 164                     return true;
 165                 }
 166             } else if (doRestoreFocus(toFocus, vetoedComponent, false)) {
 167                 return true;
 168             }
 169         }
 170         if (clearOnFailure) {
 171             clearGlobalFocusOwnerPriv();
 172             return true;
 173         } else {
 174             return false;
 175         }
 176     }
 177     private boolean restoreFocus(Component toFocus, boolean clearOnFailure) {
 178         return doRestoreFocus(toFocus, null, clearOnFailure);
 179     }
 180     private boolean doRestoreFocus(Component toFocus, Component vetoedComponent,
 181                                    boolean clearOnFailure)
 182     {
 183         if (toFocus != vetoedComponent && toFocus.isShowing() && toFocus.canBeFocusOwner() &&
 184             toFocus.requestFocus(false, FocusEvent.Cause.ROLLBACK))
 185         {
 186             return true;
 187         } else {
 188             Component nextFocus = toFocus.getNextFocusCandidate();
 189             if (nextFocus != null && nextFocus != vetoedComponent &&
 190                 nextFocus.requestFocusInWindow(FocusEvent.Cause.ROLLBACK))
 191             {
 192                 return true;
 193             } else if (clearOnFailure) {
 194                 clearGlobalFocusOwnerPriv();
 195                 return true;
 196             } else {
 197                 return false;
 198             }
 199         }
 200     }
 201 
 202     /**
 203      * A special type of SentEvent which updates a counter in the target
 204      * KeyboardFocusManager if it is an instance of
 205      * DefaultKeyboardFocusManager.
 206      */
 207     private static class DefaultKeyboardFocusManagerSentEvent
 208         extends SentEvent
 209     {
 210         /*
 211          * serialVersionUID
 212          */
 213         private static final long serialVersionUID = -2924743257508701758L;
 214 
 215         public DefaultKeyboardFocusManagerSentEvent(AWTEvent nested,
 216                                                     AppContext toNotify) {
 217             super(nested, toNotify);
 218         }
 219         public final void dispatch() {
 220             KeyboardFocusManager manager =
 221                 KeyboardFocusManager.getCurrentKeyboardFocusManager();
 222             DefaultKeyboardFocusManager defaultManager =
 223                 (manager instanceof DefaultKeyboardFocusManager)
 224                 ? (DefaultKeyboardFocusManager)manager
 225                 : null;
 226 
 227             if (defaultManager != null) {
 228                 synchronized (defaultManager) {
 229                     defaultManager.inSendMessage++;
 230                 }
 231             }
 232 
 233             super.dispatch();
 234 
 235             if (defaultManager != null) {
 236                 synchronized (defaultManager) {
 237                     defaultManager.inSendMessage--;
 238                 }
 239             }
 240         }
 241     }
 242 
 243     /**
 244      * Sends a synthetic AWTEvent to a Component. If the Component is in
 245      * the current AppContext, then the event is immediately dispatched.
 246      * If the Component is in a different AppContext, then the event is
 247      * posted to the other AppContext's EventQueue, and this method blocks
 248      * until the event is handled or target AppContext is disposed.
 249      * Returns true if successfully dispatched event, false if failed
 250      * to dispatch.
 251      */
 252     static boolean sendMessage(Component target, AWTEvent e) {
 253         e.isPosted = true;
 254         AppContext myAppContext = AppContext.getAppContext();
 255         final AppContext targetAppContext = target.appContext;
 256         final SentEvent se =
 257             new DefaultKeyboardFocusManagerSentEvent(e, myAppContext);
 258 
 259         if (myAppContext == targetAppContext) {
 260             se.dispatch();
 261         } else {
 262             if (targetAppContext.isDisposed()) {
 263                 return false;
 264             }
 265             SunToolkit.postEvent(targetAppContext, se);
 266             if (EventQueue.isDispatchThread()) {
 267                 EventDispatchThread edt = (EventDispatchThread)
 268                     Thread.currentThread();
 269                 edt.pumpEvents(SentEvent.ID, new Conditional() {
 270                         public boolean evaluate() {
 271                             return !se.dispatched && !targetAppContext.isDisposed();
 272                         }
 273                     });
 274             } else {
 275                 synchronized (se) {
 276                     while (!se.dispatched && !targetAppContext.isDisposed()) {
 277                         try {
 278                             se.wait(1000);
 279                         } catch (InterruptedException ie) {
 280                             break;
 281                         }
 282                     }
 283                 }
 284             }
 285         }
 286         return se.dispatched;
 287     }
 288 
 289     /*
 290      * Checks if the focus window event follows key events waiting in the type-ahead
 291      * queue (if any). This may happen when a user types ahead in the window, the client
 292      * listeners hang EDT for a while, and the user switches b/w toplevels. In that
 293      * case the focus window events may be dispatched before the type-ahead events
 294      * get handled. This may lead to wrong focus behavior and in order to avoid it,
 295      * the focus window events are reposted to the end of the event queue. See 6981400.
 296      */
 297     private boolean repostIfFollowsKeyEvents(WindowEvent e) {
 298         if (!(e instanceof TimedWindowEvent)) {
 299             return false;
 300         }
 301         TimedWindowEvent we = (TimedWindowEvent)e;
 302         long time = we.getWhen();
 303         synchronized (this) {
 304             KeyEvent ke = enqueuedKeyEvents.isEmpty() ? null : enqueuedKeyEvents.getFirst();
 305             if (ke != null && time >= ke.getWhen()) {
 306                 TypeAheadMarker marker = typeAheadMarkers.isEmpty() ? null : typeAheadMarkers.getFirst();
 307                 if (marker != null) {
 308                     Window toplevel = marker.untilFocused.getContainingWindow();
 309                     // Check that the component awaiting focus belongs to
 310                     // the current focused window. See 8015454.
 311                     if (toplevel != null && toplevel.isFocused()) {
 312                         SunToolkit.postEvent(AppContext.getAppContext(), new SequencedEvent(e));
 313                         return true;
 314                     }
 315                 }
 316             }
 317         }
 318         return false;
 319     }
 320 
 321     /**
 322      * This method is called by the AWT event dispatcher requesting that the
 323      * current KeyboardFocusManager dispatch the specified event on its behalf.
 324      * DefaultKeyboardFocusManagers dispatch all FocusEvents, all WindowEvents
 325      * related to focus, and all KeyEvents. These events are dispatched based
 326      * on the KeyboardFocusManager's notion of the focus owner and the focused
 327      * and active Windows, sometimes overriding the source of the specified
 328      * AWTEvent. If this method returns {@code false}, then the AWT event
 329      * dispatcher will attempt to dispatch the event itself.
 330      *
 331      * @param e the AWTEvent to be dispatched
 332      * @return {@code true} if this method dispatched the event;
 333      *         {@code false} otherwise
 334      */
 335     public boolean dispatchEvent(AWTEvent e) {
 336         if (focusLog.isLoggable(PlatformLogger.Level.FINE) && (e instanceof WindowEvent || e instanceof FocusEvent)) {
 337             focusLog.fine("" + e);
 338         }
 339         switch (e.getID()) {
 340             case WindowEvent.WINDOW_GAINED_FOCUS: {
 341                 if (repostIfFollowsKeyEvents((WindowEvent)e)) {
 342                     break;
 343                 }
 344 
 345                 WindowEvent we = (WindowEvent)e;
 346                 Window oldFocusedWindow = getGlobalFocusedWindow();
 347                 Window newFocusedWindow = we.getWindow();
 348                 if (newFocusedWindow == oldFocusedWindow) {
 349                     break;
 350                 }
 351 
 352                 if (!(newFocusedWindow.isFocusableWindow()
 353                       && newFocusedWindow.isVisible()
 354                       && newFocusedWindow.isDisplayable()))
 355                 {
 356                     // we can not accept focus on such window, so reject it.
 357                     restoreFocus(we);
 358                     break;
 359                 }
 360                 // If there exists a current focused window, then notify it
 361                 // that it has lost focus.
 362                 if (oldFocusedWindow != null) {
 363                     boolean isEventDispatched =
 364                         sendMessage(oldFocusedWindow,
 365                                 new WindowEvent(oldFocusedWindow,
 366                                                 WindowEvent.WINDOW_LOST_FOCUS,
 367                                                 newFocusedWindow));
 368                     // Failed to dispatch, clear by ourselves
 369                     if (!isEventDispatched) {
 370                         setGlobalFocusOwner(null);
 371                         setGlobalFocusedWindow(null);
 372                     }
 373                 }
 374 
 375                 // Because the native libraries do not post WINDOW_ACTIVATED
 376                 // events, we need to synthesize one if the active Window
 377                 // changed.
 378                 Window newActiveWindow =
 379                     getOwningFrameDialog(newFocusedWindow);
 380                 Window currentActiveWindow = getGlobalActiveWindow();
 381                 if (newActiveWindow != currentActiveWindow) {
 382                     sendMessage(newActiveWindow,
 383                                 new WindowEvent(newActiveWindow,
 384                                                 WindowEvent.WINDOW_ACTIVATED,
 385                                                 currentActiveWindow));
 386                     if (newActiveWindow != getGlobalActiveWindow()) {
 387                         // Activation change was rejected. Unlikely, but
 388                         // possible.
 389                         restoreFocus(we);
 390                         break;
 391                     }
 392                 }
 393 
 394                 setGlobalFocusedWindow(newFocusedWindow);
 395 
 396                 if (newFocusedWindow != getGlobalFocusedWindow()) {
 397                     // Focus change was rejected. Will happen if
 398                     // newFocusedWindow is not a focusable Window.
 399                     restoreFocus(we);
 400                     break;
 401                 }
 402 
 403                 // Restore focus to the Component which last held it. We do
 404                 // this here so that client code can override our choice in
 405                 // a WINDOW_GAINED_FOCUS handler.
 406                 //
 407                 // Make sure that the focus change request doesn't change the
 408                 // focused Window in case we are no longer the focused Window
 409                 // when the request is handled.
 410                 if (inSendMessage == 0) {
 411                     // Identify which Component should initially gain focus
 412                     // in the Window.
 413                     //
 414                     // * If we're in SendMessage, then this is a synthetic
 415                     //   WINDOW_GAINED_FOCUS message which was generated by a
 416                     //   the FOCUS_GAINED handler. Allow the Component to
 417                     //   which the FOCUS_GAINED message was targeted to
 418                     //   receive the focus.
 419                     // * Otherwise, look up the correct Component here.
 420                     //   We don't use Window.getMostRecentFocusOwner because
 421                     //   window is focused now and 'null' will be returned
 422 
 423 
 424                     // Calculating of most recent focus owner and focus
 425                     // request should be synchronized on KeyboardFocusManager.class
 426                     // to prevent from thread race when user will request
 427                     // focus between calculation and our request.
 428                     // But if focus transfer is synchronous, this synchronization
 429                     // may cause deadlock, thus we don't synchronize this block.
 430                     Component toFocus = KeyboardFocusManager.
 431                         getMostRecentFocusOwner(newFocusedWindow);
 432                     boolean isFocusRestore = restoreFocusTo != null &&
 433                                                       toFocus == restoreFocusTo;
 434                     if ((toFocus == null) &&
 435                         newFocusedWindow.isFocusableWindow())
 436                     {
 437                         toFocus = newFocusedWindow.getFocusTraversalPolicy().
 438                             getInitialComponent(newFocusedWindow);
 439                     }
 440                     Component tempLost = null;
 441                     synchronized(KeyboardFocusManager.class) {
 442                         tempLost = newFocusedWindow.setTemporaryLostComponent(null);
 443                     }
 444 
 445                     // The component which last has the focus when this window was focused
 446                     // should receive focus first
 447                     if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
 448                         focusLog.finer("tempLost {0}, toFocus {1}",
 449                                        tempLost, toFocus);
 450                     }
 451                     if (tempLost != null) {
 452                         tempLost.requestFocusInWindow(isFocusRestore ?
 453                                                 FocusEvent.Cause.ROLLBACK :
 454                                                 FocusEvent.Cause.ACTIVATION);
 455                     }
 456 
 457                     if (toFocus != null && toFocus != tempLost) {
 458                         // If there is a component which requested focus when this window
 459                         // was inactive it expects to receive focus after activation.
 460                         toFocus.requestFocusInWindow(FocusEvent.Cause.ACTIVATION);
 461                     }
 462                 }
 463                 restoreFocusTo = null;
 464 
 465                 Window realOppositeWindow = this.realOppositeWindowWR.get();
 466                 if (realOppositeWindow != we.getOppositeWindow()) {
 467                     we = new WindowEvent(newFocusedWindow,
 468                                          WindowEvent.WINDOW_GAINED_FOCUS,
 469                                          realOppositeWindow);
 470                 }
 471                 return typeAheadAssertions(newFocusedWindow, we);
 472             }
 473 
 474             case WindowEvent.WINDOW_ACTIVATED: {
 475                 WindowEvent we = (WindowEvent)e;
 476                 Window oldActiveWindow = getGlobalActiveWindow();
 477                 Window newActiveWindow = we.getWindow();
 478                 if (oldActiveWindow == newActiveWindow) {
 479                     break;
 480                 }
 481 
 482                 // If there exists a current active window, then notify it that
 483                 // it has lost activation.
 484                 if (oldActiveWindow != null) {
 485                     boolean isEventDispatched =
 486                         sendMessage(oldActiveWindow,
 487                                 new WindowEvent(oldActiveWindow,
 488                                                 WindowEvent.WINDOW_DEACTIVATED,
 489                                                 newActiveWindow));
 490                     // Failed to dispatch, clear by ourselves
 491                     if (!isEventDispatched) {
 492                         setGlobalActiveWindow(null);
 493                     }
 494                     if (getGlobalActiveWindow() != null) {
 495                         // Activation change was rejected. Unlikely, but
 496                         // possible.
 497                         break;
 498                     }
 499                 }
 500 
 501                 setGlobalActiveWindow(newActiveWindow);
 502 
 503                 if (newActiveWindow != getGlobalActiveWindow()) {
 504                     // Activation change was rejected. Unlikely, but
 505                     // possible.
 506                     break;
 507                 }
 508 
 509                 return typeAheadAssertions(newActiveWindow, we);
 510             }
 511 
 512             case FocusEvent.FOCUS_GAINED: {
 513                 restoreFocusTo = null;
 514                 FocusEvent fe = (FocusEvent)e;
 515                 Component oldFocusOwner = getGlobalFocusOwner();
 516                 Component newFocusOwner = fe.getComponent();
 517                 if (oldFocusOwner == newFocusOwner) {
 518                     if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
 519                         focusLog.fine("Skipping {0} because focus owner is the same", e);
 520                     }
 521                     // We can't just drop the event - there could be
 522                     // type-ahead markers associated with it.
 523                     dequeueKeyEvents(-1, newFocusOwner);
 524                     break;
 525                 }
 526 
 527                 // If there exists a current focus owner, then notify it that
 528                 // it has lost focus.
 529                 if (oldFocusOwner != null) {
 530                     boolean isEventDispatched =
 531                         sendMessage(oldFocusOwner,
 532                                     new FocusEvent(oldFocusOwner,
 533                                                    FocusEvent.FOCUS_LOST,
 534                                                    fe.isTemporary(),
 535                                                    newFocusOwner, fe.getCause()));
 536                     // Failed to dispatch, clear by ourselves
 537                     if (!isEventDispatched) {
 538                         setGlobalFocusOwner(null);
 539                         if (!fe.isTemporary()) {
 540                             setGlobalPermanentFocusOwner(null);
 541                         }
 542                     }
 543                 }
 544 
 545                 // Because the native windowing system has a different notion
 546                 // of the current focus and activation states, it is possible
 547                 // that a Component outside of the focused Window receives a
 548                 // FOCUS_GAINED event. We synthesize a WINDOW_GAINED_FOCUS
 549                 // event in that case.
 550                 final Window newFocusedWindow = SunToolkit.getContainingWindow(newFocusOwner);
 551                 final Window currentFocusedWindow = getGlobalFocusedWindow();
 552                 if (newFocusedWindow != null &&
 553                     newFocusedWindow != currentFocusedWindow)
 554                 {
 555                     sendMessage(newFocusedWindow,
 556                                 new WindowEvent(newFocusedWindow,
 557                                         WindowEvent.WINDOW_GAINED_FOCUS,
 558                                                 currentFocusedWindow));
 559                     if (newFocusedWindow != getGlobalFocusedWindow()) {
 560                         // Focus change was rejected. Will happen if
 561                         // newFocusedWindow is not a focusable Window.
 562 
 563                         // Need to recover type-ahead, but don't bother
 564                         // restoring focus. That was done by the
 565                         // WINDOW_GAINED_FOCUS handler
 566                         dequeueKeyEvents(-1, newFocusOwner);
 567                         break;
 568                     }
 569                 }
 570 
 571                 if (!(newFocusOwner.isFocusable() && newFocusOwner.isShowing() &&
 572                     // Refuse focus on a disabled component if the focus event
 573                     // isn't of UNKNOWN reason (i.e. not a result of a direct request
 574                     // but traversal, activation or system generated).
 575                     (newFocusOwner.isEnabled() || fe.getCause().equals(FocusEvent.Cause.UNKNOWN))))
 576                 {
 577                     // we should not accept focus on such component, so reject it.
 578                     dequeueKeyEvents(-1, newFocusOwner);
 579                     if (KeyboardFocusManager.isAutoFocusTransferEnabled()) {
 580                         // If FOCUS_GAINED is for a disposed component (however
 581                         // it shouldn't happen) its toplevel parent is null. In this
 582                         // case we have to try to restore focus in the current focused
 583                         // window (for the details: 6607170).
 584                         if (newFocusedWindow == null) {
 585                             restoreFocus(fe, currentFocusedWindow);
 586                         } else {
 587                             restoreFocus(fe, newFocusedWindow);
 588                         }
 589                         setMostRecentFocusOwner(newFocusedWindow, null); // see: 8013773
 590                     }
 591                     break;
 592                 }
 593 
 594                 setGlobalFocusOwner(newFocusOwner);
 595 
 596                 if (newFocusOwner != getGlobalFocusOwner()) {
 597                     // Focus change was rejected. Will happen if
 598                     // newFocusOwner is not focus traversable.
 599                     dequeueKeyEvents(-1, newFocusOwner);
 600                     if (KeyboardFocusManager.isAutoFocusTransferEnabled()) {
 601                         restoreFocus(fe, newFocusedWindow);
 602                     }
 603                     break;
 604                 }
 605 
 606                 if (!fe.isTemporary()) {
 607                     setGlobalPermanentFocusOwner(newFocusOwner);
 608 
 609                     if (newFocusOwner != getGlobalPermanentFocusOwner()) {
 610                         // Focus change was rejected. Unlikely, but possible.
 611                         dequeueKeyEvents(-1, newFocusOwner);
 612                         if (KeyboardFocusManager.isAutoFocusTransferEnabled()) {
 613                             restoreFocus(fe, newFocusedWindow);
 614                         }
 615                         break;
 616                     }
 617                 }
 618 
 619                 setNativeFocusOwner(getHeavyweight(newFocusOwner));
 620 
 621                 Component realOppositeComponent = this.realOppositeComponentWR.get();
 622                 if (realOppositeComponent != null &&
 623                     realOppositeComponent != fe.getOppositeComponent()) {
 624                     fe = new FocusEvent(newFocusOwner,
 625                                         FocusEvent.FOCUS_GAINED,
 626                                         fe.isTemporary(),
 627                                         realOppositeComponent, fe.getCause());
 628                     ((AWTEvent) fe).isPosted = true;
 629                 }
 630                 return typeAheadAssertions(newFocusOwner, fe);
 631             }
 632 
 633             case FocusEvent.FOCUS_LOST: {
 634                 FocusEvent fe = (FocusEvent)e;
 635                 Component currentFocusOwner = getGlobalFocusOwner();
 636                 if (currentFocusOwner == null) {
 637                     if (focusLog.isLoggable(PlatformLogger.Level.FINE))
 638                         focusLog.fine("Skipping {0} because focus owner is null", e);
 639                     break;
 640                 }
 641                 // Ignore cases where a Component loses focus to itself.
 642                 // If we make a mistake because of retargeting, then the
 643                 // FOCUS_GAINED handler will correct it.
 644                 if (currentFocusOwner == fe.getOppositeComponent()) {
 645                     if (focusLog.isLoggable(PlatformLogger.Level.FINE))
 646                         focusLog.fine("Skipping {0} because current focus owner is equal to opposite", e);
 647                     break;
 648                 }
 649 
 650                 setGlobalFocusOwner(null);
 651 
 652                 if (getGlobalFocusOwner() != null) {
 653                     // Focus change was rejected. Unlikely, but possible.
 654                     restoreFocus(currentFocusOwner, true);
 655                     break;
 656                 }
 657 
 658                 if (!fe.isTemporary()) {
 659                     setGlobalPermanentFocusOwner(null);
 660 
 661                     if (getGlobalPermanentFocusOwner() != null) {
 662                         // Focus change was rejected. Unlikely, but possible.
 663                         restoreFocus(currentFocusOwner, true);
 664                         break;
 665                     }
 666                 } else {
 667                     Window owningWindow = currentFocusOwner.getContainingWindow();
 668                     if (owningWindow != null) {
 669                         owningWindow.setTemporaryLostComponent(currentFocusOwner);
 670                     }
 671                 }
 672 
 673                 setNativeFocusOwner(null);
 674 
 675                 fe.setSource(currentFocusOwner);
 676 
 677                 realOppositeComponentWR = (fe.getOppositeComponent() != null)
 678                     ? new WeakReference<Component>(currentFocusOwner)
 679                     : NULL_COMPONENT_WR;
 680 
 681                 return typeAheadAssertions(currentFocusOwner, fe);
 682             }
 683 
 684             case WindowEvent.WINDOW_DEACTIVATED: {
 685                 WindowEvent we = (WindowEvent)e;
 686                 Window currentActiveWindow = getGlobalActiveWindow();
 687                 if (currentActiveWindow == null) {
 688                     break;
 689                 }
 690 
 691                 if (currentActiveWindow != e.getSource()) {
 692                     // The event is lost in time.
 693                     // Allow listeners to precess the event but do not
 694                     // change any global states
 695                     break;
 696                 }
 697 
 698                 setGlobalActiveWindow(null);
 699                 if (getGlobalActiveWindow() != null) {
 700                     // Activation change was rejected. Unlikely, but possible.
 701                     break;
 702                 }
 703 
 704                 we.setSource(currentActiveWindow);
 705                 return typeAheadAssertions(currentActiveWindow, we);
 706             }
 707 
 708             case WindowEvent.WINDOW_LOST_FOCUS: {
 709                 if (repostIfFollowsKeyEvents((WindowEvent)e)) {
 710                     break;
 711                 }
 712 
 713                 WindowEvent we = (WindowEvent)e;
 714                 Window currentFocusedWindow = getGlobalFocusedWindow();
 715                 Window losingFocusWindow = we.getWindow();
 716                 Window activeWindow = getGlobalActiveWindow();
 717                 Window oppositeWindow = we.getOppositeWindow();
 718                 if (focusLog.isLoggable(PlatformLogger.Level.FINE))
 719                     focusLog.fine("Active {0}, Current focused {1}, losing focus {2} opposite {3}",
 720                                   activeWindow, currentFocusedWindow,
 721                                   losingFocusWindow, oppositeWindow);
 722                 if (currentFocusedWindow == null) {
 723                     break;
 724                 }
 725 
 726                 // Special case -- if the native windowing system posts an
 727                 // event claiming that the active Window has lost focus to the
 728                 // focused Window, then discard the event. This is an artifact
 729                 // of the native windowing system not knowing which Window is
 730                 // really focused.
 731                 if (inSendMessage == 0 && losingFocusWindow == activeWindow &&
 732                     oppositeWindow == currentFocusedWindow)
 733                 {
 734                     break;
 735                 }
 736 
 737                 Component currentFocusOwner = getGlobalFocusOwner();
 738                 if (currentFocusOwner != null) {
 739                     // The focus owner should always receive a FOCUS_LOST event
 740                     // before the Window is defocused.
 741                     Component oppositeComp = null;
 742                     if (oppositeWindow != null) {
 743                         oppositeComp = oppositeWindow.getTemporaryLostComponent();
 744                         if (oppositeComp == null) {
 745                             oppositeComp = oppositeWindow.getMostRecentFocusOwner();
 746                         }
 747                     }
 748                     if (oppositeComp == null) {
 749                         oppositeComp = oppositeWindow;
 750                     }
 751                     sendMessage(currentFocusOwner,
 752                                 new FocusEvent(currentFocusOwner,
 753                                                FocusEvent.FOCUS_LOST,
 754                                                true,
 755                                                oppositeComp, FocusEvent.Cause.ACTIVATION));
 756                 }
 757 
 758                 setGlobalFocusedWindow(null);
 759                 if (getGlobalFocusedWindow() != null) {
 760                     // Focus change was rejected. Unlikely, but possible.
 761                     restoreFocus(currentFocusedWindow, null, true);
 762                     break;
 763                 }
 764 
 765                 we.setSource(currentFocusedWindow);
 766                 realOppositeWindowWR = (oppositeWindow != null)
 767                     ? new WeakReference<Window>(currentFocusedWindow)
 768                     : NULL_WINDOW_WR;
 769                 typeAheadAssertions(currentFocusedWindow, we);
 770 
 771                 if (oppositeWindow == null) {
 772                     // Then we need to deactivate the active Window as well.
 773                     // No need to synthesize in other cases, because
 774                     // WINDOW_ACTIVATED will handle it if necessary.
 775                     sendMessage(activeWindow,
 776                                 new WindowEvent(activeWindow,
 777                                                 WindowEvent.WINDOW_DEACTIVATED,
 778                                                 null));
 779                     if (getGlobalActiveWindow() != null) {
 780                         // Activation change was rejected. Unlikely,
 781                         // but possible.
 782                         restoreFocus(currentFocusedWindow, null, true);
 783                     }
 784                 }
 785                 break;
 786             }
 787 
 788             case KeyEvent.KEY_TYPED:
 789             case KeyEvent.KEY_PRESSED:
 790             case KeyEvent.KEY_RELEASED:
 791                 return typeAheadAssertions(null, e);
 792 
 793             default:
 794                 return false;
 795         }
 796 
 797         return true;
 798     }
 799 
 800     /**
 801      * Called by {@code dispatchEvent} if no other
 802      * KeyEventDispatcher in the dispatcher chain dispatched the KeyEvent, or
 803      * if no other KeyEventDispatchers are registered. If the event has not
 804      * been consumed, its target is enabled, and the focus owner is not null,
 805      * this method dispatches the event to its target. This method will also
 806      * subsequently dispatch the event to all registered
 807      * KeyEventPostProcessors. After all this operations are finished,
 808      * the event is passed to peers for processing.
 809      * <p>
 810      * In all cases, this method returns {@code true}, since
 811      * DefaultKeyboardFocusManager is designed so that neither
 812      * {@code dispatchEvent}, nor the AWT event dispatcher, should take
 813      * further action on the event in any situation.
 814      *
 815      * @param e the KeyEvent to be dispatched
 816      * @return {@code true}
 817      * @see Component#dispatchEvent
 818      */
 819     public boolean dispatchKeyEvent(KeyEvent e) {
 820         Component focusOwner = (((AWTEvent)e).isPosted) ? getFocusOwner() : e.getComponent();
 821 
 822         if (focusOwner != null && focusOwner.isShowing() && focusOwner.canBeFocusOwner()) {
 823             if (!e.isConsumed()) {
 824                 Component comp = e.getComponent();
 825                 if (comp != null && comp.isEnabled()) {
 826                     redispatchEvent(comp, e);
 827                 }
 828             }
 829         }
 830         boolean stopPostProcessing = false;
 831         java.util.List<KeyEventPostProcessor> processors = getKeyEventPostProcessors();
 832         if (processors != null) {
 833             for (java.util.Iterator<KeyEventPostProcessor> iter = processors.iterator();
 834                  !stopPostProcessing && iter.hasNext(); )
 835             {
 836                 stopPostProcessing = iter.next().
 837                             postProcessKeyEvent(e);
 838             }
 839         }
 840         if (!stopPostProcessing) {
 841             postProcessKeyEvent(e);
 842         }
 843 
 844         // Allow the peer to process KeyEvent
 845         Component source = e.getComponent();
 846         ComponentPeer peer = source.peer;
 847 
 848         if (peer == null || peer instanceof LightweightPeer) {
 849             // if focus owner is lightweight then its native container
 850             // processes event
 851             Container target = source.getNativeContainer();
 852             if (target != null) {
 853                 peer = target.peer;
 854             }
 855         }
 856         if (peer != null) {
 857             peer.handleEvent(e);
 858         }
 859 
 860         return true;
 861     }
 862 
 863     /**
 864      * This method will be called by {@code dispatchKeyEvent}. It will
 865      * handle any unconsumed KeyEvents that map to an AWT
 866      * {@code MenuShortcut} by consuming the event and activating the
 867      * shortcut.
 868      *
 869      * @param e the KeyEvent to post-process
 870      * @return {@code true}
 871      * @see #dispatchKeyEvent
 872      * @see MenuShortcut
 873      */
 874     public boolean postProcessKeyEvent(KeyEvent e) {
 875         if (!e.isConsumed()) {
 876             Component target = e.getComponent();
 877             Container p = (Container)
 878                 (target instanceof Container ? target : target.getParent());
 879             if (p != null) {
 880                 p.postProcessKeyEvent(e);
 881             }
 882         }
 883         return true;
 884     }
 885 
 886     private void pumpApprovedKeyEvents() {
 887         KeyEvent ke;
 888         do {
 889             ke = null;
 890             synchronized (this) {
 891                 if (enqueuedKeyEvents.size() != 0) {
 892                     ke = enqueuedKeyEvents.getFirst();
 893                     if (typeAheadMarkers.size() != 0) {
 894                         TypeAheadMarker marker = typeAheadMarkers.getFirst();
 895                         // Fixed 5064013: may appears that the events have the same time
 896                         // if (ke.getWhen() >= marker.after) {
 897                         // The fix is rolled out.
 898 
 899                         if (ke.getWhen() > marker.after) {
 900                             ke = null;
 901                         }
 902                     }
 903                     if (ke != null) {
 904                         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
 905                             focusLog.finer("Pumping approved event {0}", ke);
 906                         }
 907                         enqueuedKeyEvents.removeFirst();
 908                     }
 909                 }
 910             }
 911             if (ke != null) {
 912                 preDispatchKeyEvent(ke);
 913             }
 914         } while (ke != null);
 915     }
 916 
 917     /**
 918      * Dumps the list of type-ahead queue markers to stderr
 919      */
 920     void dumpMarkers() {
 921         if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
 922             focusLog.finest(">>> Markers dump, time: {0}", System.currentTimeMillis());
 923             synchronized (this) {
 924                 if (typeAheadMarkers.size() != 0) {
 925                     Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator();
 926                     while (iter.hasNext()) {
 927                         TypeAheadMarker marker = iter.next();
 928                         focusLog.finest("    {0}", marker);
 929                     }
 930                 }
 931             }
 932         }
 933     }
 934 
 935     private boolean typeAheadAssertions(Component target, AWTEvent e) {
 936 
 937         // Clear any pending events here as well as in the FOCUS_GAINED
 938         // handler. We need this call here in case a marker was removed in
 939         // response to a call to dequeueKeyEvents.
 940         pumpApprovedKeyEvents();
 941 
 942         switch (e.getID()) {
 943             case KeyEvent.KEY_TYPED:
 944             case KeyEvent.KEY_PRESSED:
 945             case KeyEvent.KEY_RELEASED: {
 946                 KeyEvent ke = (KeyEvent)e;
 947                 synchronized (this) {
 948                     if (e.isPosted && typeAheadMarkers.size() != 0) {
 949                         TypeAheadMarker marker = typeAheadMarkers.getFirst();
 950                         // Fixed 5064013: may appears that the events have the same time
 951                         // if (ke.getWhen() >= marker.after) {
 952                         // The fix is rolled out.
 953 
 954                         if (ke.getWhen() > marker.after) {
 955                             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
 956                                 focusLog.finer("Storing event {0} because of marker {1}", ke, marker);
 957                             }
 958                             enqueuedKeyEvents.addLast(ke);
 959                             return true;
 960                         }
 961                     }
 962                 }
 963 
 964                 // KeyEvent was posted before focus change request
 965                 return preDispatchKeyEvent(ke);
 966             }
 967 
 968             case FocusEvent.FOCUS_GAINED:
 969                 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
 970                     focusLog.finest("Markers before FOCUS_GAINED on {0}", target);
 971                 }
 972                 dumpMarkers();
 973                 // Search the marker list for the first marker tied to
 974                 // the Component which just gained focus. Then remove
 975                 // that marker, any markers which immediately follow
 976                 // and are tied to the same component, and all markers
 977                 // that precede it. This handles the case where
 978                 // multiple focus requests were made for the same
 979                 // Component in a row and when we lost some of the
 980                 // earlier requests. Since FOCUS_GAINED events will
 981                 // not be generated for these additional requests, we
 982                 // need to clear those markers too.
 983                 synchronized (this) {
 984                     boolean found = false;
 985                     if (hasMarker(target)) {
 986                         for (Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator();
 987                              iter.hasNext(); )
 988                         {
 989                             if (iter.next().untilFocused == target) {
 990                                 found = true;
 991                             } else if (found) {
 992                                 break;
 993                             }
 994                             iter.remove();
 995                         }
 996                     } else {
 997                         // Exception condition - event without marker
 998                         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
 999                             focusLog.finer("Event without marker {0}", e);
1000                         }
1001                     }
1002                 }
1003                 focusLog.finest("Markers after FOCUS_GAINED");
1004                 dumpMarkers();
1005 
1006                 redispatchEvent(target, e);
1007 
1008                 // Now, dispatch any pending KeyEvents which have been
1009                 // released because of the FOCUS_GAINED event so that we don't
1010                 // have to wait for another event to be posted to the queue.
1011                 pumpApprovedKeyEvents();
1012                 return true;
1013 
1014             default:
1015                 redispatchEvent(target, e);
1016                 return true;
1017         }
1018     }
1019 
1020     /**
1021      * Returns true if there are some marker associated with component {@code comp}
1022      * in a markers' queue
1023      * @since 1.5
1024      */
1025     private boolean hasMarker(Component comp) {
1026         for (Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator(); iter.hasNext(); ) {
1027             if (iter.next().untilFocused == comp) {
1028                 return true;
1029             }
1030         }
1031         return false;
1032     }
1033 
1034     /**
1035      * Clears markers queue
1036      * @since 1.5
1037      */
1038     void clearMarkers() {
1039         synchronized(this) {
1040             typeAheadMarkers.clear();
1041         }
1042     }
1043 
1044     @SuppressWarnings("deprecation")
1045     private boolean preDispatchKeyEvent(KeyEvent ke) {
1046         if (((AWTEvent) ke).isPosted) {
1047             Component focusOwner = getFocusOwner();
1048             ke.setSource(((focusOwner != null) ? focusOwner : getFocusedWindow()));
1049         }
1050         if (ke.getSource() == null) {
1051             return true;
1052         }
1053 
1054         // Explicitly set the key event timestamp here (not in Component.dispatchEventImpl):
1055         // - A key event is anyway passed to this method which starts its actual dispatching.
1056         // - If a key event is put to the type ahead queue, its time stamp should not be registered
1057         //   until its dispatching actually starts (by this method).
1058         EventQueue.setCurrentEventAndMostRecentTime(ke);
1059 
1060         /**
1061          * Fix for 4495473.
1062          * This fix allows to correctly dispatch events when native
1063          * event proxying mechanism is active.
1064          * If it is active we should redispatch key events after
1065          * we detected its correct target.
1066          */
1067         if (KeyboardFocusManager.isProxyActive(ke)) {
1068             Component source = (Component)ke.getSource();
1069             Container target = source.getNativeContainer();
1070             if (target != null) {
1071                 ComponentPeer peer = target.peer;
1072                 if (peer != null) {
1073                     peer.handleEvent(ke);
1074                     /**
1075                      * Fix for 4478780 - consume event after it was dispatched by peer.
1076                      */
1077                     ke.consume();
1078                 }
1079             }
1080             return true;
1081         }
1082 
1083         java.util.List<KeyEventDispatcher> dispatchers = getKeyEventDispatchers();
1084         if (dispatchers != null) {
1085             for (java.util.Iterator<KeyEventDispatcher> iter = dispatchers.iterator();
1086                  iter.hasNext(); )
1087              {
1088                  if (iter.next().
1089                      dispatchKeyEvent(ke))
1090                  {
1091                      return true;
1092                  }
1093              }
1094         }
1095         return dispatchKeyEvent(ke);
1096     }
1097 
1098     /*
1099      * @param e is a KEY_PRESSED event that can be used
1100      *          to track the next KEY_TYPED related.
1101      */
1102     private void consumeNextKeyTyped(KeyEvent e) {
1103         consumeNextKeyTyped = true;
1104     }
1105 
1106     private void consumeTraversalKey(KeyEvent e) {
1107         e.consume();
1108         consumeNextKeyTyped = (e.getID() == KeyEvent.KEY_PRESSED) &&
1109                               !e.isActionKey();
1110     }
1111 
1112     /*
1113      * return true if event was consumed
1114      */
1115     private boolean consumeProcessedKeyEvent(KeyEvent e) {
1116         if ((e.getID() == KeyEvent.KEY_TYPED) && consumeNextKeyTyped) {
1117             e.consume();
1118             consumeNextKeyTyped = false;
1119             return true;
1120         }
1121         return false;
1122     }
1123 
1124     /**
1125      * This method initiates a focus traversal operation if and only if the
1126      * KeyEvent represents a focus traversal key for the specified
1127      * focusedComponent. It is expected that focusedComponent is the current
1128      * focus owner, although this need not be the case. If it is not,
1129      * focus traversal will nevertheless proceed as if focusedComponent
1130      * were the focus owner.
1131      *
1132      * @param focusedComponent the Component that is the basis for a focus
1133      *        traversal operation if the specified event represents a focus
1134      *        traversal key for the Component
1135      * @param e the event that may represent a focus traversal key
1136      */
1137     public void processKeyEvent(Component focusedComponent, KeyEvent e) {
1138         // consume processed event if needed
1139         if (consumeProcessedKeyEvent(e)) {
1140             return;
1141         }
1142 
1143         // KEY_TYPED events cannot be focus traversal keys
1144         if (e.getID() == KeyEvent.KEY_TYPED) {
1145             return;
1146         }
1147 
1148         if (focusedComponent.getFocusTraversalKeysEnabled() &&
1149             !e.isConsumed())
1150         {
1151             AWTKeyStroke stroke = AWTKeyStroke.getAWTKeyStrokeForEvent(e),
1152                 oppStroke = AWTKeyStroke.getAWTKeyStroke(stroke.getKeyCode(),
1153                                                  stroke.getModifiers(),
1154                                                  !stroke.isOnKeyRelease());
1155             Set<AWTKeyStroke> toTest;
1156             boolean contains, containsOpp;
1157 
1158             toTest = focusedComponent.getFocusTraversalKeys(
1159                 KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
1160             contains = toTest.contains(stroke);
1161             containsOpp = toTest.contains(oppStroke);
1162 
1163             if (contains || containsOpp) {
1164                 consumeTraversalKey(e);
1165                 if (contains) {
1166                     focusNextComponent(focusedComponent);
1167                 }
1168                 return;
1169             } else if (e.getID() == KeyEvent.KEY_PRESSED) {
1170                 // Fix for 6637607: consumeNextKeyTyped should be reset.
1171                 consumeNextKeyTyped = false;
1172             }
1173 
1174             toTest = focusedComponent.getFocusTraversalKeys(
1175                 KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
1176             contains = toTest.contains(stroke);
1177             containsOpp = toTest.contains(oppStroke);
1178 
1179             if (contains || containsOpp) {
1180                 consumeTraversalKey(e);
1181                 if (contains) {
1182                     focusPreviousComponent(focusedComponent);
1183                 }
1184                 return;
1185             }
1186 
1187             toTest = focusedComponent.getFocusTraversalKeys(
1188                 KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS);
1189             contains = toTest.contains(stroke);
1190             containsOpp = toTest.contains(oppStroke);
1191 
1192             if (contains || containsOpp) {
1193                 consumeTraversalKey(e);
1194                 if (contains) {
1195                     upFocusCycle(focusedComponent);
1196                 }
1197                 return;
1198             }
1199 
1200             if (!((focusedComponent instanceof Container) &&
1201                   ((Container)focusedComponent).isFocusCycleRoot())) {
1202                 return;
1203             }
1204 
1205             toTest = focusedComponent.getFocusTraversalKeys(
1206                 KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS);
1207             contains = toTest.contains(stroke);
1208             containsOpp = toTest.contains(oppStroke);
1209 
1210             if (contains || containsOpp) {
1211                 consumeTraversalKey(e);
1212                 if (contains) {
1213                     downFocusCycle((Container)focusedComponent);
1214                 }
1215             }
1216         }
1217     }
1218 
1219     /**
1220      * Delays dispatching of KeyEvents until the specified Component becomes
1221      * the focus owner. KeyEvents with timestamps later than the specified
1222      * timestamp will be enqueued until the specified Component receives a
1223      * FOCUS_GAINED event, or the AWT cancels the delay request by invoking
1224      * {@code dequeueKeyEvents} or {@code discardKeyEvents}.
1225      *
1226      * @param after timestamp of current event, or the current, system time if
1227      *        the current event has no timestamp, or the AWT cannot determine
1228      *        which event is currently being handled
1229      * @param untilFocused Component which will receive a FOCUS_GAINED event
1230      *        before any pending KeyEvents
1231      * @see #dequeueKeyEvents
1232      * @see #discardKeyEvents
1233      */
1234     protected synchronized void enqueueKeyEvents(long after,
1235                                                  Component untilFocused) {
1236         if (untilFocused == null) {
1237             return;
1238         }
1239 
1240         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
1241             focusLog.finer("Enqueue at {0} for {1}",
1242                        after, untilFocused);
1243         }
1244 
1245         int insertionIndex = 0,
1246             i = typeAheadMarkers.size();
1247         ListIterator<TypeAheadMarker> iter = typeAheadMarkers.listIterator(i);
1248 
1249         for (; i > 0; i--) {
1250             TypeAheadMarker marker = iter.previous();
1251             if (marker.after <= after) {
1252                 insertionIndex = i;
1253                 break;
1254             }
1255         }
1256 
1257         typeAheadMarkers.add(insertionIndex,
1258                              new TypeAheadMarker(after, untilFocused));
1259     }
1260 
1261     /**
1262      * Releases for normal dispatching to the current focus owner all
1263      * KeyEvents which were enqueued because of a call to
1264      * {@code enqueueKeyEvents} with the same timestamp and Component.
1265      * If the given timestamp is less than zero, the outstanding enqueue
1266      * request for the given Component with the <b>oldest</b> timestamp (if
1267      * any) should be cancelled.
1268      *
1269      * @param after the timestamp specified in the call to
1270      *        {@code enqueueKeyEvents}, or any value &lt; 0
1271      * @param untilFocused the Component specified in the call to
1272      *        {@code enqueueKeyEvents}
1273      * @see #enqueueKeyEvents
1274      * @see #discardKeyEvents
1275      */
1276     protected synchronized void dequeueKeyEvents(long after,
1277                                                  Component untilFocused) {
1278         if (untilFocused == null) {
1279             return;
1280         }
1281 
1282         if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
1283             focusLog.finer("Dequeue at {0} for {1}",
1284                        after, untilFocused);
1285         }
1286 
1287         TypeAheadMarker marker;
1288         ListIterator<TypeAheadMarker> iter = typeAheadMarkers.listIterator
1289             ((after >= 0) ? typeAheadMarkers.size() : 0);
1290 
1291         if (after < 0) {
1292             while (iter.hasNext()) {
1293                 marker = iter.next();
1294                 if (marker.untilFocused == untilFocused)
1295                 {
1296                     iter.remove();
1297                     return;
1298                 }
1299             }
1300         } else {
1301             while (iter.hasPrevious()) {
1302                 marker = iter.previous();
1303                 if (marker.untilFocused == untilFocused &&
1304                     marker.after == after)
1305                 {
1306                     iter.remove();
1307                     return;
1308                 }
1309             }
1310         }
1311     }
1312 
1313     /**
1314      * Discards all KeyEvents which were enqueued because of one or more calls
1315      * to {@code enqueueKeyEvents} with the specified Component, or one of
1316      * its descendants.
1317      *
1318      * @param comp the Component specified in one or more calls to
1319      *        {@code enqueueKeyEvents}, or a parent of such a Component
1320      * @see #enqueueKeyEvents
1321      * @see #dequeueKeyEvents
1322      */
1323     protected synchronized void discardKeyEvents(Component comp) {
1324         if (comp == null) {
1325             return;
1326         }
1327 
1328         long start = -1;
1329 
1330         for (Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator(); iter.hasNext(); ) {
1331             TypeAheadMarker marker = iter.next();
1332             Component toTest = marker.untilFocused;
1333             boolean match = (toTest == comp);
1334             while (!match && toTest != null && !(toTest instanceof Window)) {
1335                 toTest = toTest.getParent();
1336                 match = (toTest == comp);
1337             }
1338             if (match) {
1339                 if (start < 0) {
1340                     start = marker.after;
1341                 }
1342                 iter.remove();
1343             } else if (start >= 0) {
1344                 purgeStampedEvents(start, marker.after);
1345                 start = -1;
1346             }
1347         }
1348 
1349         purgeStampedEvents(start, -1);
1350     }
1351 
1352     // Notes:
1353     //   * must be called inside a synchronized block
1354     //   * if 'start' is < 0, then this function does nothing
1355     //   * if 'end' is < 0, then all KeyEvents from 'start' to the end of the
1356     //     queue will be removed
1357     private void purgeStampedEvents(long start, long end) {
1358         if (start < 0) {
1359             return;
1360         }
1361 
1362         for (Iterator<KeyEvent> iter = enqueuedKeyEvents.iterator(); iter.hasNext(); ) {
1363             KeyEvent ke = iter.next();
1364             long time = ke.getWhen();
1365 
1366             if (start < time && (end < 0 || time <= end)) {
1367                 iter.remove();
1368             }
1369 
1370             if (end >= 0 && time > end) {
1371                 break;
1372             }
1373         }
1374     }
1375 
1376     /**
1377      * Focuses the Component before aComponent, typically based on a
1378      * FocusTraversalPolicy.
1379      *
1380      * @param aComponent the Component that is the basis for the focus
1381      *        traversal operation
1382      * @see FocusTraversalPolicy
1383      * @see Component#transferFocusBackward
1384      */
1385     public void focusPreviousComponent(Component aComponent) {
1386         if (aComponent != null) {
1387             aComponent.transferFocusBackward();
1388         }
1389     }
1390 
1391     /**
1392      * Focuses the Component after aComponent, typically based on a
1393      * FocusTraversalPolicy.
1394      *
1395      * @param aComponent the Component that is the basis for the focus
1396      *        traversal operation
1397      * @see FocusTraversalPolicy
1398      * @see Component#transferFocus
1399      */
1400     public void focusNextComponent(Component aComponent) {
1401         if (aComponent != null) {
1402             aComponent.transferFocus();
1403         }
1404     }
1405 
1406     /**
1407      * Moves the focus up one focus traversal cycle. Typically, the focus owner
1408      * is set to aComponent's focus cycle root, and the current focus cycle
1409      * root is set to the new focus owner's focus cycle root. If, however,
1410      * aComponent's focus cycle root is a Window, then the focus owner is set
1411      * to the focus cycle root's default Component to focus, and the current
1412      * focus cycle root is unchanged.
1413      *
1414      * @param aComponent the Component that is the basis for the focus
1415      *        traversal operation
1416      * @see Component#transferFocusUpCycle
1417      */
1418     public void upFocusCycle(Component aComponent) {
1419         if (aComponent != null) {
1420             aComponent.transferFocusUpCycle();
1421         }
1422     }
1423 
1424     /**
1425      * Moves the focus down one focus traversal cycle. If aContainer is a focus
1426      * cycle root, then the focus owner is set to aContainer's default
1427      * Component to focus, and the current focus cycle root is set to
1428      * aContainer. If aContainer is not a focus cycle root, then no focus
1429      * traversal operation occurs.
1430      *
1431      * @param aContainer the Container that is the basis for the focus
1432      *        traversal operation
1433      * @see Container#transferFocusDownCycle
1434      */
1435     public void downFocusCycle(Container aContainer) {
1436         if (aContainer != null && aContainer.isFocusCycleRoot()) {
1437             aContainer.transferFocusDownCycle();
1438         }
1439     }
1440 }