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