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