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