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