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