1 /*
   2  * Copyright (c) 1995, 2019, 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 java.awt;
  27 
  28 import java.awt.datatransfer.Clipboard;
  29 import java.awt.dnd.DragGestureListener;
  30 import java.awt.dnd.DragGestureRecognizer;
  31 import java.awt.dnd.DragSource;
  32 import java.awt.event.AWTEventListener;
  33 import java.awt.event.AWTEventListenerProxy;
  34 import java.awt.event.ActionEvent;
  35 import java.awt.event.AdjustmentEvent;
  36 import java.awt.event.ComponentEvent;
  37 import java.awt.event.ContainerEvent;
  38 import java.awt.event.FocusEvent;
  39 import java.awt.event.HierarchyEvent;
  40 import java.awt.event.InputEvent;
  41 import java.awt.event.InputMethodEvent;
  42 import java.awt.event.InvocationEvent;
  43 import java.awt.event.ItemEvent;
  44 import java.awt.event.KeyEvent;
  45 import java.awt.event.MouseEvent;
  46 import java.awt.event.PaintEvent;
  47 import java.awt.event.TextEvent;
  48 import java.awt.event.WindowEvent;
  49 import java.awt.im.InputMethodHighlight;
  50 import java.awt.image.ColorModel;
  51 import java.awt.image.ImageObserver;
  52 import java.awt.image.ImageProducer;
  53 import java.beans.PropertyChangeEvent;
  54 import java.beans.PropertyChangeListener;
  55 import java.beans.PropertyChangeSupport;
  56 import java.io.File;
  57 import java.io.FileInputStream;
  58 import java.net.URL;
  59 import java.security.AccessController;
  60 import java.security.PrivilegedAction;
  61 import java.util.ArrayList;
  62 import java.util.Arrays;
  63 import java.util.EventListener;
  64 import java.util.HashMap;
  65 import java.util.Map;
  66 import java.util.MissingResourceException;
  67 import java.util.Properties;
  68 import java.util.ResourceBundle;
  69 import java.util.ServiceLoader;
  70 import java.util.Set;
  71 import java.util.WeakHashMap;
  72 import java.util.stream.Collectors;
  73 
  74 import javax.accessibility.AccessibilityProvider;
  75 
  76 import sun.awt.AWTAccessor;
  77 import sun.awt.AWTPermissions;
  78 import sun.awt.AppContext;
  79 import sun.awt.HeadlessToolkit;
  80 import sun.awt.PeerEvent;
  81 import sun.awt.SunToolkit;
  82 
  83 /**
  84  * This class is the abstract superclass of all actual
  85  * implementations of the Abstract Window Toolkit. Subclasses of
  86  * the {@code Toolkit} class are used to bind the various components
  87  * to particular native toolkit implementations.
  88  * <p>
  89  * Many GUI events may be delivered to user
  90  * asynchronously, if the opposite is not specified explicitly.
  91  * As well as
  92  * many GUI operations may be performed asynchronously.
  93  * This fact means that if the state of a component is set, and then
  94  * the state immediately queried, the returned value may not yet
  95  * reflect the requested change.  This behavior includes, but is not
  96  * limited to:
  97  * <ul>
  98  * <li>Scrolling to a specified position.
  99  * <br>For example, calling {@code ScrollPane.setScrollPosition}
 100  *     and then {@code getScrollPosition} may return an incorrect
 101  *     value if the original request has not yet been processed.
 102  *
 103  * <li>Moving the focus from one component to another.
 104  * <br>For more information, see
 105  * <a href="https://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html#transferTiming">Timing
 106  * Focus Transfers</a>, a section in
 107  * <a href="https://docs.oracle.com/javase/tutorial/uiswing/">The Swing
 108  * Tutorial</a>.
 109  *
 110  * <li>Making a top-level container visible.
 111  * <br>Calling {@code setVisible(true)} on a {@code Window},
 112  *     {@code Frame} or {@code Dialog} may occur
 113  *     asynchronously.
 114  *
 115  * <li>Setting the size or location of a top-level container.
 116  * <br>Calls to {@code setSize}, {@code setBounds} or
 117  *     {@code setLocation} on a {@code Window},
 118  *     {@code Frame} or {@code Dialog} are forwarded
 119  *     to the underlying window management system and may be
 120  *     ignored or modified.  See {@link java.awt.Window} for
 121  *     more information.
 122  * </ul>
 123  * <p>
 124  * Most applications should not call any of the methods in this
 125  * class directly. The methods defined by {@code Toolkit} are
 126  * the "glue" that joins the platform-independent classes in the
 127  * {@code java.awt} package with their counterparts in
 128  * {@code java.awt.peer}. Some methods defined by
 129  * {@code Toolkit} query the native operating system directly.
 130  *
 131  * @author      Sami Shaio
 132  * @author      Arthur van Hoff
 133  * @author      Fred Ecks
 134  * @since       1.0
 135  */
 136 public abstract class Toolkit {
 137 
 138     // The following method is called by the private method
 139     // <code>updateSystemColors</code> in <code>SystemColor</code>.
 140 
 141     /**
 142      * Fills in the integer array that is supplied as an argument
 143      * with the current system color values.
 144      *
 145      * @param     systemColors an integer array.
 146      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 147      * returns true
 148      * @see       java.awt.GraphicsEnvironment#isHeadless
 149      * @since     1.1
 150      */
 151     protected void loadSystemColors(int[] systemColors)
 152         throws HeadlessException {
 153         GraphicsEnvironment.checkHeadless();
 154     }
 155 
 156     /**
 157      * Controls whether the layout of Containers is validated dynamically
 158      * during resizing, or statically, after resizing is complete.
 159      * Use {@code isDynamicLayoutActive()} to detect if this feature enabled
 160      * in this program and is supported by this operating system
 161      * and/or window manager.
 162      * Note that this feature is supported not on all platforms, and
 163      * conversely, that this feature cannot be turned off on some platforms.
 164      * On these platforms where dynamic layout during resizing is not supported
 165      * (or is always supported), setting this property has no effect.
 166      * Note that this feature can be set or unset as a property of the
 167      * operating system or window manager on some platforms.  On such
 168      * platforms, the dynamic resize property must be set at the operating
 169      * system or window manager level before this method can take effect.
 170      * This method does not change support or settings of the underlying
 171      * operating system or
 172      * window manager.  The OS/WM support can be
 173      * queried using getDesktopProperty("awt.dynamicLayoutSupported") method.
 174      *
 175      * @param     dynamic  If true, Containers should re-layout their
 176      *            components as the Container is being resized.  If false,
 177      *            the layout will be validated after resizing is completed.
 178      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 179      *            returns true
 180      * @see       #isDynamicLayoutSet()
 181      * @see       #isDynamicLayoutActive()
 182      * @see       #getDesktopProperty(String propertyName)
 183      * @see       java.awt.GraphicsEnvironment#isHeadless
 184      * @since     1.4
 185      */
 186     public void setDynamicLayout(final boolean dynamic)
 187         throws HeadlessException {
 188         GraphicsEnvironment.checkHeadless();
 189         if (this != getDefaultToolkit()) {
 190             getDefaultToolkit().setDynamicLayout(dynamic);
 191         }
 192     }
 193 
 194     /**
 195      * Returns whether the layout of Containers is validated dynamically
 196      * during resizing, or statically, after resizing is complete.
 197      * Note: this method returns the value that was set programmatically;
 198      * it does not reflect support at the level of the operating system
 199      * or window manager for dynamic layout on resizing, or the current
 200      * operating system or window manager settings.  The OS/WM support can
 201      * be queried using getDesktopProperty("awt.dynamicLayoutSupported").
 202      *
 203      * @return    true if validation of Containers is done dynamically,
 204      *            false if validation is done after resizing is finished.
 205      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 206      *            returns true
 207      * @see       #setDynamicLayout(boolean dynamic)
 208      * @see       #isDynamicLayoutActive()
 209      * @see       #getDesktopProperty(String propertyName)
 210      * @see       java.awt.GraphicsEnvironment#isHeadless
 211      * @since     1.4
 212      */
 213     protected boolean isDynamicLayoutSet()
 214         throws HeadlessException {
 215         GraphicsEnvironment.checkHeadless();
 216 
 217         if (this != Toolkit.getDefaultToolkit()) {
 218             return Toolkit.getDefaultToolkit().isDynamicLayoutSet();
 219         } else {
 220             return false;
 221         }
 222     }
 223 
 224     /**
 225      * Returns whether dynamic layout of Containers on resize is currently
 226      * enabled on the underlying operating system and/or window manager. If the
 227      * platform supports it, {@code setDynamicLayout(boolean)} may be used to
 228      * programmatically enable or disable platform dynamic layout. Regardless of
 229      * whether that toggling is supported, or whether {@code true} or {@code
 230      * false} is specified as an argument, or has never been called at all, this
 231      * method will return the active current platform behavior and which will be
 232      * followed by the JDK in determining layout policy during resizing.
 233      * <p>
 234      * If dynamic layout is currently inactive then Containers re-layout their
 235      * components when resizing is completed. As a result the
 236      * {@code Component.validate()} method will be invoked only once per resize.
 237      * If dynamic layout is currently active then Containers re-layout their
 238      * components on every native resize event and the {@code validate()} method
 239      * will be invoked each time. The OS/WM support can be queried using the
 240      * getDesktopProperty("awt.dynamicLayoutSupported") method. This property
 241      * will reflect the platform capability but is not sufficient to tell if it
 242      * is presently enabled.
 243      *
 244      * @return true if dynamic layout of Containers on resize is currently
 245      *         active, false otherwise.
 246      * @throws HeadlessException if the GraphicsEnvironment.isHeadless() method
 247      *         returns true
 248      * @see #setDynamicLayout(boolean dynamic)
 249      * @see #isDynamicLayoutSet()
 250      * @see #getDesktopProperty(String propertyName)
 251      * @see java.awt.GraphicsEnvironment#isHeadless
 252      * @since 1.4
 253      */
 254     public boolean isDynamicLayoutActive()
 255         throws HeadlessException {
 256         GraphicsEnvironment.checkHeadless();
 257 
 258         if (this != Toolkit.getDefaultToolkit()) {
 259             return Toolkit.getDefaultToolkit().isDynamicLayoutActive();
 260         } else {
 261             return false;
 262         }
 263     }
 264 
 265     /**
 266      * Gets the size of the screen.  On systems with multiple displays, the
 267      * primary display is used.  Multi-screen aware display dimensions are
 268      * available from {@code GraphicsConfiguration} and
 269      * {@code GraphicsDevice}.
 270      * @return    the size of this toolkit's screen, in pixels.
 271      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 272      * returns true
 273      * @see       java.awt.GraphicsConfiguration#getBounds
 274      * @see       java.awt.GraphicsDevice#getDisplayMode
 275      * @see       java.awt.GraphicsEnvironment#isHeadless
 276      */
 277     public abstract Dimension getScreenSize()
 278         throws HeadlessException;
 279 
 280     /**
 281      * Returns the screen resolution in dots-per-inch.
 282      * @return    this toolkit's screen resolution, in dots-per-inch.
 283      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 284      * returns true
 285      * @see       java.awt.GraphicsEnvironment#isHeadless
 286      */
 287     public abstract int getScreenResolution()
 288         throws HeadlessException;
 289 
 290     /**
 291      * Gets the insets of the screen.
 292      * @param     gc a {@code GraphicsConfiguration}
 293      * @return    the insets of this toolkit's screen, in pixels.
 294      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 295      * returns true
 296      * @see       java.awt.GraphicsEnvironment#isHeadless
 297      * @since     1.4
 298      */
 299     public Insets getScreenInsets(GraphicsConfiguration gc)
 300         throws HeadlessException {
 301         GraphicsEnvironment.checkHeadless();
 302         if (this != Toolkit.getDefaultToolkit()) {
 303             return Toolkit.getDefaultToolkit().getScreenInsets(gc);
 304         } else {
 305             return new Insets(0, 0, 0, 0);
 306         }
 307     }
 308 
 309     /**
 310      * Determines the color model of this toolkit's screen.
 311      * <p>
 312      * {@code ColorModel} is an abstract class that
 313      * encapsulates the ability to translate between the
 314      * pixel values of an image and its red, green, blue,
 315      * and alpha components.
 316      * <p>
 317      * This toolkit method is called by the
 318      * {@code getColorModel} method
 319      * of the {@code Component} class.
 320      * @return    the color model of this toolkit's screen.
 321      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 322      * returns true
 323      * @see       java.awt.GraphicsEnvironment#isHeadless
 324      * @see       java.awt.image.ColorModel
 325      * @see       java.awt.Component#getColorModel
 326      */
 327     public abstract ColorModel getColorModel()
 328         throws HeadlessException;
 329 
 330     /**
 331      * Returns the names of the available fonts in this toolkit.<p>
 332      * For 1.1, the following font names are deprecated (the replacement
 333      * name follows):
 334      * <ul>
 335      * <li>TimesRoman (use Serif)
 336      * <li>Helvetica (use SansSerif)
 337      * <li>Courier (use Monospaced)
 338      * </ul><p>
 339      * The ZapfDingbats fontname is also deprecated in 1.1 but the characters
 340      * are defined in Unicode starting at 0x2700, and as of 1.1 Java supports
 341      * those characters.
 342      * @return    the names of the available fonts in this toolkit.
 343      * @deprecated see {@link java.awt.GraphicsEnvironment#getAvailableFontFamilyNames()}
 344      * @see java.awt.GraphicsEnvironment#getAvailableFontFamilyNames()
 345      */
 346     @Deprecated
 347     public abstract String[] getFontList();
 348 
 349     /**
 350      * Gets the screen device metrics for rendering of the font.
 351      * @param     font   a font
 352      * @return    the screen metrics of the specified font in this toolkit
 353      * @deprecated  As of JDK version 1.2, replaced by the {@code Font}
 354      *          method {@code getLineMetrics}.
 355      * @see java.awt.font.LineMetrics
 356      * @see java.awt.Font#getLineMetrics
 357      * @see java.awt.GraphicsEnvironment#getScreenDevices
 358      */
 359     @Deprecated
 360     public abstract FontMetrics getFontMetrics(Font font);
 361 
 362     /**
 363      * Synchronizes this toolkit's graphics state. Some window systems
 364      * may do buffering of graphics events.
 365      * <p>
 366      * This method ensures that the display is up-to-date. It is useful
 367      * for animation.
 368      */
 369     public abstract void sync();
 370 
 371     /**
 372      * The default toolkit.
 373      */
 374     private static Toolkit toolkit;
 375 
 376     /**
 377      * Used internally by the assistive technologies functions; set at
 378      * init time and used at load time
 379      */
 380     private static String atNames;
 381 
 382     /**
 383      * Initializes properties related to assistive technologies.
 384      * These properties are used both in the loadAssistiveProperties()
 385      * function below, as well as other classes in the jdk that depend
 386      * on the properties (such as the use of the screen_magnifier_present
 387      * property in Java2D hardware acceleration initialization).  The
 388      * initialization of the properties must be done before the platform-
 389      * specific Toolkit class is instantiated so that all necessary
 390      * properties are set up properly before any classes dependent upon them
 391      * are initialized.
 392      */
 393     private static void initAssistiveTechnologies() {
 394 
 395         // Get accessibility properties
 396         final String sep = File.separator;
 397         final Properties properties = new Properties();
 398 
 399 
 400         atNames = java.security.AccessController.doPrivileged(
 401             new java.security.PrivilegedAction<String>() {
 402             public String run() {
 403 
 404                 // Try loading the per-user accessibility properties file.
 405                 try {
 406                     File propsFile = new File(
 407                       System.getProperty("user.home") +
 408                       sep + ".accessibility.properties");
 409                     FileInputStream in =
 410                         new FileInputStream(propsFile);
 411 
 412                     // Inputstream has been buffered in Properties class
 413                     properties.load(in);
 414                     in.close();
 415                 } catch (Exception e) {
 416                     // Per-user accessibility properties file does not exist
 417                 }
 418 
 419                 // Try loading the system-wide accessibility properties
 420                 // file only if a per-user accessibility properties
 421                 // file does not exist or is empty.
 422                 if (properties.size() == 0) {
 423                     try {
 424                         File propsFile = new File(
 425                             System.getProperty("java.home") + sep + "conf" +
 426                             sep + "accessibility.properties");
 427                         FileInputStream in =
 428                             new FileInputStream(propsFile);
 429 
 430                         // Inputstream has been buffered in Properties class
 431                         properties.load(in);
 432                         in.close();
 433                     } catch (Exception e) {
 434                         // System-wide accessibility properties file does
 435                         // not exist;
 436                     }
 437                 }
 438 
 439                 // Get whether a screen magnifier is present.  First check
 440                 // the system property and then check the properties file.
 441                 String magPresent = System.getProperty("javax.accessibility.screen_magnifier_present");
 442                 if (magPresent == null) {
 443                     magPresent = properties.getProperty("screen_magnifier_present", null);
 444                     if (magPresent != null) {
 445                         System.setProperty("javax.accessibility.screen_magnifier_present", magPresent);
 446                     }
 447                 }
 448 
 449                 // Get the names of any assistive technologies to load.  First
 450                 // check the system property and then check the properties
 451                 // file.
 452                 String classNames = System.getProperty("javax.accessibility.assistive_technologies");
 453                 if (classNames == null) {
 454                     classNames = properties.getProperty("assistive_technologies", null);
 455                     if (classNames != null) {
 456                         System.setProperty("javax.accessibility.assistive_technologies", classNames);
 457                     }
 458                 }
 459                 return classNames;
 460             }
 461         });
 462     }
 463 
 464     /**
 465      * Rethrow the AWTError but include the cause.
 466      *
 467      * @param s the error message
 468      * @param e the original exception
 469      * @throws AWTError the new AWTError including the cause (the original exception)
 470      */
 471     private static void newAWTError(Throwable e, String s) {
 472         AWTError newAWTError = new AWTError(s);
 473         newAWTError.initCause(e);
 474         throw newAWTError;
 475     }
 476 
 477     /**
 478      * When a service provider for Assistive Technology is not found look for a
 479      * supporting class on the class path and instantiate it.
 480      *
 481      * @param atName the name of the class to be loaded
 482      */
 483     private static void fallbackToLoadClassForAT(String atName) {
 484         try {
 485             Class<?> c = Class.forName(atName, false, ClassLoader.getSystemClassLoader());
 486             c.getConstructor().newInstance();
 487         } catch (ClassNotFoundException e) {
 488             newAWTError(e, "Assistive Technology not found: " + atName);
 489         } catch (InstantiationException e) {
 490             newAWTError(e, "Could not instantiate Assistive Technology: " + atName);
 491         } catch (IllegalAccessException e) {
 492             newAWTError(e, "Could not access Assistive Technology: " + atName);
 493         } catch (Exception e) {
 494             newAWTError(e, "Error trying to install Assistive Technology: " + atName);
 495         }
 496     }
 497 
 498     /**
 499      * Loads accessibility support using the property assistive_technologies.
 500      * The form is assistive_technologies= followed by a comma-separated list of
 501      * assistive technology providers to load.  The order in which providers are
 502      * loaded is determined by the order in which the ServiceLoader discovers
 503      * implementations of the AccessibilityProvider interface, not by the order
 504      * of provider names in the property list.  When a provider is found its
 505      * accessibility implementation will be started by calling the provider's
 506      * activate method.  If the list of assistive technology providers is empty string,
 507      * or contains only white space characters or null then the method returns immediately.
 508      * All other errors are handled via an AWTError exception.
 509      */
 510     private static void loadAssistiveTechnologies() {
 511         // Load any assistive technologies
 512         if (atNames != null && !atNames.trim().isEmpty()) {
 513             ClassLoader cl = ClassLoader.getSystemClassLoader();
 514             Set<String> names = Arrays.stream(atNames.split(","))
 515                                         .map(String::trim)
 516                                         .collect(Collectors.toSet());
 517             final Map<String, AccessibilityProvider> providers = new HashMap<>();
 518             AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 519                 try {
 520                     for (AccessibilityProvider p : ServiceLoader.load(AccessibilityProvider.class, cl)) {
 521                         String name = p.getName();
 522                         if (names.contains(name) && !providers.containsKey(name)) {
 523                             p.activate();
 524                             providers.put(name, p);
 525                         }
 526                     }
 527                 } catch (java.util.ServiceConfigurationError | Exception e) {
 528                     newAWTError(e, "Could not load or activate service provider");
 529                 }
 530                 return null;
 531             });
 532             names.stream()
 533                     .filter(n -> !providers.containsKey(n))
 534                     .forEach(Toolkit::fallbackToLoadClassForAT);
 535         }
 536     }
 537 
 538     /**
 539      * Gets the default toolkit.
 540      * <p>
 541      * If a system property named {@code "java.awt.headless"} is set
 542      * to {@code true} then the headless implementation
 543      * of {@code Toolkit} is used,
 544      * otherwise the default platform-specific implementation of
 545      * {@code Toolkit} is used.
 546      * <p>
 547      * If this Toolkit is not a headless implementation and if they exist, service
 548      * providers of {@link javax.accessibility.AccessibilityProvider} will be loaded
 549      * if specified by the system property
 550      * {@code javax.accessibility.assistive_technologies}.
 551      * <p>
 552      * An example of setting this property is to invoke Java with
 553      * {@code -Djavax.accessibility.assistive_technologies=MyServiceProvider}.
 554      * In addition to MyServiceProvider other service providers can be specified
 555      * using a comma separated list.  Service providers are loaded after the AWT
 556      * toolkit is created. All errors are handled via an AWTError exception.
 557      * <p>
 558      * The names specified in the assistive_technologies property are used to query
 559      * each service provider implementation.  If the requested name matches the
 560      * {@linkplain AccessibilityProvider#getName name} of the service provider, the
 561      * {@link AccessibilityProvider#activate} method will be invoked to activate the
 562      * matching service provider.
 563      *
 564      * @implSpec
 565      * If assistive technology service providers are not specified with a system
 566      * property this implementation will look in a properties file located as follows:
 567      * <ul>
 568      * <li> {@code ${user.home}/.accessibility.properties}
 569      * <li> {@code ${java.home}/conf/accessibility.properties}
 570      * </ul>
 571      * Only the first of these files to be located will be consulted.  The requested
 572      * service providers are specified by setting the {@code assistive_technologies=}
 573      * property.  A single provider or a comma separated list of providers can be
 574      * specified.
 575      *
 576      * @return     the default toolkit.
 577      * @exception  AWTError  if a toolkit could not be found, or
 578      *                 if one could not be accessed or instantiated.
 579      * @see java.util.ServiceLoader
 580      * @see javax.accessibility.AccessibilityProvider
 581      */
 582     public static synchronized Toolkit getDefaultToolkit() {
 583         if (toolkit == null) {
 584             java.security.AccessController.doPrivileged(
 585                     new java.security.PrivilegedAction<Void>() {
 586                 public Void run() {
 587                     Class<?> cls = null;
 588                     String nm = System.getProperty("awt.toolkit");
 589                     try {
 590                         cls = Class.forName(nm);
 591                     } catch (ClassNotFoundException e) {
 592                         ClassLoader cl = ClassLoader.getSystemClassLoader();
 593                         if (cl != null) {
 594                             try {
 595                                 cls = cl.loadClass(nm);
 596                             } catch (final ClassNotFoundException ignored) {
 597                                 throw new AWTError("Toolkit not found: " + nm);
 598                             }
 599                         }
 600                     }
 601                     try {
 602                         if (cls != null) {
 603                             toolkit = (Toolkit)cls.getConstructor().newInstance();
 604                             if (GraphicsEnvironment.isHeadless()) {
 605                                 toolkit = new HeadlessToolkit(toolkit);
 606                             }
 607                         }
 608                     } catch (final ReflectiveOperationException ignored) {
 609                         throw new AWTError("Could not create Toolkit: " + nm);
 610                     }
 611                     return null;
 612                 }
 613             });
 614             if (!GraphicsEnvironment.isHeadless()) {
 615                 loadAssistiveTechnologies();
 616             }
 617         }
 618         return toolkit;
 619     }
 620 
 621     /**
 622      * Returns an image which gets pixel data from the specified file,
 623      * whose format can be either GIF, JPEG or PNG.
 624      * The underlying toolkit attempts to resolve multiple requests
 625      * with the same filename to the same returned Image.
 626      * <p>
 627      * Since the mechanism required to facilitate this sharing of
 628      * {@code Image} objects may continue to hold onto images
 629      * that are no longer in use for an indefinite period of time,
 630      * developers are encouraged to implement their own caching of
 631      * images by using the {@link #createImage(java.lang.String) createImage}
 632      * variant wherever available.
 633      * If the image data contained in the specified file changes,
 634      * the {@code Image} object returned from this method may
 635      * still contain stale information which was loaded from the
 636      * file after a prior call.
 637      * Previously loaded image data can be manually discarded by
 638      * calling the {@link Image#flush flush} method on the
 639      * returned {@code Image}.
 640      * <p>
 641      * This method first checks if there is a security manager installed.
 642      * If so, the method calls the security manager's
 643      * {@code checkRead} method with the file specified to ensure
 644      * that the access to the image is allowed.
 645      * @param     filename   the name of a file containing pixel data
 646      *                         in a recognized file format.
 647      * @return    an image which gets its pixel data from
 648      *                         the specified file.
 649      * @throws SecurityException  if a security manager exists and its
 650      *                            checkRead method doesn't allow the operation.
 651      * @see #createImage(java.lang.String)
 652      */
 653     public abstract Image getImage(String filename);
 654 
 655     /**
 656      * Returns an image which gets pixel data from the specified URL.
 657      * The pixel data referenced by the specified URL must be in one
 658      * of the following formats: GIF, JPEG or PNG.
 659      * The underlying toolkit attempts to resolve multiple requests
 660      * with the same URL to the same returned Image.
 661      * <p>
 662      * Since the mechanism required to facilitate this sharing of
 663      * {@code Image} objects may continue to hold onto images
 664      * that are no longer in use for an indefinite period of time,
 665      * developers are encouraged to implement their own caching of
 666      * images by using the {@link #createImage(java.net.URL) createImage}
 667      * variant wherever available.
 668      * If the image data stored at the specified URL changes,
 669      * the {@code Image} object returned from this method may
 670      * still contain stale information which was fetched from the
 671      * URL after a prior call.
 672      * Previously loaded image data can be manually discarded by
 673      * calling the {@link Image#flush flush} method on the
 674      * returned {@code Image}.
 675      * <p>
 676      * This method first checks if there is a security manager installed.
 677      * If so, the method calls the security manager's
 678      * {@code checkPermission} method with the corresponding
 679      * permission to ensure that the access to the image is allowed.
 680      * If the connection to the specified URL requires
 681      * either {@code URLPermission} or {@code SocketPermission},
 682      * then {@code URLPermission} is used for security checks.
 683      * @param     url   the URL to use in fetching the pixel data.
 684      * @return    an image which gets its pixel data from
 685      *                         the specified URL.
 686      * @throws SecurityException  if a security manager exists and its
 687      *                            checkPermission method doesn't allow
 688      *                            the operation.
 689      * @see #createImage(java.net.URL)
 690      */
 691     public abstract Image getImage(URL url);
 692 
 693     /**
 694      * Returns an image which gets pixel data from the specified file.
 695      * The returned Image is a new object which will not be shared
 696      * with any other caller of this method or its getImage variant.
 697      * <p>
 698      * This method first checks if there is a security manager installed.
 699      * If so, the method calls the security manager's
 700      * {@code checkRead} method with the specified file to ensure
 701      * that the image creation is allowed.
 702      * @param     filename   the name of a file containing pixel data
 703      *                         in a recognized file format.
 704      * @return    an image which gets its pixel data from
 705      *                         the specified file.
 706      * @throws SecurityException  if a security manager exists and its
 707      *                            checkRead method doesn't allow the operation.
 708      * @see #getImage(java.lang.String)
 709      */
 710     public abstract Image createImage(String filename);
 711 
 712     /**
 713      * Returns an image which gets pixel data from the specified URL.
 714      * The returned Image is a new object which will not be shared
 715      * with any other caller of this method or its getImage variant.
 716      * <p>
 717      * This method first checks if there is a security manager installed.
 718      * If so, the method calls the security manager's
 719      * {@code checkPermission} method with the corresponding
 720      * permission to ensure that the image creation is allowed.
 721      * If the connection to the specified URL requires
 722      * either {@code URLPermission} or {@code SocketPermission},
 723      * then {@code URLPermission} is used for security checks.
 724      * @param     url   the URL to use in fetching the pixel data.
 725      * @return    an image which gets its pixel data from
 726      *                         the specified URL.
 727      * @throws SecurityException  if a security manager exists and its
 728      *                            checkPermission method doesn't allow
 729      *                            the operation.
 730      * @see #getImage(java.net.URL)
 731      */
 732     public abstract Image createImage(URL url);
 733 
 734     /**
 735      * Prepares an image for rendering.
 736      * <p>
 737      * If the values of the width and height arguments are both
 738      * {@code -1}, this method prepares the image for rendering
 739      * on the default screen; otherwise, this method prepares an image
 740      * for rendering on the default screen at the specified width and height.
 741      * <p>
 742      * The image data is downloaded asynchronously in another thread,
 743      * and an appropriately scaled screen representation of the image is
 744      * generated.
 745      * <p>
 746      * This method is called by components {@code prepareImage}
 747      * methods.
 748      * <p>
 749      * Information on the flags returned by this method can be found
 750      * with the definition of the {@code ImageObserver} interface.
 751 
 752      * @param     image      the image for which to prepare a
 753      *                           screen representation.
 754      * @param     width      the width of the desired screen
 755      *                           representation, or {@code -1}.
 756      * @param     height     the height of the desired screen
 757      *                           representation, or {@code -1}.
 758      * @param     observer   the {@code ImageObserver}
 759      *                           object to be notified as the
 760      *                           image is being prepared.
 761      * @return    {@code true} if the image has already been
 762      *                 fully prepared; {@code false} otherwise.
 763      * @see       java.awt.Component#prepareImage(java.awt.Image,
 764      *                 java.awt.image.ImageObserver)
 765      * @see       java.awt.Component#prepareImage(java.awt.Image,
 766      *                 int, int, java.awt.image.ImageObserver)
 767      * @see       java.awt.image.ImageObserver
 768      */
 769     public abstract boolean prepareImage(Image image, int width, int height,
 770                                          ImageObserver observer);
 771 
 772     /**
 773      * Indicates the construction status of a specified image that is
 774      * being prepared for display.
 775      * <p>
 776      * If the values of the width and height arguments are both
 777      * {@code -1}, this method returns the construction status of
 778      * a screen representation of the specified image in this toolkit.
 779      * Otherwise, this method returns the construction status of a
 780      * scaled representation of the image at the specified width
 781      * and height.
 782      * <p>
 783      * This method does not cause the image to begin loading.
 784      * An application must call {@code prepareImage} to force
 785      * the loading of an image.
 786      * <p>
 787      * This method is called by the component's {@code checkImage}
 788      * methods.
 789      * <p>
 790      * Information on the flags returned by this method can be found
 791      * with the definition of the {@code ImageObserver} interface.
 792      * @param     image   the image whose status is being checked.
 793      * @param     width   the width of the scaled version whose status is
 794      *                 being checked, or {@code -1}.
 795      * @param     height  the height of the scaled version whose status
 796      *                 is being checked, or {@code -1}.
 797      * @param     observer   the {@code ImageObserver} object to be
 798      *                 notified as the image is being prepared.
 799      * @return    the bitwise inclusive <strong>OR</strong> of the
 800      *                 {@code ImageObserver} flags for the
 801      *                 image data that is currently available.
 802      * @see       java.awt.Toolkit#prepareImage(java.awt.Image,
 803      *                 int, int, java.awt.image.ImageObserver)
 804      * @see       java.awt.Component#checkImage(java.awt.Image,
 805      *                 java.awt.image.ImageObserver)
 806      * @see       java.awt.Component#checkImage(java.awt.Image,
 807      *                 int, int, java.awt.image.ImageObserver)
 808      * @see       java.awt.image.ImageObserver
 809      */
 810     public abstract int checkImage(Image image, int width, int height,
 811                                    ImageObserver observer);
 812 
 813     /**
 814      * Creates an image with the specified image producer.
 815      * @param     producer the image producer to be used.
 816      * @return    an image with the specified image producer.
 817      * @see       java.awt.Image
 818      * @see       java.awt.image.ImageProducer
 819      * @see       java.awt.Component#createImage(java.awt.image.ImageProducer)
 820      */
 821     public abstract Image createImage(ImageProducer producer);
 822 
 823     /**
 824      * Creates an image which decodes the image stored in the specified
 825      * byte array.
 826      * <p>
 827      * The data must be in some image format, such as GIF or JPEG,
 828      * that is supported by this toolkit.
 829      * @param     imagedata   an array of bytes, representing
 830      *                         image data in a supported image format.
 831      * @return    an image.
 832      * @since     1.1
 833      */
 834     public Image createImage(byte[] imagedata) {
 835         return createImage(imagedata, 0, imagedata.length);
 836     }
 837 
 838     /**
 839      * Creates an image which decodes the image stored in the specified
 840      * byte array, and at the specified offset and length.
 841      * The data must be in some image format, such as GIF or JPEG,
 842      * that is supported by this toolkit.
 843      * @param     imagedata   an array of bytes, representing
 844      *                         image data in a supported image format.
 845      * @param     imageoffset  the offset of the beginning
 846      *                         of the data in the array.
 847      * @param     imagelength  the length of the data in the array.
 848      * @return    an image.
 849      * @since     1.1
 850      */
 851     public abstract Image createImage(byte[] imagedata,
 852                                       int imageoffset,
 853                                       int imagelength);
 854 
 855     /**
 856      * Gets a {@code PrintJob} object which is the result of initiating
 857      * a print operation on the toolkit's platform.
 858      * <p>
 859      * Each actual implementation of this method should first check if there
 860      * is a security manager installed. If there is, the method should call
 861      * the security manager's {@code checkPrintJobAccess} method to
 862      * ensure initiation of a print operation is allowed. If the default
 863      * implementation of {@code checkPrintJobAccess} is used (that is,
 864      * that method is not overriden), then this results in a call to the
 865      * security manager's {@code checkPermission} method with a
 866      * {@code RuntimePermission("queuePrintJob")} permission.
 867      *
 868      * @param   frame the parent of the print dialog. May not be null.
 869      * @param   jobtitle the title of the PrintJob. A null title is equivalent
 870      *          to "".
 871      * @param   props a Properties object containing zero or more properties.
 872      *          Properties are not standardized and are not consistent across
 873      *          implementations. Because of this, PrintJobs which require job
 874      *          and page control should use the version of this function which
 875      *          takes JobAttributes and PageAttributes objects. This object
 876      *          may be updated to reflect the user's job choices on exit. May
 877      *          be null.
 878      * @return  a {@code PrintJob} object, or {@code null} if the
 879      *          user cancelled the print job.
 880      * @throws  NullPointerException if frame is null
 881      * @throws  SecurityException if this thread is not allowed to initiate a
 882      *          print job request
 883      * @see     java.awt.GraphicsEnvironment#isHeadless
 884      * @see     java.awt.PrintJob
 885      * @see     java.lang.RuntimePermission
 886      * @since   1.1
 887      */
 888     public abstract PrintJob getPrintJob(Frame frame, String jobtitle,
 889                                          Properties props);
 890 
 891     /**
 892      * Gets a {@code PrintJob} object which is the result of initiating
 893      * a print operation on the toolkit's platform.
 894      * <p>
 895      * Each actual implementation of this method should first check if there
 896      * is a security manager installed. If there is, the method should call
 897      * the security manager's {@code checkPrintJobAccess} method to
 898      * ensure initiation of a print operation is allowed. If the default
 899      * implementation of {@code checkPrintJobAccess} is used (that is,
 900      * that method is not overriden), then this results in a call to the
 901      * security manager's {@code checkPermission} method with a
 902      * {@code RuntimePermission("queuePrintJob")} permission.
 903      *
 904      * @param   frame the parent of the print dialog. May not be null.
 905      * @param   jobtitle the title of the PrintJob. A null title is equivalent
 906      *          to "".
 907      * @param   jobAttributes a set of job attributes which will control the
 908      *          PrintJob. The attributes will be updated to reflect the user's
 909      *          choices as outlined in the JobAttributes documentation. May be
 910      *          null.
 911      * @param   pageAttributes a set of page attributes which will control the
 912      *          PrintJob. The attributes will be applied to every page in the
 913      *          job. The attributes will be updated to reflect the user's
 914      *          choices as outlined in the PageAttributes documentation. May be
 915      *          null.
 916      * @return  a {@code PrintJob} object, or {@code null} if the
 917      *          user cancelled the print job.
 918      * @throws  NullPointerException if frame is null
 919      * @throws  IllegalArgumentException if pageAttributes specifies differing
 920      *          cross feed and feed resolutions. Also if this thread has
 921      *          access to the file system and jobAttributes specifies
 922      *          print to file, and the specified destination file exists but
 923      *          is a directory rather than a regular file, does not exist but
 924      *          cannot be created, or cannot be opened for any other reason.
 925      *          However in the case of print to file, if a dialog is also
 926      *          requested to be displayed then the user will be given an
 927      *          opportunity to select a file and proceed with printing.
 928      *          The dialog will ensure that the selected output file
 929      *          is valid before returning from this method.
 930      * @throws  SecurityException if this thread is not allowed to initiate a
 931      *          print job request, or if jobAttributes specifies print to file,
 932      *          and this thread is not allowed to access the file system
 933      * @see     java.awt.PrintJob
 934      * @see     java.awt.GraphicsEnvironment#isHeadless
 935      * @see     java.lang.RuntimePermission
 936      * @see     java.awt.JobAttributes
 937      * @see     java.awt.PageAttributes
 938      * @since   1.3
 939      */
 940     public PrintJob getPrintJob(Frame frame, String jobtitle,
 941                                 JobAttributes jobAttributes,
 942                                 PageAttributes pageAttributes) {
 943         // Override to add printing support with new job/page control classes
 944 
 945         if (this != Toolkit.getDefaultToolkit()) {
 946             return Toolkit.getDefaultToolkit().getPrintJob(frame, jobtitle,
 947                                                            jobAttributes,
 948                                                            pageAttributes);
 949         } else {
 950             return getPrintJob(frame, jobtitle, null);
 951         }
 952     }
 953 
 954     /**
 955      * Emits an audio beep depending on native system settings and hardware
 956      * capabilities.
 957      * @since     1.1
 958      */
 959     public abstract void beep();
 960 
 961     /**
 962      * Gets the singleton instance of the system Clipboard which interfaces
 963      * with clipboard facilities provided by the native platform. This
 964      * clipboard enables data transfer between Java programs and native
 965      * applications which use native clipboard facilities.
 966      * <p>
 967      * In addition to any and all default formats text returned by the system
 968      * Clipboard's {@code getTransferData()} method is available in the
 969      * following flavors:
 970      * <ul>
 971      * <li>DataFlavor.stringFlavor</li>
 972      * <li>DataFlavor.plainTextFlavor (<b>deprecated</b>)</li>
 973      * </ul>
 974      * As with {@code java.awt.datatransfer.StringSelection}, if the
 975      * requested flavor is {@code DataFlavor.plainTextFlavor}, or an
 976      * equivalent flavor, a Reader is returned. <b>Note:</b> The behavior of
 977      * the system Clipboard's {@code getTransferData()} method for
 978      * {@code DataFlavor.plainTextFlavor}, and equivalent DataFlavors, is
 979      * inconsistent with the definition of {@code DataFlavor.plainTextFlavor}.
 980      * Because of this, support for
 981      * {@code DataFlavor.plainTextFlavor}, and equivalent flavors, is
 982      * <b>deprecated</b>.
 983      * <p>
 984      * Each actual implementation of this method should first check if there
 985      * is a security manager installed. If there is, the method should call
 986      * the security manager's {@link SecurityManager#checkPermission
 987      * checkPermission} method to check {@code AWTPermission("accessClipboard")}.
 988      *
 989      * @return    the system Clipboard
 990      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
 991      * returns true
 992      * @see       java.awt.GraphicsEnvironment#isHeadless
 993      * @see       java.awt.datatransfer.Clipboard
 994      * @see       java.awt.datatransfer.StringSelection
 995      * @see       java.awt.datatransfer.DataFlavor#stringFlavor
 996      * @see       java.awt.datatransfer.DataFlavor#plainTextFlavor
 997      * @see       java.io.Reader
 998      * @see       java.awt.AWTPermission
 999      * @since     1.1
1000      */
1001     public abstract Clipboard getSystemClipboard()
1002         throws HeadlessException;
1003 
1004     /**
1005      * Gets the singleton instance of the system selection as a
1006      * {@code Clipboard} object. This allows an application to read and
1007      * modify the current, system-wide selection.
1008      * <p>
1009      * An application is responsible for updating the system selection whenever
1010      * the user selects text, using either the mouse or the keyboard.
1011      * Typically, this is implemented by installing a
1012      * {@code FocusListener} on all {@code Component}s which support
1013      * text selection, and, between {@code FOCUS_GAINED} and
1014      * {@code FOCUS_LOST} events delivered to that {@code Component},
1015      * updating the system selection {@code Clipboard} when the selection
1016      * changes inside the {@code Component}. Properly updating the system
1017      * selection ensures that a Java application will interact correctly with
1018      * native applications and other Java applications running simultaneously
1019      * on the system. Note that {@code java.awt.TextComponent} and
1020      * {@code javax.swing.text.JTextComponent} already adhere to this
1021      * policy. When using these classes, and their subclasses, developers need
1022      * not write any additional code.
1023      * <p>
1024      * Some platforms do not support a system selection {@code Clipboard}.
1025      * On those platforms, this method will return {@code null}. In such a
1026      * case, an application is absolved from its responsibility to update the
1027      * system selection {@code Clipboard} as described above.
1028      * <p>
1029      * Each actual implementation of this method should first check if there
1030      * is a security manager installed. If there is, the method should call
1031      * the security manager's {@link SecurityManager#checkPermission
1032      * checkPermission} method to check {@code AWTPermission("accessClipboard")}.
1033      *
1034      * @return the system selection as a {@code Clipboard}, or
1035      *         {@code null} if the native platform does not support a
1036      *         system selection {@code Clipboard}
1037      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1038      *            returns true
1039      *
1040      * @see java.awt.datatransfer.Clipboard
1041      * @see java.awt.event.FocusListener
1042      * @see java.awt.event.FocusEvent#FOCUS_GAINED
1043      * @see java.awt.event.FocusEvent#FOCUS_LOST
1044      * @see TextComponent
1045      * @see javax.swing.text.JTextComponent
1046      * @see AWTPermission
1047      * @see GraphicsEnvironment#isHeadless
1048      * @since 1.4
1049      */
1050     public Clipboard getSystemSelection() throws HeadlessException {
1051         GraphicsEnvironment.checkHeadless();
1052 
1053         if (this != Toolkit.getDefaultToolkit()) {
1054             return Toolkit.getDefaultToolkit().getSystemSelection();
1055         } else {
1056             GraphicsEnvironment.checkHeadless();
1057             return null;
1058         }
1059     }
1060 
1061     /**
1062      * Determines which modifier key is the appropriate accelerator
1063      * key for menu shortcuts.
1064      * <p>
1065      * Menu shortcuts, which are embodied in the
1066      * {@code MenuShortcut} class, are handled by the
1067      * {@code MenuBar} class.
1068      * <p>
1069      * By default, this method returns {@code Event.CTRL_MASK}.
1070      * Toolkit implementations should override this method if the
1071      * <b>Control</b> key isn't the correct key for accelerators.
1072      * @return    the modifier mask on the {@code Event} class
1073      *                 that is used for menu shortcuts on this toolkit.
1074      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1075      * returns true
1076      * @see       java.awt.GraphicsEnvironment#isHeadless
1077      * @see       java.awt.MenuBar
1078      * @see       java.awt.MenuShortcut
1079      * @deprecated It is recommended that extended modifier keys and
1080      *             {@link #getMenuShortcutKeyMaskEx()} be used instead
1081      * @since     1.1
1082      */
1083     @Deprecated(since = "10")
1084     public int getMenuShortcutKeyMask() throws HeadlessException {
1085         GraphicsEnvironment.checkHeadless();
1086 
1087         return Event.CTRL_MASK;
1088     }
1089 
1090     /**
1091      * Determines which extended modifier key is the appropriate accelerator
1092      * key for menu shortcuts.
1093      * <p>
1094      * Menu shortcuts, which are embodied in the {@code MenuShortcut} class, are
1095      * handled by the {@code MenuBar} class.
1096      * <p>
1097      * By default, this method returns {@code InputEvent.CTRL_DOWN_MASK}.
1098      * Toolkit implementations should override this method if the
1099      * <b>Control</b> key isn't the correct key for accelerators.
1100      *
1101      * @return the modifier mask on the {@code InputEvent} class that is used
1102      *         for menu shortcuts on this toolkit
1103      * @throws HeadlessException if GraphicsEnvironment.isHeadless() returns
1104      *         true
1105      * @see java.awt.GraphicsEnvironment#isHeadless
1106      * @see java.awt.MenuBar
1107      * @see java.awt.MenuShortcut
1108      * @since 10
1109      */
1110     public int getMenuShortcutKeyMaskEx() throws HeadlessException {
1111         GraphicsEnvironment.checkHeadless();
1112 
1113         return InputEvent.CTRL_DOWN_MASK;
1114     }
1115 
1116     /**
1117      * Returns whether the given locking key on the keyboard is currently in
1118      * its "on" state.
1119      * Valid key codes are
1120      * {@link java.awt.event.KeyEvent#VK_CAPS_LOCK VK_CAPS_LOCK},
1121      * {@link java.awt.event.KeyEvent#VK_NUM_LOCK VK_NUM_LOCK},
1122      * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and
1123      * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}.
1124      *
1125      * @param  keyCode the key code
1126      * @return {@code true} if the given key is currently in its "on" state;
1127      *          otherwise {@code false}
1128      * @exception java.lang.IllegalArgumentException if {@code keyCode}
1129      * is not one of the valid key codes
1130      * @exception java.lang.UnsupportedOperationException if the host system doesn't
1131      * allow getting the state of this key programmatically, or if the keyboard
1132      * doesn't have this key
1133      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1134      * returns true
1135      * @see       java.awt.GraphicsEnvironment#isHeadless
1136      * @since 1.3
1137      */
1138     public boolean getLockingKeyState(int keyCode)
1139         throws UnsupportedOperationException
1140     {
1141         GraphicsEnvironment.checkHeadless();
1142 
1143         if (! (keyCode == KeyEvent.VK_CAPS_LOCK || keyCode == KeyEvent.VK_NUM_LOCK ||
1144                keyCode == KeyEvent.VK_SCROLL_LOCK || keyCode == KeyEvent.VK_KANA_LOCK)) {
1145             throw new IllegalArgumentException("invalid key for Toolkit.getLockingKeyState");
1146         }
1147         throw new UnsupportedOperationException("Toolkit.getLockingKeyState");
1148     }
1149 
1150     /**
1151      * Sets the state of the given locking key on the keyboard.
1152      * Valid key codes are
1153      * {@link java.awt.event.KeyEvent#VK_CAPS_LOCK VK_CAPS_LOCK},
1154      * {@link java.awt.event.KeyEvent#VK_NUM_LOCK VK_NUM_LOCK},
1155      * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and
1156      * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}.
1157      * <p>
1158      * Depending on the platform, setting the state of a locking key may
1159      * involve event processing and therefore may not be immediately
1160      * observable through getLockingKeyState.
1161      *
1162      * @param  keyCode the key code
1163      * @param  on the state of the key
1164      * @exception java.lang.IllegalArgumentException if {@code keyCode}
1165      * is not one of the valid key codes
1166      * @exception java.lang.UnsupportedOperationException if the host system doesn't
1167      * allow setting the state of this key programmatically, or if the keyboard
1168      * doesn't have this key
1169      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1170      * returns true
1171      * @see       java.awt.GraphicsEnvironment#isHeadless
1172      * @since 1.3
1173      */
1174     public void setLockingKeyState(int keyCode, boolean on)
1175         throws UnsupportedOperationException
1176     {
1177         GraphicsEnvironment.checkHeadless();
1178 
1179         if (! (keyCode == KeyEvent.VK_CAPS_LOCK || keyCode == KeyEvent.VK_NUM_LOCK ||
1180                keyCode == KeyEvent.VK_SCROLL_LOCK || keyCode == KeyEvent.VK_KANA_LOCK)) {
1181             throw new IllegalArgumentException("invalid key for Toolkit.setLockingKeyState");
1182         }
1183         throw new UnsupportedOperationException("Toolkit.setLockingKeyState");
1184     }
1185 
1186     /**
1187      * Give native peers the ability to query the native container
1188      * given a native component (eg the direct parent may be lightweight).
1189      *
1190      * @param  c the component to fetch the container for
1191      * @return the native container object for the component
1192      */
1193     protected static Container getNativeContainer(Component c) {
1194         return c.getNativeContainer();
1195     }
1196 
1197     /**
1198      * Creates a new custom cursor object.
1199      * If the image to display is invalid, the cursor will be hidden (made
1200      * completely transparent), and the hotspot will be set to (0, 0).
1201      *
1202      * <p>Note that multi-frame images are invalid and may cause this
1203      * method to hang.
1204      *
1205      * @param cursor the image to display when the cursor is activated
1206      * @param hotSpot the X and Y of the large cursor's hot spot; the
1207      *   hotSpot values must be less than the Dimension returned by
1208      *   {@code getBestCursorSize}
1209      * @param     name a localized description of the cursor, for Java Accessibility use
1210      * @exception IndexOutOfBoundsException if the hotSpot values are outside
1211      *   the bounds of the cursor
1212      * @return the cursor created
1213      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1214      * returns true
1215      * @see       java.awt.GraphicsEnvironment#isHeadless
1216      * @since     1.2
1217      */
1218     public Cursor createCustomCursor(Image cursor, Point hotSpot, String name)
1219         throws IndexOutOfBoundsException, HeadlessException
1220     {
1221         // Override to implement custom cursor support.
1222         if (this != Toolkit.getDefaultToolkit()) {
1223             return Toolkit.getDefaultToolkit().
1224                 createCustomCursor(cursor, hotSpot, name);
1225         } else {
1226             return new Cursor(Cursor.DEFAULT_CURSOR);
1227         }
1228     }
1229 
1230     /**
1231      * Returns the supported cursor dimension which is closest to the desired
1232      * sizes.  Systems which only support a single cursor size will return that
1233      * size regardless of the desired sizes.  Systems which don't support custom
1234      * cursors will return a dimension of 0, 0. <p>
1235      * Note:  if an image is used whose dimensions don't match a supported size
1236      * (as returned by this method), the Toolkit implementation will attempt to
1237      * resize the image to a supported size.
1238      * Since converting low-resolution images is difficult,
1239      * no guarantees are made as to the quality of a cursor image which isn't a
1240      * supported size.  It is therefore recommended that this method
1241      * be called and an appropriate image used so no image conversion is made.
1242      *
1243      * @param     preferredWidth the preferred cursor width the component would like
1244      * to use.
1245      * @param     preferredHeight the preferred cursor height the component would like
1246      * to use.
1247      * @return    the closest matching supported cursor size, or a dimension of 0,0 if
1248      * the Toolkit implementation doesn't support custom cursors.
1249      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1250      * returns true
1251      * @see       java.awt.GraphicsEnvironment#isHeadless
1252      * @since     1.2
1253      */
1254     public Dimension getBestCursorSize(int preferredWidth,
1255         int preferredHeight) throws HeadlessException {
1256         GraphicsEnvironment.checkHeadless();
1257 
1258         // Override to implement custom cursor support.
1259         if (this != Toolkit.getDefaultToolkit()) {
1260             return Toolkit.getDefaultToolkit().
1261                 getBestCursorSize(preferredWidth, preferredHeight);
1262         } else {
1263             return new Dimension(0, 0);
1264         }
1265     }
1266 
1267     /**
1268      * Returns the maximum number of colors the Toolkit supports in a custom cursor
1269      * palette.<p>
1270      * Note: if an image is used which has more colors in its palette than
1271      * the supported maximum, the Toolkit implementation will attempt to flatten the
1272      * palette to the maximum.  Since converting low-resolution images is difficult,
1273      * no guarantees are made as to the quality of a cursor image which has more
1274      * colors than the system supports.  It is therefore recommended that this method
1275      * be called and an appropriate image used so no image conversion is made.
1276      *
1277      * @return    the maximum number of colors, or zero if custom cursors are not
1278      * supported by this Toolkit implementation.
1279      * @exception HeadlessException if GraphicsEnvironment.isHeadless()
1280      * returns true
1281      * @see       java.awt.GraphicsEnvironment#isHeadless
1282      * @since     1.2
1283      */
1284     public int getMaximumCursorColors() throws HeadlessException {
1285         GraphicsEnvironment.checkHeadless();
1286 
1287         // Override to implement custom cursor support.
1288         if (this != Toolkit.getDefaultToolkit()) {
1289             return Toolkit.getDefaultToolkit().getMaximumCursorColors();
1290         } else {
1291             return 0;
1292         }
1293     }
1294 
1295     /**
1296      * Returns whether Toolkit supports this state for
1297      * {@code Frame}s.  This method tells whether the <em>UI
1298      * concept</em> of, say, maximization or iconification is
1299      * supported.  It will always return false for "compound" states
1300      * like {@code Frame.ICONIFIED|Frame.MAXIMIZED_VERT}.
1301      * In other words, the rule of thumb is that only queries with a
1302      * single frame state constant as an argument are meaningful.
1303      * <p>Note that supporting a given concept is a platform-
1304      * dependent feature. Due to native limitations the Toolkit
1305      * object may report a particular state as supported, however at
1306      * the same time the Toolkit object will be unable to apply the
1307      * state to a given frame.  This circumstance has two following
1308      * consequences:
1309      * <ul>
1310      * <li>Only the return value of {@code false} for the present
1311      * method actually indicates that the given state is not
1312      * supported. If the method returns {@code true} the given state
1313      * may still be unsupported and/or unavailable for a particular
1314      * frame.
1315      * <li>The developer should consider examining the value of the
1316      * {@link java.awt.event.WindowEvent#getNewState} method of the
1317      * {@code WindowEvent} received through the {@link
1318      * java.awt.event.WindowStateListener}, rather than assuming
1319      * that the state given to the {@code setExtendedState()} method
1320      * will be definitely applied. For more information see the
1321      * documentation for the {@link Frame#setExtendedState} method.
1322      * </ul>
1323      *
1324      * @param state one of named frame state constants.
1325      * @return {@code true} is this frame state is supported by
1326      *     this Toolkit implementation, {@code false} otherwise.
1327      * @exception HeadlessException
1328      *     if {@code GraphicsEnvironment.isHeadless()}
1329      *     returns {@code true}.
1330      * @see java.awt.Window#addWindowStateListener
1331      * @since   1.4
1332      */
1333     public boolean isFrameStateSupported(int state)
1334         throws HeadlessException
1335     {
1336         GraphicsEnvironment.checkHeadless();
1337 
1338         if (this != Toolkit.getDefaultToolkit()) {
1339             return Toolkit.getDefaultToolkit().
1340                 isFrameStateSupported(state);
1341         } else {
1342             return (state == Frame.NORMAL); // others are not guaranteed
1343         }
1344     }
1345 
1346     /**
1347      * Support for I18N: any visible strings should be stored in
1348      * sun.awt.resources.awt.properties.  The ResourceBundle is stored
1349      * here, so that only one copy is maintained.
1350      */
1351     private static ResourceBundle resources;
1352     private static ResourceBundle platformResources;
1353 
1354     // called by platform toolkit
1355     private static void setPlatformResources(ResourceBundle bundle) {
1356         platformResources = bundle;
1357     }
1358 
1359     /**
1360      * Initialize JNI field and method ids
1361      */
1362     private static native void initIDs();
1363 
1364     /**
1365      * WARNING: This is a temporary workaround for a problem in the
1366      * way the AWT loads native libraries. A number of classes in the
1367      * AWT package have a native method, initIDs(), which initializes
1368      * the JNI field and method ids used in the native portion of
1369      * their implementation.
1370      *
1371      * Since the use and storage of these ids is done by the
1372      * implementation libraries, the implementation of these method is
1373      * provided by the particular AWT implementations (for example,
1374      * "Toolkit"s/Peer), such as Motif, Microsoft Windows, or Tiny. The
1375      * problem is that this means that the native libraries must be
1376      * loaded by the java.* classes, which do not necessarily know the
1377      * names of the libraries to load. A better way of doing this
1378      * would be to provide a separate library which defines java.awt.*
1379      * initIDs, and exports the relevant symbols out to the
1380      * implementation libraries.
1381      *
1382      * For now, we know it's done by the implementation, and we assume
1383      * that the name of the library is "awt".  -br.
1384      *
1385      * If you change loadLibraries(), please add the change to
1386      * java.awt.image.ColorModel.loadLibraries(). Unfortunately,
1387      * classes can be loaded in java.awt.image that depend on
1388      * libawt and there is no way to call Toolkit.loadLibraries()
1389      * directly.  -hung
1390      */
1391     private static boolean loaded = false;
1392     static void loadLibraries() {
1393         if (!loaded) {
1394             java.security.AccessController.doPrivileged(
1395                 new java.security.PrivilegedAction<Void>() {
1396                     public Void run() {
1397                         System.loadLibrary("awt");
1398                         return null;
1399                     }
1400                 });
1401             loaded = true;
1402         }
1403     }
1404 
1405     static {
1406         AWTAccessor.setToolkitAccessor(
1407                 new AWTAccessor.ToolkitAccessor() {
1408                     @Override
1409                     public void setPlatformResources(ResourceBundle bundle) {
1410                         Toolkit.setPlatformResources(bundle);
1411                     }
1412                 });
1413 
1414         java.security.AccessController.doPrivileged(
1415                                  new java.security.PrivilegedAction<Void>() {
1416             public Void run() {
1417                 try {
1418                     resources = ResourceBundle.getBundle("sun.awt.resources.awt");
1419                 } catch (MissingResourceException e) {
1420                     // No resource file; defaults will be used.
1421                 }
1422                 return null;
1423             }
1424         });
1425 
1426         // ensure that the proper libraries are loaded
1427         loadLibraries();
1428         initAssistiveTechnologies();
1429         initIDs();
1430     }
1431 
1432     /**
1433      * Gets a property with the specified key and default.
1434      * This method returns defaultValue if the property is not found.
1435      *
1436      * @param  key the key
1437      * @param  defaultValue the default value
1438      * @return the value of the property or the default value
1439      *         if the property was not found
1440      */
1441     public static String getProperty(String key, String defaultValue) {
1442         // first try platform specific bundle
1443         if (platformResources != null) {
1444             try {
1445                 return platformResources.getString(key);
1446             }
1447             catch (MissingResourceException e) {}
1448         }
1449 
1450         // then shared one
1451         if (resources != null) {
1452             try {
1453                 return resources.getString(key);
1454             }
1455             catch (MissingResourceException e) {}
1456         }
1457 
1458         return defaultValue;
1459     }
1460 
1461     /**
1462      * Get the application's or applet's EventQueue instance.
1463      * Depending on the Toolkit implementation, different EventQueues
1464      * may be returned for different applets.  Applets should
1465      * therefore not assume that the EventQueue instance returned
1466      * by this method will be shared by other applets or the system.
1467      *
1468      * <p> If there is a security manager then its
1469      * {@link SecurityManager#checkPermission checkPermission} method
1470      * is called to check {@code AWTPermission("accessEventQueue")}.
1471      *
1472      * @return    the {@code EventQueue} object
1473      * @throws  SecurityException
1474      *          if a security manager is set and it denies access to
1475      *          the {@code EventQueue}
1476      * @see     java.awt.AWTPermission
1477     */
1478     public final EventQueue getSystemEventQueue() {
1479         SecurityManager security = System.getSecurityManager();
1480         if (security != null) {
1481             security.checkPermission(AWTPermissions.CHECK_AWT_EVENTQUEUE_PERMISSION);
1482         }
1483         return getSystemEventQueueImpl();
1484     }
1485 
1486     /**
1487      * Gets the application's or applet's {@code EventQueue}
1488      * instance, without checking access.  For security reasons,
1489      * this can only be called from a {@code Toolkit} subclass.
1490      * @return the {@code EventQueue} object
1491      */
1492     protected abstract EventQueue getSystemEventQueueImpl();
1493 
1494     /* Accessor method for use by AWT package routines. */
1495     static EventQueue getEventQueue() {
1496         return getDefaultToolkit().getSystemEventQueueImpl();
1497     }
1498 
1499     /**
1500      * Creates a concrete, platform dependent, subclass of the abstract
1501      * DragGestureRecognizer class requested, and associates it with the
1502      * DragSource, Component and DragGestureListener specified.
1503      *
1504      * subclasses should override this to provide their own implementation
1505      *
1506      * @param <T> the type of DragGestureRecognizer to create
1507      * @param abstractRecognizerClass The abstract class of the required recognizer
1508      * @param ds                      The DragSource
1509      * @param c                       The Component target for the DragGestureRecognizer
1510      * @param srcActions              The actions permitted for the gesture
1511      * @param dgl                     The DragGestureListener
1512      *
1513      * @return the new object or null.  Always returns null if
1514      * GraphicsEnvironment.isHeadless() returns true.
1515      * @see java.awt.GraphicsEnvironment#isHeadless
1516      */
1517     public <T extends DragGestureRecognizer> T
1518         createDragGestureRecognizer(Class<T> abstractRecognizerClass,
1519                                     DragSource ds, Component c, int srcActions,
1520                                     DragGestureListener dgl)
1521     {
1522         return null;
1523     }
1524 
1525     /**
1526      * Obtains a value for the specified desktop property.
1527      *
1528      * A desktop property is a uniquely named value for a resource that
1529      * is Toolkit global in nature. Usually it also is an abstract
1530      * representation for an underlying platform dependent desktop setting.
1531      * For more information on desktop properties supported by the AWT see
1532      * <a href="doc-files/DesktopProperties.html">AWT Desktop Properties</a>.
1533      *
1534      * @param  propertyName the property name
1535      * @return the value for the specified desktop property
1536      */
1537     public final synchronized Object getDesktopProperty(String propertyName) {
1538         // This is a workaround for headless toolkits.  It would be
1539         // better to override this method but it is declared final.
1540         // "this instanceof" syntax defeats polymorphism.
1541         // --mm, 03/03/00
1542         if (this instanceof HeadlessToolkit) {
1543             return ((HeadlessToolkit)this).getUnderlyingToolkit()
1544                 .getDesktopProperty(propertyName);
1545         }
1546 
1547         if (desktopProperties.isEmpty()) {
1548             initializeDesktopProperties();
1549         }
1550 
1551         Object value;
1552 
1553         // This property should never be cached
1554         if (propertyName.equals("awt.dynamicLayoutSupported")) {
1555             return getDefaultToolkit().lazilyLoadDesktopProperty(propertyName);
1556         }
1557 
1558         value = desktopProperties.get(propertyName);
1559 
1560         if (value == null) {
1561             value = lazilyLoadDesktopProperty(propertyName);
1562 
1563             if (value != null) {
1564                 setDesktopProperty(propertyName, value);
1565             }
1566         }
1567 
1568         /* for property "awt.font.desktophints" */
1569         if (value instanceof RenderingHints) {
1570             value = ((RenderingHints)value).clone();
1571         }
1572 
1573         return value;
1574     }
1575 
1576     /**
1577      * Sets the named desktop property to the specified value and fires a
1578      * property change event to notify any listeners that the value has changed.
1579      *
1580      * @param  name the property name
1581      * @param  newValue the new property value
1582      */
1583     protected final void setDesktopProperty(String name, Object newValue) {
1584         // This is a workaround for headless toolkits.  It would be
1585         // better to override this method but it is declared final.
1586         // "this instanceof" syntax defeats polymorphism.
1587         // --mm, 03/03/00
1588         if (this instanceof HeadlessToolkit) {
1589             ((HeadlessToolkit)this).getUnderlyingToolkit()
1590                 .setDesktopProperty(name, newValue);
1591             return;
1592         }
1593         Object oldValue;
1594 
1595         synchronized (this) {
1596             oldValue = desktopProperties.get(name);
1597             desktopProperties.put(name, newValue);
1598         }
1599 
1600         // Don't fire change event if old and new values are null.
1601         // It helps to avoid recursive resending of WM_THEMECHANGED
1602         if (oldValue != null || newValue != null) {
1603             desktopPropsSupport.firePropertyChange(name, oldValue, newValue);
1604         }
1605     }
1606 
1607     /**
1608      * An opportunity to lazily evaluate desktop property values.
1609      * @return the desktop property or null
1610      * @param name the name
1611      */
1612     protected Object lazilyLoadDesktopProperty(String name) {
1613         return null;
1614     }
1615 
1616     /**
1617      * initializeDesktopProperties
1618      */
1619     protected void initializeDesktopProperties() {
1620     }
1621 
1622     /**
1623      * Adds the specified property change listener for the named desktop
1624      * property. When a {@link java.beans.PropertyChangeListenerProxy} object is added,
1625      * its property name is ignored, and the wrapped listener is added.
1626      * If {@code name} is {@code null} or {@code pcl} is {@code null},
1627      * no exception is thrown and no action is performed.
1628      *
1629      * @param   name The name of the property to listen for
1630      * @param   pcl The property change listener
1631      * @see PropertyChangeSupport#addPropertyChangeListener(String,
1632                 PropertyChangeListener)
1633      * @since   1.2
1634      */
1635     public void addPropertyChangeListener(String name, PropertyChangeListener pcl) {
1636         desktopPropsSupport.addPropertyChangeListener(name, pcl);
1637     }
1638 
1639     /**
1640      * Removes the specified property change listener for the named
1641      * desktop property. When a {@link java.beans.PropertyChangeListenerProxy} object
1642      * is removed, its property name is ignored, and
1643      * the wrapped listener is removed.
1644      * If {@code name} is {@code null} or {@code pcl} is {@code null},
1645      * no exception is thrown and no action is performed.
1646      *
1647      * @param   name The name of the property to remove
1648      * @param   pcl The property change listener
1649      * @see PropertyChangeSupport#removePropertyChangeListener(String,
1650                 PropertyChangeListener)
1651      * @since   1.2
1652      */
1653     public void removePropertyChangeListener(String name, PropertyChangeListener pcl) {
1654         desktopPropsSupport.removePropertyChangeListener(name, pcl);
1655     }
1656 
1657     /**
1658      * Returns an array of all the property change listeners
1659      * registered on this toolkit. The returned array
1660      * contains {@link java.beans.PropertyChangeListenerProxy} objects
1661      * that associate listeners with the names of desktop properties.
1662      *
1663      * @return all of this toolkit's {@link PropertyChangeListener}
1664      *         objects wrapped in {@code java.beans.PropertyChangeListenerProxy} objects
1665      *         or an empty array  if no listeners are added
1666      *
1667      * @see PropertyChangeSupport#getPropertyChangeListeners()
1668      * @since 1.4
1669      */
1670     public PropertyChangeListener[] getPropertyChangeListeners() {
1671         return desktopPropsSupport.getPropertyChangeListeners();
1672     }
1673 
1674     /**
1675      * Returns an array of all property change listeners
1676      * associated with the specified name of a desktop property.
1677      *
1678      * @param  propertyName the named property
1679      * @return all of the {@code PropertyChangeListener} objects
1680      *         associated with the specified name of a desktop property
1681      *         or an empty array if no such listeners are added
1682      *
1683      * @see PropertyChangeSupport#getPropertyChangeListeners(String)
1684      * @since 1.4
1685      */
1686     public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
1687         return desktopPropsSupport.getPropertyChangeListeners(propertyName);
1688     }
1689 
1690     /**
1691      * The desktop properties.
1692      */
1693     protected final Map<String,Object> desktopProperties =
1694             new HashMap<String,Object>();
1695     /**
1696      * The desktop properties change support.
1697      */
1698     protected final PropertyChangeSupport desktopPropsSupport =
1699             Toolkit.createPropertyChangeSupport(this);
1700 
1701     /**
1702      * Returns whether the always-on-top mode is supported by this toolkit.
1703      * To detect whether the always-on-top mode is supported for a
1704      * particular Window, use {@link Window#isAlwaysOnTopSupported}.
1705      * @return {@code true}, if current toolkit supports the always-on-top mode,
1706      *     otherwise returns {@code false}
1707      * @see Window#isAlwaysOnTopSupported
1708      * @see Window#setAlwaysOnTop(boolean)
1709      * @since 1.6
1710      */
1711     public boolean isAlwaysOnTopSupported() {
1712         return true;
1713     }
1714 
1715     /**
1716      * Returns whether the given modality type is supported by this toolkit. If
1717      * a dialog with unsupported modality type is created, then
1718      * {@code Dialog.ModalityType.MODELESS} is used instead.
1719      *
1720      * @param modalityType modality type to be checked for support by this toolkit
1721      *
1722      * @return {@code true}, if current toolkit supports given modality
1723      *     type, {@code false} otherwise
1724      *
1725      * @see java.awt.Dialog.ModalityType
1726      * @see java.awt.Dialog#getModalityType
1727      * @see java.awt.Dialog#setModalityType
1728      *
1729      * @since 1.6
1730      */
1731     public abstract boolean isModalityTypeSupported(Dialog.ModalityType modalityType);
1732 
1733     /**
1734      * Returns whether the given modal exclusion type is supported by this
1735      * toolkit. If an unsupported modal exclusion type property is set on a window,
1736      * then {@code Dialog.ModalExclusionType.NO_EXCLUDE} is used instead.
1737      *
1738      * @param modalExclusionType modal exclusion type to be checked for support by this toolkit
1739      *
1740      * @return {@code true}, if current toolkit supports given modal exclusion
1741      *     type, {@code false} otherwise
1742      *
1743      * @see java.awt.Dialog.ModalExclusionType
1744      * @see java.awt.Window#getModalExclusionType
1745      * @see java.awt.Window#setModalExclusionType
1746      *
1747      * @since 1.6
1748      */
1749     public abstract boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType modalExclusionType);
1750 
1751     // 8014718: logging has been removed from SunToolkit
1752 
1753     private static final int LONG_BITS = 64;
1754     private int[] calls = new int[LONG_BITS];
1755     private static volatile long enabledOnToolkitMask;
1756     private AWTEventListener eventListener = null;
1757     private WeakHashMap<AWTEventListener, SelectiveAWTEventListener> listener2SelectiveListener = new WeakHashMap<>();
1758 
1759     /*
1760      * Extracts a "pure" AWTEventListener from a AWTEventListenerProxy,
1761      * if the listener is proxied.
1762      */
1763     private static AWTEventListener deProxyAWTEventListener(AWTEventListener l)
1764     {
1765         AWTEventListener localL = l;
1766 
1767         if (localL == null) {
1768             return null;
1769         }
1770         // if user passed in a AWTEventListenerProxy object, extract
1771         // the listener
1772         if (l instanceof AWTEventListenerProxy) {
1773             localL = ((AWTEventListenerProxy)l).getListener();
1774         }
1775         return localL;
1776     }
1777 
1778     /**
1779      * Adds an AWTEventListener to receive all AWTEvents dispatched
1780      * system-wide that conform to the given {@code eventMask}.
1781      * <p>
1782      * First, if there is a security manager, its {@code checkPermission}
1783      * method is called with an
1784      * {@code AWTPermission("listenToAllAWTEvents")} permission.
1785      * This may result in a SecurityException.
1786      * <p>
1787      * {@code eventMask} is a bitmask of event types to receive.
1788      * It is constructed by bitwise OR-ing together the event masks
1789      * defined in {@code AWTEvent}.
1790      * <p>
1791      * Note:  event listener use is not recommended for normal
1792      * application use, but are intended solely to support special
1793      * purpose facilities including support for accessibility,
1794      * event record/playback, and diagnostic tracing.
1795      *
1796      * If listener is null, no exception is thrown and no action is performed.
1797      *
1798      * @param    listener   the event listener.
1799      * @param    eventMask  the bitmask of event types to receive
1800      * @throws SecurityException
1801      *        if a security manager exists and its
1802      *        {@code checkPermission} method doesn't allow the operation.
1803      * @see      #removeAWTEventListener
1804      * @see      #getAWTEventListeners
1805      * @see      SecurityManager#checkPermission
1806      * @see      java.awt.AWTEvent
1807      * @see      java.awt.AWTPermission
1808      * @see      java.awt.event.AWTEventListener
1809      * @see      java.awt.event.AWTEventListenerProxy
1810      * @since    1.2
1811      */
1812     public void addAWTEventListener(AWTEventListener listener, long eventMask) {
1813         AWTEventListener localL = deProxyAWTEventListener(listener);
1814 
1815         if (localL == null) {
1816             return;
1817         }
1818         SecurityManager security = System.getSecurityManager();
1819         if (security != null) {
1820           security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION);
1821         }
1822         synchronized (this) {
1823             SelectiveAWTEventListener selectiveListener =
1824                 listener2SelectiveListener.get(localL);
1825 
1826             if (selectiveListener == null) {
1827                 // Create a new selectiveListener.
1828                 selectiveListener = new SelectiveAWTEventListener(localL,
1829                                                                  eventMask);
1830                 listener2SelectiveListener.put(localL, selectiveListener);
1831                 eventListener = ToolkitEventMulticaster.add(eventListener,
1832                                                             selectiveListener);
1833             }
1834             // OR the eventMask into the selectiveListener's event mask.
1835             selectiveListener.orEventMasks(eventMask);
1836 
1837             enabledOnToolkitMask |= eventMask;
1838 
1839             long mask = eventMask;
1840             for (int i=0; i<LONG_BITS; i++) {
1841                 // If no bits are set, break out of loop.
1842                 if (mask == 0) {
1843                     break;
1844                 }
1845                 if ((mask & 1L) != 0) {  // Always test bit 0.
1846                     calls[i]++;
1847                 }
1848                 mask >>>= 1;  // Right shift, fill with zeros on left.
1849             }
1850         }
1851     }
1852 
1853     /**
1854      * Removes an AWTEventListener from receiving dispatched AWTEvents.
1855      * <p>
1856      * First, if there is a security manager, its {@code checkPermission}
1857      * method is called with an
1858      * {@code AWTPermission("listenToAllAWTEvents")} permission.
1859      * This may result in a SecurityException.
1860      * <p>
1861      * Note:  event listener use is not recommended for normal
1862      * application use, but are intended solely to support special
1863      * purpose facilities including support for accessibility,
1864      * event record/playback, and diagnostic tracing.
1865      *
1866      * If listener is null, no exception is thrown and no action is performed.
1867      *
1868      * @param    listener   the event listener.
1869      * @throws SecurityException
1870      *        if a security manager exists and its
1871      *        {@code checkPermission} method doesn't allow the operation.
1872      * @see      #addAWTEventListener
1873      * @see      #getAWTEventListeners
1874      * @see      SecurityManager#checkPermission
1875      * @see      java.awt.AWTEvent
1876      * @see      java.awt.AWTPermission
1877      * @see      java.awt.event.AWTEventListener
1878      * @see      java.awt.event.AWTEventListenerProxy
1879      * @since    1.2
1880      */
1881     public void removeAWTEventListener(AWTEventListener listener) {
1882         AWTEventListener localL = deProxyAWTEventListener(listener);
1883 
1884         if (listener == null) {
1885             return;
1886         }
1887         SecurityManager security = System.getSecurityManager();
1888         if (security != null) {
1889             security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION);
1890         }
1891 
1892         synchronized (this) {
1893             SelectiveAWTEventListener selectiveListener =
1894                 listener2SelectiveListener.get(localL);
1895 
1896             if (selectiveListener != null) {
1897                 listener2SelectiveListener.remove(localL);
1898                 int[] listenerCalls = selectiveListener.getCalls();
1899                 for (int i=0; i<LONG_BITS; i++) {
1900                     calls[i] -= listenerCalls[i];
1901                     assert calls[i] >= 0: "Negative Listeners count";
1902 
1903                     if (calls[i] == 0) {
1904                         enabledOnToolkitMask &= ~(1L<<i);
1905                     }
1906                 }
1907             }
1908             eventListener = ToolkitEventMulticaster.remove(eventListener,
1909             (selectiveListener == null) ? localL : selectiveListener);
1910         }
1911     }
1912 
1913     static boolean enabledOnToolkit(long eventMask) {
1914         return (enabledOnToolkitMask & eventMask) != 0;
1915         }
1916 
1917     synchronized int countAWTEventListeners(long eventMask) {
1918         int ci = 0;
1919         for (; eventMask != 0; eventMask >>>= 1, ci++) {
1920         }
1921         ci--;
1922         return calls[ci];
1923     }
1924     /**
1925      * Returns an array of all the {@code AWTEventListener}s
1926      * registered on this toolkit.
1927      * If there is a security manager, its {@code checkPermission}
1928      * method is called with an
1929      * {@code AWTPermission("listenToAllAWTEvents")} permission.
1930      * This may result in a SecurityException.
1931      * Listeners can be returned
1932      * within {@code AWTEventListenerProxy} objects, which also contain
1933      * the event mask for the given listener.
1934      * Note that listener objects
1935      * added multiple times appear only once in the returned array.
1936      *
1937      * @return all of the {@code AWTEventListener}s or an empty
1938      *         array if no listeners are currently registered
1939      * @throws SecurityException
1940      *        if a security manager exists and its
1941      *        {@code checkPermission} method doesn't allow the operation.
1942      * @see      #addAWTEventListener
1943      * @see      #removeAWTEventListener
1944      * @see      SecurityManager#checkPermission
1945      * @see      java.awt.AWTEvent
1946      * @see      java.awt.AWTPermission
1947      * @see      java.awt.event.AWTEventListener
1948      * @see      java.awt.event.AWTEventListenerProxy
1949      * @since 1.4
1950      */
1951     public AWTEventListener[] getAWTEventListeners() {
1952         SecurityManager security = System.getSecurityManager();
1953         if (security != null) {
1954             security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION);
1955         }
1956         synchronized (this) {
1957             EventListener[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class);
1958 
1959             AWTEventListener[] ret = new AWTEventListener[la.length];
1960             for (int i = 0; i < la.length; i++) {
1961                 SelectiveAWTEventListener sael = (SelectiveAWTEventListener)la[i];
1962                 AWTEventListener tempL = sael.getListener();
1963                 //assert tempL is not an AWTEventListenerProxy - we should
1964                 // have weeded them all out
1965                 // don't want to wrap a proxy inside a proxy
1966                 ret[i] = new AWTEventListenerProxy(sael.getEventMask(), tempL);
1967             }
1968             return ret;
1969         }
1970     }
1971 
1972     /**
1973      * Returns an array of all the {@code AWTEventListener}s
1974      * registered on this toolkit which listen to all of the event
1975      * types specified in the {@code eventMask} argument.
1976      * If there is a security manager, its {@code checkPermission}
1977      * method is called with an
1978      * {@code AWTPermission("listenToAllAWTEvents")} permission.
1979      * This may result in a SecurityException.
1980      * Listeners can be returned
1981      * within {@code AWTEventListenerProxy} objects, which also contain
1982      * the event mask for the given listener.
1983      * Note that listener objects
1984      * added multiple times appear only once in the returned array.
1985      *
1986      * @param  eventMask the bitmask of event types to listen for
1987      * @return all of the {@code AWTEventListener}s registered
1988      *         on this toolkit for the specified
1989      *         event types, or an empty array if no such listeners
1990      *         are currently registered
1991      * @throws SecurityException
1992      *        if a security manager exists and its
1993      *        {@code checkPermission} method doesn't allow the operation.
1994      * @see      #addAWTEventListener
1995      * @see      #removeAWTEventListener
1996      * @see      SecurityManager#checkPermission
1997      * @see      java.awt.AWTEvent
1998      * @see      java.awt.AWTPermission
1999      * @see      java.awt.event.AWTEventListener
2000      * @see      java.awt.event.AWTEventListenerProxy
2001      * @since 1.4
2002      */
2003     public AWTEventListener[] getAWTEventListeners(long eventMask) {
2004         SecurityManager security = System.getSecurityManager();
2005         if (security != null) {
2006             security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION);
2007         }
2008         synchronized (this) {
2009             EventListener[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class);
2010 
2011             java.util.List<AWTEventListenerProxy> list = new ArrayList<>(la.length);
2012 
2013             for (int i = 0; i < la.length; i++) {
2014                 SelectiveAWTEventListener sael = (SelectiveAWTEventListener)la[i];
2015                 if ((sael.getEventMask() & eventMask) == eventMask) {
2016                     //AWTEventListener tempL = sael.getListener();
2017                     list.add(new AWTEventListenerProxy(sael.getEventMask(),
2018                                                        sael.getListener()));
2019                 }
2020             }
2021             return list.toArray(new AWTEventListener[0]);
2022         }
2023     }
2024 
2025     /*
2026      * This method notifies any AWTEventListeners that an event
2027      * is about to be dispatched.
2028      *
2029      * @param theEvent the event which will be dispatched.
2030      */
2031     void notifyAWTEventListeners(AWTEvent theEvent) {
2032         // This is a workaround for headless toolkits.  It would be
2033         // better to override this method but it is declared package private.
2034         // "this instanceof" syntax defeats polymorphism.
2035         // --mm, 03/03/00
2036         if (this instanceof HeadlessToolkit) {
2037             ((HeadlessToolkit)this).getUnderlyingToolkit()
2038                 .notifyAWTEventListeners(theEvent);
2039             return;
2040         }
2041 
2042         AWTEventListener eventListener = this.eventListener;
2043         if (eventListener != null) {
2044             eventListener.eventDispatched(theEvent);
2045         }
2046     }
2047 
2048     private static class ToolkitEventMulticaster extends AWTEventMulticaster
2049         implements AWTEventListener {
2050         // Implementation cloned from AWTEventMulticaster.
2051 
2052         ToolkitEventMulticaster(AWTEventListener a, AWTEventListener b) {
2053             super(a, b);
2054         }
2055 
2056         @SuppressWarnings("overloads")
2057         static AWTEventListener add(AWTEventListener a,
2058                                     AWTEventListener b) {
2059             if (a == null)  return b;
2060             if (b == null)  return a;
2061             return new ToolkitEventMulticaster(a, b);
2062         }
2063 
2064         @SuppressWarnings("overloads")
2065         static AWTEventListener remove(AWTEventListener l,
2066                                        AWTEventListener oldl) {
2067             return (AWTEventListener) removeInternal(l, oldl);
2068         }
2069 
2070         // #4178589: must overload remove(EventListener) to call our add()
2071         // instead of the static addInternal() so we allocate a
2072         // ToolkitEventMulticaster instead of an AWTEventMulticaster.
2073         // Note: this method is called by AWTEventListener.removeInternal(),
2074         // so its method signature must match AWTEventListener.remove().
2075         protected EventListener remove(EventListener oldl) {
2076             if (oldl == a)  return b;
2077             if (oldl == b)  return a;
2078             AWTEventListener a2 = (AWTEventListener)removeInternal(a, oldl);
2079             AWTEventListener b2 = (AWTEventListener)removeInternal(b, oldl);
2080             if (a2 == a && b2 == b) {
2081                 return this;    // it's not here
2082             }
2083             return add(a2, b2);
2084         }
2085 
2086         public void eventDispatched(AWTEvent event) {
2087             ((AWTEventListener)a).eventDispatched(event);
2088             ((AWTEventListener)b).eventDispatched(event);
2089         }
2090     }
2091 
2092     private class SelectiveAWTEventListener implements AWTEventListener {
2093         AWTEventListener listener;
2094         private long eventMask;
2095         // This array contains the number of times to call the eventlistener
2096         // for each event type.
2097         int[] calls = new int[Toolkit.LONG_BITS];
2098 
2099         public AWTEventListener getListener() {return listener;}
2100         public long getEventMask() {return eventMask;}
2101         public int[] getCalls() {return calls;}
2102 
2103         public void orEventMasks(long mask) {
2104             eventMask |= mask;
2105             // For each event bit set in mask, increment its call count.
2106             for (int i=0; i<Toolkit.LONG_BITS; i++) {
2107                 // If no bits are set, break out of loop.
2108                 if (mask == 0) {
2109                     break;
2110                 }
2111                 if ((mask & 1L) != 0) {  // Always test bit 0.
2112                     calls[i]++;
2113                 }
2114                 mask >>>= 1;  // Right shift, fill with zeros on left.
2115             }
2116         }
2117 
2118         SelectiveAWTEventListener(AWTEventListener l, long mask) {
2119             listener = l;
2120             eventMask = mask;
2121         }
2122 
2123         public void eventDispatched(AWTEvent event) {
2124             long eventBit = 0; // Used to save the bit of the event type.
2125             if (((eventBit = eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 &&
2126                  event.id >= ComponentEvent.COMPONENT_FIRST &&
2127                  event.id <= ComponentEvent.COMPONENT_LAST)
2128              || ((eventBit = eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 &&
2129                  event.id >= ContainerEvent.CONTAINER_FIRST &&
2130                  event.id <= ContainerEvent.CONTAINER_LAST)
2131              || ((eventBit = eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 &&
2132                  event.id >= FocusEvent.FOCUS_FIRST &&
2133                  event.id <= FocusEvent.FOCUS_LAST)
2134              || ((eventBit = eventMask & AWTEvent.KEY_EVENT_MASK) != 0 &&
2135                  event.id >= KeyEvent.KEY_FIRST &&
2136                  event.id <= KeyEvent.KEY_LAST)
2137              || ((eventBit = eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 &&
2138                  event.id == MouseEvent.MOUSE_WHEEL)
2139              || ((eventBit = eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 &&
2140                  (event.id == MouseEvent.MOUSE_MOVED ||
2141                   event.id == MouseEvent.MOUSE_DRAGGED))
2142              || ((eventBit = eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 &&
2143                  event.id != MouseEvent.MOUSE_MOVED &&
2144                  event.id != MouseEvent.MOUSE_DRAGGED &&
2145                  event.id != MouseEvent.MOUSE_WHEEL &&
2146                  event.id >= MouseEvent.MOUSE_FIRST &&
2147                  event.id <= MouseEvent.MOUSE_LAST)
2148              || ((eventBit = eventMask & AWTEvent.WINDOW_EVENT_MASK) != 0 &&
2149                  (event.id >= WindowEvent.WINDOW_FIRST &&
2150                  event.id <= WindowEvent.WINDOW_LAST))
2151              || ((eventBit = eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 &&
2152                  event.id >= ActionEvent.ACTION_FIRST &&
2153                  event.id <= ActionEvent.ACTION_LAST)
2154              || ((eventBit = eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0 &&
2155                  event.id >= AdjustmentEvent.ADJUSTMENT_FIRST &&
2156                  event.id <= AdjustmentEvent.ADJUSTMENT_LAST)
2157              || ((eventBit = eventMask & AWTEvent.ITEM_EVENT_MASK) != 0 &&
2158                  event.id >= ItemEvent.ITEM_FIRST &&
2159                  event.id <= ItemEvent.ITEM_LAST)
2160              || ((eventBit = eventMask & AWTEvent.TEXT_EVENT_MASK) != 0 &&
2161                  event.id >= TextEvent.TEXT_FIRST &&
2162                  event.id <= TextEvent.TEXT_LAST)
2163              || ((eventBit = eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 &&
2164                  event.id >= InputMethodEvent.INPUT_METHOD_FIRST &&
2165                  event.id <= InputMethodEvent.INPUT_METHOD_LAST)
2166              || ((eventBit = eventMask & AWTEvent.PAINT_EVENT_MASK) != 0 &&
2167                  event.id >= PaintEvent.PAINT_FIRST &&
2168                  event.id <= PaintEvent.PAINT_LAST)
2169              || ((eventBit = eventMask & AWTEvent.INVOCATION_EVENT_MASK) != 0 &&
2170                  event.id >= InvocationEvent.INVOCATION_FIRST &&
2171                  event.id <= InvocationEvent.INVOCATION_LAST)
2172              || ((eventBit = eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
2173                  event.id == HierarchyEvent.HIERARCHY_CHANGED)
2174              || ((eventBit = eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
2175                  (event.id == HierarchyEvent.ANCESTOR_MOVED ||
2176                   event.id == HierarchyEvent.ANCESTOR_RESIZED))
2177              || ((eventBit = eventMask & AWTEvent.WINDOW_STATE_EVENT_MASK) != 0 &&
2178                  event.id == WindowEvent.WINDOW_STATE_CHANGED)
2179              || ((eventBit = eventMask & AWTEvent.WINDOW_FOCUS_EVENT_MASK) != 0 &&
2180                  (event.id == WindowEvent.WINDOW_GAINED_FOCUS ||
2181                   event.id == WindowEvent.WINDOW_LOST_FOCUS))
2182                 || ((eventBit = eventMask & sun.awt.SunToolkit.GRAB_EVENT_MASK) != 0 &&
2183                     (event instanceof sun.awt.UngrabEvent))) {
2184                 // Get the index of the call count for this event type.
2185                 // Instead of using Math.log(...) we will calculate it with
2186                 // bit shifts. That's what previous implementation looked like:
2187                 //
2188                 // int ci = (int) (Math.log(eventBit)/Math.log(2));
2189                 int ci = 0;
2190                 for (long eMask = eventBit; eMask != 0; eMask >>>= 1, ci++) {
2191                 }
2192                 ci--;
2193                 // Call the listener as many times as it was added for this
2194                 // event type.
2195                 for (int i=0; i<calls[ci]; i++) {
2196                     listener.eventDispatched(event);
2197                 }
2198             }
2199         }
2200     }
2201 
2202     /**
2203      * Returns a map of visual attributes for the abstract level description
2204      * of the given input method highlight, or null if no mapping is found.
2205      * The style field of the input method highlight is ignored. The map
2206      * returned is unmodifiable.
2207      * @param highlight input method highlight
2208      * @return style attribute map, or {@code null}
2209      * @exception HeadlessException if
2210      *     {@code GraphicsEnvironment.isHeadless} returns true
2211      * @see       java.awt.GraphicsEnvironment#isHeadless
2212      * @since 1.3
2213      */
2214     public abstract Map<java.awt.font.TextAttribute,?>
2215         mapInputMethodHighlight(InputMethodHighlight highlight)
2216         throws HeadlessException;
2217 
2218     private static PropertyChangeSupport createPropertyChangeSupport(Toolkit toolkit) {
2219         if (toolkit instanceof SunToolkit || toolkit instanceof HeadlessToolkit) {
2220             return new DesktopPropertyChangeSupport(toolkit);
2221         } else {
2222             return new PropertyChangeSupport(toolkit);
2223         }
2224     }
2225 
2226     @SuppressWarnings("serial")
2227     private static class DesktopPropertyChangeSupport extends PropertyChangeSupport {
2228 
2229         private static final StringBuilder PROP_CHANGE_SUPPORT_KEY =
2230                 new StringBuilder("desktop property change support key");
2231         private final Object source;
2232 
2233         public DesktopPropertyChangeSupport(Object sourceBean) {
2234             super(sourceBean);
2235             source = sourceBean;
2236         }
2237 
2238         @Override
2239         public synchronized void addPropertyChangeListener(
2240                 String propertyName,
2241                 PropertyChangeListener listener)
2242         {
2243             PropertyChangeSupport pcs = (PropertyChangeSupport)
2244                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2245             if (null == pcs) {
2246                 pcs = new PropertyChangeSupport(source);
2247                 AppContext.getAppContext().put(PROP_CHANGE_SUPPORT_KEY, pcs);
2248             }
2249             pcs.addPropertyChangeListener(propertyName, listener);
2250         }
2251 
2252         @Override
2253         public synchronized void removePropertyChangeListener(
2254                 String propertyName,
2255                 PropertyChangeListener listener)
2256         {
2257             PropertyChangeSupport pcs = (PropertyChangeSupport)
2258                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2259             if (null != pcs) {
2260                 pcs.removePropertyChangeListener(propertyName, listener);
2261             }
2262         }
2263 
2264         @Override
2265         public synchronized PropertyChangeListener[] getPropertyChangeListeners()
2266         {
2267             PropertyChangeSupport pcs = (PropertyChangeSupport)
2268                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2269             if (null != pcs) {
2270                 return pcs.getPropertyChangeListeners();
2271             } else {
2272                 return new PropertyChangeListener[0];
2273             }
2274         }
2275 
2276         @Override
2277         public synchronized PropertyChangeListener[] getPropertyChangeListeners(String propertyName)
2278         {
2279             PropertyChangeSupport pcs = (PropertyChangeSupport)
2280                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2281             if (null != pcs) {
2282                 return pcs.getPropertyChangeListeners(propertyName);
2283             } else {
2284                 return new PropertyChangeListener[0];
2285             }
2286         }
2287 
2288         @Override
2289         public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
2290             PropertyChangeSupport pcs = (PropertyChangeSupport)
2291                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2292             if (null == pcs) {
2293                 pcs = new PropertyChangeSupport(source);
2294                 AppContext.getAppContext().put(PROP_CHANGE_SUPPORT_KEY, pcs);
2295             }
2296             pcs.addPropertyChangeListener(listener);
2297         }
2298 
2299         @Override
2300         public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
2301             PropertyChangeSupport pcs = (PropertyChangeSupport)
2302                     AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2303             if (null != pcs) {
2304                 pcs.removePropertyChangeListener(listener);
2305             }
2306         }
2307 
2308         /*
2309          * we do expect that all other fireXXX() methods of java.beans.PropertyChangeSupport
2310          * use this method.  If this will be changed we will need to change this class.
2311          */
2312         @Override
2313         public void firePropertyChange(final PropertyChangeEvent evt) {
2314             Object oldValue = evt.getOldValue();
2315             Object newValue = evt.getNewValue();
2316             String propertyName = evt.getPropertyName();
2317             if (oldValue != null && newValue != null && oldValue.equals(newValue)) {
2318                 return;
2319             }
2320             Runnable updater = new Runnable() {
2321                 public void run() {
2322                     PropertyChangeSupport pcs = (PropertyChangeSupport)
2323                             AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY);
2324                     if (null != pcs) {
2325                         pcs.firePropertyChange(evt);
2326                     }
2327                 }
2328             };
2329             final AppContext currentAppContext = AppContext.getAppContext();
2330             for (AppContext appContext : AppContext.getAppContexts()) {
2331                 if (null == appContext || appContext.isDisposed()) {
2332                     continue;
2333                 }
2334                 if (currentAppContext == appContext) {
2335                     updater.run();
2336                 } else {
2337                     final PeerEvent e = new PeerEvent(source, updater, PeerEvent.ULTIMATE_PRIORITY_EVENT);
2338                     SunToolkit.postEvent(appContext, e);
2339                 }
2340             }
2341         }
2342     }
2343 
2344     /**
2345     * Reports whether events from extra mouse buttons are allowed to be processed and posted into
2346     * {@code EventQueue}.
2347     * <br>
2348     * To change the returned value it is necessary to set the {@code sun.awt.enableExtraMouseButtons}
2349     * property before the {@code Toolkit} class initialization. This setting could be done on the application
2350     * startup by the following command:
2351     * <pre>
2352     * java -Dsun.awt.enableExtraMouseButtons=false Application
2353     * </pre>
2354     * Alternatively, the property could be set in the application by using the following code:
2355     * <pre>
2356     * System.setProperty("sun.awt.enableExtraMouseButtons", "true");
2357     * </pre>
2358     * before the {@code Toolkit} class initialization.
2359     * If not set by the time of the {@code Toolkit} class initialization, this property will be
2360     * initialized with {@code true}.
2361     * Changing this value after the {@code Toolkit} class initialization will have no effect.
2362     *
2363     * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
2364     * @return {@code true} if events from extra mouse buttons are allowed to be processed and posted;
2365     *         {@code false} otherwise
2366     * @see System#getProperty(String propertyName)
2367     * @see System#setProperty(String propertyName, String value)
2368     * @see java.awt.EventQueue
2369     * @since 1.7
2370      */
2371     public boolean areExtraMouseButtonsEnabled() throws HeadlessException {
2372         GraphicsEnvironment.checkHeadless();
2373 
2374         return Toolkit.getDefaultToolkit().areExtraMouseButtonsEnabled();
2375     }
2376 }