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