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