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