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 imgCache = new SoftCache();
 719 
 720     static Image getImageFromHash(Toolkit tk, URL url) {
 721         checkPermissions(url);
 722         synchronized (imgCache) {
 723             Image img = (Image)imgCache.get(url);
 724             if (img == null) {
 725                 try {
 726                     img = tk.createImage(new URLImageSource(url));
 727                     imgCache.put(url, img);
 728                 } catch (Exception e) {
 729                 }
 730             }
 731             return img;
 732         }
 733     }
 734 
 735     static Image getImageFromHash(Toolkit tk,
 736                                                String filename) {
 737         checkPermissions(filename);
 738         synchronized (imgCache) {
 739             Image img = (Image)imgCache.get(filename);
 740             if (img == null) {
 741                 try {
 742                     img = tk.createImage(new FileImageSource(filename));
 743                     imgCache.put(filename, img);
 744                 } catch (Exception e) {
 745                 }
 746             }
 747             return img;
 748         }
 749     }
 750 
 751     public Image getImage(String filename) {
 752         return getImageFromHash(this, filename);
 753     }
 754 
 755     public Image getImage(URL url) {
 756         return getImageFromHash(this, url);
 757     }
 758 
 759     protected Image getImageWithResolutionVariant(String fileName,
 760             String resolutionVariantName) {
 761         synchronized (imgCache) {
 762             Image image = getImageFromHash(this, fileName);
 763             if (image instanceof MultiResolutionImage) {
 764                 return image;
 765             }
 766             Image resolutionVariant = getImageFromHash(this, resolutionVariantName);
 767             image = createImageWithResolutionVariant(image, resolutionVariant);
 768             imgCache.put(fileName, image);
 769             return image;
 770         }
 771     }
 772 
 773     protected Image getImageWithResolutionVariant(URL url,
 774             URL resolutionVariantURL) {
 775         synchronized (imgCache) {
 776             Image image = getImageFromHash(this, url);
 777             if (image instanceof MultiResolutionImage) {
 778                 return image;
 779             }
 780             Image resolutionVariant = getImageFromHash(this, resolutionVariantURL);
 781             image = createImageWithResolutionVariant(image, resolutionVariant);
 782             imgCache.put(url, image);
 783             return image;
 784         }
 785     }
 786 
 787 
 788     public Image createImage(String filename) {
 789         checkPermissions(filename);
 790         return createImage(new FileImageSource(filename));
 791     }
 792 
 793     public Image createImage(URL url) {
 794         checkPermissions(url);
 795         return createImage(new URLImageSource(url));
 796     }
 797 
 798     public Image createImage(byte[] data, int offset, int length) {
 799         return createImage(new ByteArrayImageSource(data, offset, length));
 800     }
 801 
 802     public Image createImage(ImageProducer producer) {
 803         return new ToolkitImage(producer);
 804     }
 805 
 806     public static Image createImageWithResolutionVariant(Image image,
 807             Image resolutionVariant) {
 808         return new MultiResolutionToolkitImage(image, resolutionVariant);
 809     }
 810 
 811     public int checkImage(Image img, int w, int h, ImageObserver o) {
 812         if (!(img instanceof ToolkitImage)) {
 813             return ImageObserver.ALLBITS;
 814         }
 815 
 816         ToolkitImage tkimg = (ToolkitImage)img;
 817         int repbits;
 818         if (w == 0 || h == 0) {
 819             repbits = ImageObserver.ALLBITS;
 820         } else {
 821             repbits = tkimg.getImageRep().check(o);
 822         }
 823         return (tkimg.check(o) | repbits) & checkResolutionVariant(img, w, h, o);
 824     }
 825 
 826     public boolean prepareImage(Image img, int w, int h, ImageObserver o) {
 827         if (w == 0 || h == 0) {
 828             return true;
 829         }
 830 
 831         // Must be a ToolkitImage
 832         if (!(img instanceof ToolkitImage)) {
 833             return true;
 834         }
 835 
 836         ToolkitImage tkimg = (ToolkitImage)img;
 837         if (tkimg.hasError()) {
 838             if (o != null) {
 839                 o.imageUpdate(img, ImageObserver.ERROR|ImageObserver.ABORT,
 840                               -1, -1, -1, -1);
 841             }
 842             return false;
 843         }
 844         ImageRepresentation ir = tkimg.getImageRep();
 845         return ir.prepare(o) & prepareResolutionVariant(img, w, h, o);
 846     }
 847 
 848     private int checkResolutionVariant(Image img, int w, int h, ImageObserver o) {
 849         ToolkitImage rvImage = getResolutionVariant(img);
 850         int rvw = getRVSize(w);
 851         int rvh = getRVSize(h);
 852         // Ignore the resolution variant in case of error
 853         return (rvImage == null || rvImage.hasError()) ? 0xFFFF :
 854                 checkImage(rvImage, rvw, rvh, MultiResolutionToolkitImage.
 855                                 getResolutionVariantObserver(
 856                                         img, o, w, h, rvw, rvh, true));
 857     }
 858 
 859     private boolean prepareResolutionVariant(Image img, int w, int h,
 860             ImageObserver o) {
 861 
 862         ToolkitImage rvImage = getResolutionVariant(img);
 863         int rvw = getRVSize(w);
 864         int rvh = getRVSize(h);
 865         // Ignore the resolution variant in case of error
 866         return rvImage == null || rvImage.hasError() || prepareImage(
 867                 rvImage, rvw, rvh,
 868                 MultiResolutionToolkitImage.getResolutionVariantObserver(
 869                         img, o, w, h, rvw, rvh, true));
 870     }
 871 
 872     private static int getRVSize(int size){
 873         return size == -1 ? -1 : 2 * size;
 874     }
 875 
 876     private static ToolkitImage getResolutionVariant(Image image) {
 877         if (image instanceof MultiResolutionToolkitImage) {
 878             Image resolutionVariant = ((MultiResolutionToolkitImage) image).
 879                     getResolutionVariant();
 880             if (resolutionVariant instanceof ToolkitImage) {
 881                 return (ToolkitImage) resolutionVariant;
 882             }
 883         }
 884         return null;
 885     }
 886 
 887     protected static boolean imageCached(Object key) {
 888         return imgCache.containsKey(key);
 889     }
 890 
 891     protected static boolean imageExists(String filename) {
 892         if (filename != null) {
 893             checkPermissions(filename);
 894             return new File(filename).exists();
 895         }
 896         return false;
 897     }
 898 
 899     @SuppressWarnings("try")
 900     protected static boolean imageExists(URL url) {
 901         if (url != null) {
 902             checkPermissions(url);
 903             try (InputStream is = url.openStream()) {
 904                 return true;
 905             }catch(IOException e){
 906                 return false;
 907             }
 908         }
 909         return false;
 910     }
 911 
 912     private static void checkPermissions(String filename) {
 913         SecurityManager security = System.getSecurityManager();
 914         if (security != null) {
 915             security.checkRead(filename);
 916         }
 917     }
 918 
 919     private static void checkPermissions(URL url) {
 920         SecurityManager sm = System.getSecurityManager();
 921         if (sm != null) {
 922             try {
 923                 java.security.Permission perm =
 924                     URLUtil.getConnectPermission(url);
 925                 if (perm != null) {
 926                     try {
 927                         sm.checkPermission(perm);
 928                     } catch (SecurityException se) {
 929                         // fallback to checkRead/checkConnect for pre 1.2
 930                         // security managers
 931                         if ((perm instanceof java.io.FilePermission) &&
 932                             perm.getActions().indexOf("read") != -1) {
 933                             sm.checkRead(perm.getName());
 934                         } else if ((perm instanceof
 935                             java.net.SocketPermission) &&
 936                             perm.getActions().indexOf("connect") != -1) {
 937                             sm.checkConnect(url.getHost(), url.getPort());
 938                         } else {
 939                             throw se;
 940                         }
 941                     }
 942                 }
 943             } catch (java.io.IOException ioe) {
 944                     sm.checkConnect(url.getHost(), url.getPort());
 945             }
 946         }
 947     }
 948 
 949     /**
 950      * Scans {@code imageList} for best-looking image of specified dimensions.
 951      * Image can be scaled and/or padded with transparency.
 952      */
 953     public static BufferedImage getScaledIconImage(java.util.List<Image> imageList, int width, int height) {
 954         if (width == 0 || height == 0) {
 955             return null;
 956         }
 957         Image bestImage = null;
 958         int bestWidth = 0;
 959         int bestHeight = 0;
 960         double bestSimilarity = 3; //Impossibly high value
 961         double bestScaleFactor = 0;
 962         for (Iterator<Image> i = imageList.iterator();i.hasNext();) {
 963             //Iterate imageList looking for best matching image.
 964             //'Similarity' measure is defined as good scale factor and small insets.
 965             //best possible similarity is 0 (no scale, no insets).
 966             //It's found while the experiments that good-looking result is achieved
 967             //with scale factors x1, x3/4, x2/3, xN, x1/N.
 968             Image im = i.next();
 969             if (im == null) {
 970                 continue;
 971             }
 972             if (im instanceof ToolkitImage) {
 973                 ImageRepresentation ir = ((ToolkitImage)im).getImageRep();
 974                 ir.reconstruct(ImageObserver.ALLBITS);
 975             }
 976             int iw;
 977             int ih;
 978             try {
 979                 iw = im.getWidth(null);
 980                 ih = im.getHeight(null);
 981             } catch (Exception e){
 982                 continue;
 983             }
 984             if (iw > 0 && ih > 0) {
 985                 //Calc scale factor
 986                 double scaleFactor = Math.min((double)width / (double)iw,
 987                                               (double)height / (double)ih);
 988                 //Calculate scaled image dimensions
 989                 //adjusting scale factor to nearest "good" value
 990                 int adjw = 0;
 991                 int adjh = 0;
 992                 double scaleMeasure = 1; //0 - best (no) scale, 1 - impossibly bad
 993                 if (scaleFactor >= 2) {
 994                     //Need to enlarge image more than twice
 995                     //Round down scale factor to multiply by integer value
 996                     scaleFactor = Math.floor(scaleFactor);
 997                     adjw = iw * (int)scaleFactor;
 998                     adjh = ih * (int)scaleFactor;
 999                     scaleMeasure = 1.0 - 0.5 / scaleFactor;
1000                 } else if (scaleFactor >= 1) {
1001                     //Don't scale
1002                     scaleFactor = 1.0;
1003                     adjw = iw;
1004                     adjh = ih;
1005                     scaleMeasure = 0;
1006                 } else if (scaleFactor >= 0.75) {
1007                     //Multiply by 3/4
1008                     scaleFactor = 0.75;
1009                     adjw = iw * 3 / 4;
1010                     adjh = ih * 3 / 4;
1011                     scaleMeasure = 0.3;
1012                 } else if (scaleFactor >= 0.6666) {
1013                     //Multiply by 2/3
1014                     scaleFactor = 0.6666;
1015                     adjw = iw * 2 / 3;
1016                     adjh = ih * 2 / 3;
1017                     scaleMeasure = 0.33;
1018                 } else {
1019                     //Multiply size by 1/scaleDivider
1020                     //where scaleDivider is minimum possible integer
1021                     //larger than 1/scaleFactor
1022                     double scaleDivider = Math.ceil(1.0 / scaleFactor);
1023                     scaleFactor = 1.0 / scaleDivider;
1024                     adjw = (int)Math.round((double)iw / scaleDivider);
1025                     adjh = (int)Math.round((double)ih / scaleDivider);
1026                     scaleMeasure = 1.0 - 1.0 / scaleDivider;
1027                 }
1028                 double similarity = ((double)width - (double)adjw) / (double)width +
1029                     ((double)height - (double)adjh) / (double)height + //Large padding is bad
1030                     scaleMeasure; //Large rescale is bad
1031                 if (similarity < bestSimilarity) {
1032                     bestSimilarity = similarity;
1033                     bestScaleFactor = scaleFactor;
1034                     bestImage = im;
1035                     bestWidth = adjw;
1036                     bestHeight = adjh;
1037                 }
1038                 if (similarity == 0) break;
1039             }
1040         }
1041         if (bestImage == null) {
1042             //No images were found, possibly all are broken
1043             return null;
1044         }
1045         BufferedImage bimage =
1046             new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
1047         Graphics2D g = bimage.createGraphics();
1048         g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1049                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
1050         try {
1051             int x = (width - bestWidth) / 2;
1052             int y = (height - bestHeight) / 2;
1053             g.drawImage(bestImage, x, y, bestWidth, bestHeight, null);
1054         } finally {
1055             g.dispose();
1056         }
1057         return bimage;
1058     }
1059 
1060     public static DataBufferInt getScaledIconData(java.util.List<Image> imageList, int width, int height) {
1061         BufferedImage bimage = getScaledIconImage(imageList, width, height);
1062         if (bimage == null) {
1063             return null;
1064         }
1065         Raster raster = bimage.getRaster();
1066         DataBuffer buffer = raster.getDataBuffer();
1067         return (DataBufferInt)buffer;
1068     }
1069 
1070     protected EventQueue getSystemEventQueueImpl() {
1071         return getSystemEventQueueImplPP();
1072     }
1073 
1074     // Package private implementation
1075     static EventQueue getSystemEventQueueImplPP() {
1076         return getSystemEventQueueImplPP(AppContext.getAppContext());
1077     }
1078 
1079     public static EventQueue getSystemEventQueueImplPP(AppContext appContext) {
1080         EventQueue theEventQueue =
1081             (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY);
1082         return theEventQueue;
1083     }
1084 
1085     /**
1086      * Give native peers the ability to query the native container
1087      * given a native component (eg the direct parent may be lightweight).
1088      */
1089     public static Container getNativeContainer(Component c) {
1090         return Toolkit.getNativeContainer(c);
1091     }
1092 
1093     /**
1094      * Gives native peers the ability to query the closest HW component.
1095      * If the given component is heavyweight, then it returns this. Otherwise,
1096      * it goes one level up in the hierarchy and tests next component.
1097      */
1098     public static Component getHeavyweightComponent(Component c) {
1099         while (c != null && AWTAccessor.getComponentAccessor().isLightweight(c)) {
1100             c = AWTAccessor.getComponentAccessor().getParent(c);
1101         }
1102         return c;
1103     }
1104 
1105     /**
1106      * Returns key modifiers used by Swing to set up a focus accelerator key stroke.
1107      */
1108     public int getFocusAcceleratorKeyMask() {
1109         return InputEvent.ALT_MASK;
1110     }
1111 
1112     /**
1113      * Tests whether specified key modifiers mask can be used to enter a printable
1114      * character. This is a default implementation of this method, which reflects
1115      * the way things work on Windows: here, pressing ctrl + alt allows user to enter
1116      * characters from the extended character set (like euro sign or math symbols)
1117      */
1118     public boolean isPrintableCharacterModifiersMask(int mods) {
1119         return ((mods & InputEvent.ALT_MASK) == (mods & InputEvent.CTRL_MASK));
1120     }
1121 
1122     /**
1123      * Returns whether popup is allowed to be shown above the task bar.
1124      * This is a default implementation of this method, which checks
1125      * corresponding security permission.
1126      */
1127     public boolean canPopupOverlapTaskBar() {
1128         boolean result = true;
1129         try {
1130             SecurityManager sm = System.getSecurityManager();
1131             if (sm != null) {
1132                 sm.checkPermission(
1133                         SecurityConstants.AWT.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION);
1134             }
1135         } catch (SecurityException se) {
1136             // There is no permission to show popups over the task bar
1137             result = false;
1138         }
1139         return result;
1140     }
1141 
1142     /**
1143      * Returns a new input method window, with behavior as specified in
1144      * {@link java.awt.im.spi.InputMethodContext#createInputMethodWindow}.
1145      * If the inputContext is not null, the window should return it from its
1146      * getInputContext() method. The window needs to implement
1147      * sun.awt.im.InputMethodWindow.
1148      * <p>
1149      * SunToolkit subclasses can override this method to return better input
1150      * method windows.
1151      */
1152     public Window createInputMethodWindow(String title, InputContext context) {
1153         return new sun.awt.im.SimpleInputMethodWindow(title, context);
1154     }
1155 
1156     /**
1157      * Returns whether enableInputMethods should be set to true for peered
1158      * TextComponent instances on this platform. False by default.
1159      */
1160     public boolean enableInputMethodsForTextComponent() {
1161         return false;
1162     }
1163 
1164     private static Locale startupLocale = null;
1165 
1166     /**
1167      * Returns the locale in which the runtime was started.
1168      */
1169     public static Locale getStartupLocale() {
1170         if (startupLocale == null) {
1171             String language, region, country, variant;
1172             language = AccessController.doPrivileged(
1173                             new GetPropertyAction("user.language", "en"));
1174             // for compatibility, check for old user.region property
1175             region = AccessController.doPrivileged(
1176                             new GetPropertyAction("user.region"));
1177             if (region != null) {
1178                 // region can be of form country, country_variant, or _variant
1179                 int i = region.indexOf('_');
1180                 if (i >= 0) {
1181                     country = region.substring(0, i);
1182                     variant = region.substring(i + 1);
1183                 } else {
1184                     country = region;
1185                     variant = "";
1186                 }
1187             } else {
1188                 country = AccessController.doPrivileged(
1189                                 new GetPropertyAction("user.country", ""));
1190                 variant = AccessController.doPrivileged(
1191                                 new GetPropertyAction("user.variant", ""));
1192             }
1193             startupLocale = new Locale(language, country, variant);
1194         }
1195         return startupLocale;
1196     }
1197 
1198     /**
1199      * Returns the default keyboard locale of the underlying operating system
1200      */
1201     public Locale getDefaultKeyboardLocale() {
1202         return getStartupLocale();
1203     }
1204 
1205     // Support for window closing event notifications
1206     private transient WindowClosingListener windowClosingListener = null;
1207     /**
1208      * @see sun.awt.WindowClosingSupport#getWindowClosingListener
1209      */
1210     public WindowClosingListener getWindowClosingListener() {
1211         return windowClosingListener;
1212     }
1213     /**
1214      * @see sun.awt.WindowClosingSupport#setWindowClosingListener
1215      */
1216     public void setWindowClosingListener(WindowClosingListener wcl) {
1217         windowClosingListener = wcl;
1218     }
1219 
1220     /**
1221      * @see sun.awt.WindowClosingListener#windowClosingNotify
1222      */
1223     public RuntimeException windowClosingNotify(WindowEvent event) {
1224         if (windowClosingListener != null) {
1225             return windowClosingListener.windowClosingNotify(event);
1226         } else {
1227             return null;
1228         }
1229     }
1230     /**
1231      * @see sun.awt.WindowClosingListener#windowClosingDelivered
1232      */
1233     public RuntimeException windowClosingDelivered(WindowEvent event) {
1234         if (windowClosingListener != null) {
1235             return windowClosingListener.windowClosingDelivered(event);
1236         } else {
1237             return null;
1238         }
1239     }
1240 
1241     private static DefaultMouseInfoPeer mPeer = null;
1242 
1243     protected synchronized MouseInfoPeer getMouseInfoPeer() {
1244         if (mPeer == null) {
1245             mPeer = new DefaultMouseInfoPeer();
1246         }
1247         return mPeer;
1248     }
1249 
1250 
1251     /**
1252      * Returns whether default toolkit needs the support of the xembed
1253      * from embedding host(if any).
1254      * @return <code>true</code>, if XEmbed is needed, <code>false</code> otherwise
1255      */
1256     public static boolean needsXEmbed() {
1257         String noxembed = AccessController.
1258             doPrivileged(new GetPropertyAction("sun.awt.noxembed", "false"));
1259         if ("true".equals(noxembed)) {
1260             return false;
1261         }
1262 
1263         Toolkit tk = Toolkit.getDefaultToolkit();
1264         if (tk instanceof SunToolkit) {
1265             // SunToolkit descendants should override this method to specify
1266             // concrete behavior
1267             return ((SunToolkit)tk).needsXEmbedImpl();
1268         } else {
1269             // Non-SunToolkit doubtly might support XEmbed
1270             return false;
1271         }
1272     }
1273 
1274     /**
1275      * Returns whether this toolkit needs the support of the xembed
1276      * from embedding host(if any).
1277      * @return <code>true</code>, if XEmbed is needed, <code>false</code> otherwise
1278      */
1279     protected boolean needsXEmbedImpl() {
1280         return false;
1281     }
1282 
1283     private static Dialog.ModalExclusionType DEFAULT_MODAL_EXCLUSION_TYPE = null;
1284 
1285     /**
1286      * Returns whether the XEmbed server feature is requested by
1287      * developer.  If true, Toolkit should return an
1288      * XEmbed-server-enabled CanvasPeer instead of the ordinary CanvasPeer.
1289      */
1290     protected final boolean isXEmbedServerRequested() {
1291         return AccessController.doPrivileged(new GetBooleanAction("sun.awt.xembedserver"));
1292     }
1293 
1294     /**
1295      * Returns whether the modal exclusion API is supported by the current toolkit.
1296      * When it isn't supported, calling <code>setModalExcluded</code> has no
1297      * effect, and <code>isModalExcluded</code> returns false for all windows.
1298      *
1299      * @return true if modal exclusion is supported by the toolkit, false otherwise
1300      *
1301      * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window)
1302      * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window)
1303      *
1304      * @since 1.5
1305      */
1306     public static boolean isModalExcludedSupported()
1307     {
1308         Toolkit tk = Toolkit.getDefaultToolkit();
1309         return tk.isModalExclusionTypeSupported(DEFAULT_MODAL_EXCLUSION_TYPE);
1310     }
1311     /*
1312      * Default implementation for isModalExcludedSupportedImpl(), returns false.
1313      *
1314      * @see sun.awt.windows.WToolkit#isModalExcludeSupportedImpl
1315      * @see sun.awt.X11.XToolkit#isModalExcludeSupportedImpl
1316      *
1317      * @since 1.5
1318      */
1319     protected boolean isModalExcludedSupportedImpl()
1320     {
1321         return false;
1322     }
1323 
1324     /*
1325      * Sets this window to be excluded from being modally blocked. When the
1326      * toolkit supports modal exclusion and this method is called, input
1327      * events, focus transfer and z-order will continue to work for the
1328      * window, it's owned windows and child components, even in the
1329      * presence of a modal dialog.
1330      * For details on which <code>Window</code>s are normally blocked
1331      * by modal dialog, see {@link java.awt.Dialog}.
1332      * Invoking this method when the modal exclusion API is not supported by
1333      * the current toolkit has no effect.
1334      * @param window Window to be marked as not modally blocked
1335      * @see java.awt.Dialog
1336      * @see java.awt.Dialog#setModal(boolean)
1337      * @see sun.awt.SunToolkit#isModalExcludedSupported
1338      * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window)
1339      */
1340     public static void setModalExcluded(Window window)
1341     {
1342         if (DEFAULT_MODAL_EXCLUSION_TYPE == null) {
1343             DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE;
1344         }
1345         window.setModalExclusionType(DEFAULT_MODAL_EXCLUSION_TYPE);
1346     }
1347 
1348     /*
1349      * Returns whether the specified window is blocked by modal dialogs.
1350      * If the modal exclusion API isn't supported by the current toolkit,
1351      * it returns false for all windows.
1352      *
1353      * @param window Window to test for modal exclusion
1354      *
1355      * @return true if the window is modal excluded, false otherwise. If
1356      * the modal exclusion isn't supported by the current Toolkit, false
1357      * is returned
1358      *
1359      * @see sun.awt.SunToolkit#isModalExcludedSupported
1360      * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window)
1361      *
1362      * @since 1.5
1363      */
1364     public static boolean isModalExcluded(Window window)
1365     {
1366         if (DEFAULT_MODAL_EXCLUSION_TYPE == null) {
1367             DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE;
1368         }
1369         return window.getModalExclusionType().compareTo(DEFAULT_MODAL_EXCLUSION_TYPE) >= 0;
1370     }
1371 
1372     /**
1373      * Overridden in XToolkit and WToolkit
1374      */
1375     public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) {
1376         return (modalityType == Dialog.ModalityType.MODELESS) ||
1377                (modalityType == Dialog.ModalityType.APPLICATION_MODAL);
1378     }
1379 
1380     /**
1381      * Overridden in XToolkit and WToolkit
1382      */
1383     public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) {
1384         return (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE);
1385     }
1386 
1387     ///////////////////////////////////////////////////////////////////////////
1388     //
1389     // The following is used by the Java Plug-in to coordinate dialog modality
1390     // between containing applications (browsers, ActiveX containers etc) and
1391     // the AWT.
1392     //
1393     ///////////////////////////////////////////////////////////////////////////
1394 
1395     private ModalityListenerList modalityListeners = new ModalityListenerList();
1396 
1397     public void addModalityListener(ModalityListener listener) {
1398         modalityListeners.add(listener);
1399     }
1400 
1401     public void removeModalityListener(ModalityListener listener) {
1402         modalityListeners.remove(listener);
1403     }
1404 
1405     public void notifyModalityPushed(Dialog dialog) {
1406         notifyModalityChange(ModalityEvent.MODALITY_PUSHED, dialog);
1407     }
1408 
1409     public void notifyModalityPopped(Dialog dialog) {
1410         notifyModalityChange(ModalityEvent.MODALITY_POPPED, dialog);
1411     }
1412 
1413     final void notifyModalityChange(int id, Dialog source) {
1414         ModalityEvent ev = new ModalityEvent(source, modalityListeners, id);
1415         ev.dispatch();
1416     }
1417 
1418     static class ModalityListenerList implements ModalityListener {
1419 
1420         Vector<ModalityListener> listeners = new Vector<ModalityListener>();
1421 
1422         void add(ModalityListener listener) {
1423             listeners.addElement(listener);
1424         }
1425 
1426         void remove(ModalityListener listener) {
1427             listeners.removeElement(listener);
1428         }
1429 
1430         public void modalityPushed(ModalityEvent ev) {
1431             Iterator<ModalityListener> it = listeners.iterator();
1432             while (it.hasNext()) {
1433                 it.next().modalityPushed(ev);
1434             }
1435         }
1436 
1437         public void modalityPopped(ModalityEvent ev) {
1438             Iterator<ModalityListener> it = listeners.iterator();
1439             while (it.hasNext()) {
1440                 it.next().modalityPopped(ev);
1441             }
1442         }
1443     } // end of class ModalityListenerList
1444 
1445     ///////////////////////////////////////////////////////////////////////////
1446     // End Plug-in code
1447     ///////////////////////////////////////////////////////////////////////////
1448 
1449     public static boolean isLightweightOrUnknown(Component comp) {
1450         if (comp.isLightweight()
1451             || !(getDefaultToolkit() instanceof SunToolkit))
1452         {
1453             return true;
1454         }
1455         return !(comp instanceof Button
1456             || comp instanceof Canvas
1457             || comp instanceof Checkbox
1458             || comp instanceof Choice
1459             || comp instanceof Label
1460             || comp instanceof java.awt.List
1461             || comp instanceof Panel
1462             || comp instanceof Scrollbar
1463             || comp instanceof ScrollPane
1464             || comp instanceof TextArea
1465             || comp instanceof TextField
1466             || comp instanceof Window);
1467     }
1468 
1469     @SuppressWarnings("serial")
1470     public static class OperationTimedOut extends RuntimeException {
1471         public OperationTimedOut(String msg) {
1472             super(msg);
1473         }
1474         public OperationTimedOut() {
1475         }
1476     }
1477 
1478     @SuppressWarnings("serial")
1479     public static class InfiniteLoop extends RuntimeException {
1480     }
1481 
1482     @SuppressWarnings("serial")
1483     public static class IllegalThreadException extends RuntimeException {
1484         public IllegalThreadException(String msg) {
1485             super(msg);
1486         }
1487         public IllegalThreadException() {
1488         }
1489     }
1490 
1491     public static final int DEFAULT_WAIT_TIME = 10000;
1492     private static final int MAX_ITERS = 20;
1493     private static final int MIN_ITERS = 0;
1494     private static final int MINIMAL_EDELAY = 0;
1495 
1496     /**
1497      * Parameterless version of realsync which uses default timout (see DEFAUL_WAIT_TIME).
1498      */
1499     public void realSync() throws OperationTimedOut, InfiniteLoop {
1500         realSync(DEFAULT_WAIT_TIME);
1501     }
1502 
1503     /**
1504      * Forces toolkit to synchronize with the native windowing
1505      * sub-system, flushing all pending work and waiting for all the
1506      * events to be processed.  This method guarantees that after
1507      * return no additional Java events will be generated, unless
1508      * cause by user. Obviously, the method cannot be used on the
1509      * event dispatch thread (EDT). In case it nevertheless gets
1510      * invoked on this thread, the method throws the
1511      * IllegalThreadException runtime exception.
1512      *
1513      * <p> This method allows to write tests without explicit timeouts
1514      * or wait for some event.  Example:
1515      * <code>
1516      * Frame f = ...;
1517      * f.setVisible(true);
1518      * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
1519      * </code>
1520      *
1521      * <p> After realSync, <code>f</code> will be completely visible
1522      * on the screen, its getLocationOnScreen will be returning the
1523      * right result and it will be the focus owner.
1524      *
1525      * <p> Another example:
1526      * <code>
1527      * b.requestFocus();
1528      * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
1529      * </code>
1530      *
1531      * <p> After realSync, <code>b</code> will be focus owner.
1532      *
1533      * <p> Notice that realSync isn't guaranteed to work if recurring
1534      * actions occur, such as if during processing of some event
1535      * another request which may generate some events occurs.  By
1536      * default, sync tries to perform as much as {@value MAX_ITERS}
1537      * cycles of event processing, allowing for roughly {@value
1538      * MAX_ITERS} additional requests.
1539      *
1540      * <p> For example, requestFocus() generates native request, which
1541      * generates one or two Java focus events, which then generate a
1542      * serie of paint events, a serie of Java focus events, which then
1543      * generate a serie of paint events which then are processed -
1544      * three cycles, minimum.
1545      *
1546      * @param timeout the maximum time to wait in milliseconds, negative means "forever".
1547      */
1548     public void realSync(final long timeout) throws OperationTimedOut, InfiniteLoop
1549     {
1550         if (EventQueue.isDispatchThread()) {
1551             throw new IllegalThreadException("The SunToolkit.realSync() method cannot be used on the event dispatch thread (EDT).");
1552         }
1553         int bigLoop = 0;
1554         do {
1555             // Let's do sync first
1556             sync();
1557 
1558             // During the wait process, when we were processing incoming
1559             // events, we could have made some new request, which can
1560             // generate new events.  Example: MapNotify/XSetInputFocus.
1561             // Therefore, we dispatch them as long as there is something
1562             // to dispatch.
1563             int iters = 0;
1564             while (iters < MIN_ITERS) {
1565                 syncNativeQueue(timeout);
1566                 iters++;
1567             }
1568             while (syncNativeQueue(timeout) && iters < MAX_ITERS) {
1569                 iters++;
1570             }
1571             if (iters >= MAX_ITERS) {
1572                 throw new InfiniteLoop();
1573             }
1574 
1575             // native requests were dispatched by X/Window Manager or Windows
1576             // Moreover, we processed them all on Toolkit thread
1577             // Now wait while EDT processes them.
1578             //
1579             // During processing of some events (focus, for example),
1580             // some other events could have been generated.  So, after
1581             // waitForIdle, we may end up with full EventQueue
1582             iters = 0;
1583             while (iters < MIN_ITERS) {
1584                 waitForIdle(timeout);
1585                 iters++;
1586             }
1587             while (waitForIdle(timeout) && iters < MAX_ITERS) {
1588                 iters++;
1589             }
1590             if (iters >= MAX_ITERS) {
1591                 throw new InfiniteLoop();
1592             }
1593 
1594             bigLoop++;
1595             // Again, for Java events, it was simple to check for new Java
1596             // events by checking event queue, but what if Java events
1597             // resulted in native requests?  Therefor, check native events again.
1598         } while ((syncNativeQueue(timeout) || waitForIdle(timeout)) && bigLoop < MAX_ITERS);
1599     }
1600 
1601     /**
1602      * Platform toolkits need to implement this method to perform the
1603      * sync of the native queue.  The method should wait until native
1604      * requests are processed, all native events are processed and
1605      * corresponding Java events are generated.  Should return
1606      * <code>true</code> if some events were processed,
1607      * <code>false</code> otherwise.
1608      */
1609     protected abstract boolean syncNativeQueue(final long timeout);
1610 
1611     private boolean eventDispatched = false;
1612     private boolean queueEmpty = false;
1613     private final Object waitLock = "Wait Lock";
1614 
1615     private boolean isEQEmpty() {
1616         EventQueue queue = getSystemEventQueueImpl();
1617         return AWTAccessor.getEventQueueAccessor().noEvents(queue);
1618     }
1619 
1620     /**
1621      * Waits for the Java event queue to empty.  Ensures that all
1622      * events are processed (including paint events), and that if
1623      * recursive events were generated, they are also processed.
1624      * Should return <code>true</code> if more processing is
1625      * necessary, <code>false</code> otherwise.
1626      */
1627     @SuppressWarnings("serial")
1628     protected final boolean waitForIdle(final long timeout) {
1629         flushPendingEvents();
1630         boolean queueWasEmpty = isEQEmpty();
1631         queueEmpty = false;
1632         eventDispatched = false;
1633         synchronized(waitLock) {
1634             postEvent(AppContext.getAppContext(),
1635                       new PeerEvent(getSystemEventQueueImpl(), null, PeerEvent.LOW_PRIORITY_EVENT) {
1636                           public void dispatch() {
1637                               // Here we block EDT.  It could have some
1638                               // events, it should have dispatched them by
1639                               // now.  So native requests could have been
1640                               // generated.  First, dispatch them.  Then,
1641                               // flush Java events again.
1642                               int iters = 0;
1643                               while (iters < MIN_ITERS) {
1644                                   syncNativeQueue(timeout);
1645                                   iters++;
1646                               }
1647                               while (syncNativeQueue(timeout) && iters < MAX_ITERS) {
1648                                   iters++;
1649                               }
1650                               flushPendingEvents();
1651 
1652                               synchronized(waitLock) {
1653                                   queueEmpty = isEQEmpty();
1654                                   eventDispatched = true;
1655                                   waitLock.notifyAll();
1656                               }
1657                           }
1658                       });
1659             try {
1660                 while (!eventDispatched) {
1661                     waitLock.wait();
1662                 }
1663             } catch (InterruptedException ie) {
1664                 return false;
1665             }
1666         }
1667 
1668         try {
1669             Thread.sleep(MINIMAL_EDELAY);
1670         } catch (InterruptedException ie) {
1671             throw new RuntimeException("Interrupted");
1672         }
1673 
1674         flushPendingEvents();
1675 
1676         // Lock to force write-cache flush for queueEmpty.
1677         synchronized (waitLock) {
1678             return !(queueEmpty && isEQEmpty() && queueWasEmpty);
1679         }
1680     }
1681 
1682     /**
1683      * Grabs the mouse input for the given window.  The window must be
1684      * visible.  The window or its children do not receive any
1685      * additional mouse events besides those targeted to them.  All
1686      * other events will be dispatched as before - to the respective
1687      * targets.  This Window will receive UngrabEvent when automatic
1688      * ungrab is about to happen.  The event can be listened to by
1689      * installing AWTEventListener with WINDOW_EVENT_MASK.  See
1690      * UngrabEvent class for the list of conditions when ungrab is
1691      * about to happen.
1692      * @see UngrabEvent
1693      */
1694     public abstract void grab(Window w);
1695 
1696     /**
1697      * Forces ungrab.  No event will be sent.
1698      */
1699     public abstract void ungrab(Window w);
1700 
1701 
1702     /**
1703      * Locates the splash screen library in a platform dependent way and closes
1704      * the splash screen. Should be invoked on first top-level frame display.
1705      * @see java.awt.SplashScreen
1706      * @since 1.6
1707      */
1708     public static native void closeSplashScreen();
1709 
1710     /* The following methods and variables are to support retrieving
1711      * desktop text anti-aliasing settings
1712      */
1713 
1714     /* Need an instance method because setDesktopProperty(..) is protected. */
1715     private void fireDesktopFontPropertyChanges() {
1716         setDesktopProperty(SunToolkit.DESKTOPFONTHINTS,
1717                            SunToolkit.getDesktopFontHints());
1718     }
1719 
1720     private static boolean checkedSystemAAFontSettings;
1721     private static boolean useSystemAAFontSettings;
1722     private static boolean lastExtraCondition = true;
1723     private static RenderingHints desktopFontHints;
1724 
1725     /* Since Swing is the reason for this "extra condition" logic its
1726      * worth documenting it in some detail.
1727      * First, a goal is for Swing and applications to both retrieve and
1728      * use the same desktop property value so that there is complete
1729      * consistency between the settings used by JDK's Swing implementation
1730      * and 3rd party custom Swing components, custom L&Fs and any general
1731      * text rendering that wants to be consistent with these.
1732      * But by default on Solaris & Linux Swing will not use AA text over
1733      * remote X11 display (unless Xrender can be used which is TBD and may not
1734      * always be available anyway) as that is a noticeable performance hit.
1735      * So there needs to be a way to express that extra condition so that
1736      * it is seen by all clients of the desktop property API.
1737      * If this were the only condition it could be handled here as it would
1738      * be the same for any L&F and could reasonably be considered to be
1739      * a static behaviour of those systems.
1740      * But GTK currently has an additional test based on locale which is
1741      * not applied by Metal. So mixing GTK in a few locales with Metal
1742      * would mean the last one wins.
1743      * This could be stored per-app context which would work
1744      * for different applets, but wouldn't help for a single application
1745      * using GTK and some other L&F concurrently.
1746      * But it is expected this will be addressed within GTK and the font
1747      * system so is a temporary and somewhat unlikely harmless corner case.
1748      */
1749     public static void setAAFontSettingsCondition(boolean extraCondition) {
1750         if (extraCondition != lastExtraCondition) {
1751             lastExtraCondition = extraCondition;
1752             if (checkedSystemAAFontSettings) {
1753                 /* Someone already asked for this info, under a different
1754                  * condition.
1755                  * We'll force re-evaluation instead of replicating the
1756                  * logic, then notify any listeners of any change.
1757                  */
1758                 checkedSystemAAFontSettings = false;
1759                 Toolkit tk = Toolkit.getDefaultToolkit();
1760                 if (tk instanceof SunToolkit) {
1761                      ((SunToolkit)tk).fireDesktopFontPropertyChanges();
1762                 }
1763             }
1764         }
1765     }
1766 
1767     /* "false", "off", ""default" aren't explicitly tested, they
1768      * just fall through to produce a null return which all are equated to
1769      * "false".
1770      */
1771     private static RenderingHints getDesktopAAHintsByName(String hintname) {
1772         Object aaHint = null;
1773         hintname = hintname.toLowerCase(Locale.ENGLISH);
1774         if (hintname.equals("on")) {
1775             aaHint = VALUE_TEXT_ANTIALIAS_ON;
1776         } else if (hintname.equals("gasp")) {
1777             aaHint = VALUE_TEXT_ANTIALIAS_GASP;
1778         } else if (hintname.equals("lcd") || hintname.equals("lcd_hrgb")) {
1779             aaHint = VALUE_TEXT_ANTIALIAS_LCD_HRGB;
1780         } else if (hintname.equals("lcd_hbgr")) {
1781             aaHint = VALUE_TEXT_ANTIALIAS_LCD_HBGR;
1782         } else if (hintname.equals("lcd_vrgb")) {
1783             aaHint = VALUE_TEXT_ANTIALIAS_LCD_VRGB;
1784         } else if (hintname.equals("lcd_vbgr")) {
1785             aaHint = VALUE_TEXT_ANTIALIAS_LCD_VBGR;
1786         }
1787         if (aaHint != null) {
1788             RenderingHints map = new RenderingHints(null);
1789             map.put(KEY_TEXT_ANTIALIASING, aaHint);
1790             return map;
1791         } else {
1792             return null;
1793         }
1794     }
1795 
1796     /* This method determines whether to use the system font settings,
1797      * or ignore them if a L&F has specified they should be ignored, or
1798      * to override both of these with a system property specified value.
1799      * If the toolkit isn't a SunToolkit, (eg may be headless) then that
1800      * system property isn't applied as desktop properties are considered
1801      * to be inapplicable in that case. In that headless case although
1802      * this method will return "true" the toolkit will return a null map.
1803      */
1804     private static boolean useSystemAAFontSettings() {
1805         if (!checkedSystemAAFontSettings) {
1806             useSystemAAFontSettings = true; /* initially set this true */
1807             String systemAAFonts = null;
1808             Toolkit tk = Toolkit.getDefaultToolkit();
1809             if (tk instanceof SunToolkit) {
1810                 systemAAFonts =
1811                     AccessController.doPrivileged(
1812                          new GetPropertyAction("awt.useSystemAAFontSettings"));
1813             }
1814             if (systemAAFonts != null) {
1815                 useSystemAAFontSettings =
1816                     Boolean.valueOf(systemAAFonts).booleanValue();
1817                 /* If it is anything other than "true", then it may be
1818                  * a hint name , or it may be "off, "default", etc.
1819                  */
1820                 if (!useSystemAAFontSettings) {
1821                     desktopFontHints = getDesktopAAHintsByName(systemAAFonts);
1822                 }
1823             }
1824             /* If its still true, apply the extra condition */
1825             if (useSystemAAFontSettings) {
1826                  useSystemAAFontSettings = lastExtraCondition;
1827             }
1828             checkedSystemAAFontSettings = true;
1829         }
1830         return useSystemAAFontSettings;
1831     }
1832 
1833     /* A variable defined for the convenience of JDK code */
1834     public static final String DESKTOPFONTHINTS = "awt.font.desktophints";
1835 
1836     /* Overridden by subclasses to return platform/desktop specific values */
1837     protected RenderingHints getDesktopAAHints() {
1838         return null;
1839     }
1840 
1841     /* Subclass desktop property loading methods call this which
1842      * in turn calls the appropriate subclass implementation of
1843      * getDesktopAAHints() when system settings are being used.
1844      * Its public rather than protected because subclasses may delegate
1845      * to a helper class.
1846      */
1847     public static RenderingHints getDesktopFontHints() {
1848         if (useSystemAAFontSettings()) {
1849              Toolkit tk = Toolkit.getDefaultToolkit();
1850              if (tk instanceof SunToolkit) {
1851                  Object map = ((SunToolkit)tk).getDesktopAAHints();
1852                  return (RenderingHints)map;
1853              } else { /* Headless Toolkit */
1854                  return null;
1855              }
1856         } else if (desktopFontHints != null) {
1857             /* cloning not necessary as the return value is cloned later, but
1858              * its harmless.
1859              */
1860             return (RenderingHints)(desktopFontHints.clone());
1861         } else {
1862             return null;
1863         }
1864     }
1865 
1866 
1867     public abstract boolean isDesktopSupported();
1868 
1869     /*
1870      * consumeNextKeyTyped() method is not currently used,
1871      * however Swing could use it in the future.
1872      */
1873     public static synchronized void consumeNextKeyTyped(KeyEvent keyEvent) {
1874         try {
1875             AWTAccessor.getDefaultKeyboardFocusManagerAccessor().consumeNextKeyTyped(
1876                 (DefaultKeyboardFocusManager)KeyboardFocusManager.
1877                     getCurrentKeyboardFocusManager(),
1878                 keyEvent);
1879         } catch (ClassCastException cce) {
1880              cce.printStackTrace();
1881         }
1882     }
1883 
1884     protected static void dumpPeers(final PlatformLogger aLog) {
1885         AWTAutoShutdown.getInstance().dumpPeers(aLog);
1886     }
1887 
1888     /**
1889      * Returns the <code>Window</code> ancestor of the component <code>comp</code>.
1890      * @return Window ancestor of the component or component by itself if it is Window;
1891      *         null, if component is not a part of window hierarchy
1892      */
1893     public static Window getContainingWindow(Component comp) {
1894         while (comp != null && !(comp instanceof Window)) {
1895             comp = comp.getParent();
1896         }
1897         return (Window)comp;
1898     }
1899 
1900     private static Boolean sunAwtDisableMixing = null;
1901 
1902     /**
1903      * Returns the value of "sun.awt.disableMixing" property. Default
1904      * value is {@code false}.
1905      */
1906     public synchronized static boolean getSunAwtDisableMixing() {
1907         if (sunAwtDisableMixing == null) {
1908             sunAwtDisableMixing = AccessController.doPrivileged(
1909                                       new GetBooleanAction("sun.awt.disableMixing"));
1910         }
1911         return sunAwtDisableMixing.booleanValue();
1912     }
1913 
1914     /**
1915      * Returns true if the native GTK libraries are available.  The
1916      * default implementation returns false, but UNIXToolkit overrides this
1917      * method to provide a more specific answer.
1918      */
1919     public boolean isNativeGTKAvailable() {
1920         return false;
1921     }
1922 
1923     private static final Object DEACTIVATION_TIMES_MAP_KEY = new Object();
1924 
1925     public synchronized void setWindowDeactivationTime(Window w, long time) {
1926         AppContext ctx = getAppContext(w);
1927         WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY);
1928         if (map == null) {
1929             map = new WeakHashMap<Window, Long>();
1930             ctx.put(DEACTIVATION_TIMES_MAP_KEY, map);
1931         }
1932         map.put(w, time);
1933     }
1934 
1935     public synchronized long getWindowDeactivationTime(Window w) {
1936         AppContext ctx = getAppContext(w);
1937         WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY);
1938         if (map == null) {
1939             return -1;
1940         }
1941         Long time = map.get(w);
1942         return time == null ? -1 : time;
1943     }
1944 
1945     // Cosntant alpha
1946     public boolean isWindowOpacitySupported() {
1947         return false;
1948     }
1949 
1950     // Shaping
1951     public boolean isWindowShapingSupported() {
1952         return false;
1953     }
1954 
1955     // Per-pixel alpha
1956     public boolean isWindowTranslucencySupported() {
1957         return false;
1958     }
1959 
1960     public boolean isTranslucencyCapable(GraphicsConfiguration gc) {
1961         return false;
1962     }
1963 
1964     /**
1965      * Returns true if swing backbuffer should be translucent.
1966      */
1967     public boolean isSwingBackbufferTranslucencySupported() {
1968         return false;
1969     }
1970 
1971     /**
1972      * Returns whether or not a containing top level window for the passed
1973      * component is
1974      * {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT PERPIXEL_TRANSLUCENT}.
1975      *
1976      * @param c a Component which toplevel's to check
1977      * @return {@code true}  if the passed component is not null and has a
1978      * containing toplevel window which is opaque (so per-pixel translucency
1979      * is not enabled), {@code false} otherwise
1980      * @see GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
1981      */
1982     public static boolean isContainingTopLevelOpaque(Component c) {
1983         Window w = getContainingWindow(c);
1984         return w != null && w.isOpaque();
1985     }
1986 
1987     /**
1988      * Returns whether or not a containing top level window for the passed
1989      * component is
1990      * {@link GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}.
1991      *
1992      * @param c a Component which toplevel's to check
1993      * @return {@code true} if the passed component is not null and has a
1994      * containing toplevel window which has opacity less than
1995      * 1.0f (which means that it is translucent), {@code false} otherwise
1996      * @see GraphicsDevice.WindowTranslucency#TRANSLUCENT
1997      */
1998     public static boolean isContainingTopLevelTranslucent(Component c) {
1999         Window w = getContainingWindow(c);
2000         return w != null && w.getOpacity() < 1.0f;
2001     }
2002 
2003     /**
2004      * Returns whether the native system requires using the peer.updateWindow()
2005      * method to update the contents of a non-opaque window, or if usual
2006      * painting procedures are sufficient. The default return value covers
2007      * the X11 systems. On MS Windows this method is overriden in WToolkit
2008      * to return true.
2009      */
2010     public boolean needUpdateWindow() {
2011         return false;
2012     }
2013 
2014     /**
2015      * Descendants of the SunToolkit should override and put their own logic here.
2016      */
2017     public int getNumberOfButtons(){
2018         return 3;
2019     }
2020 
2021     /**
2022      * Checks that the given object implements/extends the given
2023      * interface/class.
2024      *
2025      * Note that using the instanceof operator causes a class to be loaded.
2026      * Using this method doesn't load a class and it can be used instead of
2027      * the instanceof operator for performance reasons.
2028      *
2029      * @param obj Object to be checked
2030      * @param type The name of the interface/class. Must be
2031      * fully-qualified interface/class name.
2032      * @return true, if this object implements/extends the given
2033      *         interface/class, false, otherwise, or if obj or type is null
2034      */
2035     public static boolean isInstanceOf(Object obj, String type) {
2036         if (obj == null) return false;
2037         if (type == null) return false;
2038 
2039         return isInstanceOf(obj.getClass(), type);
2040     }
2041 
2042     private static boolean isInstanceOf(Class<?> cls, String type) {
2043         if (cls == null) return false;
2044 
2045         if (cls.getName().equals(type)) {
2046             return true;
2047         }
2048 
2049         for (Class<?> c : cls.getInterfaces()) {
2050             if (c.getName().equals(type)) {
2051                 return true;
2052             }
2053         }
2054         return isInstanceOf(cls.getSuperclass(), type);
2055     }
2056 
2057     protected static LightweightFrame getLightweightFrame(Component c) {
2058         for (; c != null; c = c.getParent()) {
2059             if (c instanceof LightweightFrame) {
2060                 return (LightweightFrame)c;
2061             }
2062             if (c instanceof Window) {
2063                 // Don't traverse owner windows
2064                 return null;
2065             }
2066         }
2067         return null;
2068     }
2069 
2070     ///////////////////////////////////////////////////////////////////////////
2071     //
2072     // The following methods help set and identify whether a particular
2073     // AWTEvent object was produced by the system or by user code. As of this
2074     // writing the only consumer is the Java Plug-In, although this information
2075     // could be useful to more clients and probably should be formalized in
2076     // the public API.
2077     //
2078     ///////////////////////////////////////////////////////////////////////////
2079 
2080     public static void setSystemGenerated(AWTEvent e) {
2081         AWTAccessor.getAWTEventAccessor().setSystemGenerated(e);
2082     }
2083 
2084     public static boolean isSystemGenerated(AWTEvent e) {
2085         return AWTAccessor.getAWTEventAccessor().isSystemGenerated(e);
2086     }
2087 
2088 } // class SunToolkit
2089 
2090 
2091 /*
2092  * PostEventQueue is a Thread that runs in the same AppContext as the
2093  * Java EventQueue.  It is a queue of AWTEvents to be posted to the
2094  * Java EventQueue.  The toolkit Thread (AWT-Windows/AWT-Motif) posts
2095  * events to this queue, which then calls EventQueue.postEvent().
2096  *
2097  * We do this because EventQueue.postEvent() may be overridden by client
2098  * code, and we mustn't ever call client code from the toolkit thread.
2099  */
2100 class PostEventQueue {
2101     private EventQueueItem queueHead = null;
2102     private EventQueueItem queueTail = null;
2103     private final EventQueue eventQueue;
2104 
2105     private Thread flushThread = null;
2106 
2107     PostEventQueue(EventQueue eq) {
2108         eventQueue = eq;
2109     }
2110 
2111     /*
2112      * Continually post pending AWTEvents to the Java EventQueue. The method
2113      * is synchronized to ensure the flush is completed before a new event
2114      * can be posted to this queue.
2115      *
2116      * 7177040: The method couldn't be wholly synchronized because of calls
2117      * of EventQueue.postEvent() that uses pushPopLock, otherwise it could
2118      * potentially lead to deadlock
2119      */
2120     public void flush() {
2121 
2122         Thread newThread = Thread.currentThread();
2123 
2124         try {
2125             EventQueueItem tempQueue;
2126             synchronized (this) {
2127                 // Avoid method recursion
2128                 if (newThread == flushThread) {
2129                     return;
2130                 }
2131                 // Wait for other threads' flushing
2132                 while (flushThread != null) {
2133                     wait();
2134                 }
2135                 // Skip everything if queue is empty
2136                 if (queueHead == null) {
2137                     return;
2138                 }
2139                 // Remember flushing thread
2140                 flushThread = newThread;
2141 
2142                 tempQueue = queueHead;
2143                 queueHead = queueTail = null;
2144             }
2145             try {
2146                 while (tempQueue != null) {
2147                     eventQueue.postEvent(tempQueue.event);
2148                     tempQueue = tempQueue.next;
2149                 }
2150             }
2151             finally {
2152                 // Only the flushing thread can get here
2153                 synchronized (this) {
2154                     // Forget flushing thread, inform other pending threads
2155                     flushThread = null;
2156                     notifyAll();
2157                 }
2158             }
2159         }
2160         catch (InterruptedException e) {
2161             // Couldn't allow exception go up, so at least recover the flag
2162             newThread.interrupt();
2163         }
2164     }
2165 
2166     /*
2167      * Enqueue an AWTEvent to be posted to the Java EventQueue.
2168      */
2169     void postEvent(AWTEvent event) {
2170         EventQueueItem item = new EventQueueItem(event);
2171 
2172         synchronized (this) {
2173             if (queueHead == null) {
2174                 queueHead = queueTail = item;
2175             } else {
2176                 queueTail.next = item;
2177                 queueTail = item;
2178             }
2179         }
2180         SunToolkit.wakeupEventQueue(eventQueue, event.getSource() == AWTAutoShutdown.getInstance());
2181     }
2182 } // class PostEventQueue