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