1 /*
   2  * Copyright (c) 1996, 2010, 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.InputEvent;
  29 import java.awt.event.MouseEvent;
  30 import java.awt.event.ActionEvent;
  31 import java.awt.event.WindowEvent;
  32 import java.lang.reflect.Method;
  33 import java.security.AccessController;
  34 import sun.security.action.GetPropertyAction;
  35 import sun.awt.AWTAutoShutdown;
  36 import sun.awt.SunToolkit;
  37 import sun.awt.AppContext;
  38 
  39 import java.util.ArrayList;
  40 import java.util.List;
  41 import sun.util.logging.PlatformLogger;
  42 
  43 import sun.awt.dnd.SunDragSourceContextPeer;
  44 import sun.awt.EventQueueDelegate;
  45 
  46 /**
  47  * EventDispatchThread is a package-private AWT class which takes
  48  * events off the EventQueue and dispatches them to the appropriate
  49  * AWT components.
  50  *
  51  * The Thread starts a "permanent" event pump with a call to
  52  * pumpEvents(Conditional) in its run() method. Event handlers can choose to
  53  * block this event pump at any time, but should start a new pump (<b>not</b>
  54  * a new EventDispatchThread) by again calling pumpEvents(Conditional). This
  55  * secondary event pump will exit automatically as soon as the Condtional
  56  * evaluate()s to false and an additional Event is pumped and dispatched.
  57  *
  58  * @author Tom Ball
  59  * @author Amy Fowler
  60  * @author Fred Ecks
  61  * @author David Mendenhall
  62  *
  63  * @since 1.1
  64  */
  65 class EventDispatchThread extends Thread {
  66 
  67     private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.EventDispatchThread");
  68 
  69     private EventQueue theQueue;
  70     private boolean doDispatch = true;
  71     private volatile boolean shutdown = false;
  72 
  73     private static final int ANY_EVENT = -1;
  74 
  75     private ArrayList<EventFilter> eventFilters = new ArrayList<EventFilter>();
  76 
  77     EventDispatchThread(ThreadGroup group, String name, EventQueue queue) {
  78         super(group, name);
  79         setEventQueue(queue);
  80     }
  81 
  82     /*
  83      * Must be called on EDT only, that's why no synchronization
  84      */
  85     public void stopDispatching() {
  86         doDispatch = false;
  87     }
  88     
  89     public void interrupt() {
  90         shutdown = true;
  91         super.interrupt();
  92     }
  93 
  94     public void run() {
  95         while (true) {
  96             try {
  97                 pumpEvents(new Conditional() {
  98                     public boolean evaluate() {
  99                         return true;
 100                     }
 101                 });
 102             } finally {
 103                 if(getEventQueue().detachDispatchThread(this, shutdown)) {
 104                     break;
 105                 }
 106             }
 107         }
 108     }
 109 
 110     void pumpEvents(Conditional cond) {
 111         pumpEvents(ANY_EVENT, cond);
 112     }
 113 
 114     void pumpEventsForHierarchy(Conditional cond, Component modalComponent) {
 115         pumpEventsForHierarchy(ANY_EVENT, cond, modalComponent);
 116     }
 117 
 118     void pumpEvents(int id, Conditional cond) {
 119         pumpEventsForHierarchy(id, cond, null);
 120     }
 121 
 122     void pumpEventsForHierarchy(int id, Conditional cond, Component modalComponent) {
 123         pumpEventsForFilter(id, cond, new HierarchyEventFilter(modalComponent));
 124     }
 125 
 126     void pumpEventsForFilter(Conditional cond, EventFilter filter) {
 127         pumpEventsForFilter(ANY_EVENT, cond, filter);
 128     }
 129 
 130     void pumpEventsForFilter(int id, Conditional cond, EventFilter filter) {
 131         addEventFilter(filter);
 132         doDispatch = true;
 133         while (doDispatch && !shutdown && cond.evaluate()) {
 134             pumpOneEventForFilters(id);
 135         }
 136         removeEventFilter(filter);
 137     }
 138 
 139     void addEventFilter(EventFilter filter) {
 140         eventLog.finest("adding the event filter: " + filter);
 141         synchronized (eventFilters) {
 142             if (!eventFilters.contains(filter)) {
 143                 if (filter instanceof ModalEventFilter) {
 144                     ModalEventFilter newFilter = (ModalEventFilter)filter;
 145                     int k = 0;
 146                     for (k = 0; k < eventFilters.size(); k++) {
 147                         EventFilter f = eventFilters.get(k);
 148                         if (f instanceof ModalEventFilter) {
 149                             ModalEventFilter cf = (ModalEventFilter)f;
 150                             if (cf.compareTo(newFilter) > 0) {
 151                                 break;
 152                             }
 153                         }
 154                     }
 155                     eventFilters.add(k, filter);
 156                 } else {
 157                     eventFilters.add(filter);
 158                 }
 159             }
 160         }
 161     }
 162 
 163     void removeEventFilter(EventFilter filter) {
 164         eventLog.finest("removing the event filter: " + filter);
 165         synchronized (eventFilters) {
 166             eventFilters.remove(filter);
 167         }
 168     }
 169 
 170     void pumpOneEventForFilters(int id) {
 171         AWTEvent event = null;
 172         boolean eventOK = false;
 173         try {
 174             EventQueue eq = null;
 175             EventQueueDelegate.Delegate delegate = null;
 176             do {
 177                 // EventQueue may change during the dispatching
 178                 eq = getEventQueue();
 179                 delegate = EventQueueDelegate.getDelegate();
 180 
 181                 if (delegate != null && id == ANY_EVENT) {
 182                     event = delegate.getNextEvent(eq);
 183                 } else {
 184                     event = (id == ANY_EVENT) ? eq.getNextEvent() : eq.getNextEvent(id);
 185                 }
 186 
 187                 eventOK = true;
 188                 synchronized (eventFilters) {
 189                     for (int i = eventFilters.size() - 1; i >= 0; i--) {
 190                         EventFilter f = eventFilters.get(i);
 191                         EventFilter.FilterAction accept = f.acceptEvent(event);
 192                         if (accept == EventFilter.FilterAction.REJECT) {
 193                             eventOK = false;
 194                             break;
 195                         } else if (accept == EventFilter.FilterAction.ACCEPT_IMMEDIATELY) {
 196                             break;
 197                         }
 198                     }
 199                 }
 200                 eventOK = eventOK && SunDragSourceContextPeer.checkEvent(event);
 201                 if (!eventOK) {
 202                     event.consume();
 203                 }
 204             }
 205             while (eventOK == false);
 206 
 207             if (eventLog.isLoggable(PlatformLogger.FINEST)) {
 208                 eventLog.finest("Dispatching: " + event);
 209             }
 210 
 211             Object handle = null;
 212             if (delegate != null) {
 213                 handle = delegate.beforeDispatch(event);
 214             }
 215             eq.dispatchEvent(event);
 216             if (delegate != null) {
 217                 delegate.afterDispatch(event, handle);
 218             }
 219         }
 220         catch (ThreadDeath death) {
 221             shutdown = true;
 222             throw death;
 223         }
 224         catch (InterruptedException interruptedException) {
 225             shutdown = true; // AppContext.dispose() interrupts all
 226                              // Threads in the AppContext
 227         }
 228         catch (Throwable e) {
 229             processException(e);
 230         }
 231     }
 232 
 233     private void processException(Throwable e) {
 234         if (eventLog.isLoggable(PlatformLogger.FINE)) {
 235             eventLog.fine("Processing exception: " + e);
 236         }
 237         getUncaughtExceptionHandler().uncaughtException(this, e);
 238     }
 239 
 240     public synchronized EventQueue getEventQueue() {
 241         return theQueue;
 242     }
 243     public synchronized void setEventQueue(EventQueue eq) {
 244         theQueue = eq;
 245     }
 246 
 247     private static class HierarchyEventFilter implements EventFilter {
 248         private Component modalComponent;
 249         public HierarchyEventFilter(Component modalComponent) {
 250             this.modalComponent = modalComponent;
 251         }
 252         public FilterAction acceptEvent(AWTEvent event) {
 253             if (modalComponent != null) {
 254                 int eventID = event.getID();
 255                 boolean mouseEvent = (eventID >= MouseEvent.MOUSE_FIRST) &&
 256                                      (eventID <= MouseEvent.MOUSE_LAST);
 257                 boolean actionEvent = (eventID >= ActionEvent.ACTION_FIRST) &&
 258                                       (eventID <= ActionEvent.ACTION_LAST);
 259                 boolean windowClosingEvent = (eventID == WindowEvent.WINDOW_CLOSING);
 260                 /*
 261                  * filter out MouseEvent and ActionEvent that's outside
 262                  * the modalComponent hierarchy.
 263                  * KeyEvent is handled by using enqueueKeyEvent
 264                  * in Dialog.show
 265                  */
 266                 if (Component.isInstanceOf(modalComponent, "javax.swing.JInternalFrame")) {
 267                     /*
 268                      * Modal internal frames are handled separately. If event is
 269                      * for some component from another heavyweight than modalComp,
 270                      * it is accepted. If heavyweight is the same - we still accept
 271                      * event and perform further filtering in LightweightDispatcher
 272                      */
 273                     return windowClosingEvent ? FilterAction.REJECT : FilterAction.ACCEPT;
 274                 }
 275                 if (mouseEvent || actionEvent || windowClosingEvent) {
 276                     Object o = event.getSource();
 277                     if (o instanceof sun.awt.ModalExclude) {
 278                         // Exclude this object from modality and
 279                         // continue to pump it's events.
 280                         return FilterAction.ACCEPT;
 281                     } else if (o instanceof Component) {
 282                         Component c = (Component) o;
 283                         // 5.0u3 modal exclusion
 284                         boolean modalExcluded = false;
 285                         if (modalComponent instanceof Container) {
 286                             while (c != modalComponent && c != null) {
 287                                 if ((c instanceof Window) &&
 288                                     (sun.awt.SunToolkit.isModalExcluded((Window)c))) {
 289                                     // Exclude this window and all its children from
 290                                     //  modality and continue to pump it's events.
 291                                     modalExcluded = true;
 292                                     break;
 293                                 }
 294                                 c = c.getParent();
 295                             }
 296                         }
 297                         if (!modalExcluded && (c != modalComponent)) {
 298                             return FilterAction.REJECT;
 299                         }
 300                     }
 301                 }
 302             }
 303             return FilterAction.ACCEPT;
 304         }
 305     }
 306 }