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