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