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