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