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