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