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