1 /* 2 * Copyright (c) 1996, 2011, 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 26 package java.awt; 27 28 import java.awt.event.*; 29 30 import java.awt.peer.ComponentPeer; 31 32 import java.lang.ref.WeakReference; 33 import java.lang.reflect.InvocationTargetException; 34 35 import java.security.AccessController; 36 import java.security.PrivilegedAction; 37 38 import java.util.EmptyStackException; 39 40 import sun.awt.dnd.SunDropTargetEvent; 41 import sun.util.logging.PlatformLogger; 42 43 import sun.awt.AppContext; 44 import sun.awt.AWTAutoShutdown; 45 import sun.awt.PeerEvent; 46 import sun.awt.SunToolkit; 47 import sun.awt.EventQueueItem; 48 import sun.awt.AWTAccessor; 49 50 import java.util.concurrent.locks.Condition; 51 import java.util.concurrent.locks.Lock; 52 import java.util.concurrent.atomic.AtomicInteger; 53 54 import java.security.AccessControlContext; 55 56 import sun.misc.SharedSecrets; 57 import sun.misc.JavaSecurityAccess; 58 59 /** 60 * <code>EventQueue</code> is a platform-independent class 61 * that queues events, both from the underlying peer classes 62 * and from trusted application classes. 63 * <p> 64 * It encapsulates asynchronous event dispatch machinery which 65 * extracts events from the queue and dispatches them by calling 66 * {@link #dispatchEvent(AWTEvent) dispatchEvent(AWTEvent)} method 67 * on this <code>EventQueue</code> with the event to be dispatched 68 * as an argument. The particular behavior of this machinery is 69 * implementation-dependent. The only requirements are that events 70 * which were actually enqueued to this queue (note that events 71 * being posted to the <code>EventQueue</code> can be coalesced) 72 * are dispatched: 73 * <dl> 74 * <dt> Sequentially. 75 * <dd> That is, it is not permitted that several events from 76 * this queue are dispatched simultaneously. 77 * <dt> In the same order as they are enqueued. 78 * <dd> That is, if <code>AWTEvent</code> A is enqueued 79 * to the <code>EventQueue</code> before 80 * <code>AWTEvent</code> B then event B will not be 81 * dispatched before event A. 82 * </dl> 83 * <p> 84 * Some browsers partition applets in different code bases into 85 * separate contexts, and establish walls between these contexts. 86 * In such a scenario, there will be one <code>EventQueue</code> 87 * per context. Other browsers place all applets into the same 88 * context, implying that there will be only a single, global 89 * <code>EventQueue</code> for all applets. This behavior is 90 * implementation-dependent. Consult your browser's documentation 91 * for more information. 92 * <p> 93 * For information on the threading issues of the event dispatch 94 * machinery, see <a href="doc-files/AWTThreadIssues.html#Autoshutdown" 95 * >AWT Threading Issues</a>. 96 * 97 * @author Thomas Ball 98 * @author Fred Ecks 99 * @author David Mendenhall 100 * 101 * @since 1.1 102 */ 103 public class EventQueue { 104 private static final AtomicInteger threadInitNumber = new AtomicInteger(0); 105 106 private static final int LOW_PRIORITY = 0; 107 private static final int NORM_PRIORITY = 1; 108 private static final int HIGH_PRIORITY = 2; 109 private static final int ULTIMATE_PRIORITY = 3; 110 111 private static final int NUM_PRIORITIES = ULTIMATE_PRIORITY + 1; 112 113 /* 114 * We maintain one Queue for each priority that the EventQueue supports. 115 * That is, the EventQueue object is actually implemented as 116 * NUM_PRIORITIES queues and all Events on a particular internal Queue 117 * have identical priority. Events are pulled off the EventQueue starting 118 * with the Queue of highest priority. We progress in decreasing order 119 * across all Queues. 120 */ 121 private Queue[] queues = new Queue[NUM_PRIORITIES]; 122 123 /* 124 * The next EventQueue on the stack, or null if this EventQueue is 125 * on the top of the stack. If nextQueue is non-null, requests to post 126 * an event are forwarded to nextQueue. 127 */ 128 private EventQueue nextQueue; 129 130 /* 131 * The previous EventQueue on the stack, or null if this is the 132 * "base" EventQueue. 133 */ 134 private EventQueue previousQueue; 135 136 /* 137 * A single lock to synchronize the push()/pop() and related operations with 138 * all the EventQueues from the AppContext. Synchronization on any particular 139 * event queue(s) is not enough: we should lock the whole stack. 140 */ 141 private final Lock pushPopLock; 142 private final Condition pushPopCond; 143 144 /* 145 * Dummy runnable to wake up EDT from getNextEvent() after 146 push/pop is performed 147 */ 148 private final static Runnable dummyRunnable = new Runnable() { 149 public void run() { 150 } 151 }; 152 153 private EventDispatchThread dispatchThread; 154 155 private final ThreadGroup threadGroup = 156 Thread.currentThread().getThreadGroup(); 157 private final ClassLoader classLoader = 158 Thread.currentThread().getContextClassLoader(); 159 160 /* 161 * The time stamp of the last dispatched InputEvent or ActionEvent. 162 */ 163 private long mostRecentEventTime = System.currentTimeMillis(); 164 165 /* 166 * The time stamp of the last KeyEvent . 167 */ 168 private long mostRecentKeyEventTime = System.currentTimeMillis(); 169 170 /** 171 * The modifiers field of the current event, if the current event is an 172 * InputEvent or ActionEvent. 173 */ 174 private WeakReference<AWTEvent> currentEvent; 175 176 /* 177 * Non-zero if a thread is waiting in getNextEvent(int) for an event of 178 * a particular ID to be posted to the queue. 179 */ 180 private volatile int waitForID; 181 182 private final String name = "AWT-EventQueue-" + threadInitNumber.getAndIncrement(); 183 184 private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.EventQueue"); 185 186 static { 187 AWTAccessor.setEventQueueAccessor( 188 new AWTAccessor.EventQueueAccessor() { 189 public Thread getDispatchThread(EventQueue eventQueue) { 190 return eventQueue.getDispatchThread(); 191 } 192 public boolean isDispatchThreadImpl(EventQueue eventQueue) { 193 return eventQueue.isDispatchThreadImpl(); 194 } 195 public void removeSourceEvents(EventQueue eventQueue, 196 Object source, 197 boolean removeAllEvents) 198 { 199 eventQueue.removeSourceEvents(source, removeAllEvents); 200 } 201 public boolean noEvents(EventQueue eventQueue) { 202 return eventQueue.noEvents(); 203 } 204 public void wakeup(EventQueue eventQueue, boolean isShutdown) { 205 eventQueue.wakeup(isShutdown); 206 } 207 public void invokeAndWait(Object source, Runnable r) 208 throws InterruptedException, InvocationTargetException 209 { 210 EventQueue.invokeAndWait(source, r); 211 } 212 }); 213 } 214 215 public EventQueue() { 216 for (int i = 0; i < NUM_PRIORITIES; i++) { 217 queues[i] = new Queue(); 218 } 219 /* 220 * NOTE: if you ever have to start the associated event dispatch 221 * thread at this point, be aware of the following problem: 222 * If this EventQueue instance is created in 223 * SunToolkit.createNewAppContext() the started dispatch thread 224 * may call AppContext.getAppContext() before createNewAppContext() 225 * completes thus causing mess in thread group to appcontext mapping. 226 */ 227 228 pushPopLock = (Lock)AppContext.getAppContext().get(AppContext.EVENT_QUEUE_LOCK_KEY); 229 pushPopCond = (Condition)AppContext.getAppContext().get(AppContext.EVENT_QUEUE_COND_KEY); 230 } 231 232 /** 233 * Posts a 1.1-style event to the <code>EventQueue</code>. 234 * If there is an existing event on the queue with the same ID 235 * and event source, the source <code>Component</code>'s 236 * <code>coalesceEvents</code> method will be called. 237 * 238 * @param theEvent an instance of <code>java.awt.AWTEvent</code>, 239 * or a subclass of it 240 * @throws NullPointerException if <code>theEvent</code> is <code>null</code> 241 */ 242 public void postEvent(AWTEvent theEvent) { 243 SunToolkit.flushPendingEvents(); 244 postEventPrivate(theEvent); 245 } 246 247 /** 248 * Posts a 1.1-style event to the <code>EventQueue</code>. 249 * If there is an existing event on the queue with the same ID 250 * and event source, the source <code>Component</code>'s 251 * <code>coalesceEvents</code> method will be called. 252 * 253 * @param theEvent an instance of <code>java.awt.AWTEvent</code>, 254 * or a subclass of it 255 */ 256 private final void postEventPrivate(AWTEvent theEvent) { 257 theEvent.isPosted = true; 258 pushPopLock.lock(); 259 try { 260 if (nextQueue != null) { 261 // Forward the event to the top of EventQueue stack 262 nextQueue.postEventPrivate(theEvent); 263 return; 264 } 265 if (dispatchThread == null) { 266 if (theEvent.getSource() == AWTAutoShutdown.getInstance()) { 267 return; 268 } else { 269 initDispatchThread(); 270 } 271 } 272 postEvent(theEvent, getPriority(theEvent)); 273 } finally { 274 pushPopLock.unlock(); 275 } 276 } 277 278 private static int getPriority(AWTEvent theEvent) { 279 if (theEvent instanceof PeerEvent) { 280 PeerEvent peerEvent = (PeerEvent)theEvent; 281 if ((peerEvent.getFlags() & PeerEvent.ULTIMATE_PRIORITY_EVENT) != 0) { 282 return ULTIMATE_PRIORITY; 283 } 284 if ((peerEvent.getFlags() & PeerEvent.PRIORITY_EVENT) != 0) { 285 return HIGH_PRIORITY; 286 } 287 if ((peerEvent.getFlags() & PeerEvent.LOW_PRIORITY_EVENT) != 0) { 288 return LOW_PRIORITY; 289 } 290 } 291 int id = theEvent.getID(); 292 if ((id >= PaintEvent.PAINT_FIRST) && (id <= PaintEvent.PAINT_LAST)) { 293 return LOW_PRIORITY; 294 } 295 return NORM_PRIORITY; 296 } 297 298 /** 299 * Posts the event to the internal Queue of specified priority, 300 * coalescing as appropriate. 301 * 302 * @param theEvent an instance of <code>java.awt.AWTEvent</code>, 303 * or a subclass of it 304 * @param priority the desired priority of the event 305 */ 306 private void postEvent(AWTEvent theEvent, int priority) { 307 if (coalesceEvent(theEvent, priority)) { 308 return; 309 } 310 311 EventQueueItem newItem = new EventQueueItem(theEvent); 312 313 cacheEQItem(newItem); 314 315 boolean notifyID = (theEvent.getID() == this.waitForID); 316 317 if (queues[priority].head == null) { 318 boolean shouldNotify = noEvents(); 319 queues[priority].head = queues[priority].tail = newItem; 320 321 if (shouldNotify) { 322 if (theEvent.getSource() != AWTAutoShutdown.getInstance()) { 323 AWTAutoShutdown.getInstance().notifyThreadBusy(dispatchThread); 324 } 325 pushPopCond.signalAll(); 326 } else if (notifyID) { 327 pushPopCond.signalAll(); 328 } 329 } else { 330 // The event was not coalesced or has non-Component source. 331 // Insert it at the end of the appropriate Queue. 332 queues[priority].tail.next = newItem; 333 queues[priority].tail = newItem; 334 if (notifyID) { 335 pushPopCond.signalAll(); 336 } 337 } 338 } 339 340 private boolean coalescePaintEvent(PaintEvent e) { 341 ComponentPeer sourcePeer = ((Component)e.getSource()).peer; 342 if (sourcePeer != null) { 343 sourcePeer.coalescePaintEvent(e); 344 } 345 EventQueueItem[] cache = ((Component)e.getSource()).eventCache; 346 if (cache == null) { 347 return false; 348 } 349 int index = eventToCacheIndex(e); 350 351 if (index != -1 && cache[index] != null) { 352 PaintEvent merged = mergePaintEvents(e, (PaintEvent)cache[index].event); 353 if (merged != null) { 354 cache[index].event = merged; 355 return true; 356 } 357 } 358 return false; 359 } 360 361 private PaintEvent mergePaintEvents(PaintEvent a, PaintEvent b) { 362 Rectangle aRect = a.getUpdateRect(); 363 Rectangle bRect = b.getUpdateRect(); 364 if (bRect.contains(aRect)) { 365 return b; 366 } 367 if (aRect.contains(bRect)) { 368 return a; 369 } 370 return null; 371 } 372 373 private boolean coalesceMouseEvent(MouseEvent e) { 374 EventQueueItem[] cache = ((Component)e.getSource()).eventCache; 375 if (cache == null) { 376 return false; 377 } 378 int index = eventToCacheIndex(e); 379 if (index != -1 && cache[index] != null) { 380 cache[index].event = e; 381 return true; 382 } 383 return false; 384 } 385 386 private boolean coalescePeerEvent(PeerEvent e) { 387 EventQueueItem[] cache = ((Component)e.getSource()).eventCache; 388 if (cache == null) { 389 return false; 390 } 391 int index = eventToCacheIndex(e); 392 if (index != -1 && cache[index] != null) { 393 e = e.coalesceEvents((PeerEvent)cache[index].event); 394 if (e != null) { 395 cache[index].event = e; 396 return true; 397 } else { 398 cache[index] = null; 399 } 400 } 401 return false; 402 } 403 404 /* 405 * Should avoid of calling this method by any means 406 * as it's working time is dependant on EQ length. 407 * In the wors case this method alone can slow down the entire application 408 * 10 times by stalling the Event processing. 409 * Only here by backward compatibility reasons. 410 */ 411 private boolean coalesceOtherEvent(AWTEvent e, int priority) { 412 int id = e.getID(); 413 Component source = (Component)e.getSource(); 414 for (EventQueueItem entry = queues[priority].head; 415 entry != null; entry = entry.next) 416 { 417 // Give Component.coalesceEvents a chance 418 if (entry.event.getSource() == source && entry.event.getID() == id) { 419 AWTEvent coalescedEvent = source.coalesceEvents( 420 entry.event, e); 421 if (coalescedEvent != null) { 422 entry.event = coalescedEvent; 423 return true; 424 } 425 } 426 } 427 return false; 428 } 429 430 private boolean coalesceEvent(AWTEvent e, int priority) { 431 if (!(e.getSource() instanceof Component)) { 432 return false; 433 } 434 if (e instanceof PeerEvent) { 435 return coalescePeerEvent((PeerEvent)e); 436 } 437 // The worst case 438 if (((Component)e.getSource()).isCoalescingEnabled() 439 && coalesceOtherEvent(e, priority)) 440 { 441 return true; 442 } 443 if (e instanceof PaintEvent) { 444 return coalescePaintEvent((PaintEvent)e); 445 } 446 if (e instanceof MouseEvent) { 447 return coalesceMouseEvent((MouseEvent)e); 448 } 449 return false; 450 } 451 452 private void cacheEQItem(EventQueueItem entry) { 453 int index = eventToCacheIndex(entry.event); 454 if (index != -1 && entry.event.getSource() instanceof Component) { 455 Component source = (Component)entry.event.getSource(); 456 if (source.eventCache == null) { 457 source.eventCache = new EventQueueItem[CACHE_LENGTH]; 458 } 459 source.eventCache[index] = entry; 460 } 461 } 462 463 private void uncacheEQItem(EventQueueItem entry) { 464 int index = eventToCacheIndex(entry.event); 465 if (index != -1 && entry.event.getSource() instanceof Component) { 466 Component source = (Component)entry.event.getSource(); 467 if (source.eventCache == null) { 468 return; 469 } 470 source.eventCache[index] = null; 471 } 472 } 473 474 private static final int PAINT = 0; 475 private static final int UPDATE = 1; 476 private static final int MOVE = 2; 477 private static final int DRAG = 3; 478 private static final int PEER = 4; 479 private static final int CACHE_LENGTH = 5; 480 481 private static int eventToCacheIndex(AWTEvent e) { 482 switch(e.getID()) { 483 case PaintEvent.PAINT: 484 return PAINT; 485 case PaintEvent.UPDATE: 486 return UPDATE; 487 case MouseEvent.MOUSE_MOVED: 488 return MOVE; 489 case MouseEvent.MOUSE_DRAGGED: 490 // Return -1 for SunDropTargetEvent since they are usually synchronous 491 // and we don't want to skip them by coalescing with MouseEvent or other drag events 492 return e instanceof SunDropTargetEvent ? -1 : DRAG; 493 default: 494 return e instanceof PeerEvent ? PEER : -1; 495 } 496 } 497 498 /** 499 * Returns whether an event is pending on any of the separate 500 * Queues. 501 * @return whether an event is pending on any of the separate Queues 502 */ 503 private boolean noEvents() { 504 for (int i = 0; i < NUM_PRIORITIES; i++) { 505 if (queues[i].head != null) { 506 return false; 507 } 508 } 509 510 return true; 511 } 512 513 /** 514 * Removes an event from the <code>EventQueue</code> and 515 * returns it. This method will block until an event has 516 * been posted by another thread. 517 * @return the next <code>AWTEvent</code> 518 * @exception InterruptedException 519 * if any thread has interrupted this thread 520 */ 521 public AWTEvent getNextEvent() throws InterruptedException { 522 do { 523 /* 524 * SunToolkit.flushPendingEvents must be called outside 525 * of the synchronized block to avoid deadlock when 526 * event queues are nested with push()/pop(). 527 */ 528 SunToolkit.flushPendingEvents(); 529 pushPopLock.lock(); 530 try { 531 AWTEvent event = getNextEventPrivate(); 532 if (event != null) { 533 return event; 534 } 535 AWTAutoShutdown.getInstance().notifyThreadFree(dispatchThread); 536 pushPopCond.await(); 537 } finally { 538 pushPopLock.unlock(); 539 } 540 } while(true); 541 } 542 543 /* 544 * Must be called under the lock. Doesn't call flushPendingEvents() 545 */ 546 AWTEvent getNextEventPrivate() throws InterruptedException { 547 for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { 548 if (queues[i].head != null) { 549 EventQueueItem entry = queues[i].head; 550 queues[i].head = entry.next; 551 if (entry.next == null) { 552 queues[i].tail = null; 553 } 554 uncacheEQItem(entry); 555 return entry.event; 556 } 557 } 558 return null; 559 } 560 561 AWTEvent getNextEvent(int id) throws InterruptedException { 562 do { 563 /* 564 * SunToolkit.flushPendingEvents must be called outside 565 * of the synchronized block to avoid deadlock when 566 * event queues are nested with push()/pop(). 567 */ 568 SunToolkit.flushPendingEvents(); 569 pushPopLock.lock(); 570 try { 571 for (int i = 0; i < NUM_PRIORITIES; i++) { 572 for (EventQueueItem entry = queues[i].head, prev = null; 573 entry != null; prev = entry, entry = entry.next) 574 { 575 if (entry.event.getID() == id) { 576 if (prev == null) { 577 queues[i].head = entry.next; 578 } else { 579 prev.next = entry.next; 580 } 581 if (queues[i].tail == entry) { 582 queues[i].tail = prev; 583 } 584 uncacheEQItem(entry); 585 return entry.event; 586 } 587 } 588 } 589 waitForID = id; 590 pushPopCond.await(); 591 waitForID = 0; 592 } finally { 593 pushPopLock.unlock(); 594 } 595 } while(true); 596 } 597 598 /** 599 * Returns the first event on the <code>EventQueue</code> 600 * without removing it. 601 * @return the first event 602 */ 603 public AWTEvent peekEvent() { 604 pushPopLock.lock(); 605 try { 606 for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { 607 if (queues[i].head != null) { 608 return queues[i].head.event; 609 } 610 } 611 } finally { 612 pushPopLock.unlock(); 613 } 614 615 return null; 616 } 617 618 /** 619 * Returns the first event with the specified id, if any. 620 * @param id the id of the type of event desired 621 * @return the first event of the specified id or <code>null</code> 622 * if there is no such event 623 */ 624 public AWTEvent peekEvent(int id) { 625 pushPopLock.lock(); 626 try { 627 for (int i = NUM_PRIORITIES - 1; i >= 0; i--) { 628 EventQueueItem q = queues[i].head; 629 for (; q != null; q = q.next) { 630 if (q.event.getID() == id) { 631 return q.event; 632 } 633 } 634 } 635 } finally { 636 pushPopLock.unlock(); 637 } 638 639 return null; 640 } 641 642 private static final JavaSecurityAccess javaSecurityAccess = 643 SharedSecrets.getJavaSecurityAccess(); 644 645 /** 646 * Dispatches an event. The manner in which the event is 647 * dispatched depends upon the type of the event and the 648 * type of the event's source object: 649 * <p> </p> 650 * <table border=1 summary="Event types, source types, and dispatch methods"> 651 * <tr> 652 * <th>Event Type</th> 653 * <th>Source Type</th> 654 * <th>Dispatched To</th> 655 * </tr> 656 * <tr> 657 * <td>ActiveEvent</td> 658 * <td>Any</td> 659 * <td>event.dispatch()</td> 660 * </tr> 661 * <tr> 662 * <td>Other</td> 663 * <td>Component</td> 664 * <td>source.dispatchEvent(AWTEvent)</td> 665 * </tr> 666 * <tr> 667 * <td>Other</td> 668 * <td>MenuComponent</td> 669 * <td>source.dispatchEvent(AWTEvent)</td> 670 * </tr> 671 * <tr> 672 * <td>Other</td> 673 * <td>Other</td> 674 * <td>No action (ignored)</td> 675 * </tr> 676 * </table> 677 * <p> </p> 678 * @param event an instance of <code>java.awt.AWTEvent</code>, 679 * or a subclass of it 680 * @throws NullPointerException if <code>event</code> is <code>null</code> 681 * @since 1.2 682 */ 683 protected void dispatchEvent(final AWTEvent event) { 684 final Object src = event.getSource(); 685 final PrivilegedAction<Void> action = new PrivilegedAction<Void>() { 686 public Void run() { 687 dispatchEventImpl(event, src); 688 return null; 689 } 690 }; 691 692 final AccessControlContext stack = AccessController.getContext(); 693 final AccessControlContext srcAcc = getAccessControlContextFrom(src); 694 final AccessControlContext eventAcc = event.getAccessControlContext(); 695 if (srcAcc == null) { 696 javaSecurityAccess.doIntersectionPrivilege(action, stack, eventAcc); 697 } else { 698 javaSecurityAccess.doIntersectionPrivilege( 699 new PrivilegedAction<Void>() { 700 public Void run() { 701 javaSecurityAccess.doIntersectionPrivilege(action, eventAcc); 702 return null; 703 } 704 }, stack, srcAcc); 705 } 706 } 707 708 private static AccessControlContext getAccessControlContextFrom(Object src) { 709 return src instanceof Component ? 710 ((Component)src).getAccessControlContext() : 711 src instanceof MenuComponent ? 712 ((MenuComponent)src).getAccessControlContext() : 713 src instanceof TrayIcon ? 714 ((TrayIcon)src).getAccessControlContext() : 715 null; 716 } 717 718 /** 719 * Called from dispatchEvent() under a correct AccessControlContext 720 */ 721 private void dispatchEventImpl(final AWTEvent event, final Object src) { 722 event.isPosted = true; 723 if (event instanceof ActiveEvent) { 724 // This could become the sole method of dispatching in time. 725 setCurrentEventAndMostRecentTimeImpl(event); 726 ((ActiveEvent)event).dispatch(); 727 } else if (src instanceof Component) { 728 ((Component)src).dispatchEvent(event); 729 event.dispatched(); 730 } else if (src instanceof MenuComponent) { 731 ((MenuComponent)src).dispatchEvent(event); 732 } else if (src instanceof TrayIcon) { 733 ((TrayIcon)src).dispatchEvent(event); 734 } else if (src instanceof AWTAutoShutdown) { 735 if (noEvents()) { 736 dispatchThread.stopDispatching(); 737 } 738 } else { 739 if (eventLog.isLoggable(PlatformLogger.FINE)) { 740 eventLog.fine("Unable to dispatch event: " + event); 741 } 742 } 743 } 744 745 /** 746 * Returns the timestamp of the most recent event that had a timestamp, and 747 * that was dispatched from the <code>EventQueue</code> associated with the 748 * calling thread. If an event with a timestamp is currently being 749 * dispatched, its timestamp will be returned. If no events have yet 750 * been dispatched, the EventQueue's initialization time will be 751 * returned instead.In the current version of 752 * the JDK, only <code>InputEvent</code>s, 753 * <code>ActionEvent</code>s, and <code>InvocationEvent</code>s have 754 * timestamps; however, future versions of the JDK may add timestamps to 755 * additional event types. Note that this method should only be invoked 756 * from an application's {@link #isDispatchThread event dispatching thread}. 757 * If this method is 758 * invoked from another thread, the current system time (as reported by 759 * <code>System.currentTimeMillis()</code>) will be returned instead. 760 * 761 * @return the timestamp of the last <code>InputEvent</code>, 762 * <code>ActionEvent</code>, or <code>InvocationEvent</code> to be 763 * dispatched, or <code>System.currentTimeMillis()</code> if this 764 * method is invoked on a thread other than an event dispatching 765 * thread 766 * @see java.awt.event.InputEvent#getWhen 767 * @see java.awt.event.ActionEvent#getWhen 768 * @see java.awt.event.InvocationEvent#getWhen 769 * @see #isDispatchThread 770 * 771 * @since 1.4 772 */ 773 public static long getMostRecentEventTime() { 774 return Toolkit.getEventQueue().getMostRecentEventTimeImpl(); 775 } 776 private long getMostRecentEventTimeImpl() { 777 pushPopLock.lock(); 778 try { 779 return (Thread.currentThread() == dispatchThread) 780 ? mostRecentEventTime 781 : System.currentTimeMillis(); 782 } finally { 783 pushPopLock.unlock(); 784 } 785 } 786 787 /** 788 * @return most recent event time on all threads. 789 */ 790 long getMostRecentEventTimeEx() { 791 pushPopLock.lock(); 792 try { 793 return mostRecentEventTime; 794 } finally { 795 pushPopLock.unlock(); 796 } 797 } 798 799 /** 800 * Returns the the event currently being dispatched by the 801 * <code>EventQueue</code> associated with the calling thread. This is 802 * useful if a method needs access to the event, but was not designed to 803 * receive a reference to it as an argument. Note that this method should 804 * only be invoked from an application's event dispatching thread. If this 805 * method is invoked from another thread, null will be returned. 806 * 807 * @return the event currently being dispatched, or null if this method is 808 * invoked on a thread other than an event dispatching thread 809 * @since 1.4 810 */ 811 public static AWTEvent getCurrentEvent() { 812 return Toolkit.getEventQueue().getCurrentEventImpl(); 813 } 814 private AWTEvent getCurrentEventImpl() { 815 pushPopLock.lock(); 816 try { 817 return (Thread.currentThread() == dispatchThread) 818 ? currentEvent.get() 819 : null; 820 } finally { 821 pushPopLock.unlock(); 822 } 823 } 824 825 /** 826 * Replaces the existing <code>EventQueue</code> with the specified one. 827 * Any pending events are transferred to the new <code>EventQueue</code> 828 * for processing by it. 829 * 830 * @param newEventQueue an <code>EventQueue</code> 831 * (or subclass thereof) instance to be use 832 * @see java.awt.EventQueue#pop 833 * @throws NullPointerException if <code>newEventQueue</code> is <code>null</code> 834 * @since 1.2 835 */ 836 public void push(EventQueue newEventQueue) { 837 if (eventLog.isLoggable(PlatformLogger.FINE)) { 838 eventLog.fine("EventQueue.push(" + newEventQueue + ")"); 839 } 840 841 pushPopLock.lock(); 842 try { 843 EventQueue topQueue = this; 844 while (topQueue.nextQueue != null) { 845 topQueue = topQueue.nextQueue; 846 } 847 848 if ((topQueue.dispatchThread != null) && 849 (topQueue.dispatchThread.getEventQueue() == this)) 850 { 851 newEventQueue.dispatchThread = topQueue.dispatchThread; 852 topQueue.dispatchThread.setEventQueue(newEventQueue); 853 } 854 855 // Transfer all events forward to new EventQueue. 856 while (topQueue.peekEvent() != null) { 857 try { 858 // Use getNextEventPrivate() as it doesn't call flushPendingEvents() 859 newEventQueue.postEventPrivate(topQueue.getNextEventPrivate()); 860 } catch (InterruptedException ie) { 861 if (eventLog.isLoggable(PlatformLogger.FINE)) { 862 eventLog.fine("Interrupted push", ie); 863 } 864 } 865 } 866 867 // Wake up EDT waiting in getNextEvent(), so it can 868 // pick up a new EventQueue. Post the waking event before 869 // topQueue.nextQueue is assigned, otherwise the event would 870 // go newEventQueue 871 topQueue.postEventPrivate(new InvocationEvent(topQueue, dummyRunnable)); 872 873 newEventQueue.previousQueue = topQueue; 874 topQueue.nextQueue = newEventQueue; 875 876 AppContext appContext = AppContext.getAppContext(); 877 if (appContext.get(AppContext.EVENT_QUEUE_KEY) == topQueue) { 878 appContext.put(AppContext.EVENT_QUEUE_KEY, newEventQueue); 879 } 880 881 pushPopCond.signalAll(); 882 } finally { 883 pushPopLock.unlock(); 884 } 885 } 886 887 /** 888 * Stops dispatching events using this <code>EventQueue</code>. 889 * Any pending events are transferred to the previous 890 * <code>EventQueue</code> for processing. 891 * <p> 892 * Warning: To avoid deadlock, do not declare this method 893 * synchronized in a subclass. 894 * 895 * @exception EmptyStackException if no previous push was made 896 * on this <code>EventQueue</code> 897 * @see java.awt.EventQueue#push 898 * @since 1.2 899 */ 900 protected void pop() throws EmptyStackException { 901 if (eventLog.isLoggable(PlatformLogger.FINE)) { 902 eventLog.fine("EventQueue.pop(" + this + ")"); 903 } 904 905 pushPopLock.lock(); 906 try { 907 EventQueue topQueue = this; 908 while (topQueue.nextQueue != null) { 909 topQueue = topQueue.nextQueue; 910 } 911 EventQueue prevQueue = topQueue.previousQueue; 912 if (prevQueue == null) { 913 throw new EmptyStackException(); 914 } 915 916 topQueue.previousQueue = null; 917 prevQueue.nextQueue = null; 918 919 // Transfer all events back to previous EventQueue. 920 while (topQueue.peekEvent() != null) { 921 try { 922 prevQueue.postEventPrivate(topQueue.getNextEventPrivate()); 923 } catch (InterruptedException ie) { 924 if (eventLog.isLoggable(PlatformLogger.FINE)) { 925 eventLog.fine("Interrupted pop", ie); 926 } 927 } 928 } 929 930 if ((topQueue.dispatchThread != null) && 931 (topQueue.dispatchThread.getEventQueue() == this)) 932 { 933 prevQueue.dispatchThread = topQueue.dispatchThread; 934 topQueue.dispatchThread.setEventQueue(prevQueue); 935 } 936 937 AppContext appContext = AppContext.getAppContext(); 938 if (appContext.get(AppContext.EVENT_QUEUE_KEY) == this) { 939 appContext.put(AppContext.EVENT_QUEUE_KEY, prevQueue); 940 } 941 942 // Wake up EDT waiting in getNextEvent(), so it can 943 // pick up a new EventQueue 944 topQueue.postEventPrivate(new InvocationEvent(topQueue, dummyRunnable)); 945 946 pushPopCond.signalAll(); 947 } finally { 948 pushPopLock.unlock(); 949 } 950 } 951 952 /** 953 * Creates a new {@code secondary loop} associated with this 954 * event queue. Use the {@link SecondaryLoop#enter} and 955 * {@link SecondaryLoop#exit} methods to start and stop the 956 * event loop and dispatch the events from this queue. 957 * 958 * @return secondaryLoop A new secondary loop object, which can 959 * be used to launch a new nested event 960 * loop and dispatch events from this queue 961 * 962 * @see SecondaryLoop#enter 963 * @see SecondaryLoop#exit 964 * 965 * @since 1.7 966 */ 967 public SecondaryLoop createSecondaryLoop() { 968 return createSecondaryLoop(null, null, 0); 969 } 970 971 SecondaryLoop createSecondaryLoop(Conditional cond, EventFilter filter, long interval) { 972 pushPopLock.lock(); 973 try { 974 if (nextQueue != null) { 975 // Forward the request to the top of EventQueue stack 976 return nextQueue.createSecondaryLoop(cond, filter, interval); 977 } 978 if (dispatchThread == null) { 979 initDispatchThread(); 980 } 981 return new WaitDispatchSupport(dispatchThread, cond, filter, interval); 982 } finally { 983 pushPopLock.unlock(); 984 } 985 } 986 987 /** 988 * Returns true if the calling thread is 989 * {@link Toolkit#getSystemEventQueue the current AWT EventQueue}'s 990 * dispatch thread. Use this method to ensure that a particular 991 * task is being executed (or not being) there. 992 * <p> 993 * Note: use the {@link #invokeLater} or {@link #invokeAndWait} 994 * methods to execute a task in 995 * {@link Toolkit#getSystemEventQueue the current AWT EventQueue}'s 996 * dispatch thread. 997 * <p> 998 * 999 * @return true if running in 1000 * {@link Toolkit#getSystemEventQueue the current AWT EventQueue}'s 1001 * dispatch thread 1002 * @see #invokeLater 1003 * @see #invokeAndWait 1004 * @see Toolkit#getSystemEventQueue 1005 * @since 1.2 1006 */ 1007 public static boolean isDispatchThread() { 1008 EventQueue eq = Toolkit.getEventQueue(); 1009 return eq.isDispatchThreadImpl(); 1010 } 1011 1012 final boolean isDispatchThreadImpl() { 1013 EventQueue eq = this; 1014 pushPopLock.lock(); 1015 try { 1016 EventQueue next = eq.nextQueue; 1017 while (next != null) { 1018 eq = next; 1019 next = eq.nextQueue; 1020 } 1021 return (Thread.currentThread() == eq.dispatchThread); 1022 } finally { 1023 pushPopLock.unlock(); 1024 } 1025 } 1026 1027 final void initDispatchThread() { 1028 pushPopLock.lock(); 1029 try { 1030 AppContext appContext = AppContext.getAppContext(); 1031 if (dispatchThread == null && !threadGroup.isDestroyed() && !appContext.isDisposed()) { 1032 dispatchThread = AccessController.doPrivileged( 1033 new PrivilegedAction<EventDispatchThread>() { 1034 public EventDispatchThread run() { 1035 EventDispatchThread t = 1036 new EventDispatchThread(threadGroup, 1037 name, 1038 EventQueue.this); 1039 t.setContextClassLoader(classLoader); 1040 t.setPriority(Thread.NORM_PRIORITY + 1); 1041 t.setDaemon(false); 1042 return t; 1043 } 1044 } 1045 ); 1046 AWTAutoShutdown.getInstance().notifyThreadBusy(dispatchThread); 1047 dispatchThread.start(); 1048 } 1049 } finally { 1050 pushPopLock.unlock(); 1051 } 1052 } 1053 1054 final boolean detachDispatchThread(EventDispatchThread edt, boolean forceDetach) { 1055 /* 1056 * Minimize discard possibility for non-posted events 1057 */ 1058 SunToolkit.flushPendingEvents(); 1059 /* 1060 * This synchronized block is to secure that the event dispatch 1061 * thread won't die in the middle of posting a new event to the 1062 * associated event queue. It is important because we notify 1063 * that the event dispatch thread is busy after posting a new event 1064 * to its queue, so the EventQueue.dispatchThread reference must 1065 * be valid at that point. 1066 */ 1067 pushPopLock.lock(); 1068 try { 1069 if (edt == dispatchThread) { 1070 /* 1071 * Don't detach the thread if any events are pending. Not 1072 * sure if it's a possible scenario, though. 1073 */ 1074 if (!forceDetach && (peekEvent() != null)) { 1075 return false; 1076 } 1077 dispatchThread = null; 1078 } 1079 AWTAutoShutdown.getInstance().notifyThreadFree(edt); 1080 return true; 1081 } finally { 1082 pushPopLock.unlock(); 1083 } 1084 } 1085 1086 /* 1087 * Gets the <code>EventDispatchThread</code> for this 1088 * <code>EventQueue</code>. 1089 * @return the event dispatch thread associated with this event queue 1090 * or <code>null</code> if this event queue doesn't have a 1091 * working thread associated with it 1092 * @see java.awt.EventQueue#initDispatchThread 1093 * @see java.awt.EventQueue#detachDispatchThread 1094 */ 1095 final EventDispatchThread getDispatchThread() { 1096 pushPopLock.lock(); 1097 try { 1098 return dispatchThread; 1099 } finally { 1100 pushPopLock.unlock(); 1101 } 1102 } 1103 1104 /* 1105 * Removes any pending events for the specified source object. 1106 * If removeAllEvents parameter is <code>true</code> then all 1107 * events for the specified source object are removed, if it 1108 * is <code>false</code> then <code>SequencedEvent</code>, <code>SentEvent</code>, 1109 * <code>FocusEvent</code>, <code>WindowEvent</code>, <code>KeyEvent</code>, 1110 * and <code>InputMethodEvent</code> are kept in the queue, but all other 1111 * events are removed. 1112 * 1113 * This method is normally called by the source's 1114 * <code>removeNotify</code> method. 1115 */ 1116 final void removeSourceEvents(Object source, boolean removeAllEvents) { 1117 SunToolkit.flushPendingEvents(); 1118 pushPopLock.lock(); 1119 try { 1120 for (int i = 0; i < NUM_PRIORITIES; i++) { 1121 EventQueueItem entry = queues[i].head; 1122 EventQueueItem prev = null; 1123 while (entry != null) { 1124 if ((entry.event.getSource() == source) 1125 && (removeAllEvents 1126 || ! (entry.event instanceof SequencedEvent 1127 || entry.event instanceof SentEvent 1128 || entry.event instanceof FocusEvent 1129 || entry.event instanceof WindowEvent 1130 || entry.event instanceof KeyEvent 1131 || entry.event instanceof InputMethodEvent))) 1132 { 1133 if (entry.event instanceof SequencedEvent) { 1134 ((SequencedEvent)entry.event).dispose(); 1135 } 1136 if (entry.event instanceof SentEvent) { 1137 ((SentEvent)entry.event).dispose(); 1138 } 1139 if (prev == null) { 1140 queues[i].head = entry.next; 1141 } else { 1142 prev.next = entry.next; 1143 } 1144 uncacheEQItem(entry); 1145 } else { 1146 prev = entry; 1147 } 1148 entry = entry.next; 1149 } 1150 queues[i].tail = prev; 1151 } 1152 } finally { 1153 pushPopLock.unlock(); 1154 } 1155 } 1156 1157 synchronized long getMostRecentKeyEventTime() { 1158 pushPopLock.lock(); 1159 try { 1160 return mostRecentKeyEventTime; 1161 } finally { 1162 pushPopLock.unlock(); 1163 } 1164 } 1165 1166 static void setCurrentEventAndMostRecentTime(AWTEvent e) { 1167 Toolkit.getEventQueue().setCurrentEventAndMostRecentTimeImpl(e); 1168 } 1169 private void setCurrentEventAndMostRecentTimeImpl(AWTEvent e) { 1170 pushPopLock.lock(); 1171 try { 1172 if (Thread.currentThread() != dispatchThread) { 1173 return; 1174 } 1175 1176 currentEvent = new WeakReference<>(e); 1177 1178 // This series of 'instanceof' checks should be replaced with a 1179 // polymorphic type (for example, an interface which declares a 1180 // getWhen() method). However, this would require us to make such 1181 // a type public, or to place it in sun.awt. Both of these approaches 1182 // have been frowned upon. So for now, we hack. 1183 // 1184 // In tiger, we will probably give timestamps to all events, so this 1185 // will no longer be an issue. 1186 long mostRecentEventTime2 = Long.MIN_VALUE; 1187 if (e instanceof InputEvent) { 1188 InputEvent ie = (InputEvent)e; 1189 mostRecentEventTime2 = ie.getWhen(); 1190 if (e instanceof KeyEvent) { 1191 mostRecentKeyEventTime = ie.getWhen(); 1192 } 1193 } else if (e instanceof InputMethodEvent) { 1194 InputMethodEvent ime = (InputMethodEvent)e; 1195 mostRecentEventTime2 = ime.getWhen(); 1196 } else if (e instanceof ActionEvent) { 1197 ActionEvent ae = (ActionEvent)e; 1198 mostRecentEventTime2 = ae.getWhen(); 1199 } else if (e instanceof InvocationEvent) { 1200 InvocationEvent ie = (InvocationEvent)e; 1201 mostRecentEventTime2 = ie.getWhen(); 1202 } 1203 mostRecentEventTime = Math.max(mostRecentEventTime, mostRecentEventTime2); 1204 } finally { 1205 pushPopLock.unlock(); 1206 } 1207 } 1208 1209 /** 1210 * Causes <code>runnable</code> to have its <code>run</code> 1211 * method called in the {@link #isDispatchThread dispatch thread} of 1212 * {@link Toolkit#getSystemEventQueue the system EventQueue}. 1213 * This will happen after all pending events are processed. 1214 * 1215 * @param runnable the <code>Runnable</code> whose <code>run</code> 1216 * method should be executed 1217 * asynchronously in the 1218 * {@link #isDispatchThread event dispatch thread} 1219 * of {@link Toolkit#getSystemEventQueue the system EventQueue} 1220 * @see #invokeAndWait 1221 * @see Toolkit#getSystemEventQueue 1222 * @see #isDispatchThread 1223 * @since 1.2 1224 */ 1225 public static void invokeLater(Runnable runnable) { 1226 Toolkit.getEventQueue().postEvent( 1227 new InvocationEvent(Toolkit.getDefaultToolkit(), runnable)); 1228 } 1229 1230 /** 1231 * Causes <code>runnable</code> to have its <code>run</code> 1232 * method called in the {@link #isDispatchThread dispatch thread} of 1233 * {@link Toolkit#getSystemEventQueue the system EventQueue}. 1234 * This will happen after all pending events are processed. 1235 * The call blocks until this has happened. This method 1236 * will throw an Error if called from the 1237 * {@link #isDispatchThread event dispatcher thread}. 1238 * 1239 * @param runnable the <code>Runnable</code> whose <code>run</code> 1240 * method should be executed 1241 * synchronously in the 1242 * {@link #isDispatchThread event dispatch thread} 1243 * of {@link Toolkit#getSystemEventQueue the system EventQueue} 1244 * @exception InterruptedException if any thread has 1245 * interrupted this thread 1246 * @exception InvocationTargetException if an throwable is thrown 1247 * when running <code>runnable</code> 1248 * @see #invokeLater 1249 * @see Toolkit#getSystemEventQueue 1250 * @see #isDispatchThread 1251 * @since 1.2 1252 */ 1253 public static void invokeAndWait(Runnable runnable) 1254 throws InterruptedException, InvocationTargetException 1255 { 1256 invokeAndWait(Toolkit.getDefaultToolkit(), runnable); 1257 } 1258 1259 static void invokeAndWait(Object source, Runnable runnable) 1260 throws InterruptedException, InvocationTargetException 1261 { 1262 if (EventQueue.isDispatchThread()) { 1263 throw new Error("Cannot call invokeAndWait from the event dispatcher thread"); 1264 } 1265 1266 class AWTInvocationLock {} 1267 Object lock = new AWTInvocationLock(); 1268 1269 InvocationEvent event = 1270 new InvocationEvent(source, runnable, lock, true); 1271 1272 synchronized (lock) { 1273 Toolkit.getEventQueue().postEvent(event); 1274 while (!event.isDispatched()) { 1275 lock.wait(); 1276 } 1277 } 1278 1279 Throwable eventThrowable = event.getThrowable(); 1280 if (eventThrowable != null) { 1281 throw new InvocationTargetException(eventThrowable); 1282 } 1283 } 1284 1285 /* 1286 * Called from PostEventQueue.postEvent to notify that a new event 1287 * appeared. First it proceeds to the EventQueue on the top of the 1288 * stack, then notifies the associated dispatch thread if it exists 1289 * or starts a new one otherwise. 1290 */ 1291 private void wakeup(boolean isShutdown) { 1292 pushPopLock.lock(); 1293 try { 1294 if (nextQueue != null) { 1295 // Forward call to the top of EventQueue stack. 1296 nextQueue.wakeup(isShutdown); 1297 } else if (dispatchThread != null) { 1298 pushPopCond.signalAll(); 1299 } else if (!isShutdown) { 1300 initDispatchThread(); 1301 } 1302 } finally { 1303 pushPopLock.unlock(); 1304 } 1305 } 1306 } 1307 1308 /** 1309 * The Queue object holds pointers to the beginning and end of one internal 1310 * queue. An EventQueue object is composed of multiple internal Queues, one 1311 * for each priority supported by the EventQueue. All Events on a particular 1312 * internal Queue have identical priority. 1313 */ 1314 class Queue { 1315 EventQueueItem head; 1316 EventQueueItem tail; 1317 }