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