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