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