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