View Javadoc
1   /*
2    * Copyright (c) 1997, 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 sun.awt;
27  
28  import java.awt.*;
29  import static java.awt.RenderingHints.*;
30  import java.awt.dnd.*;
31  import java.awt.dnd.peer.DragSourceContextPeer;
32  import java.awt.peer.*;
33  import java.awt.event.WindowEvent;
34  import java.awt.event.KeyEvent;
35  import java.awt.image.*;
36  import java.awt.TrayIcon;
37  import java.awt.SystemTray;
38  import java.awt.event.InputEvent;
39  import java.net.URL;
40  import java.util.*;
41  import java.util.concurrent.TimeUnit;
42  import java.util.concurrent.locks.Condition;
43  import java.util.concurrent.locks.Lock;
44  import java.util.concurrent.locks.ReentrantLock;
45  
46  import sun.security.util.SecurityConstants;
47  import sun.util.logging.PlatformLogger;
48  import sun.misc.SoftCache;
49  import sun.font.FontDesignMetrics;
50  import sun.awt.im.InputContext;
51  import sun.awt.image.*;
52  import sun.security.action.GetPropertyAction;
53  import sun.security.action.GetBooleanAction;
54  import java.lang.reflect.InvocationTargetException;
55  import java.security.AccessController;
56  
57  public abstract class SunToolkit extends Toolkit
58      implements WindowClosingSupport, WindowClosingListener,
59      ComponentFactory, InputMethodSupport, KeyboardFocusManagerPeerProvider {
60  
61      // 8014718: logging has been removed from SunToolkit
62  
63      /* Load debug settings for native code */
64      static {
65          if (AccessController.doPrivileged(new GetBooleanAction("sun.awt.nativedebug"))) {
66              DebugSettings.init();
67          }
68      };
69  
70      /**
71       * Special mask for the UngrabEvent events, in addition to the
72       * public masks defined in AWTEvent.  Should be used as the mask
73       * value for Toolkit.addAWTEventListener.
74       */
75      public static final int GRAB_EVENT_MASK = 0x80000000;
76  
77      /* The key to put()/get() the PostEventQueue into/from the AppContext.
78       */
79      private static final String POST_EVENT_QUEUE_KEY = "PostEventQueue";
80  
81      /**
82       * Number of buttons.
83       * By default it's taken from the system. If system value does not
84       * fit into int type range, use our own MAX_BUTTONS_SUPPORT value.
85       */
86      protected static int numberOfButtons = 0;
87  
88  
89      /* XFree standard mention 24 buttons as maximum:
90       * http://www.xfree86.org/current/mouse.4.html
91       * We workaround systems supporting more than 24 buttons.
92       * Otherwise, we have to use long type values as masks
93       * which leads to API change.
94       * InputEvent.BUTTON_DOWN_MASK may contain only 21 masks due to
95       * the 4-bytes limit for the int type. (CR 6799099)
96       * One more bit is reserved for FIRST_HIGH_BIT.
97       */
98      public final static int MAX_BUTTONS_SUPPORTED = 20;
99  
100     /**
101      * Creates and initializes EventQueue instance for the specified
102      * AppContext.
103      * Note that event queue must be created from createNewAppContext()
104      * only in order to ensure that EventQueue constructor obtains
105      * the correct AppContext.
106      * @param appContext AppContext to associate with the event queue
107      */
108     private static void initEQ(AppContext appContext) {
109         EventQueue eventQueue;
110 
111         String eqName = System.getProperty("AWT.EventQueueClass",
112                 "java.awt.EventQueue");
113 
114         try {
115             eventQueue = (EventQueue)Class.forName(eqName).newInstance();
116         } catch (Exception e) {
117             e.printStackTrace();
118             System.err.println("Failed loading " + eqName + ": " + e);
119             eventQueue = new EventQueue();
120         }
121         appContext.put(AppContext.EVENT_QUEUE_KEY, eventQueue);
122 
123         PostEventQueue postEventQueue = new PostEventQueue(eventQueue);
124         appContext.put(POST_EVENT_QUEUE_KEY, postEventQueue);
125     }
126 
127     public SunToolkit() {
128     }
129 
130     public boolean useBufferPerWindow() {
131         return false;
132     }
133 
134     public abstract WindowPeer createWindow(Window target)
135         throws HeadlessException;
136 
137     public abstract FramePeer createFrame(Frame target)
138         throws HeadlessException;
139 
140     public abstract FramePeer createLightweightFrame(LightweightFrame target)
141         throws HeadlessException;
142 
143     public abstract DialogPeer createDialog(Dialog target)
144         throws HeadlessException;
145 
146     public abstract ButtonPeer createButton(Button target)
147         throws HeadlessException;
148 
149     public abstract TextFieldPeer createTextField(TextField target)
150         throws HeadlessException;
151 
152     public abstract ChoicePeer createChoice(Choice target)
153         throws HeadlessException;
154 
155     public abstract LabelPeer createLabel(Label target)
156         throws HeadlessException;
157 
158     public abstract ListPeer createList(java.awt.List target)
159         throws HeadlessException;
160 
161     public abstract CheckboxPeer createCheckbox(Checkbox target)
162         throws HeadlessException;
163 
164     public abstract ScrollbarPeer createScrollbar(Scrollbar target)
165         throws HeadlessException;
166 
167     public abstract ScrollPanePeer createScrollPane(ScrollPane target)
168         throws HeadlessException;
169 
170     public abstract TextAreaPeer createTextArea(TextArea target)
171         throws HeadlessException;
172 
173     public abstract FileDialogPeer createFileDialog(FileDialog target)
174         throws HeadlessException;
175 
176     public abstract MenuBarPeer createMenuBar(MenuBar target)
177         throws HeadlessException;
178 
179     public abstract MenuPeer createMenu(Menu target)
180         throws HeadlessException;
181 
182     public abstract PopupMenuPeer createPopupMenu(PopupMenu target)
183         throws HeadlessException;
184 
185     public abstract MenuItemPeer createMenuItem(MenuItem target)
186         throws HeadlessException;
187 
188     public abstract CheckboxMenuItemPeer createCheckboxMenuItem(
189         CheckboxMenuItem target)
190         throws HeadlessException;
191 
192     public abstract DragSourceContextPeer createDragSourceContextPeer(
193         DragGestureEvent dge)
194         throws InvalidDnDOperationException;
195 
196     public abstract TrayIconPeer createTrayIcon(TrayIcon target)
197         throws HeadlessException, AWTException;
198 
199     public abstract SystemTrayPeer createSystemTray(SystemTray target);
200 
201     public abstract boolean isTraySupported();
202 
203     @SuppressWarnings("deprecation")
204     public abstract FontPeer getFontPeer(String name, int style);
205 
206     public abstract RobotPeer createRobot(Robot target, GraphicsDevice screen)
207         throws AWTException;
208 
209     public abstract KeyboardFocusManagerPeer getKeyboardFocusManagerPeer()
210         throws HeadlessException;
211 
212     /**
213      * The AWT lock is typically only used on Unix platforms to synchronize
214      * access to Xlib, OpenGL, etc.  However, these methods are implemented
215      * in SunToolkit so that they can be called from shared code (e.g.
216      * from the OGL pipeline) or from the X11 pipeline regardless of whether
217      * XToolkit or MToolkit is currently in use.  There are native macros
218      * (such as AWT_LOCK) defined in awt.h, so if the implementation of these
219      * methods is changed, make sure it is compatible with the native macros.
220      *
221      * Note: The following methods (awtLock(), awtUnlock(), etc) should be
222      * used in place of:
223      *     synchronized (getAWTLock()) {
224      *         ...
225      *     }
226      *
227      * By factoring these methods out specially, we are able to change the
228      * implementation of these methods (e.g. use more advanced locking
229      * mechanisms) without impacting calling code.
230      *
231      * Sample usage:
232      *     private void doStuffWithXlib() {
233      *         assert !SunToolkit.isAWTLockHeldByCurrentThread();
234      *         SunToolkit.awtLock();
235      *         try {
236      *             ...
237      *             XlibWrapper.XDoStuff();
238      *         } finally {
239      *             SunToolkit.awtUnlock();
240      *         }
241      *     }
242      */
243 
244     private static final ReentrantLock AWT_LOCK = new ReentrantLock();
245     private static final Condition AWT_LOCK_COND = AWT_LOCK.newCondition();
246 
247     public static final void awtLock() {
248         AWT_LOCK.lock();
249     }
250 
251     public static final boolean awtTryLock() {
252         return AWT_LOCK.tryLock();
253     }
254 
255     public static final void awtUnlock() {
256         AWT_LOCK.unlock();
257     }
258 
259     public static final void awtLockWait()
260         throws InterruptedException
261     {
262         AWT_LOCK_COND.await();
263     }
264 
265     public static final void awtLockWait(long timeout)
266         throws InterruptedException
267     {
268         AWT_LOCK_COND.await(timeout, TimeUnit.MILLISECONDS);
269     }
270 
271     public static final void awtLockNotify() {
272         AWT_LOCK_COND.signal();
273     }
274 
275     public static final void awtLockNotifyAll() {
276         AWT_LOCK_COND.signalAll();
277     }
278 
279     public static final boolean isAWTLockHeldByCurrentThread() {
280         return AWT_LOCK.isHeldByCurrentThread();
281     }
282 
283     /*
284      * Create a new AppContext, along with its EventQueue, for a
285      * new ThreadGroup.  Browser code, for example, would use this
286      * method to create an AppContext & EventQueue for an Applet.
287      */
288     public static AppContext createNewAppContext() {
289         ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
290         return createNewAppContext(threadGroup);
291     }
292 
293     static final AppContext createNewAppContext(ThreadGroup threadGroup) {
294         // Create appContext before initialization of EventQueue, so all
295         // the calls to AppContext.getAppContext() from EventQueue ctor
296         // return correct values
297         AppContext appContext = new AppContext(threadGroup);
298         initEQ(appContext);
299 
300         return appContext;
301     }
302 
303     static void wakeupEventQueue(EventQueue q, boolean isShutdown){
304         AWTAccessor.getEventQueueAccessor().wakeup(q, isShutdown);
305     }
306 
307     /*
308      * Fetch the peer associated with the given target (as specified
309      * in the peer creation method).  This can be used to determine
310      * things like what the parent peer is.  If the target is null
311      * or the target can't be found (either because the a peer was
312      * never created for it or the peer was disposed), a null will
313      * be returned.
314      */
315     protected static Object targetToPeer(Object target) {
316         if (target != null && !GraphicsEnvironment.isHeadless()) {
317             return AWTAutoShutdown.getInstance().getPeer(target);
318         }
319         return null;
320     }
321 
322     protected static void targetCreatedPeer(Object target, Object peer) {
323         if (target != null && peer != null &&
324             !GraphicsEnvironment.isHeadless())
325         {
326             AWTAutoShutdown.getInstance().registerPeer(target, peer);
327         }
328     }
329 
330     protected static void targetDisposedPeer(Object target, Object peer) {
331         if (target != null && peer != null &&
332             !GraphicsEnvironment.isHeadless())
333         {
334             AWTAutoShutdown.getInstance().unregisterPeer(target, peer);
335         }
336     }
337 
338     // Maps from non-Component/MenuComponent to AppContext.
339     // WeakHashMap<Component,AppContext>
340     private static final Map<Object, AppContext> appContextMap =
341         Collections.synchronizedMap(new WeakHashMap<Object, AppContext>());
342 
343     /**
344      * Sets the appContext field of target. If target is not a Component or
345      * MenuComponent, this returns false.
346      */
347     private static boolean setAppContext(Object target,
348                                          AppContext context) {
349         if (target instanceof Component) {
350             AWTAccessor.getComponentAccessor().
351                 setAppContext((Component)target, context);
352         } else if (target instanceof MenuComponent) {
353             AWTAccessor.getMenuComponentAccessor().
354                 setAppContext((MenuComponent)target, context);
355         } else {
356             return false;
357         }
358         return true;
359     }
360 
361     /**
362      * Returns the appContext field for target. If target is not a
363      * Component or MenuComponent this returns null.
364      */
365     private static AppContext getAppContext(Object target) {
366         if (target instanceof Component) {
367             return AWTAccessor.getComponentAccessor().
368                        getAppContext((Component)target);
369         } else if (target instanceof MenuComponent) {
370             return AWTAccessor.getMenuComponentAccessor().
371                        getAppContext((MenuComponent)target);
372         } else {
373             return null;
374         }
375     }
376 
377     /*
378      * Fetch the AppContext associated with the given target.
379      * This can be used to determine things like which EventQueue
380      * to use for posting events to a Component.  If the target is
381      * null or the target can't be found, a null with be returned.
382      */
383     public static AppContext targetToAppContext(Object target) {
384         if (target == null || GraphicsEnvironment.isHeadless()) {
385             return null;
386         }
387         AppContext context = getAppContext(target);
388         if (context == null) {
389             // target is not a Component/MenuComponent, try the
390             // appContextMap.
391             context = appContextMap.get(target);
392         }
393         return context;
394     }
395 
396      /**
397       * Sets the synchronous status of focus requests on lightweight
398       * components in the specified window to the specified value.
399       * If the boolean parameter is <code>true</code> then the focus
400       * requests on lightweight components will be performed
401       * synchronously, if it is <code>false</code>, then asynchronously.
402       * By default, all windows have their lightweight request status
403       * set to asynchronous.
404       * <p>
405       * The application can only set the status of lightweight focus
406       * requests to synchronous for any of its windows if it doesn't
407       * perform focus transfers between different heavyweight containers.
408       * In this case the observable focus behaviour is the same as with
409       * asynchronous status.
410       * <p>
411       * If the application performs focus transfer between different
412       * heavyweight containers and sets the lightweight focus request
413       * status to synchronous for any of its windows, then further focus
414       * behaviour is unspecified.
415       * <p>
416       * @param    w window for which the lightweight focus request status
417       *             should be set
418       * @param    status the value of lightweight focus request status
419       */
420 
421     public static void setLWRequestStatus(Window changed,boolean status){
422         AWTAccessor.getWindowAccessor().setLWRequestStatus(changed, status);
423     };
424 
425     public static void checkAndSetPolicy(Container cont) {
426         FocusTraversalPolicy defaultPolicy = KeyboardFocusManager.
427             getCurrentKeyboardFocusManager().
428                 getDefaultFocusTraversalPolicy();
429 
430         cont.setFocusTraversalPolicy(defaultPolicy);
431     }
432 
433     private static FocusTraversalPolicy createLayoutPolicy() {
434         FocusTraversalPolicy policy = null;
435         try {
436             Class<?> layoutPolicyClass =
437                 Class.forName("javax.swing.LayoutFocusTraversalPolicy");
438             policy = (FocusTraversalPolicy)layoutPolicyClass.newInstance();
439         }
440         catch (ClassNotFoundException e) {
441             assert false;
442         }
443         catch (InstantiationException e) {
444             assert false;
445         }
446         catch (IllegalAccessException e) {
447             assert false;
448         }
449 
450         return policy;
451     }
452 
453     /*
454      * Insert a mapping from target to AppContext, for later retrieval
455      * via targetToAppContext() above.
456      */
457     public static void insertTargetMapping(Object target, AppContext appContext) {
458         if (!GraphicsEnvironment.isHeadless()) {
459             if (!setAppContext(target, appContext)) {
460                 // Target is not a Component/MenuComponent, use the private Map
461                 // instead.
462                 appContextMap.put(target, appContext);
463             }
464         }
465     }
466 
467     /*
468      * Post an AWTEvent to the Java EventQueue, using the PostEventQueue
469      * to avoid possibly calling client code (EventQueueSubclass.postEvent())
470      * on the toolkit (AWT-Windows/AWT-Motif) thread.  This function should
471      * not be called under another lock since it locks the EventQueue.
472      * See bugids 4632918, 4526597.
473      */
474     public static void postEvent(AppContext appContext, AWTEvent event) {
475         if (event == null) {
476             throw new NullPointerException();
477         }
478 
479         AWTAccessor.SequencedEventAccessor sea = AWTAccessor.getSequencedEventAccessor();
480         if (sea != null && sea.isSequencedEvent(event)) {
481             AWTEvent nested = sea.getNested(event);
482             if (nested.getID() == WindowEvent.WINDOW_LOST_FOCUS &&
483                 nested instanceof TimedWindowEvent)
484             {
485                 TimedWindowEvent twe = (TimedWindowEvent)nested;
486                 ((SunToolkit)Toolkit.getDefaultToolkit()).
487                     setWindowDeactivationTime((Window)twe.getSource(), twe.getWhen());
488             }
489         }
490 
491         // All events posted via this method are system-generated.
492         // Placing the following call here reduces considerably the
493         // number of places throughout the toolkit that would
494         // otherwise have to be modified to precisely identify
495         // system-generated events.
496         setSystemGenerated(event);
497         AppContext eventContext = targetToAppContext(event.getSource());
498         if (eventContext != null && !eventContext.equals(appContext)) {
499             throw new RuntimeException("Event posted on wrong app context : " + event);
500         }
501         PostEventQueue postEventQueue =
502             (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY);
503         if (postEventQueue != null) {
504             postEventQueue.postEvent(event);
505         }
506     }
507 
508     /*
509      * Post AWTEvent of high priority.
510      */
511     public static void postPriorityEvent(final AWTEvent e) {
512         PeerEvent pe = new PeerEvent(Toolkit.getDefaultToolkit(), new Runnable() {
513                 public void run() {
514                     AWTAccessor.getAWTEventAccessor().setPosted(e);
515                     ((Component)e.getSource()).dispatchEvent(e);
516                 }
517             }, PeerEvent.ULTIMATE_PRIORITY_EVENT);
518         postEvent(targetToAppContext(e.getSource()), pe);
519     }
520 
521     /*
522      * Flush any pending events which haven't been posted to the AWT
523      * EventQueue yet.
524      */
525     public static void flushPendingEvents()  {
526         AppContext appContext = AppContext.getAppContext();
527         flushPendingEvents(appContext);
528     }
529 
530     /*
531      * Flush the PostEventQueue for the right AppContext.
532      * The default flushPendingEvents only flushes the thread-local context,
533      * which is not always correct, c.f. 3746956
534      */
535     public static void flushPendingEvents(AppContext appContext) {
536         PostEventQueue postEventQueue =
537                 (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY);
538         if (postEventQueue != null) {
539             postEventQueue.flush();
540         }
541     }
542 
543     /*
544      * Execute a chunk of code on the Java event handler thread for the
545      * given target.  Does not wait for the execution to occur before
546      * returning to the caller.
547      */
548     public static void executeOnEventHandlerThread(Object target,
549                                                    Runnable runnable) {
550         executeOnEventHandlerThread(new PeerEvent(target, runnable, PeerEvent.PRIORITY_EVENT));
551     }
552 
553     /*
554      * Fixed 5064013: the InvocationEvent time should be equals
555      * the time of the ActionEvent
556      */
557     @SuppressWarnings("serial")
558     public static void executeOnEventHandlerThread(Object target,
559                                                    Runnable runnable,
560                                                    final long when) {
561         executeOnEventHandlerThread(
562             new PeerEvent(target, runnable, PeerEvent.PRIORITY_EVENT) {
563                 public long getWhen() {
564                     return when;
565                 }
566             });
567     }
568 
569     /*
570      * Execute a chunk of code on the Java event handler thread for the
571      * given target.  Does not wait for the execution to occur before
572      * returning to the caller.
573      */
574     public static void executeOnEventHandlerThread(PeerEvent peerEvent) {
575         postEvent(targetToAppContext(peerEvent.getSource()), peerEvent);
576     }
577 
578     /*
579      * Execute a chunk of code on the Java event handler thread. The
580      * method takes into account provided AppContext and sets
581      * <code>SunToolkit.getDefaultToolkit()</code> as a target of the
582      * event. See 6451487 for detailes.
583      * Does not wait for the execution to occur before returning to
584      * the caller.
585      */
586      public static void invokeLaterOnAppContext(
587         AppContext appContext, Runnable dispatcher)
588      {
589         postEvent(appContext,
590             new PeerEvent(Toolkit.getDefaultToolkit(), dispatcher,
591                 PeerEvent.PRIORITY_EVENT));
592      }
593 
594     /*
595      * Execute a chunk of code on the Java event handler thread for the
596      * given target.  Waits for the execution to occur before returning
597      * to the caller.
598      */
599     public static void executeOnEDTAndWait(Object target, Runnable runnable)
600         throws InterruptedException, InvocationTargetException
601     {
602         if (EventQueue.isDispatchThread()) {
603             throw new Error("Cannot call executeOnEDTAndWait from any event dispatcher thread");
604         }
605 
606         class AWTInvocationLock {}
607         Object lock = new AWTInvocationLock();
608 
609         PeerEvent event = new PeerEvent(target, runnable, lock, true, PeerEvent.PRIORITY_EVENT);
610 
611         synchronized (lock) {
612             executeOnEventHandlerThread(event);
613             while(!event.isDispatched()) {
614                 lock.wait();
615             }
616         }
617 
618         Throwable eventThrowable = event.getThrowable();
619         if (eventThrowable != null) {
620             throw new InvocationTargetException(eventThrowable);
621         }
622     }
623 
624     /*
625      * Returns true if the calling thread is the event dispatch thread
626      * contained within AppContext which associated with the given target.
627      * Use this call to ensure that a given task is being executed
628      * (or not being) on the event dispatch thread for the given target.
629      */
630     public static boolean isDispatchThreadForAppContext(Object target) {
631         AppContext appContext = targetToAppContext(target);
632         EventQueue eq = (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY);
633 
634         AWTAccessor.EventQueueAccessor accessor = AWTAccessor.getEventQueueAccessor();
635         return accessor.isDispatchThreadImpl(eq);
636     }
637 
638     public Dimension getScreenSize() {
639         return new Dimension(getScreenWidth(), getScreenHeight());
640     }
641     protected abstract int getScreenWidth();
642     protected abstract int getScreenHeight();
643 
644     @SuppressWarnings("deprecation")
645     public FontMetrics getFontMetrics(Font font) {
646         return FontDesignMetrics.getMetrics(font);
647     }
648 
649     @SuppressWarnings("deprecation")
650     public String[] getFontList() {
651         String[] hardwiredFontList = {
652             Font.DIALOG, Font.SANS_SERIF, Font.SERIF, Font.MONOSPACED,
653             Font.DIALOG_INPUT
654 
655             // -- Obsolete font names from 1.0.2.  It was decided that
656             // -- getFontList should not return these old names:
657             //    "Helvetica", "TimesRoman", "Courier", "ZapfDingbats"
658         };
659         return hardwiredFontList;
660     }
661 
662     public PanelPeer createPanel(Panel target) {
663         return (PanelPeer)createComponent(target);
664     }
665 
666     public CanvasPeer createCanvas(Canvas target) {
667         return (CanvasPeer)createComponent(target);
668     }
669 
670     /**
671      * Disables erasing of background on the canvas before painting if
672      * this is supported by the current toolkit. It is recommended to
673      * call this method early, before the Canvas becomes displayable,
674      * because some Toolkit implementations do not support changing
675      * this property once the Canvas becomes displayable.
676      */
677     public void disableBackgroundErase(Canvas canvas) {
678         disableBackgroundEraseImpl(canvas);
679     }
680 
681     /**
682      * Disables the native erasing of the background on the given
683      * component before painting if this is supported by the current
684      * toolkit. This only has an effect for certain components such as
685      * Canvas, Panel and Window. It is recommended to call this method
686      * early, before the Component becomes displayable, because some
687      * Toolkit implementations do not support changing this property
688      * once the Component becomes displayable.
689      */
690     public void disableBackgroundErase(Component component) {
691         disableBackgroundEraseImpl(component);
692     }
693 
694     private void disableBackgroundEraseImpl(Component component) {
695         AWTAccessor.getComponentAccessor().setBackgroundEraseDisabled(component, true);
696     }
697 
698     /**
699      * Returns the value of "sun.awt.noerasebackground" property. Default
700      * value is {@code false}.
701      */
702     public static boolean getSunAwtNoerasebackground() {
703         return AccessController.doPrivileged(new GetBooleanAction("sun.awt.noerasebackground"));
704     }
705 
706     /**
707      * Returns the value of "sun.awt.erasebackgroundonresize" property. Default
708      * value is {@code false}.
709      */
710     public static boolean getSunAwtErasebackgroundonresize() {
711         return AccessController.doPrivileged(new GetBooleanAction("sun.awt.erasebackgroundonresize"));
712     }
713 
714 
715     static final SoftCache imgCache = new SoftCache();
716 
717     static Image getImageFromHash(Toolkit tk, URL url) {
718         SecurityManager sm = System.getSecurityManager();
719         if (sm != null) {
720             try {
721                 java.security.Permission perm =
722                     url.openConnection().getPermission();
723                 if (perm != null) {
724                     try {
725                         sm.checkPermission(perm);
726                     } catch (SecurityException se) {
727                         // fallback to checkRead/checkConnect for pre 1.2
728                         // security managers
729                         if ((perm instanceof java.io.FilePermission) &&
730                             perm.getActions().indexOf("read") != -1) {
731                             sm.checkRead(perm.getName());
732                         } else if ((perm instanceof
733                             java.net.SocketPermission) &&
734                             perm.getActions().indexOf("connect") != -1) {
735                             sm.checkConnect(url.getHost(), url.getPort());
736                         } else {
737                             throw se;
738                         }
739                     }
740                 }
741             } catch (java.io.IOException ioe) {
742                     sm.checkConnect(url.getHost(), url.getPort());
743             }
744         }
745         synchronized (imgCache) {
746             Image img = (Image)imgCache.get(url);
747             if (img == null) {
748                 try {
749                     img = tk.createImage(new URLImageSource(url));
750                     imgCache.put(url, img);
751                 } catch (Exception e) {
752                 }
753             }
754             return img;
755         }
756     }
757 
758     static Image getImageFromHash(Toolkit tk,
759                                                String filename) {
760         SecurityManager security = System.getSecurityManager();
761         if (security != null) {
762             security.checkRead(filename);
763         }
764         synchronized (imgCache) {
765             Image img = (Image)imgCache.get(filename);
766             if (img == null) {
767                 try {
768                     img = tk.createImage(new FileImageSource(filename));
769                     imgCache.put(filename, img);
770                 } catch (Exception e) {
771                 }
772             }
773             return img;
774         }
775     }
776 
777     public Image getImage(String filename) {
778         return getImageFromHash(this, filename);
779     }
780 
781     public Image getImage(URL url) {
782         return getImageFromHash(this, url);
783     }
784 
785     public Image createImage(String filename) {
786         SecurityManager security = System.getSecurityManager();
787         if (security != null) {
788             security.checkRead(filename);
789         }
790         return createImage(new FileImageSource(filename));
791     }
792 
793     public Image createImage(URL url) {
794         SecurityManager sm = System.getSecurityManager();
795         if (sm != null) {
796             try {
797                 java.security.Permission perm =
798                     url.openConnection().getPermission();
799                 if (perm != null) {
800                     try {
801                         sm.checkPermission(perm);
802                     } catch (SecurityException se) {
803                         // fallback to checkRead/checkConnect for pre 1.2
804                         // security managers
805                         if ((perm instanceof java.io.FilePermission) &&
806                             perm.getActions().indexOf("read") != -1) {
807                             sm.checkRead(perm.getName());
808                         } else if ((perm instanceof
809                             java.net.SocketPermission) &&
810                             perm.getActions().indexOf("connect") != -1) {
811                             sm.checkConnect(url.getHost(), url.getPort());
812                         } else {
813                             throw se;
814                         }
815                     }
816                 }
817             } catch (java.io.IOException ioe) {
818                     sm.checkConnect(url.getHost(), url.getPort());
819             }
820         }
821         return createImage(new URLImageSource(url));
822     }
823 
824     public Image createImage(byte[] data, int offset, int length) {
825         return createImage(new ByteArrayImageSource(data, offset, length));
826     }
827 
828     public Image createImage(ImageProducer producer) {
829         return new ToolkitImage(producer);
830     }
831 
832     public int checkImage(Image img, int w, int h, ImageObserver o) {
833         if (!(img instanceof ToolkitImage)) {
834             return ImageObserver.ALLBITS;
835         }
836 
837         ToolkitImage tkimg = (ToolkitImage)img;
838         int repbits;
839         if (w == 0 || h == 0) {
840             repbits = ImageObserver.ALLBITS;
841         } else {
842             repbits = tkimg.getImageRep().check(o);
843         }
844         return tkimg.check(o) | repbits;
845     }
846 
847     public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
848         if (w == 0 || h == 0) {
849             return true;
850         }
851 
852         // Must be a ToolkitImage
853         if (!(img instanceof ToolkitImage)) {
854             return true;
855         }
856 
857         ToolkitImage tkimg = (ToolkitImage)img;
858         if (tkimg.hasError()) {
859             if (o != null) {
860                 o.imageUpdate(img, ImageObserver.ERROR|ImageObserver.ABORT,
861                               -1, -1, -1, -1);
862             }
863             return false;
864         }
865         ImageRepresentation ir = tkimg.getImageRep();
866         return ir.prepare(o);
867     }
868 
869     /**
870      * Scans {@code imageList} for best-looking image of specified dimensions.
871      * Image can be scaled and/or padded with transparency.
872      */
873     public static BufferedImage getScaledIconImage(java.util.List<Image> imageList, int width, int height) {
874         if (width == 0 || height == 0) {
875             return null;
876         }
877         Image bestImage = null;
878         int bestWidth = 0;
879         int bestHeight = 0;
880         double bestSimilarity = 3; //Impossibly high value
881         double bestScaleFactor = 0;
882         for (Iterator<Image> i = imageList.iterator();i.hasNext();) {
883             //Iterate imageList looking for best matching image.
884             //'Similarity' measure is defined as good scale factor and small insets.
885             //best possible similarity is 0 (no scale, no insets).
886             //It's found while the experiments that good-looking result is achieved
887             //with scale factors x1, x3/4, x2/3, xN, x1/N.
888             Image im = i.next();
889             if (im == null) {
890                 continue;
891             }
892             if (im instanceof ToolkitImage) {
893                 ImageRepresentation ir = ((ToolkitImage)im).getImageRep();
894                 ir.reconstruct(ImageObserver.ALLBITS);
895             }
896             int iw;
897             int ih;
898             try {
899                 iw = im.getWidth(null);
900                 ih = im.getHeight(null);
901             } catch (Exception e){
902                 continue;
903             }
904             if (iw > 0 && ih > 0) {
905                 //Calc scale factor
906                 double scaleFactor = Math.min((double)width / (double)iw,
907                                               (double)height / (double)ih);
908                 //Calculate scaled image dimensions
909                 //adjusting scale factor to nearest "good" value
910                 int adjw = 0;
911                 int adjh = 0;
912                 double scaleMeasure = 1; //0 - best (no) scale, 1 - impossibly bad
913                 if (scaleFactor >= 2) {
914                     //Need to enlarge image more than twice
915                     //Round down scale factor to multiply by integer value
916                     scaleFactor = Math.floor(scaleFactor);
917                     adjw = iw * (int)scaleFactor;
918                     adjh = ih * (int)scaleFactor;
919                     scaleMeasure = 1.0 - 0.5 / scaleFactor;
920                 } else if (scaleFactor >= 1) {
921                     //Don't scale
922                     scaleFactor = 1.0;
923                     adjw = iw;
924                     adjh = ih;
925                     scaleMeasure = 0;
926                 } else if (scaleFactor >= 0.75) {
927                     //Multiply by 3/4
928                     scaleFactor = 0.75;
929                     adjw = iw * 3 / 4;
930                     adjh = ih * 3 / 4;
931                     scaleMeasure = 0.3;
932                 } else if (scaleFactor >= 0.6666) {
933                     //Multiply by 2/3
934                     scaleFactor = 0.6666;
935                     adjw = iw * 2 / 3;
936                     adjh = ih * 2 / 3;
937                     scaleMeasure = 0.33;
938                 } else {
939                     //Multiply size by 1/scaleDivider
940                     //where scaleDivider is minimum possible integer
941                     //larger than 1/scaleFactor
942                     double scaleDivider = Math.ceil(1.0 / scaleFactor);
943                     scaleFactor = 1.0 / scaleDivider;
944                     adjw = (int)Math.round((double)iw / scaleDivider);
945                     adjh = (int)Math.round((double)ih / scaleDivider);
946                     scaleMeasure = 1.0 - 1.0 / scaleDivider;
947                 }
948                 double similarity = ((double)width - (double)adjw) / (double)width +
949                     ((double)height - (double)adjh) / (double)height + //Large padding is bad
950                     scaleMeasure; //Large rescale is bad
951                 if (similarity < bestSimilarity) {
952                     bestSimilarity = similarity;
953                     bestScaleFactor = scaleFactor;
954                     bestImage = im;
955                     bestWidth = adjw;
956                     bestHeight = adjh;
957                 }
958                 if (similarity == 0) break;
959             }
960         }
961         if (bestImage == null) {
962             //No images were found, possibly all are broken
963             return null;
964         }
965         BufferedImage bimage =
966             new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
967         Graphics2D g = bimage.createGraphics();
968         g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
969                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
970         try {
971             int x = (width - bestWidth) / 2;
972             int y = (height - bestHeight) / 2;
973             g.drawImage(bestImage, x, y, bestWidth, bestHeight, null);
974         } finally {
975             g.dispose();
976         }
977         return bimage;
978     }
979 
980     public static DataBufferInt getScaledIconData(java.util.List<Image> imageList, int width, int height) {
981         BufferedImage bimage = getScaledIconImage(imageList, width, height);
982         if (bimage == null) {
983             return null;
984         }
985         Raster raster = bimage.getRaster();
986         DataBuffer buffer = raster.getDataBuffer();
987         return (DataBufferInt)buffer;
988     }
989 
990     protected EventQueue getSystemEventQueueImpl() {
991         return getSystemEventQueueImplPP();
992     }
993 
994     // Package private implementation
995     static EventQueue getSystemEventQueueImplPP() {
996         return getSystemEventQueueImplPP(AppContext.getAppContext());
997     }
998 
999     public static EventQueue getSystemEventQueueImplPP(AppContext appContext) {
1000         EventQueue theEventQueue =
1001             (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY);
1002         return theEventQueue;
1003     }
1004 
1005     /**
1006      * Give native peers the ability to query the native container
1007      * given a native component (eg the direct parent may be lightweight).
1008      */
1009     public static Container getNativeContainer(Component c) {
1010         return Toolkit.getNativeContainer(c);
1011     }
1012 
1013     /**
1014      * Gives native peers the ability to query the closest HW component.
1015      * If the given component is heavyweight, then it returns this. Otherwise,
1016      * it goes one level up in the hierarchy and tests next component.
1017      */
1018     public static Component getHeavyweightComponent(Component c) {
1019         while (c != null && AWTAccessor.getComponentAccessor().isLightweight(c)) {
1020             c = AWTAccessor.getComponentAccessor().getParent(c);
1021         }
1022         return c;
1023     }
1024 
1025     /**
1026      * Returns key modifiers used by Swing to set up a focus accelerator key stroke.
1027      */
1028     public int getFocusAcceleratorKeyMask() {
1029         return InputEvent.ALT_MASK;
1030     }
1031 
1032     /**
1033      * Tests whether specified key modifiers mask can be used to enter a printable
1034      * character. This is a default implementation of this method, which reflects
1035      * the way things work on Windows: here, pressing ctrl + alt allows user to enter
1036      * characters from the extended character set (like euro sign or math symbols)
1037      */
1038     public boolean isPrintableCharacterModifiersMask(int mods) {
1039         return ((mods & InputEvent.ALT_MASK) == (mods & InputEvent.CTRL_MASK));
1040     }
1041 
1042     /**
1043      * Returns whether popup is allowed to be shown above the task bar.
1044      * This is a default implementation of this method, which checks
1045      * corresponding security permission.
1046      */
1047     public boolean canPopupOverlapTaskBar() {
1048         boolean result = true;
1049         try {
1050             SecurityManager sm = System.getSecurityManager();
1051             if (sm != null) {
1052                 sm.checkPermission(
1053                         SecurityConstants.AWT.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION);
1054             }
1055         } catch (SecurityException se) {
1056             // There is no permission to show popups over the task bar
1057             result = false;
1058         }
1059         return result;
1060     }
1061 
1062     /**
1063      * Returns a new input method window, with behavior as specified in
1064      * {@link java.awt.im.spi.InputMethodContext#createInputMethodWindow}.
1065      * If the inputContext is not null, the window should return it from its
1066      * getInputContext() method. The window needs to implement
1067      * sun.awt.im.InputMethodWindow.
1068      * <p>
1069      * SunToolkit subclasses can override this method to return better input
1070      * method windows.
1071      */
1072     public Window createInputMethodWindow(String title, InputContext context) {
1073         return new sun.awt.im.SimpleInputMethodWindow(title, context);
1074     }
1075 
1076     /**
1077      * Returns whether enableInputMethods should be set to true for peered
1078      * TextComponent instances on this platform. False by default.
1079      */
1080     public boolean enableInputMethodsForTextComponent() {
1081         return false;
1082     }
1083 
1084     private static Locale startupLocale = null;
1085 
1086     /**
1087      * Returns the locale in which the runtime was started.
1088      */
1089     public static Locale getStartupLocale() {
1090         if (startupLocale == null) {
1091             String language, region, country, variant;
1092             language = AccessController.doPrivileged(
1093                             new GetPropertyAction("user.language", "en"));
1094             // for compatibility, check for old user.region property
1095             region = AccessController.doPrivileged(
1096                             new GetPropertyAction("user.region"));
1097             if (region != null) {
1098                 // region can be of form country, country_variant, or _variant
1099                 int i = region.indexOf('_');
1100                 if (i >= 0) {
1101                     country = region.substring(0, i);
1102                     variant = region.substring(i + 1);
1103                 } else {
1104                     country = region;
1105                     variant = "";
1106                 }
1107             } else {
1108                 country = AccessController.doPrivileged(
1109                                 new GetPropertyAction("user.country", ""));
1110                 variant = AccessController.doPrivileged(
1111                                 new GetPropertyAction("user.variant", ""));
1112             }
1113             startupLocale = new Locale(language, country, variant);
1114         }
1115         return startupLocale;
1116     }
1117 
1118     /**
1119      * Returns the default keyboard locale of the underlying operating system
1120      */
1121     public Locale getDefaultKeyboardLocale() {
1122         return getStartupLocale();
1123     }
1124 
1125     private static String dataTransfererClassName = null;
1126 
1127     protected static void setDataTransfererClassName(String className) {
1128         dataTransfererClassName = className;
1129     }
1130 
1131     public static String getDataTransfererClassName() {
1132         if (dataTransfererClassName == null) {
1133             Toolkit.getDefaultToolkit(); // transferer set during toolkit init
1134         }
1135         return dataTransfererClassName;
1136     }
1137 
1138     // Support for window closing event notifications
1139     private transient WindowClosingListener windowClosingListener = null;
1140     /**
1141      * @see sun.awt.WindowClosingSupport#getWindowClosingListener
1142      */
1143     public WindowClosingListener getWindowClosingListener() {
1144         return windowClosingListener;
1145     }
1146     /**
1147      * @see sun.awt.WindowClosingSupport#setWindowClosingListener
1148      */
1149     public void setWindowClosingListener(WindowClosingListener wcl) {
1150         windowClosingListener = wcl;
1151     }
1152 
1153     /**
1154      * @see sun.awt.WindowClosingListener#windowClosingNotify
1155      */
1156     public RuntimeException windowClosingNotify(WindowEvent event) {
1157         if (windowClosingListener != null) {
1158             return windowClosingListener.windowClosingNotify(event);
1159         } else {
1160             return null;
1161         }
1162     }
1163     /**
1164      * @see sun.awt.WindowClosingListener#windowClosingDelivered
1165      */
1166     public RuntimeException windowClosingDelivered(WindowEvent event) {
1167         if (windowClosingListener != null) {
1168             return windowClosingListener.windowClosingDelivered(event);
1169         } else {
1170             return null;
1171         }
1172     }
1173 
1174     private static DefaultMouseInfoPeer mPeer = null;
1175 
1176     protected synchronized MouseInfoPeer getMouseInfoPeer() {
1177         if (mPeer == null) {
1178             mPeer = new DefaultMouseInfoPeer();
1179         }
1180         return mPeer;
1181     }
1182 
1183 
1184     /**
1185      * Returns whether default toolkit needs the support of the xembed
1186      * from embedding host(if any).
1187      * @return <code>true</code>, if XEmbed is needed, <code>false</code> otherwise
1188      */
1189     public static boolean needsXEmbed() {
1190         String noxembed = AccessController.
1191             doPrivileged(new GetPropertyAction("sun.awt.noxembed", "false"));
1192         if ("true".equals(noxembed)) {
1193             return false;
1194         }
1195 
1196         Toolkit tk = Toolkit.getDefaultToolkit();
1197         if (tk instanceof SunToolkit) {
1198             // SunToolkit descendants should override this method to specify
1199             // concrete behavior
1200             return ((SunToolkit)tk).needsXEmbedImpl();
1201         } else {
1202             // Non-SunToolkit doubtly might support XEmbed
1203             return false;
1204         }
1205     }
1206 
1207     /**
1208      * Returns whether this toolkit needs the support of the xembed
1209      * from embedding host(if any).
1210      * @return <code>true</code>, if XEmbed is needed, <code>false</code> otherwise
1211      */
1212     protected boolean needsXEmbedImpl() {
1213         return false;
1214     }
1215 
1216     private static Dialog.ModalExclusionType DEFAULT_MODAL_EXCLUSION_TYPE = null;
1217 
1218     /**
1219      * Returns whether the XEmbed server feature is requested by
1220      * developer.  If true, Toolkit should return an
1221      * XEmbed-server-enabled CanvasPeer instead of the ordinary CanvasPeer.
1222      */
1223     protected final boolean isXEmbedServerRequested() {
1224         return AccessController.doPrivileged(new GetBooleanAction("sun.awt.xembedserver"));
1225     }
1226 
1227     /**
1228      * Returns whether the modal exclusion API is supported by the current toolkit.
1229      * When it isn't supported, calling <code>setModalExcluded</code> has no
1230      * effect, and <code>isModalExcluded</code> returns false for all windows.
1231      *
1232      * @return true if modal exclusion is supported by the toolkit, false otherwise
1233      *
1234      * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window)
1235      * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window)
1236      *
1237      * @since 1.5
1238      */
1239     public static boolean isModalExcludedSupported()
1240     {
1241         Toolkit tk = Toolkit.getDefaultToolkit();
1242         return tk.isModalExclusionTypeSupported(DEFAULT_MODAL_EXCLUSION_TYPE);
1243     }
1244     /*
1245      * Default implementation for isModalExcludedSupportedImpl(), returns false.
1246      *
1247      * @see sun.awt.windows.WToolkit#isModalExcludeSupportedImpl
1248      * @see sun.awt.X11.XToolkit#isModalExcludeSupportedImpl
1249      *
1250      * @since 1.5
1251      */
1252     protected boolean isModalExcludedSupportedImpl()
1253     {
1254         return false;
1255     }
1256 
1257     /*
1258      * Sets this window to be excluded from being modally blocked. When the
1259      * toolkit supports modal exclusion and this method is called, input
1260      * events, focus transfer and z-order will continue to work for the
1261      * window, it's owned windows and child components, even in the
1262      * presence of a modal dialog.
1263      * For details on which <code>Window</code>s are normally blocked
1264      * by modal dialog, see {@link java.awt.Dialog}.
1265      * Invoking this method when the modal exclusion API is not supported by
1266      * the current toolkit has no effect.
1267      * @param window Window to be marked as not modally blocked
1268      * @see java.awt.Dialog
1269      * @see java.awt.Dialog#setModal(boolean)
1270      * @see sun.awt.SunToolkit#isModalExcludedSupported
1271      * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window)
1272      */
1273     public static void setModalExcluded(Window window)
1274     {
1275         if (DEFAULT_MODAL_EXCLUSION_TYPE == null) {
1276             DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE;
1277         }
1278         window.setModalExclusionType(DEFAULT_MODAL_EXCLUSION_TYPE);
1279     }
1280 
1281     /*
1282      * Returns whether the specified window is blocked by modal dialogs.
1283      * If the modal exclusion API isn't supported by the current toolkit,
1284      * it returns false for all windows.
1285      *
1286      * @param window Window to test for modal exclusion
1287      *
1288      * @return true if the window is modal excluded, false otherwise. If
1289      * the modal exclusion isn't supported by the current Toolkit, false
1290      * is returned
1291      *
1292      * @see sun.awt.SunToolkit#isModalExcludedSupported
1293      * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window)
1294      *
1295      * @since 1.5
1296      */
1297     public static boolean isModalExcluded(Window window)
1298     {
1299         if (DEFAULT_MODAL_EXCLUSION_TYPE == null) {
1300             DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE;
1301         }
1302         return window.getModalExclusionType().compareTo(DEFAULT_MODAL_EXCLUSION_TYPE) >= 0;
1303     }
1304 
1305     /**
1306      * Overridden in XToolkit and WToolkit
1307      */
1308     public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) {
1309         return (modalityType == Dialog.ModalityType.MODELESS) ||
1310                (modalityType == Dialog.ModalityType.APPLICATION_MODAL);
1311     }
1312 
1313     /**
1314      * Overridden in XToolkit and WToolkit
1315      */
1316     public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) {
1317         return (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE);
1318     }
1319 
1320     ///////////////////////////////////////////////////////////////////////////
1321     //
1322     // The following is used by the Java Plug-in to coordinate dialog modality
1323     // between containing applications (browsers, ActiveX containers etc) and
1324     // the AWT.
1325     //
1326     ///////////////////////////////////////////////////////////////////////////
1327 
1328     private ModalityListenerList modalityListeners = new ModalityListenerList();
1329 
1330     public void addModalityListener(ModalityListener listener) {
1331         modalityListeners.add(listener);
1332     }
1333 
1334     public void removeModalityListener(ModalityListener listener) {
1335         modalityListeners.remove(listener);
1336     }
1337 
1338     public void notifyModalityPushed(Dialog dialog) {
1339         notifyModalityChange(ModalityEvent.MODALITY_PUSHED, dialog);
1340     }
1341 
1342     public void notifyModalityPopped(Dialog dialog) {
1343         notifyModalityChange(ModalityEvent.MODALITY_POPPED, dialog);
1344     }
1345 
1346     final void notifyModalityChange(int id, Dialog source) {
1347         ModalityEvent ev = new ModalityEvent(source, modalityListeners, id);
1348         ev.dispatch();
1349     }
1350 
1351     static class ModalityListenerList implements ModalityListener {
1352 
1353         Vector<ModalityListener> listeners = new Vector<ModalityListener>();
1354 
1355         void add(ModalityListener listener) {
1356             listeners.addElement(listener);
1357         }
1358 
1359         void remove(ModalityListener listener) {
1360             listeners.removeElement(listener);
1361         }
1362 
1363         public void modalityPushed(ModalityEvent ev) {
1364             Iterator<ModalityListener> it = listeners.iterator();
1365             while (it.hasNext()) {
1366                 it.next().modalityPushed(ev);
1367             }
1368         }
1369 
1370         public void modalityPopped(ModalityEvent ev) {
1371             Iterator<ModalityListener> it = listeners.iterator();
1372             while (it.hasNext()) {
1373                 it.next().modalityPopped(ev);
1374             }
1375         }
1376     } // end of class ModalityListenerList
1377 
1378     ///////////////////////////////////////////////////////////////////////////
1379     // End Plug-in code
1380     ///////////////////////////////////////////////////////////////////////////
1381 
1382     public static boolean isLightweightOrUnknown(Component comp) {
1383         if (comp.isLightweight()
1384             || !(getDefaultToolkit() instanceof SunToolkit))
1385         {
1386             return true;
1387         }
1388         return !(comp instanceof Button
1389             || comp instanceof Canvas
1390             || comp instanceof Checkbox
1391             || comp instanceof Choice
1392             || comp instanceof Label
1393             || comp instanceof java.awt.List
1394             || comp instanceof Panel
1395             || comp instanceof Scrollbar
1396             || comp instanceof ScrollPane
1397             || comp instanceof TextArea
1398             || comp instanceof TextField
1399             || comp instanceof Window);
1400     }
1401 
1402     @SuppressWarnings("serial")
1403     public static class OperationTimedOut extends RuntimeException {
1404         public OperationTimedOut(String msg) {
1405             super(msg);
1406         }
1407         public OperationTimedOut() {
1408         }
1409     }
1410 
1411     @SuppressWarnings("serial")
1412     public static class InfiniteLoop extends RuntimeException {
1413     }
1414 
1415     @SuppressWarnings("serial")
1416     public static class IllegalThreadException extends RuntimeException {
1417         public IllegalThreadException(String msg) {
1418             super(msg);
1419         }
1420         public IllegalThreadException() {
1421         }
1422     }
1423 
1424     public static final int DEFAULT_WAIT_TIME = 10000;
1425     private static final int MAX_ITERS = 20;
1426     private static final int MIN_ITERS = 0;
1427     private static final int MINIMAL_EDELAY = 0;
1428 
1429     /**
1430      * Parameterless version of realsync which uses default timout (see DEFAUL_WAIT_TIME).
1431      */
1432     public void realSync() throws OperationTimedOut, InfiniteLoop {
1433         realSync(DEFAULT_WAIT_TIME);
1434     }
1435 
1436     /**
1437      * Forces toolkit to synchronize with the native windowing
1438      * sub-system, flushing all pending work and waiting for all the
1439      * events to be processed.  This method guarantees that after
1440      * return no additional Java events will be generated, unless
1441      * cause by user. Obviously, the method cannot be used on the
1442      * event dispatch thread (EDT). In case it nevertheless gets
1443      * invoked on this thread, the method throws the
1444      * IllegalThreadException runtime exception.
1445      *
1446      * <p> This method allows to write tests without explicit timeouts
1447      * or wait for some event.  Example:
1448      * <code>
1449      * Frame f = ...;
1450      * f.setVisible(true);
1451      * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
1452      * </code>
1453      *
1454      * <p> After realSync, <code>f</code> will be completely visible
1455      * on the screen, its getLocationOnScreen will be returning the
1456      * right result and it will be the focus owner.
1457      *
1458      * <p> Another example:
1459      * <code>
1460      * b.requestFocus();
1461      * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
1462      * </code>
1463      *
1464      * <p> After realSync, <code>b</code> will be focus owner.
1465      *
1466      * <p> Notice that realSync isn't guaranteed to work if recurring
1467      * actions occur, such as if during processing of some event
1468      * another request which may generate some events occurs.  By
1469      * default, sync tries to perform as much as {@value MAX_ITERS}
1470      * cycles of event processing, allowing for roughly {@value
1471      * MAX_ITERS} additional requests.
1472      *
1473      * <p> For example, requestFocus() generates native request, which
1474      * generates one or two Java focus events, which then generate a
1475      * serie of paint events, a serie of Java focus events, which then
1476      * generate a serie of paint events which then are processed -
1477      * three cycles, minimum.
1478      *
1479      * @param timeout the maximum time to wait in milliseconds, negative means "forever".
1480      */
1481     public void realSync(final long timeout) throws OperationTimedOut, InfiniteLoop
1482     {
1483         if (EventQueue.isDispatchThread()) {
1484             throw new IllegalThreadException("The SunToolkit.realSync() method cannot be used on the event dispatch thread (EDT).");
1485         }
1486         int bigLoop = 0;
1487         do {
1488             // Let's do sync first
1489             sync();
1490 
1491             // During the wait process, when we were processing incoming
1492             // events, we could have made some new request, which can
1493             // generate new events.  Example: MapNotify/XSetInputFocus.
1494             // Therefore, we dispatch them as long as there is something
1495             // to dispatch.
1496             int iters = 0;
1497             while (iters < MIN_ITERS) {
1498                 syncNativeQueue(timeout);
1499                 iters++;
1500             }
1501             while (syncNativeQueue(timeout) && iters < MAX_ITERS) {
1502                 iters++;
1503             }
1504             if (iters >= MAX_ITERS) {
1505                 throw new InfiniteLoop();
1506             }
1507 
1508             // native requests were dispatched by X/Window Manager or Windows
1509             // Moreover, we processed them all on Toolkit thread
1510             // Now wait while EDT processes them.
1511             //
1512             // During processing of some events (focus, for example),
1513             // some other events could have been generated.  So, after
1514             // waitForIdle, we may end up with full EventQueue
1515             iters = 0;
1516             while (iters < MIN_ITERS) {
1517                 waitForIdle(timeout);
1518                 iters++;
1519             }
1520             while (waitForIdle(timeout) && iters < MAX_ITERS) {
1521                 iters++;
1522             }
1523             if (iters >= MAX_ITERS) {
1524                 throw new InfiniteLoop();
1525             }
1526 
1527             bigLoop++;
1528             // Again, for Java events, it was simple to check for new Java
1529             // events by checking event queue, but what if Java events
1530             // resulted in native requests?  Therefor, check native events again.
1531         } while ((syncNativeQueue(timeout) || waitForIdle(timeout)) && bigLoop < MAX_ITERS);
1532     }
1533 
1534     /**
1535      * Platform toolkits need to implement this method to perform the
1536      * sync of the native queue.  The method should wait until native
1537      * requests are processed, all native events are processed and
1538      * corresponding Java events are generated.  Should return
1539      * <code>true</code> if some events were processed,
1540      * <code>false</code> otherwise.
1541      */
1542     protected abstract boolean syncNativeQueue(final long timeout);
1543 
1544     private boolean eventDispatched = false;
1545     private boolean queueEmpty = false;
1546     private final Object waitLock = "Wait Lock";
1547 
1548     private boolean isEQEmpty() {
1549         EventQueue queue = getSystemEventQueueImpl();
1550         return AWTAccessor.getEventQueueAccessor().noEvents(queue);
1551     }
1552 
1553     /**
1554      * Waits for the Java event queue to empty.  Ensures that all
1555      * events are processed (including paint events), and that if
1556      * recursive events were generated, they are also processed.
1557      * Should return <code>true</code> if more processing is
1558      * necessary, <code>false</code> otherwise.
1559      */
1560     @SuppressWarnings("serial")
1561     protected final boolean waitForIdle(final long timeout) {
1562         flushPendingEvents();
1563         boolean queueWasEmpty = isEQEmpty();
1564         queueEmpty = false;
1565         eventDispatched = false;
1566         synchronized(waitLock) {
1567             postEvent(AppContext.getAppContext(),
1568                       new PeerEvent(getSystemEventQueueImpl(), null, PeerEvent.LOW_PRIORITY_EVENT) {
1569                           public void dispatch() {
1570                               // Here we block EDT.  It could have some
1571                               // events, it should have dispatched them by
1572                               // now.  So native requests could have been
1573                               // generated.  First, dispatch them.  Then,
1574                               // flush Java events again.
1575                               int iters = 0;
1576                               while (iters < MIN_ITERS) {
1577                                   syncNativeQueue(timeout);
1578                                   iters++;
1579                               }
1580                               while (syncNativeQueue(timeout) && iters < MAX_ITERS) {
1581                                   iters++;
1582                               }
1583                               flushPendingEvents();
1584 
1585                               synchronized(waitLock) {
1586                                   queueEmpty = isEQEmpty();
1587                                   eventDispatched = true;
1588                                   waitLock.notifyAll();
1589                               }
1590                           }
1591                       });
1592             try {
1593                 while (!eventDispatched) {
1594                     waitLock.wait();
1595                 }
1596             } catch (InterruptedException ie) {
1597                 return false;
1598             }
1599         }
1600 
1601         try {
1602             Thread.sleep(MINIMAL_EDELAY);
1603         } catch (InterruptedException ie) {
1604             throw new RuntimeException("Interrupted");
1605         }
1606 
1607         flushPendingEvents();
1608 
1609         // Lock to force write-cache flush for queueEmpty.
1610         synchronized (waitLock) {
1611             return !(queueEmpty && isEQEmpty() && queueWasEmpty);
1612         }
1613     }
1614 
1615     /**
1616      * Grabs the mouse input for the given window.  The window must be
1617      * visible.  The window or its children do not receive any
1618      * additional mouse events besides those targeted to them.  All
1619      * other events will be dispatched as before - to the respective
1620      * targets.  This Window will receive UngrabEvent when automatic
1621      * ungrab is about to happen.  The event can be listened to by
1622      * installing AWTEventListener with WINDOW_EVENT_MASK.  See
1623      * UngrabEvent class for the list of conditions when ungrab is
1624      * about to happen.
1625      * @see UngrabEvent
1626      */
1627     public abstract void grab(Window w);
1628 
1629     /**
1630      * Forces ungrab.  No event will be sent.
1631      */
1632     public abstract void ungrab(Window w);
1633 
1634 
1635     /**
1636      * Locates the splash screen library in a platform dependent way and closes
1637      * the splash screen. Should be invoked on first top-level frame display.
1638      * @see java.awt.SplashScreen
1639      * @since 1.6
1640      */
1641     public static native void closeSplashScreen();
1642 
1643     /* The following methods and variables are to support retrieving
1644      * desktop text anti-aliasing settings
1645      */
1646 
1647     /* Need an instance method because setDesktopProperty(..) is protected. */
1648     private void fireDesktopFontPropertyChanges() {
1649         setDesktopProperty(SunToolkit.DESKTOPFONTHINTS,
1650                            SunToolkit.getDesktopFontHints());
1651     }
1652 
1653     private static boolean checkedSystemAAFontSettings;
1654     private static boolean useSystemAAFontSettings;
1655     private static boolean lastExtraCondition = true;
1656     private static RenderingHints desktopFontHints;
1657 
1658     /* Since Swing is the reason for this "extra condition" logic its
1659      * worth documenting it in some detail.
1660      * First, a goal is for Swing and applications to both retrieve and
1661      * use the same desktop property value so that there is complete
1662      * consistency between the settings used by JDK's Swing implementation
1663      * and 3rd party custom Swing components, custom L&Fs and any general
1664      * text rendering that wants to be consistent with these.
1665      * But by default on Solaris & Linux Swing will not use AA text over
1666      * remote X11 display (unless Xrender can be used which is TBD and may not
1667      * always be available anyway) as that is a noticeable performance hit.
1668      * So there needs to be a way to express that extra condition so that
1669      * it is seen by all clients of the desktop property API.
1670      * If this were the only condition it could be handled here as it would
1671      * be the same for any L&F and could reasonably be considered to be
1672      * a static behaviour of those systems.
1673      * But GTK currently has an additional test based on locale which is
1674      * not applied by Metal. So mixing GTK in a few locales with Metal
1675      * would mean the last one wins.
1676      * This could be stored per-app context which would work
1677      * for different applets, but wouldn't help for a single application
1678      * using GTK and some other L&F concurrently.
1679      * But it is expected this will be addressed within GTK and the font
1680      * system so is a temporary and somewhat unlikely harmless corner case.
1681      */
1682     public static void setAAFontSettingsCondition(boolean extraCondition) {
1683         if (extraCondition != lastExtraCondition) {
1684             lastExtraCondition = extraCondition;
1685             if (checkedSystemAAFontSettings) {
1686                 /* Someone already asked for this info, under a different
1687                  * condition.
1688                  * We'll force re-evaluation instead of replicating the
1689                  * logic, then notify any listeners of any change.
1690                  */
1691                 checkedSystemAAFontSettings = false;
1692                 Toolkit tk = Toolkit.getDefaultToolkit();
1693                 if (tk instanceof SunToolkit) {
1694                      ((SunToolkit)tk).fireDesktopFontPropertyChanges();
1695                 }
1696             }
1697         }
1698     }
1699 
1700     /* "false", "off", ""default" aren't explicitly tested, they
1701      * just fall through to produce a null return which all are equated to
1702      * "false".
1703      */
1704     private static RenderingHints getDesktopAAHintsByName(String hintname) {
1705         Object aaHint = null;
1706         hintname = hintname.toLowerCase(Locale.ENGLISH);
1707         if (hintname.equals("on")) {
1708             aaHint = VALUE_TEXT_ANTIALIAS_ON;
1709         } else if (hintname.equals("gasp")) {
1710             aaHint = VALUE_TEXT_ANTIALIAS_GASP;
1711         } else if (hintname.equals("lcd") || hintname.equals("lcd_hrgb")) {
1712             aaHint = VALUE_TEXT_ANTIALIAS_LCD_HRGB;
1713         } else if (hintname.equals("lcd_hbgr")) {
1714             aaHint = VALUE_TEXT_ANTIALIAS_LCD_HBGR;
1715         } else if (hintname.equals("lcd_vrgb")) {
1716             aaHint = VALUE_TEXT_ANTIALIAS_LCD_VRGB;
1717         } else if (hintname.equals("lcd_vbgr")) {
1718             aaHint = VALUE_TEXT_ANTIALIAS_LCD_VBGR;
1719         }
1720         if (aaHint != null) {
1721             RenderingHints map = new RenderingHints(null);
1722             map.put(KEY_TEXT_ANTIALIASING, aaHint);
1723             return map;
1724         } else {
1725             return null;
1726         }
1727     }
1728 
1729     /* This method determines whether to use the system font settings,
1730      * or ignore them if a L&F has specified they should be ignored, or
1731      * to override both of these with a system property specified value.
1732      * If the toolkit isn't a SunToolkit, (eg may be headless) then that
1733      * system property isn't applied as desktop properties are considered
1734      * to be inapplicable in that case. In that headless case although
1735      * this method will return "true" the toolkit will return a null map.
1736      */
1737     private static boolean useSystemAAFontSettings() {
1738         if (!checkedSystemAAFontSettings) {
1739             useSystemAAFontSettings = true; /* initially set this true */
1740             String systemAAFonts = null;
1741             Toolkit tk = Toolkit.getDefaultToolkit();
1742             if (tk instanceof SunToolkit) {
1743                 systemAAFonts =
1744                     AccessController.doPrivileged(
1745                          new GetPropertyAction("awt.useSystemAAFontSettings"));
1746             }
1747             if (systemAAFonts != null) {
1748                 useSystemAAFontSettings =
1749                     Boolean.valueOf(systemAAFonts).booleanValue();
1750                 /* If it is anything other than "true", then it may be
1751                  * a hint name , or it may be "off, "default", etc.
1752                  */
1753                 if (!useSystemAAFontSettings) {
1754                     desktopFontHints = getDesktopAAHintsByName(systemAAFonts);
1755                 }
1756             }
1757             /* If its still true, apply the extra condition */
1758             if (useSystemAAFontSettings) {
1759                  useSystemAAFontSettings = lastExtraCondition;
1760             }
1761             checkedSystemAAFontSettings = true;
1762         }
1763         return useSystemAAFontSettings;
1764     }
1765 
1766     /* A variable defined for the convenience of JDK code */
1767     public static final String DESKTOPFONTHINTS = "awt.font.desktophints";
1768 
1769     /* Overridden by subclasses to return platform/desktop specific values */
1770     protected RenderingHints getDesktopAAHints() {
1771         return null;
1772     }
1773 
1774     /* Subclass desktop property loading methods call this which
1775      * in turn calls the appropriate subclass implementation of
1776      * getDesktopAAHints() when system settings are being used.
1777      * Its public rather than protected because subclasses may delegate
1778      * to a helper class.
1779      */
1780     public static RenderingHints getDesktopFontHints() {
1781         if (useSystemAAFontSettings()) {
1782              Toolkit tk = Toolkit.getDefaultToolkit();
1783              if (tk instanceof SunToolkit) {
1784                  Object map = ((SunToolkit)tk).getDesktopAAHints();
1785                  return (RenderingHints)map;
1786              } else { /* Headless Toolkit */
1787                  return null;
1788              }
1789         } else if (desktopFontHints != null) {
1790             /* cloning not necessary as the return value is cloned later, but
1791              * its harmless.
1792              */
1793             return (RenderingHints)(desktopFontHints.clone());
1794         } else {
1795             return null;
1796         }
1797     }
1798 
1799 
1800     public abstract boolean isDesktopSupported();
1801 
1802     /*
1803      * consumeNextKeyTyped() method is not currently used,
1804      * however Swing could use it in the future.
1805      */
1806     public static synchronized void consumeNextKeyTyped(KeyEvent keyEvent) {
1807         try {
1808             AWTAccessor.getDefaultKeyboardFocusManagerAccessor().consumeNextKeyTyped(
1809                 (DefaultKeyboardFocusManager)KeyboardFocusManager.
1810                     getCurrentKeyboardFocusManager(),
1811                 keyEvent);
1812         } catch (ClassCastException cce) {
1813              cce.printStackTrace();
1814         }
1815     }
1816 
1817     protected static void dumpPeers(final PlatformLogger aLog) {
1818         AWTAutoShutdown.getInstance().dumpPeers(aLog);
1819     }
1820 
1821     /**
1822      * Returns the <code>Window</code> ancestor of the component <code>comp</code>.
1823      * @return Window ancestor of the component or component by itself if it is Window;
1824      *         null, if component is not a part of window hierarchy
1825      */
1826     public static Window getContainingWindow(Component comp) {
1827         while (comp != null && !(comp instanceof Window)) {
1828             comp = comp.getParent();
1829         }
1830         return (Window)comp;
1831     }
1832 
1833     private static Boolean sunAwtDisableMixing = null;
1834 
1835     /**
1836      * Returns the value of "sun.awt.disableMixing" property. Default
1837      * value is {@code false}.
1838      */
1839     public synchronized static boolean getSunAwtDisableMixing() {
1840         if (sunAwtDisableMixing == null) {
1841             sunAwtDisableMixing = AccessController.doPrivileged(
1842                                       new GetBooleanAction("sun.awt.disableMixing"));
1843         }
1844         return sunAwtDisableMixing.booleanValue();
1845     }
1846 
1847     /**
1848      * Returns true if the native GTK libraries are available.  The
1849      * default implementation returns false, but UNIXToolkit overrides this
1850      * method to provide a more specific answer.
1851      */
1852     public boolean isNativeGTKAvailable() {
1853         return false;
1854     }
1855 
1856     private static final Object DEACTIVATION_TIMES_MAP_KEY = new Object();
1857 
1858     public synchronized void setWindowDeactivationTime(Window w, long time) {
1859         AppContext ctx = getAppContext(w);
1860         WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY);
1861         if (map == null) {
1862             map = new WeakHashMap<Window, Long>();
1863             ctx.put(DEACTIVATION_TIMES_MAP_KEY, map);
1864         }
1865         map.put(w, time);
1866     }
1867 
1868     public synchronized long getWindowDeactivationTime(Window w) {
1869         AppContext ctx = getAppContext(w);
1870         WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY);
1871         if (map == null) {
1872             return -1;
1873         }
1874         Long time = map.get(w);
1875         return time == null ? -1 : time;
1876     }
1877 
1878     // Cosntant alpha
1879     public boolean isWindowOpacitySupported() {
1880         return false;
1881     }
1882 
1883     // Shaping
1884     public boolean isWindowShapingSupported() {
1885         return false;
1886     }
1887 
1888     // Per-pixel alpha
1889     public boolean isWindowTranslucencySupported() {
1890         return false;
1891     }
1892 
1893     public boolean isTranslucencyCapable(GraphicsConfiguration gc) {
1894         return false;
1895     }
1896 
1897     /**
1898      * Returns true if swing backbuffer should be translucent.
1899      */
1900     public boolean isSwingBackbufferTranslucencySupported() {
1901         return false;
1902     }
1903 
1904     /**
1905      * Returns whether or not a containing top level window for the passed
1906      * component is
1907      * {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT PERPIXEL_TRANSLUCENT}.
1908      *
1909      * @param c a Component which toplevel's to check
1910      * @return {@code true}  if the passed component is not null and has a
1911      * containing toplevel window which is opaque (so per-pixel translucency
1912      * is not enabled), {@code false} otherwise
1913      * @see GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
1914      */
1915     public static boolean isContainingTopLevelOpaque(Component c) {
1916         Window w = getContainingWindow(c);
1917         return w != null && w.isOpaque();
1918     }
1919 
1920     /**
1921      * Returns whether or not a containing top level window for the passed
1922      * component is
1923      * {@link GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}.
1924      *
1925      * @param c a Component which toplevel's to check
1926      * @return {@code true} if the passed component is not null and has a
1927      * containing toplevel window which has opacity less than
1928      * 1.0f (which means that it is translucent), {@code false} otherwise
1929      * @see GraphicsDevice.WindowTranslucency#TRANSLUCENT
1930      */
1931     public static boolean isContainingTopLevelTranslucent(Component c) {
1932         Window w = getContainingWindow(c);
1933         return w != null && w.getOpacity() < 1.0f;
1934     }
1935 
1936     /**
1937      * Returns whether the native system requires using the peer.updateWindow()
1938      * method to update the contents of a non-opaque window, or if usual
1939      * painting procedures are sufficient. The default return value covers
1940      * the X11 systems. On MS Windows this method is overriden in WToolkit
1941      * to return true.
1942      */
1943     public boolean needUpdateWindow() {
1944         return false;
1945     }
1946 
1947     /**
1948      * Descendants of the SunToolkit should override and put their own logic here.
1949      */
1950     public int getNumberOfButtons(){
1951         return 3;
1952     }
1953 
1954     /**
1955      * Checks that the given object implements/extends the given
1956      * interface/class.
1957      *
1958      * Note that using the instanceof operator causes a class to be loaded.
1959      * Using this method doesn't load a class and it can be used instead of
1960      * the instanceof operator for performance reasons.
1961      *
1962      * @param obj Object to be checked
1963      * @param type The name of the interface/class. Must be
1964      * fully-qualified interface/class name.
1965      * @return true, if this object implements/extends the given
1966      *         interface/class, false, otherwise, or if obj or type is null
1967      */
1968     public static boolean isInstanceOf(Object obj, String type) {
1969         if (obj == null) return false;
1970         if (type == null) return false;
1971 
1972         return isInstanceOf(obj.getClass(), type);
1973     }
1974 
1975     private static boolean isInstanceOf(Class<?> cls, String type) {
1976         if (cls == null) return false;
1977 
1978         if (cls.getName().equals(type)) {
1979             return true;
1980         }
1981 
1982         for (Class<?> c : cls.getInterfaces()) {
1983             if (c.getName().equals(type)) {
1984                 return true;
1985             }
1986         }
1987         return isInstanceOf(cls.getSuperclass(), type);
1988     }
1989 
1990     ///////////////////////////////////////////////////////////////////////////
1991     //
1992     // The following methods help set and identify whether a particular
1993     // AWTEvent object was produced by the system or by user code. As of this
1994     // writing the only consumer is the Java Plug-In, although this information
1995     // could be useful to more clients and probably should be formalized in
1996     // the public API.
1997     //
1998     ///////////////////////////////////////////////////////////////////////////
1999 
2000     public static void setSystemGenerated(AWTEvent e) {
2001         AWTAccessor.getAWTEventAccessor().setSystemGenerated(e);
2002     }
2003 
2004     public static boolean isSystemGenerated(AWTEvent e) {
2005         return AWTAccessor.getAWTEventAccessor().isSystemGenerated(e);
2006     }
2007 
2008 } // class SunToolkit
2009 
2010 
2011 /*
2012  * PostEventQueue is a Thread that runs in the same AppContext as the
2013  * Java EventQueue.  It is a queue of AWTEvents to be posted to the
2014  * Java EventQueue.  The toolkit Thread (AWT-Windows/AWT-Motif) posts
2015  * events to this queue, which then calls EventQueue.postEvent().
2016  *
2017  * We do this because EventQueue.postEvent() may be overridden by client
2018  * code, and we mustn't ever call client code from the toolkit thread.
2019  */
2020 class PostEventQueue {
2021     private EventQueueItem queueHead = null;
2022     private EventQueueItem queueTail = null;
2023     private final EventQueue eventQueue;
2024 
2025     private Thread flushThread = null;
2026 
2027     PostEventQueue(EventQueue eq) {
2028         eventQueue = eq;
2029     }
2030 
2031     /*
2032      * Continually post pending AWTEvents to the Java EventQueue. The method
2033      * is synchronized to ensure the flush is completed before a new event
2034      * can be posted to this queue.
2035      *
2036      * 7177040: The method couldn't be wholly synchronized because of calls
2037      * of EventQueue.postEvent() that uses pushPopLock, otherwise it could
2038      * potentially lead to deadlock
2039      */
2040     public void flush() {
2041 
2042         Thread newThread = Thread.currentThread();
2043 
2044         try {
2045             EventQueueItem tempQueue;
2046             synchronized (this) {
2047                 // Avoid method recursion
2048                 if (newThread == flushThread) {
2049                     return;
2050                 }
2051                 // Wait for other threads' flushing
2052                 while (flushThread != null) {
2053                     wait();
2054                 }
2055                 // Skip everything if queue is empty
2056                 if (queueHead == null) {
2057                     return;
2058                 }
2059                 // Remember flushing thread
2060                 flushThread = newThread;
2061 
2062                 tempQueue = queueHead;
2063                 queueHead = queueTail = null;
2064             }
2065             try {
2066                 while (tempQueue != null) {
2067                     eventQueue.postEvent(tempQueue.event);
2068                     tempQueue = tempQueue.next;
2069                 }
2070             }
2071             finally {
2072                 // Only the flushing thread can get here
2073                 synchronized (this) {
2074                     // Forget flushing thread, inform other pending threads
2075                     flushThread = null;
2076                     notifyAll();
2077                 }
2078             }
2079         }
2080         catch (InterruptedException e) {
2081             // Couldn't allow exception go up, so at least recover the flag
2082             newThread.interrupt();
2083         }
2084     }
2085 
2086     /*
2087      * Enqueue an AWTEvent to be posted to the Java EventQueue.
2088      */
2089     void postEvent(AWTEvent event) {
2090         EventQueueItem item = new EventQueueItem(event);
2091 
2092         synchronized (this) {
2093             if (queueHead == null) {
2094                 queueHead = queueTail = item;
2095             } else {
2096                 queueTail.next = item;
2097                 queueTail = item;
2098             }
2099         }
2100         SunToolkit.wakeupEventQueue(eventQueue, event.getSource() == AWTAutoShutdown.getInstance());
2101     }
2102 } // class PostEventQueue