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