1 /*
   2  * Copyright (c) 2010, 2013, 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.util.Timer;
  29 import java.util.TimerTask;
  30 import java.util.concurrent.atomic.AtomicBoolean;
  31 
  32 import java.security.PrivilegedAction;
  33 import java.security.AccessController;
  34 
  35 import sun.awt.PeerEvent;
  36 
  37 import sun.util.logging.PlatformLogger;
  38 
  39 /**
  40  * This utility class is used to suspend execution on a thread
  41  * while still allowing {@code EventDispatchThread} to dispatch events.
  42  * The API methods of the class are thread-safe.
  43  *
  44  * @author Anton Tarasov, Artem Ananiev
  45  *
  46  * @since 1.7
  47  */
  48 class WaitDispatchSupport implements SecondaryLoop {
  49     private final static PlatformLogger log =
  50             PlatformLogger.getLogger("java.awt.event.WaitDispatchSupport");
  51 
  52     private EventDispatchThread dispatchThread;
  53     private EventFilter filter;
  54 
  55     private volatile Conditional extCondition;
  56     private volatile Conditional condition;
  57 
  58     private long interval;
  59     // Use a shared daemon timer to serve all the WaitDispatchSupports
  60     private static Timer timer;
  61     // When this WDS expires, we cancel the timer task leaving the
  62     // shared timer up and running
  63     private TimerTask timerTask;
  64 
  65     private AtomicBoolean keepBlockingEDT = new AtomicBoolean(false);
  66     private AtomicBoolean keepBlockingCT = new AtomicBoolean(false);
  67     private AtomicBoolean afterExit = new AtomicBoolean(false);
  68 
  69     private static synchronized void initializeTimer() {
  70         if (timer == null) {
  71             timer = new Timer("AWT-WaitDispatchSupport-Timer", true);
  72         }
  73     }
  74 
  75     /**
  76      * Creates a {@code WaitDispatchSupport} instance to
  77      * serve the given event dispatch thread.
  78      *
  79      * @param dispatchThread An event dispatch thread that
  80      *                       should not stop dispatching events while waiting
  81      *
  82      * @since 1.7
  83      */
  84     public WaitDispatchSupport(EventDispatchThread dispatchThread) {
  85         this(dispatchThread, null);
  86     }
  87 
  88     /**
  89      * Creates a {@code WaitDispatchSupport} instance to
  90      * serve the given event dispatch thread.
  91      *
  92      * @param dispatchThread An event dispatch thread that
  93      *        should not stop dispatching events while waiting
  94      * @param extCond A conditional object used to determine
  95      *        if the loop should be terminated
  96      *
  97      * @since 1.7
  98      */
  99     public WaitDispatchSupport(EventDispatchThread dispatchThread,
 100                                Conditional extCond)
 101     {
 102         if (dispatchThread == null) {
 103             throw new IllegalArgumentException("The dispatchThread can not be null");
 104         }
 105 
 106         this.dispatchThread = dispatchThread;
 107         this.extCondition = extCond;
 108         this.condition = new Conditional() {
 109             @Override
 110             public boolean evaluate() {
 111                 if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 112                     log.finest("evaluate(): blockingEDT=" + keepBlockingEDT.get() +
 113                                ", blockingCT=" + keepBlockingCT.get());
 114                 }
 115                 boolean extEvaluate =
 116                     (extCondition != null) ? extCondition.evaluate() : true;
 117                 if (!keepBlockingEDT.get() || !extEvaluate || afterExit.get()) {
 118                     if (timerTask != null) {
 119                         timerTask.cancel();
 120                         timerTask = null;
 121                     }
 122                     return false;
 123                 }
 124                 return true;
 125             }
 126         };
 127     }
 128 
 129     /**
 130      * Creates a {@code WaitDispatchSupport} instance to
 131      * serve the given event dispatch thread.
 132      * <p>
 133      * The {@link EventFilter} is set on the {@code dispatchThread}
 134      * while waiting. The filter is removed on completion of the
 135      * waiting process.
 136      * <p>
 137      *
 138      *
 139      * @param dispatchThread An event dispatch thread that
 140      *        should not stop dispatching events while waiting
 141      * @param filter {@code EventFilter} to be set
 142      * @param interval A time interval to wait for. Note that
 143      *        when the waiting process takes place on EDT
 144      *        there is no guarantee to stop it in the given time
 145      *
 146      * @since 1.7
 147      */
 148     public WaitDispatchSupport(EventDispatchThread dispatchThread,
 149                                Conditional extCondition,
 150                                EventFilter filter, long interval)
 151     {
 152         this(dispatchThread, extCondition);
 153         this.filter = filter;
 154         if (interval < 0) {
 155             throw new IllegalArgumentException("The interval value must be >= 0");
 156         }
 157         this.interval = interval;
 158         if (interval != 0) {
 159             initializeTimer();
 160         }
 161     }
 162 
 163     /**
 164      * {@inheritDoc}
 165      */
 166     @Override
 167     public boolean enter() {
 168         if (log.isLoggable(PlatformLogger.Level.FINE)) {
 169             log.fine("enter(): blockingEDT=" + keepBlockingEDT.get() +
 170                      ", blockingCT=" + keepBlockingCT.get());
 171         }
 172 
 173         if (!keepBlockingEDT.compareAndSet(false, true)) {
 174             log.fine("The secondary loop is already running, aborting");
 175             return false;
 176         }
 177         try {
 178             if (afterExit.get()) {
 179                 log.fine("Exit was called already, aborting");
 180                 return false;
 181             }
 182 
 183             final Runnable run = new Runnable() {
 184                 public void run() {
 185                     log.fine("Starting a new event pump");
 186                     if (filter == null) {
 187                         dispatchThread.pumpEvents(condition);
 188                     } else {
 189                         dispatchThread.pumpEventsForFilter(condition, filter);
 190                     }
 191                 }
 192             };
 193 
 194             // We have two mechanisms for blocking: if we're on the
 195             // dispatch thread, start a new event pump; if we're
 196             // on any other thread, call wait() on the treelock
 197 
 198             Thread currentThread = Thread.currentThread();
 199             if (currentThread == dispatchThread) {
 200                 if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 201                     log.finest("On dispatch thread: " + dispatchThread);
 202                 }
 203                 if (interval != 0) {
 204                     if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 205                         log.finest("scheduling the timer for " + interval + " ms");
 206                     }
 207                     timer.schedule(timerTask = new TimerTask() {
 208                         @Override
 209                         public void run() {
 210                             if (keepBlockingEDT.compareAndSet(true, false)) {
 211                                 wakeupEDT();
 212                             }
 213                         }
 214                     }, interval);
 215                 }
 216                 // Dispose SequencedEvent we are dispatching on the current
 217                 // AppContext, to prevent us from hang - see 4531693 for details
 218                 SequencedEvent currentSE = KeyboardFocusManager.
 219                         getCurrentKeyboardFocusManager().getCurrentSequencedEvent();
 220                 if (currentSE != null) {
 221                     if (log.isLoggable(PlatformLogger.Level.FINE)) {
 222                         log.fine("Dispose current SequencedEvent: " + currentSE);
 223                     }
 224                     currentSE.dispose();
 225                 }
 226                 // In case the exit() method is called before starting
 227                 // new event pump it will post the waking event to EDT.
 228                 // The event will be handled after the new event pump
 229                 // starts. Thus, the enter() method will not hang.
 230                 //
 231                 // Event pump should be privileged. See 6300270.
 232                 AccessController.doPrivileged(new PrivilegedAction<Void>() {
 233                     public Void run() {
 234                         run.run();
 235                         return null;
 236                     }
 237                 });
 238             } else {
 239                 if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 240                     log.finest("On non-dispatch thread: " + currentThread);
 241                 }
 242                 keepBlockingCT.set(true);
 243                 synchronized (getTreeLock()) {
 244                     if (afterExit.get()) return false;
 245                     if (filter != null) {
 246                         dispatchThread.addEventFilter(filter);
 247                     }
 248                     try {
 249                         EventQueue eq = dispatchThread.getEventQueue();
 250                         eq.postEvent(new PeerEvent(this, run, PeerEvent.PRIORITY_EVENT));
 251                         if (interval > 0) {
 252                             long currTime = System.currentTimeMillis();
 253                             while (keepBlockingCT.get() &&
 254                                     ((extCondition != null) ? extCondition.evaluate() : true) &&
 255                                     (currTime + interval > System.currentTimeMillis()))
 256                             {
 257                                 getTreeLock().wait(interval);
 258                             }
 259                         } else {
 260                             while (keepBlockingCT.get() &&
 261                                     ((extCondition != null) ? extCondition.evaluate() : true))
 262                             {
 263                                 getTreeLock().wait();
 264                             }
 265                         }
 266                         if (log.isLoggable(PlatformLogger.Level.FINE)) {
 267                             log.fine("waitDone " + keepBlockingEDT.get() + " " + keepBlockingCT.get());
 268                         }
 269                     } catch (InterruptedException e) {
 270                         if (log.isLoggable(PlatformLogger.Level.FINE)) {
 271                             log.fine("Exception caught while waiting: " + e);
 272                         }
 273                     } finally {
 274                         if (filter != null) {
 275                             dispatchThread.removeEventFilter(filter);
 276                         }
 277                     }
 278                 }
 279             }
 280             return true;
 281         }
 282         finally {
 283             keepBlockingEDT.set(false);
 284             keepBlockingCT.set(false);
 285             afterExit.set(false);
 286         }
 287     }
 288 
 289     /**
 290      * {@inheritDoc}
 291      */
 292     public boolean exit() {
 293         if (log.isLoggable(PlatformLogger.Level.FINE)) {
 294             log.fine("exit(): blockingEDT=" + keepBlockingEDT.get() +
 295                     ", blockingCT=" + keepBlockingCT.get());
 296         }
 297         afterExit.set(true);
 298         if (keepBlockingEDT.getAndSet(false)) {
 299             wakeupEDT();
 300             return true;
 301         }
 302         return false;
 303     }
 304 
 305     private final static Object getTreeLock() {
 306         return Component.LOCK;
 307     }
 308 
 309     private final Runnable wakingRunnable = new Runnable() {
 310         public void run() {
 311             log.fine("Wake up EDT");
 312             synchronized (getTreeLock()) {
 313                 keepBlockingCT.set(false);
 314                 getTreeLock().notifyAll();
 315             }
 316             log.fine("Wake up EDT done");
 317         }
 318     };
 319 
 320     private void wakeupEDT() {
 321         if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 322             log.finest("wakeupEDT(): EDT == " + dispatchThread);
 323         }
 324         EventQueue eq = dispatchThread.getEventQueue();
 325         eq.postEvent(new PeerEvent(this, wakingRunnable, PeerEvent.PRIORITY_EVENT));
 326     }
 327 }