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