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