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