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