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