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