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