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