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