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