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