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