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