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