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