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