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