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 * otherwise the default platform-specific implementation of 524 * {@code Toolkit} is used. 525 * <p> 526 * If this Toolkit is not a headless implementation and if they exist, service 527 * providers of {@link javax.accessibility.AccessibilityProvider} will be loaded 528 * if specified by the system property 529 * {@code javax.accessibility.assistive_technologies}. 530 * <p> 531 * An example of setting this property is to invoke Java with 532 * {@code -Djavax.accessibility.assistive_technologies=MyServiceProvider}. 533 * In addition to MyServiceProvider other service providers can be specified 534 * using a comma separated list. Service providers are loaded after the AWT 535 * toolkit is created. All errors are handled via an AWTError exception. 536 * <p> 537 * The names specified in the assistive_technologies property are used to query 538 * each service provider implementation. If the requested name matches the 539 * {@linkplain AccessibilityProvider#getName name} of the service provider, the 540 * {@link AccessibilityProvider#activate} method will be invoked to activate the 541 * matching service provider. 542 * 543 * @implSpec 544 * If assistive technology service providers are not specified with a system 545 * property this implementation will look in a properties file located as follows: 546 * <ul> 547 * <li> {@code ${user.home}/.accessibility.properties} 548 * <li> {@code ${java.home}/conf/accessibility.properties} 549 * </ul> 550 * Only the first of these files to be located will be consulted. The requested 551 * service providers are specified by setting the {@code assistive_technologies=} 552 * property. A single provider or a comma separated list of providers can be 553 * specified. 554 * 555 * @return the default toolkit. 556 * @exception AWTError if a toolkit could not be found, or 557 * if one could not be accessed or instantiated. 558 * @see java.util.ServiceLoader 559 * @see javax.accessibility.AccessibilityProvider 560 */ 561 public static synchronized Toolkit getDefaultToolkit() { 562 if (toolkit == null) { 563 java.security.AccessController.doPrivileged( 564 new java.security.PrivilegedAction<Void>() { 565 public Void run() { 566 Class<?> cls = null; 567 String nm = System.getProperty("awt.toolkit"); 568 try { 569 cls = Class.forName(nm); 570 } catch (ClassNotFoundException e) { 571 ClassLoader cl = ClassLoader.getSystemClassLoader(); 572 if (cl != null) { 573 try { 574 cls = cl.loadClass(nm); 575 } catch (final ClassNotFoundException ignored) { 576 throw new AWTError("Toolkit not found: " + nm); 577 } 578 } 579 } 580 try { 581 if (cls != null) { 582 toolkit = (Toolkit)cls.newInstance(); 583 if (GraphicsEnvironment.isHeadless()) { 584 toolkit = new HeadlessToolkit(toolkit); 585 } 586 } 587 } catch (final InstantiationException ignored) { 588 throw new AWTError("Could not instantiate Toolkit: " + nm); 589 } catch (final IllegalAccessException ignored) { 590 throw new AWTError("Could not access Toolkit: " + nm); 591 } 592 return null; 593 } 594 }); 595 if (!GraphicsEnvironment.isHeadless()) { 596 loadAssistiveTechnologies(); 597 } 598 } 599 return toolkit; 600 } 601 602 /** 603 * Returns an image which gets pixel data from the specified file, 604 * whose format can be either GIF, JPEG or PNG. 605 * The underlying toolkit attempts to resolve multiple requests 606 * with the same filename to the same returned Image. 607 * <p> 608 * Since the mechanism required to facilitate this sharing of 609 * <code>Image</code> objects may continue to hold onto images 610 * that are no longer in use for an indefinite period of time, 611 * developers are encouraged to implement their own caching of 612 * images by using the {@link #createImage(java.lang.String) createImage} 613 * variant wherever available. 614 * If the image data contained in the specified file changes, 615 * the <code>Image</code> object returned from this method may 616 * still contain stale information which was loaded from the 617 * file after a prior call. 618 * Previously loaded image data can be manually discarded by 619 * calling the {@link Image#flush flush} method on the 620 * returned <code>Image</code>. 621 * <p> 622 * This method first checks if there is a security manager installed. 623 * If so, the method calls the security manager's 624 * <code>checkRead</code> method with the file specified to ensure 625 * that the access to the image is allowed. 626 * @param filename the name of a file containing pixel data 627 * in a recognized file format. 628 * @return an image which gets its pixel data from 629 * the specified file. 630 * @throws SecurityException if a security manager exists and its 631 * checkRead method doesn't allow the operation. 632 * @see #createImage(java.lang.String) 633 */ 634 public abstract Image getImage(String filename); 635 636 /** 637 * Returns an image which gets pixel data from the specified URL. 638 * The pixel data referenced by the specified URL must be in one 639 * of the following formats: GIF, JPEG or PNG. 640 * The underlying toolkit attempts to resolve multiple requests 641 * with the same URL to the same returned Image. 642 * <p> 643 * Since the mechanism required to facilitate this sharing of 644 * <code>Image</code> objects may continue to hold onto images 645 * that are no longer in use for an indefinite period of time, 646 * developers are encouraged to implement their own caching of 647 * images by using the {@link #createImage(java.net.URL) createImage} 648 * variant wherever available. 649 * If the image data stored at the specified URL changes, 650 * the <code>Image</code> object returned from this method may 651 * still contain stale information which was fetched from the 652 * URL after a prior call. 653 * Previously loaded image data can be manually discarded by 654 * calling the {@link Image#flush flush} method on the 655 * returned <code>Image</code>. 656 * <p> 657 * This method first checks if there is a security manager installed. 658 * If so, the method calls the security manager's 659 * <code>checkPermission</code> method with the 660 * url.openConnection().getPermission() permission to ensure 661 * that the access to the image is allowed. For compatibility 662 * with pre-1.2 security managers, if the access is denied with 663 * <code>FilePermission</code> or <code>SocketPermission</code>, 664 * the method throws the <code>SecurityException</code> 665 * if the corresponding 1.1-style SecurityManager.checkXXX method 666 * also denies permission. 667 * @param url the URL to use in fetching the pixel data. 668 * @return an image which gets its pixel data from 669 * the specified URL. 670 * @throws SecurityException if a security manager exists and its 671 * checkPermission method doesn't allow 672 * the operation. 673 * @see #createImage(java.net.URL) 674 */ 675 public abstract Image getImage(URL url); 676 677 /** 678 * Returns an image which gets pixel data from the specified file. 679 * The returned Image is a new object which will not be shared 680 * with any other caller of this method or its getImage variant. 681 * <p> 682 * This method first checks if there is a security manager installed. 683 * If so, the method calls the security manager's 684 * <code>checkRead</code> method with the specified file to ensure 685 * that the image creation is allowed. 686 * @param filename the name of a file containing pixel data 687 * in a recognized file format. 688 * @return an image which gets its pixel data from 689 * the specified file. 690 * @throws SecurityException if a security manager exists and its 691 * checkRead method doesn't allow the operation. 692 * @see #getImage(java.lang.String) 693 */ 694 public abstract Image createImage(String filename); 695 696 /** 697 * Returns an image which gets pixel data from the specified URL. 698 * The returned Image is a new object which will not be shared 699 * with any other caller of this method or its getImage variant. 700 * <p> 701 * This method first checks if there is a security manager installed. 702 * If so, the method calls the security manager's 703 * <code>checkPermission</code> method with the 704 * url.openConnection().getPermission() permission to ensure 705 * that the image creation is allowed. For compatibility 706 * with pre-1.2 security managers, if the access is denied with 707 * <code>FilePermission</code> or <code>SocketPermission</code>, 708 * the method throws <code>SecurityException</code> 709 * if the corresponding 1.1-style SecurityManager.checkXXX method 710 * also denies permission. 711 * @param url the URL to use in fetching the pixel data. 712 * @return an image which gets its pixel data from 713 * the specified URL. 714 * @throws SecurityException if a security manager exists and its 715 * checkPermission method doesn't allow 716 * the operation. 717 * @see #getImage(java.net.URL) 718 */ 719 public abstract Image createImage(URL url); 720 721 /** 722 * Prepares an image for rendering. 723 * <p> 724 * If the values of the width and height arguments are both 725 * <code>-1</code>, this method prepares the image for rendering 726 * on the default screen; otherwise, this method prepares an image 727 * for rendering on the default screen at the specified width and height. 728 * <p> 729 * The image data is downloaded asynchronously in another thread, 730 * and an appropriately scaled screen representation of the image is 731 * generated. 732 * <p> 733 * This method is called by components <code>prepareImage</code> 734 * methods. 735 * <p> 736 * Information on the flags returned by this method can be found 737 * with the definition of the <code>ImageObserver</code> interface. 738 739 * @param image the image for which to prepare a 740 * screen representation. 741 * @param width the width of the desired screen 742 * representation, or <code>-1</code>. 743 * @param height the height of the desired screen 744 * representation, or <code>-1</code>. 745 * @param observer the <code>ImageObserver</code> 746 * object to be notified as the 747 * image is being prepared. 748 * @return <code>true</code> if the image has already been 749 * fully prepared; <code>false</code> otherwise. 750 * @see java.awt.Component#prepareImage(java.awt.Image, 751 * java.awt.image.ImageObserver) 752 * @see java.awt.Component#prepareImage(java.awt.Image, 753 * int, int, java.awt.image.ImageObserver) 754 * @see java.awt.image.ImageObserver 755 */ 756 public abstract boolean prepareImage(Image image, int width, int height, 757 ImageObserver observer); 758 759 /** 760 * Indicates the construction status of a specified image that is 761 * being prepared for display. 762 * <p> 763 * If the values of the width and height arguments are both 764 * <code>-1</code>, this method returns the construction status of 765 * a screen representation of the specified image in this toolkit. 766 * Otherwise, this method returns the construction status of a 767 * scaled representation of the image at the specified width 768 * and height. 769 * <p> 770 * This method does not cause the image to begin loading. 771 * An application must call <code>prepareImage</code> to force 772 * the loading of an image. 773 * <p> 774 * This method is called by the component's <code>checkImage</code> 775 * methods. 776 * <p> 777 * Information on the flags returned by this method can be found 778 * with the definition of the <code>ImageObserver</code> interface. 779 * @param image the image whose status is being checked. 780 * @param width the width of the scaled version whose status is 781 * being checked, or <code>-1</code>. 782 * @param height the height of the scaled version whose status 783 * is being checked, or <code>-1</code>. 784 * @param observer the <code>ImageObserver</code> object to be 785 * notified as the image is being prepared. 786 * @return the bitwise inclusive <strong>OR</strong> of the 787 * <code>ImageObserver</code> flags for the 788 * image data that is currently available. 789 * @see java.awt.Toolkit#prepareImage(java.awt.Image, 790 * int, int, java.awt.image.ImageObserver) 791 * @see java.awt.Component#checkImage(java.awt.Image, 792 * java.awt.image.ImageObserver) 793 * @see java.awt.Component#checkImage(java.awt.Image, 794 * int, int, java.awt.image.ImageObserver) 795 * @see java.awt.image.ImageObserver 796 */ 797 public abstract int checkImage(Image image, int width, int height, 798 ImageObserver observer); 799 800 /** 801 * Creates an image with the specified image producer. 802 * @param producer the image producer to be used. 803 * @return an image with the specified image producer. 804 * @see java.awt.Image 805 * @see java.awt.image.ImageProducer 806 * @see java.awt.Component#createImage(java.awt.image.ImageProducer) 807 */ 808 public abstract Image createImage(ImageProducer producer); 809 810 /** 811 * Creates an image which decodes the image stored in the specified 812 * byte array. 813 * <p> 814 * The data must be in some image format, such as GIF or JPEG, 815 * that is supported by this toolkit. 816 * @param imagedata an array of bytes, representing 817 * image data in a supported image format. 818 * @return an image. 819 * @since 1.1 820 */ 821 public Image createImage(byte[] imagedata) { 822 return createImage(imagedata, 0, imagedata.length); 823 } 824 825 /** 826 * Creates an image which decodes the image stored in the specified 827 * byte array, and at the specified offset and length. 828 * The data must be in some image format, such as GIF or JPEG, 829 * that is supported by this toolkit. 830 * @param imagedata an array of bytes, representing 831 * image data in a supported image format. 832 * @param imageoffset the offset of the beginning 833 * of the data in the array. 834 * @param imagelength the length of the data in the array. 835 * @return an image. 836 * @since 1.1 837 */ 838 public abstract Image createImage(byte[] imagedata, 839 int imageoffset, 840 int imagelength); 841 842 /** 843 * Gets a <code>PrintJob</code> object which is the result of initiating 844 * a print operation on the toolkit's platform. 845 * <p> 846 * Each actual implementation of this method should first check if there 847 * is a security manager installed. If there is, the method should call 848 * the security manager's <code>checkPrintJobAccess</code> method to 849 * ensure initiation of a print operation is allowed. If the default 850 * implementation of <code>checkPrintJobAccess</code> is used (that is, 851 * that method is not overriden), then this results in a call to the 852 * security manager's <code>checkPermission</code> method with a <code> 853 * RuntimePermission("queuePrintJob")</code> permission. 854 * 855 * @param frame the parent of the print dialog. May not be null. 856 * @param jobtitle the title of the PrintJob. A null title is equivalent 857 * to "". 858 * @param props a Properties object containing zero or more properties. 859 * Properties are not standardized and are not consistent across 860 * implementations. Because of this, PrintJobs which require job 861 * and page control should use the version of this function which 862 * takes JobAttributes and PageAttributes objects. This object 863 * may be updated to reflect the user's job choices on exit. May 864 * be null. 865 * @return a <code>PrintJob</code> object, or <code>null</code> if the 866 * user cancelled the print job. 867 * @throws NullPointerException if frame is null 868 * @throws SecurityException if this thread is not allowed to initiate a 869 * print job request 870 * @see java.awt.GraphicsEnvironment#isHeadless 871 * @see java.awt.PrintJob 872 * @see java.lang.RuntimePermission 873 * @since 1.1 874 */ 875 public abstract PrintJob getPrintJob(Frame frame, String jobtitle, 876 Properties props); 877 878 /** 879 * Gets a <code>PrintJob</code> object which is the result of initiating 880 * a print operation on the toolkit's platform. 881 * <p> 882 * Each actual implementation of this method should first check if there 883 * is a security manager installed. If there is, the method should call 884 * the security manager's <code>checkPrintJobAccess</code> method to 885 * ensure initiation of a print operation is allowed. If the default 886 * implementation of <code>checkPrintJobAccess</code> is used (that is, 887 * that method is not overriden), then this results in a call to the 888 * security manager's <code>checkPermission</code> method with a <code> 889 * RuntimePermission("queuePrintJob")</code> permission. 890 * 891 * @param frame the parent of the print dialog. May not be null. 892 * @param jobtitle the title of the PrintJob. A null title is equivalent 893 * to "". 894 * @param jobAttributes a set of job attributes which will control the 895 * PrintJob. The attributes will be updated to reflect the user's 896 * choices as outlined in the JobAttributes documentation. May be 897 * null. 898 * @param pageAttributes a set of page attributes which will control the 899 * PrintJob. The attributes will be applied to every page in the 900 * job. The attributes will be updated to reflect the user's 901 * choices as outlined in the PageAttributes documentation. May be 902 * null. 903 * @return a <code>PrintJob</code> object, or <code>null</code> if the 904 * user cancelled the print job. 905 * @throws NullPointerException if frame is null 906 * @throws IllegalArgumentException if pageAttributes specifies differing 907 * cross feed and feed resolutions. Also if this thread has 908 * access to the file system and jobAttributes specifies 909 * print to file, and the specified destination file exists but 910 * is a directory rather than a regular file, does not exist but 911 * cannot be created, or cannot be opened for any other reason. 912 * However in the case of print to file, if a dialog is also 913 * requested to be displayed then the user will be given an 914 * opportunity to select a file and proceed with printing. 915 * The dialog will ensure that the selected output file 916 * is valid before returning from this method. 917 * @throws SecurityException if this thread is not allowed to initiate a 918 * print job request, or if jobAttributes specifies print to file, 919 * and this thread is not allowed to access the file system 920 * @see java.awt.PrintJob 921 * @see java.awt.GraphicsEnvironment#isHeadless 922 * @see java.lang.RuntimePermission 923 * @see java.awt.JobAttributes 924 * @see java.awt.PageAttributes 925 * @since 1.3 926 */ 927 public PrintJob getPrintJob(Frame frame, String jobtitle, 928 JobAttributes jobAttributes, 929 PageAttributes pageAttributes) { 930 // Override to add printing support with new job/page control classes 931 932 if (this != Toolkit.getDefaultToolkit()) { 933 return Toolkit.getDefaultToolkit().getPrintJob(frame, jobtitle, 934 jobAttributes, 935 pageAttributes); 936 } else { 937 return getPrintJob(frame, jobtitle, null); 938 } 939 } 940 941 /** 942 * Emits an audio beep depending on native system settings and hardware 943 * capabilities. 944 * @since 1.1 945 */ 946 public abstract void beep(); 947 948 /** 949 * Gets the singleton instance of the system Clipboard which interfaces 950 * with clipboard facilities provided by the native platform. This 951 * clipboard enables data transfer between Java programs and native 952 * applications which use native clipboard facilities. 953 * <p> 954 * In addition to any and all default formats text returned by the system 955 * Clipboard's <code>getTransferData()</code> method is available in the 956 * following flavors: 957 * <ul> 958 * <li>DataFlavor.stringFlavor</li> 959 * <li>DataFlavor.plainTextFlavor (<b>deprecated</b>)</li> 960 * </ul> 961 * As with <code>java.awt.datatransfer.StringSelection</code>, if the 962 * requested flavor is <code>DataFlavor.plainTextFlavor</code>, or an 963 * equivalent flavor, a Reader is returned. <b>Note:</b> The behavior of 964 * the system Clipboard's <code>getTransferData()</code> method for <code> 965 * DataFlavor.plainTextFlavor</code>, and equivalent DataFlavors, is 966 * inconsistent with the definition of <code>DataFlavor.plainTextFlavor 967 * </code>. Because of this, support for <code> 968 * DataFlavor.plainTextFlavor</code>, and equivalent flavors, is 969 * <b>deprecated</b>. 970 * <p> 971 * Each actual implementation of this method should first check if there 972 * is a security manager installed. If there is, the method should call 973 * the security manager's {@link SecurityManager#checkPermission 974 * checkPermission} method to check {@code AWTPermission("accessClipboard")}. 975 * 976 * @return the system Clipboard 977 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 978 * returns true 979 * @see java.awt.GraphicsEnvironment#isHeadless 980 * @see java.awt.datatransfer.Clipboard 981 * @see java.awt.datatransfer.StringSelection 982 * @see java.awt.datatransfer.DataFlavor#stringFlavor 983 * @see java.awt.datatransfer.DataFlavor#plainTextFlavor 984 * @see java.io.Reader 985 * @see java.awt.AWTPermission 986 * @since 1.1 987 */ 988 public abstract Clipboard getSystemClipboard() 989 throws HeadlessException; 990 991 /** 992 * Gets the singleton instance of the system selection as a 993 * <code>Clipboard</code> object. This allows an application to read and 994 * modify the current, system-wide selection. 995 * <p> 996 * An application is responsible for updating the system selection whenever 997 * the user selects text, using either the mouse or the keyboard. 998 * Typically, this is implemented by installing a 999 * <code>FocusListener</code> on all <code>Component</code>s which support 1000 * text selection, and, between <code>FOCUS_GAINED</code> and 1001 * <code>FOCUS_LOST</code> events delivered to that <code>Component</code>, 1002 * updating the system selection <code>Clipboard</code> when the selection 1003 * changes inside the <code>Component</code>. Properly updating the system 1004 * selection ensures that a Java application will interact correctly with 1005 * native applications and other Java applications running simultaneously 1006 * on the system. Note that <code>java.awt.TextComponent</code> and 1007 * <code>javax.swing.text.JTextComponent</code> already adhere to this 1008 * policy. When using these classes, and their subclasses, developers need 1009 * not write any additional code. 1010 * <p> 1011 * Some platforms do not support a system selection <code>Clipboard</code>. 1012 * On those platforms, this method will return <code>null</code>. In such a 1013 * case, an application is absolved from its responsibility to update the 1014 * system selection <code>Clipboard</code> as described above. 1015 * <p> 1016 * Each actual implementation of this method should first check if there 1017 * is a security manager installed. If there is, the method should call 1018 * the security manager's {@link SecurityManager#checkPermission 1019 * checkPermission} method to check {@code AWTPermission("accessClipboard")}. 1020 * 1021 * @return the system selection as a <code>Clipboard</code>, or 1022 * <code>null</code> if the native platform does not support a 1023 * system selection <code>Clipboard</code> 1024 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 1025 * returns true 1026 * 1027 * @see java.awt.datatransfer.Clipboard 1028 * @see java.awt.event.FocusListener 1029 * @see java.awt.event.FocusEvent#FOCUS_GAINED 1030 * @see java.awt.event.FocusEvent#FOCUS_LOST 1031 * @see TextComponent 1032 * @see javax.swing.text.JTextComponent 1033 * @see AWTPermission 1034 * @see GraphicsEnvironment#isHeadless 1035 * @since 1.4 1036 */ 1037 public Clipboard getSystemSelection() throws HeadlessException { 1038 GraphicsEnvironment.checkHeadless(); 1039 1040 if (this != Toolkit.getDefaultToolkit()) { 1041 return Toolkit.getDefaultToolkit().getSystemSelection(); 1042 } else { 1043 GraphicsEnvironment.checkHeadless(); 1044 return null; 1045 } 1046 } 1047 1048 /** 1049 * Determines which modifier key is the appropriate accelerator 1050 * key for menu shortcuts. 1051 * <p> 1052 * Menu shortcuts, which are embodied in the 1053 * <code>MenuShortcut</code> class, are handled by the 1054 * <code>MenuBar</code> class. 1055 * <p> 1056 * By default, this method returns <code>Event.CTRL_MASK</code>. 1057 * Toolkit implementations should override this method if the 1058 * <b>Control</b> key isn't the correct key for accelerators. 1059 * @return the modifier mask on the <code>Event</code> class 1060 * that is used for menu shortcuts on this toolkit. 1061 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 1062 * returns true 1063 * @see java.awt.GraphicsEnvironment#isHeadless 1064 * @see java.awt.MenuBar 1065 * @see java.awt.MenuShortcut 1066 * @since 1.1 1067 */ 1068 public int getMenuShortcutKeyMask() throws HeadlessException { 1069 GraphicsEnvironment.checkHeadless(); 1070 1071 return Event.CTRL_MASK; 1072 } 1073 1074 /** 1075 * Returns whether the given locking key on the keyboard is currently in 1076 * its "on" state. 1077 * Valid key codes are 1078 * {@link java.awt.event.KeyEvent#VK_CAPS_LOCK VK_CAPS_LOCK}, 1079 * {@link java.awt.event.KeyEvent#VK_NUM_LOCK VK_NUM_LOCK}, 1080 * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and 1081 * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}. 1082 * 1083 * @param keyCode the key code 1084 * @return {@code true} if the given key is currently in its "on" state; 1085 * otherwise {@code false} 1086 * @exception java.lang.IllegalArgumentException if <code>keyCode</code> 1087 * is not one of the valid key codes 1088 * @exception java.lang.UnsupportedOperationException if the host system doesn't 1089 * allow getting the state of this key programmatically, or if the keyboard 1090 * doesn't have this key 1091 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 1092 * returns true 1093 * @see java.awt.GraphicsEnvironment#isHeadless 1094 * @since 1.3 1095 */ 1096 public boolean getLockingKeyState(int keyCode) 1097 throws UnsupportedOperationException 1098 { 1099 GraphicsEnvironment.checkHeadless(); 1100 1101 if (! (keyCode == KeyEvent.VK_CAPS_LOCK || keyCode == KeyEvent.VK_NUM_LOCK || 1102 keyCode == KeyEvent.VK_SCROLL_LOCK || keyCode == KeyEvent.VK_KANA_LOCK)) { 1103 throw new IllegalArgumentException("invalid key for Toolkit.getLockingKeyState"); 1104 } 1105 throw new UnsupportedOperationException("Toolkit.getLockingKeyState"); 1106 } 1107 1108 /** 1109 * Sets the state of the given locking key on the keyboard. 1110 * Valid key codes are 1111 * {@link java.awt.event.KeyEvent#VK_CAPS_LOCK VK_CAPS_LOCK}, 1112 * {@link java.awt.event.KeyEvent#VK_NUM_LOCK VK_NUM_LOCK}, 1113 * {@link java.awt.event.KeyEvent#VK_SCROLL_LOCK VK_SCROLL_LOCK}, and 1114 * {@link java.awt.event.KeyEvent#VK_KANA_LOCK VK_KANA_LOCK}. 1115 * <p> 1116 * Depending on the platform, setting the state of a locking key may 1117 * involve event processing and therefore may not be immediately 1118 * observable through getLockingKeyState. 1119 * 1120 * @param keyCode the key code 1121 * @param on the state of the key 1122 * @exception java.lang.IllegalArgumentException if <code>keyCode</code> 1123 * is not one of the valid key codes 1124 * @exception java.lang.UnsupportedOperationException if the host system doesn't 1125 * allow setting the state of this key programmatically, or if the keyboard 1126 * doesn't have this key 1127 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 1128 * returns true 1129 * @see java.awt.GraphicsEnvironment#isHeadless 1130 * @since 1.3 1131 */ 1132 public void setLockingKeyState(int keyCode, boolean on) 1133 throws UnsupportedOperationException 1134 { 1135 GraphicsEnvironment.checkHeadless(); 1136 1137 if (! (keyCode == KeyEvent.VK_CAPS_LOCK || keyCode == KeyEvent.VK_NUM_LOCK || 1138 keyCode == KeyEvent.VK_SCROLL_LOCK || keyCode == KeyEvent.VK_KANA_LOCK)) { 1139 throw new IllegalArgumentException("invalid key for Toolkit.setLockingKeyState"); 1140 } 1141 throw new UnsupportedOperationException("Toolkit.setLockingKeyState"); 1142 } 1143 1144 /** 1145 * Give native peers the ability to query the native container 1146 * given a native component (eg the direct parent may be lightweight). 1147 * 1148 * @param c the component to fetch the container for 1149 * @return the native container object for the component 1150 */ 1151 protected static Container getNativeContainer(Component c) { 1152 return c.getNativeContainer(); 1153 } 1154 1155 /** 1156 * Creates a new custom cursor object. 1157 * If the image to display is invalid, the cursor will be hidden (made 1158 * completely transparent), and the hotspot will be set to (0, 0). 1159 * 1160 * <p>Note that multi-frame images are invalid and may cause this 1161 * method to hang. 1162 * 1163 * @param cursor the image to display when the cursor is activated 1164 * @param hotSpot the X and Y of the large cursor's hot spot; the 1165 * hotSpot values must be less than the Dimension returned by 1166 * <code>getBestCursorSize</code> 1167 * @param name a localized description of the cursor, for Java Accessibility use 1168 * @exception IndexOutOfBoundsException if the hotSpot values are outside 1169 * the bounds of the cursor 1170 * @return the cursor created 1171 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 1172 * returns true 1173 * @see java.awt.GraphicsEnvironment#isHeadless 1174 * @since 1.2 1175 */ 1176 public Cursor createCustomCursor(Image cursor, Point hotSpot, String name) 1177 throws IndexOutOfBoundsException, HeadlessException 1178 { 1179 // Override to implement custom cursor support. 1180 if (this != Toolkit.getDefaultToolkit()) { 1181 return Toolkit.getDefaultToolkit(). 1182 createCustomCursor(cursor, hotSpot, name); 1183 } else { 1184 return new Cursor(Cursor.DEFAULT_CURSOR); 1185 } 1186 } 1187 1188 /** 1189 * Returns the supported cursor dimension which is closest to the desired 1190 * sizes. Systems which only support a single cursor size will return that 1191 * size regardless of the desired sizes. Systems which don't support custom 1192 * cursors will return a dimension of 0, 0. <p> 1193 * Note: if an image is used whose dimensions don't match a supported size 1194 * (as returned by this method), the Toolkit implementation will attempt to 1195 * resize the image to a supported size. 1196 * Since converting low-resolution images is difficult, 1197 * no guarantees are made as to the quality of a cursor image which isn't a 1198 * supported size. It is therefore recommended that this method 1199 * be called and an appropriate image used so no image conversion is made. 1200 * 1201 * @param preferredWidth the preferred cursor width the component would like 1202 * to use. 1203 * @param preferredHeight the preferred cursor height the component would like 1204 * to use. 1205 * @return the closest matching supported cursor size, or a dimension of 0,0 if 1206 * the Toolkit implementation doesn't support custom cursors. 1207 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 1208 * returns true 1209 * @see java.awt.GraphicsEnvironment#isHeadless 1210 * @since 1.2 1211 */ 1212 public Dimension getBestCursorSize(int preferredWidth, 1213 int preferredHeight) throws HeadlessException { 1214 GraphicsEnvironment.checkHeadless(); 1215 1216 // Override to implement custom cursor support. 1217 if (this != Toolkit.getDefaultToolkit()) { 1218 return Toolkit.getDefaultToolkit(). 1219 getBestCursorSize(preferredWidth, preferredHeight); 1220 } else { 1221 return new Dimension(0, 0); 1222 } 1223 } 1224 1225 /** 1226 * Returns the maximum number of colors the Toolkit supports in a custom cursor 1227 * palette.<p> 1228 * Note: if an image is used which has more colors in its palette than 1229 * the supported maximum, the Toolkit implementation will attempt to flatten the 1230 * palette to the maximum. Since converting low-resolution images is difficult, 1231 * no guarantees are made as to the quality of a cursor image which has more 1232 * colors than the system supports. It is therefore recommended that this method 1233 * be called and an appropriate image used so no image conversion is made. 1234 * 1235 * @return the maximum number of colors, or zero if custom cursors are not 1236 * supported by this Toolkit implementation. 1237 * @exception HeadlessException if GraphicsEnvironment.isHeadless() 1238 * returns true 1239 * @see java.awt.GraphicsEnvironment#isHeadless 1240 * @since 1.2 1241 */ 1242 public int getMaximumCursorColors() throws HeadlessException { 1243 GraphicsEnvironment.checkHeadless(); 1244 1245 // Override to implement custom cursor support. 1246 if (this != Toolkit.getDefaultToolkit()) { 1247 return Toolkit.getDefaultToolkit().getMaximumCursorColors(); 1248 } else { 1249 return 0; 1250 } 1251 } 1252 1253 /** 1254 * Returns whether Toolkit supports this state for 1255 * <code>Frame</code>s. This method tells whether the <em>UI 1256 * concept</em> of, say, maximization or iconification is 1257 * supported. It will always return false for "compound" states 1258 * like <code>Frame.ICONIFIED|Frame.MAXIMIZED_VERT</code>. 1259 * In other words, the rule of thumb is that only queries with a 1260 * single frame state constant as an argument are meaningful. 1261 * <p>Note that supporting a given concept is a platform- 1262 * dependent feature. Due to native limitations the Toolkit 1263 * object may report a particular state as supported, however at 1264 * the same time the Toolkit object will be unable to apply the 1265 * state to a given frame. This circumstance has two following 1266 * consequences: 1267 * <ul> 1268 * <li>Only the return value of {@code false} for the present 1269 * method actually indicates that the given state is not 1270 * supported. If the method returns {@code true} the given state 1271 * may still be unsupported and/or unavailable for a particular 1272 * frame. 1273 * <li>The developer should consider examining the value of the 1274 * {@link java.awt.event.WindowEvent#getNewState} method of the 1275 * {@code WindowEvent} received through the {@link 1276 * java.awt.event.WindowStateListener}, rather than assuming 1277 * that the state given to the {@code setExtendedState()} method 1278 * will be definitely applied. For more information see the 1279 * documentation for the {@link Frame#setExtendedState} method. 1280 * </ul> 1281 * 1282 * @param state one of named frame state constants. 1283 * @return <code>true</code> is this frame state is supported by 1284 * this Toolkit implementation, <code>false</code> otherwise. 1285 * @exception HeadlessException 1286 * if <code>GraphicsEnvironment.isHeadless()</code> 1287 * returns <code>true</code>. 1288 * @see java.awt.Window#addWindowStateListener 1289 * @since 1.4 1290 */ 1291 public boolean isFrameStateSupported(int state) 1292 throws HeadlessException 1293 { 1294 GraphicsEnvironment.checkHeadless(); 1295 1296 if (this != Toolkit.getDefaultToolkit()) { 1297 return Toolkit.getDefaultToolkit(). 1298 isFrameStateSupported(state); 1299 } else { 1300 return (state == Frame.NORMAL); // others are not guaranteed 1301 } 1302 } 1303 1304 /** 1305 * Support for I18N: any visible strings should be stored in 1306 * sun.awt.resources.awt.properties. The ResourceBundle is stored 1307 * here, so that only one copy is maintained. 1308 */ 1309 private static ResourceBundle resources; 1310 private static ResourceBundle platformResources; 1311 1312 // called by platform toolkit 1313 private static void setPlatformResources(ResourceBundle bundle) { 1314 platformResources = bundle; 1315 } 1316 1317 /** 1318 * Initialize JNI field and method ids 1319 */ 1320 private static native void initIDs(); 1321 1322 /** 1323 * WARNING: This is a temporary workaround for a problem in the 1324 * way the AWT loads native libraries. A number of classes in the 1325 * AWT package have a native method, initIDs(), which initializes 1326 * the JNI field and method ids used in the native portion of 1327 * their implementation. 1328 * 1329 * Since the use and storage of these ids is done by the 1330 * implementation libraries, the implementation of these method is 1331 * provided by the particular AWT implementations (for example, 1332 * "Toolkit"s/Peer), such as Motif, Microsoft Windows, or Tiny. The 1333 * problem is that this means that the native libraries must be 1334 * loaded by the java.* classes, which do not necessarily know the 1335 * names of the libraries to load. A better way of doing this 1336 * would be to provide a separate library which defines java.awt.* 1337 * initIDs, and exports the relevant symbols out to the 1338 * implementation libraries. 1339 * 1340 * For now, we know it's done by the implementation, and we assume 1341 * that the name of the library is "awt". -br. 1342 * 1343 * If you change loadLibraries(), please add the change to 1344 * java.awt.image.ColorModel.loadLibraries(). Unfortunately, 1345 * classes can be loaded in java.awt.image that depend on 1346 * libawt and there is no way to call Toolkit.loadLibraries() 1347 * directly. -hung 1348 */ 1349 private static boolean loaded = false; 1350 static void loadLibraries() { 1351 if (!loaded) { 1352 java.security.AccessController.doPrivileged( 1353 new java.security.PrivilegedAction<Void>() { 1354 public Void run() { 1355 System.loadLibrary("awt"); 1356 return null; 1357 } 1358 }); 1359 loaded = true; 1360 } 1361 } 1362 1363 static { 1364 AWTAccessor.setToolkitAccessor( 1365 new AWTAccessor.ToolkitAccessor() { 1366 @Override 1367 public void setPlatformResources(ResourceBundle bundle) { 1368 Toolkit.setPlatformResources(bundle); 1369 } 1370 }); 1371 1372 java.security.AccessController.doPrivileged( 1373 new java.security.PrivilegedAction<Void>() { 1374 public Void run() { 1375 try { 1376 resources = 1377 ResourceBundle.getBundle("sun.awt.resources.awt", 1378 CoreResourceBundleControl.getRBControlInstance()); 1379 } catch (MissingResourceException e) { 1380 // No resource file; defaults will be used. 1381 } 1382 return null; 1383 } 1384 }); 1385 1386 // ensure that the proper libraries are loaded 1387 loadLibraries(); 1388 initAssistiveTechnologies(); 1389 if (!GraphicsEnvironment.isHeadless()) { 1390 initIDs(); 1391 } 1392 } 1393 1394 /** 1395 * Gets a property with the specified key and default. 1396 * This method returns defaultValue if the property is not found. 1397 * 1398 * @param key the key 1399 * @param defaultValue the default value 1400 * @return the value of the property or the default value 1401 * if the property was not found 1402 */ 1403 public static String getProperty(String key, String defaultValue) { 1404 // first try platform specific bundle 1405 if (platformResources != null) { 1406 try { 1407 return platformResources.getString(key); 1408 } 1409 catch (MissingResourceException e) {} 1410 } 1411 1412 // then shared one 1413 if (resources != null) { 1414 try { 1415 return resources.getString(key); 1416 } 1417 catch (MissingResourceException e) {} 1418 } 1419 1420 return defaultValue; 1421 } 1422 1423 /** 1424 * Get the application's or applet's EventQueue instance. 1425 * Depending on the Toolkit implementation, different EventQueues 1426 * may be returned for different applets. Applets should 1427 * therefore not assume that the EventQueue instance returned 1428 * by this method will be shared by other applets or the system. 1429 * 1430 * <p> If there is a security manager then its 1431 * {@link SecurityManager#checkPermission checkPermission} method 1432 * is called to check {@code AWTPermission("accessEventQueue")}. 1433 * 1434 * @return the <code>EventQueue</code> object 1435 * @throws SecurityException 1436 * if a security manager is set and it denies access to 1437 * the {@code EventQueue} 1438 * @see java.awt.AWTPermission 1439 */ 1440 public final EventQueue getSystemEventQueue() { 1441 SecurityManager security = System.getSecurityManager(); 1442 if (security != null) { 1443 security.checkPermission(AWTPermissions.CHECK_AWT_EVENTQUEUE_PERMISSION); 1444 } 1445 return getSystemEventQueueImpl(); 1446 } 1447 1448 /** 1449 * Gets the application's or applet's <code>EventQueue</code> 1450 * instance, without checking access. For security reasons, 1451 * this can only be called from a <code>Toolkit</code> subclass. 1452 * @return the <code>EventQueue</code> object 1453 */ 1454 protected abstract EventQueue getSystemEventQueueImpl(); 1455 1456 /* Accessor method for use by AWT package routines. */ 1457 static EventQueue getEventQueue() { 1458 return getDefaultToolkit().getSystemEventQueueImpl(); 1459 } 1460 1461 /** 1462 * Creates a concrete, platform dependent, subclass of the abstract 1463 * DragGestureRecognizer class requested, and associates it with the 1464 * DragSource, Component and DragGestureListener specified. 1465 * 1466 * subclasses should override this to provide their own implementation 1467 * 1468 * @param <T> the type of DragGestureRecognizer to create 1469 * @param abstractRecognizerClass The abstract class of the required recognizer 1470 * @param ds The DragSource 1471 * @param c The Component target for the DragGestureRecognizer 1472 * @param srcActions The actions permitted for the gesture 1473 * @param dgl The DragGestureListener 1474 * 1475 * @return the new object or null. Always returns null if 1476 * GraphicsEnvironment.isHeadless() returns true. 1477 * @see java.awt.GraphicsEnvironment#isHeadless 1478 */ 1479 public <T extends DragGestureRecognizer> T 1480 createDragGestureRecognizer(Class<T> abstractRecognizerClass, 1481 DragSource ds, Component c, int srcActions, 1482 DragGestureListener dgl) 1483 { 1484 return null; 1485 } 1486 1487 /** 1488 * Obtains a value for the specified desktop property. 1489 * 1490 * A desktop property is a uniquely named value for a resource that 1491 * is Toolkit global in nature. Usually it also is an abstract 1492 * representation for an underlying platform dependent desktop setting. 1493 * For more information on desktop properties supported by the AWT see 1494 * <a href="doc-files/DesktopProperties.html">AWT Desktop Properties</a>. 1495 * 1496 * @param propertyName the property name 1497 * @return the value for the specified desktop property 1498 */ 1499 public final synchronized Object getDesktopProperty(String propertyName) { 1500 // This is a workaround for headless toolkits. It would be 1501 // better to override this method but it is declared final. 1502 // "this instanceof" syntax defeats polymorphism. 1503 // --mm, 03/03/00 1504 if (this instanceof HeadlessToolkit) { 1505 return ((HeadlessToolkit)this).getUnderlyingToolkit() 1506 .getDesktopProperty(propertyName); 1507 } 1508 1509 if (desktopProperties.isEmpty()) { 1510 initializeDesktopProperties(); 1511 } 1512 1513 Object value; 1514 1515 // This property should never be cached 1516 if (propertyName.equals("awt.dynamicLayoutSupported")) { 1517 return getDefaultToolkit().lazilyLoadDesktopProperty(propertyName); 1518 } 1519 1520 value = desktopProperties.get(propertyName); 1521 1522 if (value == null) { 1523 value = lazilyLoadDesktopProperty(propertyName); 1524 1525 if (value != null) { 1526 setDesktopProperty(propertyName, value); 1527 } 1528 } 1529 1530 /* for property "awt.font.desktophints" */ 1531 if (value instanceof RenderingHints) { 1532 value = ((RenderingHints)value).clone(); 1533 } 1534 1535 return value; 1536 } 1537 1538 /** 1539 * Sets the named desktop property to the specified value and fires a 1540 * property change event to notify any listeners that the value has changed. 1541 * 1542 * @param name the property name 1543 * @param newValue the new property value 1544 */ 1545 protected final void setDesktopProperty(String name, Object newValue) { 1546 // This is a workaround for headless toolkits. It would be 1547 // better to override this method but it is declared final. 1548 // "this instanceof" syntax defeats polymorphism. 1549 // --mm, 03/03/00 1550 if (this instanceof HeadlessToolkit) { 1551 ((HeadlessToolkit)this).getUnderlyingToolkit() 1552 .setDesktopProperty(name, newValue); 1553 return; 1554 } 1555 Object oldValue; 1556 1557 synchronized (this) { 1558 oldValue = desktopProperties.get(name); 1559 desktopProperties.put(name, newValue); 1560 } 1561 1562 // Don't fire change event if old and new values are null. 1563 // It helps to avoid recursive resending of WM_THEMECHANGED 1564 if (oldValue != null || newValue != null) { 1565 desktopPropsSupport.firePropertyChange(name, oldValue, newValue); 1566 } 1567 } 1568 1569 /** 1570 * An opportunity to lazily evaluate desktop property values. 1571 * @return the desktop property or null 1572 * @param name the name 1573 */ 1574 protected Object lazilyLoadDesktopProperty(String name) { 1575 return null; 1576 } 1577 1578 /** 1579 * initializeDesktopProperties 1580 */ 1581 protected void initializeDesktopProperties() { 1582 } 1583 1584 /** 1585 * Adds the specified property change listener for the named desktop 1586 * property. When a {@link java.beans.PropertyChangeListenerProxy} object is added, 1587 * its property name is ignored, and the wrapped listener is added. 1588 * If {@code name} is {@code null} or {@code pcl} is {@code null}, 1589 * no exception is thrown and no action is performed. 1590 * 1591 * @param name The name of the property to listen for 1592 * @param pcl The property change listener 1593 * @see PropertyChangeSupport#addPropertyChangeListener(String, 1594 PropertyChangeListener) 1595 * @since 1.2 1596 */ 1597 public void addPropertyChangeListener(String name, PropertyChangeListener pcl) { 1598 desktopPropsSupport.addPropertyChangeListener(name, pcl); 1599 } 1600 1601 /** 1602 * Removes the specified property change listener for the named 1603 * desktop property. When a {@link java.beans.PropertyChangeListenerProxy} object 1604 * is removed, its property name is ignored, and 1605 * the wrapped listener is removed. 1606 * If {@code name} is {@code null} or {@code pcl} is {@code null}, 1607 * no exception is thrown and no action is performed. 1608 * 1609 * @param name The name of the property to remove 1610 * @param pcl The property change listener 1611 * @see PropertyChangeSupport#removePropertyChangeListener(String, 1612 PropertyChangeListener) 1613 * @since 1.2 1614 */ 1615 public void removePropertyChangeListener(String name, PropertyChangeListener pcl) { 1616 desktopPropsSupport.removePropertyChangeListener(name, pcl); 1617 } 1618 1619 /** 1620 * Returns an array of all the property change listeners 1621 * registered on this toolkit. The returned array 1622 * contains {@link java.beans.PropertyChangeListenerProxy} objects 1623 * that associate listeners with the names of desktop properties. 1624 * 1625 * @return all of this toolkit's {@link PropertyChangeListener} 1626 * objects wrapped in {@code java.beans.PropertyChangeListenerProxy} objects 1627 * or an empty array if no listeners are added 1628 * 1629 * @see PropertyChangeSupport#getPropertyChangeListeners() 1630 * @since 1.4 1631 */ 1632 public PropertyChangeListener[] getPropertyChangeListeners() { 1633 return desktopPropsSupport.getPropertyChangeListeners(); 1634 } 1635 1636 /** 1637 * Returns an array of all property change listeners 1638 * associated with the specified name of a desktop property. 1639 * 1640 * @param propertyName the named property 1641 * @return all of the {@code PropertyChangeListener} objects 1642 * associated with the specified name of a desktop property 1643 * or an empty array if no such listeners are added 1644 * 1645 * @see PropertyChangeSupport#getPropertyChangeListeners(String) 1646 * @since 1.4 1647 */ 1648 public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { 1649 return desktopPropsSupport.getPropertyChangeListeners(propertyName); 1650 } 1651 1652 /** 1653 * The desktop properties. 1654 */ 1655 protected final Map<String,Object> desktopProperties = 1656 new HashMap<String,Object>(); 1657 /** 1658 * The desktop properties change support. 1659 */ 1660 protected final PropertyChangeSupport desktopPropsSupport = 1661 Toolkit.createPropertyChangeSupport(this); 1662 1663 /** 1664 * Returns whether the always-on-top mode is supported by this toolkit. 1665 * To detect whether the always-on-top mode is supported for a 1666 * particular Window, use {@link Window#isAlwaysOnTopSupported}. 1667 * @return <code>true</code>, if current toolkit supports the always-on-top mode, 1668 * otherwise returns <code>false</code> 1669 * @see Window#isAlwaysOnTopSupported 1670 * @see Window#setAlwaysOnTop(boolean) 1671 * @since 1.6 1672 */ 1673 public boolean isAlwaysOnTopSupported() { 1674 return true; 1675 } 1676 1677 /** 1678 * Returns whether the given modality type is supported by this toolkit. If 1679 * a dialog with unsupported modality type is created, then 1680 * <code>Dialog.ModalityType.MODELESS</code> is used instead. 1681 * 1682 * @param modalityType modality type to be checked for support by this toolkit 1683 * 1684 * @return <code>true</code>, if current toolkit supports given modality 1685 * type, <code>false</code> otherwise 1686 * 1687 * @see java.awt.Dialog.ModalityType 1688 * @see java.awt.Dialog#getModalityType 1689 * @see java.awt.Dialog#setModalityType 1690 * 1691 * @since 1.6 1692 */ 1693 public abstract boolean isModalityTypeSupported(Dialog.ModalityType modalityType); 1694 1695 /** 1696 * Returns whether the given modal exclusion type is supported by this 1697 * toolkit. If an unsupported modal exclusion type property is set on a window, 1698 * then <code>Dialog.ModalExclusionType.NO_EXCLUDE</code> is used instead. 1699 * 1700 * @param modalExclusionType modal exclusion type to be checked for support by this toolkit 1701 * 1702 * @return <code>true</code>, if current toolkit supports given modal exclusion 1703 * type, <code>false</code> otherwise 1704 * 1705 * @see java.awt.Dialog.ModalExclusionType 1706 * @see java.awt.Window#getModalExclusionType 1707 * @see java.awt.Window#setModalExclusionType 1708 * 1709 * @since 1.6 1710 */ 1711 public abstract boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType modalExclusionType); 1712 1713 // 8014718: logging has been removed from SunToolkit 1714 1715 private static final int LONG_BITS = 64; 1716 private int[] calls = new int[LONG_BITS]; 1717 private static volatile long enabledOnToolkitMask; 1718 private AWTEventListener eventListener = null; 1719 private WeakHashMap<AWTEventListener, SelectiveAWTEventListener> listener2SelectiveListener = new WeakHashMap<>(); 1720 1721 /* 1722 * Extracts a "pure" AWTEventListener from a AWTEventListenerProxy, 1723 * if the listener is proxied. 1724 */ 1725 static private AWTEventListener deProxyAWTEventListener(AWTEventListener l) 1726 { 1727 AWTEventListener localL = l; 1728 1729 if (localL == null) { 1730 return null; 1731 } 1732 // if user passed in a AWTEventListenerProxy object, extract 1733 // the listener 1734 if (l instanceof AWTEventListenerProxy) { 1735 localL = ((AWTEventListenerProxy)l).getListener(); 1736 } 1737 return localL; 1738 } 1739 1740 /** 1741 * Adds an AWTEventListener to receive all AWTEvents dispatched 1742 * system-wide that conform to the given <code>eventMask</code>. 1743 * <p> 1744 * First, if there is a security manager, its <code>checkPermission</code> 1745 * method is called with an 1746 * <code>AWTPermission("listenToAllAWTEvents")</code> permission. 1747 * This may result in a SecurityException. 1748 * <p> 1749 * <code>eventMask</code> is a bitmask of event types to receive. 1750 * It is constructed by bitwise OR-ing together the event masks 1751 * defined in <code>AWTEvent</code>. 1752 * <p> 1753 * Note: event listener use is not recommended for normal 1754 * application use, but are intended solely to support special 1755 * purpose facilities including support for accessibility, 1756 * event record/playback, and diagnostic tracing. 1757 * 1758 * If listener is null, no exception is thrown and no action is performed. 1759 * 1760 * @param listener the event listener. 1761 * @param eventMask the bitmask of event types to receive 1762 * @throws SecurityException 1763 * if a security manager exists and its 1764 * <code>checkPermission</code> method doesn't allow the operation. 1765 * @see #removeAWTEventListener 1766 * @see #getAWTEventListeners 1767 * @see SecurityManager#checkPermission 1768 * @see java.awt.AWTEvent 1769 * @see java.awt.AWTPermission 1770 * @see java.awt.event.AWTEventListener 1771 * @see java.awt.event.AWTEventListenerProxy 1772 * @since 1.2 1773 */ 1774 public void addAWTEventListener(AWTEventListener listener, long eventMask) { 1775 AWTEventListener localL = deProxyAWTEventListener(listener); 1776 1777 if (localL == null) { 1778 return; 1779 } 1780 SecurityManager security = System.getSecurityManager(); 1781 if (security != null) { 1782 security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION); 1783 } 1784 synchronized (this) { 1785 SelectiveAWTEventListener selectiveListener = 1786 listener2SelectiveListener.get(localL); 1787 1788 if (selectiveListener == null) { 1789 // Create a new selectiveListener. 1790 selectiveListener = new SelectiveAWTEventListener(localL, 1791 eventMask); 1792 listener2SelectiveListener.put(localL, selectiveListener); 1793 eventListener = ToolkitEventMulticaster.add(eventListener, 1794 selectiveListener); 1795 } 1796 // OR the eventMask into the selectiveListener's event mask. 1797 selectiveListener.orEventMasks(eventMask); 1798 1799 enabledOnToolkitMask |= eventMask; 1800 1801 long mask = eventMask; 1802 for (int i=0; i<LONG_BITS; i++) { 1803 // If no bits are set, break out of loop. 1804 if (mask == 0) { 1805 break; 1806 } 1807 if ((mask & 1L) != 0) { // Always test bit 0. 1808 calls[i]++; 1809 } 1810 mask >>>= 1; // Right shift, fill with zeros on left. 1811 } 1812 } 1813 } 1814 1815 /** 1816 * Removes an AWTEventListener from receiving dispatched AWTEvents. 1817 * <p> 1818 * First, if there is a security manager, its <code>checkPermission</code> 1819 * method is called with an 1820 * <code>AWTPermission("listenToAllAWTEvents")</code> permission. 1821 * This may result in a SecurityException. 1822 * <p> 1823 * Note: event listener use is not recommended for normal 1824 * application use, but are intended solely to support special 1825 * purpose facilities including support for accessibility, 1826 * event record/playback, and diagnostic tracing. 1827 * 1828 * If listener is null, no exception is thrown and no action is performed. 1829 * 1830 * @param listener the event listener. 1831 * @throws SecurityException 1832 * if a security manager exists and its 1833 * <code>checkPermission</code> method doesn't allow the operation. 1834 * @see #addAWTEventListener 1835 * @see #getAWTEventListeners 1836 * @see SecurityManager#checkPermission 1837 * @see java.awt.AWTEvent 1838 * @see java.awt.AWTPermission 1839 * @see java.awt.event.AWTEventListener 1840 * @see java.awt.event.AWTEventListenerProxy 1841 * @since 1.2 1842 */ 1843 public void removeAWTEventListener(AWTEventListener listener) { 1844 AWTEventListener localL = deProxyAWTEventListener(listener); 1845 1846 if (listener == null) { 1847 return; 1848 } 1849 SecurityManager security = System.getSecurityManager(); 1850 if (security != null) { 1851 security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION); 1852 } 1853 1854 synchronized (this) { 1855 SelectiveAWTEventListener selectiveListener = 1856 listener2SelectiveListener.get(localL); 1857 1858 if (selectiveListener != null) { 1859 listener2SelectiveListener.remove(localL); 1860 int[] listenerCalls = selectiveListener.getCalls(); 1861 for (int i=0; i<LONG_BITS; i++) { 1862 calls[i] -= listenerCalls[i]; 1863 assert calls[i] >= 0: "Negative Listeners count"; 1864 1865 if (calls[i] == 0) { 1866 enabledOnToolkitMask &= ~(1L<<i); 1867 } 1868 } 1869 } 1870 eventListener = ToolkitEventMulticaster.remove(eventListener, 1871 (selectiveListener == null) ? localL : selectiveListener); 1872 } 1873 } 1874 1875 static boolean enabledOnToolkit(long eventMask) { 1876 return (enabledOnToolkitMask & eventMask) != 0; 1877 } 1878 1879 synchronized int countAWTEventListeners(long eventMask) { 1880 int ci = 0; 1881 for (; eventMask != 0; eventMask >>>= 1, ci++) { 1882 } 1883 ci--; 1884 return calls[ci]; 1885 } 1886 /** 1887 * Returns an array of all the <code>AWTEventListener</code>s 1888 * registered on this toolkit. 1889 * If there is a security manager, its {@code checkPermission} 1890 * method is called with an 1891 * {@code AWTPermission("listenToAllAWTEvents")} permission. 1892 * This may result in a SecurityException. 1893 * Listeners can be returned 1894 * within <code>AWTEventListenerProxy</code> objects, which also contain 1895 * the event mask for the given listener. 1896 * Note that listener objects 1897 * added multiple times appear only once in the returned array. 1898 * 1899 * @return all of the <code>AWTEventListener</code>s or an empty 1900 * array if no listeners are currently registered 1901 * @throws SecurityException 1902 * if a security manager exists and its 1903 * <code>checkPermission</code> method doesn't allow the operation. 1904 * @see #addAWTEventListener 1905 * @see #removeAWTEventListener 1906 * @see SecurityManager#checkPermission 1907 * @see java.awt.AWTEvent 1908 * @see java.awt.AWTPermission 1909 * @see java.awt.event.AWTEventListener 1910 * @see java.awt.event.AWTEventListenerProxy 1911 * @since 1.4 1912 */ 1913 public AWTEventListener[] getAWTEventListeners() { 1914 SecurityManager security = System.getSecurityManager(); 1915 if (security != null) { 1916 security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION); 1917 } 1918 synchronized (this) { 1919 EventListener[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class); 1920 1921 AWTEventListener[] ret = new AWTEventListener[la.length]; 1922 for (int i = 0; i < la.length; i++) { 1923 SelectiveAWTEventListener sael = (SelectiveAWTEventListener)la[i]; 1924 AWTEventListener tempL = sael.getListener(); 1925 //assert tempL is not an AWTEventListenerProxy - we should 1926 // have weeded them all out 1927 // don't want to wrap a proxy inside a proxy 1928 ret[i] = new AWTEventListenerProxy(sael.getEventMask(), tempL); 1929 } 1930 return ret; 1931 } 1932 } 1933 1934 /** 1935 * Returns an array of all the <code>AWTEventListener</code>s 1936 * registered on this toolkit which listen to all of the event 1937 * types specified in the {@code eventMask} argument. 1938 * If there is a security manager, its {@code checkPermission} 1939 * method is called with an 1940 * {@code AWTPermission("listenToAllAWTEvents")} permission. 1941 * This may result in a SecurityException. 1942 * Listeners can be returned 1943 * within <code>AWTEventListenerProxy</code> objects, which also contain 1944 * the event mask for the given listener. 1945 * Note that listener objects 1946 * added multiple times appear only once in the returned array. 1947 * 1948 * @param eventMask the bitmask of event types to listen for 1949 * @return all of the <code>AWTEventListener</code>s registered 1950 * on this toolkit for the specified 1951 * event types, or an empty array if no such listeners 1952 * are currently registered 1953 * @throws SecurityException 1954 * if a security manager exists and its 1955 * <code>checkPermission</code> method doesn't allow the operation. 1956 * @see #addAWTEventListener 1957 * @see #removeAWTEventListener 1958 * @see SecurityManager#checkPermission 1959 * @see java.awt.AWTEvent 1960 * @see java.awt.AWTPermission 1961 * @see java.awt.event.AWTEventListener 1962 * @see java.awt.event.AWTEventListenerProxy 1963 * @since 1.4 1964 */ 1965 public AWTEventListener[] getAWTEventListeners(long eventMask) { 1966 SecurityManager security = System.getSecurityManager(); 1967 if (security != null) { 1968 security.checkPermission(AWTPermissions.ALL_AWT_EVENTS_PERMISSION); 1969 } 1970 synchronized (this) { 1971 EventListener[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class); 1972 1973 java.util.List<AWTEventListenerProxy> list = new ArrayList<>(la.length); 1974 1975 for (int i = 0; i < la.length; i++) { 1976 SelectiveAWTEventListener sael = (SelectiveAWTEventListener)la[i]; 1977 if ((sael.getEventMask() & eventMask) == eventMask) { 1978 //AWTEventListener tempL = sael.getListener(); 1979 list.add(new AWTEventListenerProxy(sael.getEventMask(), 1980 sael.getListener())); 1981 } 1982 } 1983 return list.toArray(new AWTEventListener[0]); 1984 } 1985 } 1986 1987 /* 1988 * This method notifies any AWTEventListeners that an event 1989 * is about to be dispatched. 1990 * 1991 * @param theEvent the event which will be dispatched. 1992 */ 1993 void notifyAWTEventListeners(AWTEvent theEvent) { 1994 // This is a workaround for headless toolkits. It would be 1995 // better to override this method but it is declared package private. 1996 // "this instanceof" syntax defeats polymorphism. 1997 // --mm, 03/03/00 1998 if (this instanceof HeadlessToolkit) { 1999 ((HeadlessToolkit)this).getUnderlyingToolkit() 2000 .notifyAWTEventListeners(theEvent); 2001 return; 2002 } 2003 2004 AWTEventListener eventListener = this.eventListener; 2005 if (eventListener != null) { 2006 eventListener.eventDispatched(theEvent); 2007 } 2008 } 2009 2010 static private class ToolkitEventMulticaster extends AWTEventMulticaster 2011 implements AWTEventListener { 2012 // Implementation cloned from AWTEventMulticaster. 2013 2014 ToolkitEventMulticaster(AWTEventListener a, AWTEventListener b) { 2015 super(a, b); 2016 } 2017 2018 @SuppressWarnings("overloads") 2019 static AWTEventListener add(AWTEventListener a, 2020 AWTEventListener b) { 2021 if (a == null) return b; 2022 if (b == null) return a; 2023 return new ToolkitEventMulticaster(a, b); 2024 } 2025 2026 @SuppressWarnings("overloads") 2027 static AWTEventListener remove(AWTEventListener l, 2028 AWTEventListener oldl) { 2029 return (AWTEventListener) removeInternal(l, oldl); 2030 } 2031 2032 // #4178589: must overload remove(EventListener) to call our add() 2033 // instead of the static addInternal() so we allocate a 2034 // ToolkitEventMulticaster instead of an AWTEventMulticaster. 2035 // Note: this method is called by AWTEventListener.removeInternal(), 2036 // so its method signature must match AWTEventListener.remove(). 2037 protected EventListener remove(EventListener oldl) { 2038 if (oldl == a) return b; 2039 if (oldl == b) return a; 2040 AWTEventListener a2 = (AWTEventListener)removeInternal(a, oldl); 2041 AWTEventListener b2 = (AWTEventListener)removeInternal(b, oldl); 2042 if (a2 == a && b2 == b) { 2043 return this; // it's not here 2044 } 2045 return add(a2, b2); 2046 } 2047 2048 public void eventDispatched(AWTEvent event) { 2049 ((AWTEventListener)a).eventDispatched(event); 2050 ((AWTEventListener)b).eventDispatched(event); 2051 } 2052 } 2053 2054 private class SelectiveAWTEventListener implements AWTEventListener { 2055 AWTEventListener listener; 2056 private long eventMask; 2057 // This array contains the number of times to call the eventlistener 2058 // for each event type. 2059 int[] calls = new int[Toolkit.LONG_BITS]; 2060 2061 public AWTEventListener getListener() {return listener;} 2062 public long getEventMask() {return eventMask;} 2063 public int[] getCalls() {return calls;} 2064 2065 public void orEventMasks(long mask) { 2066 eventMask |= mask; 2067 // For each event bit set in mask, increment its call count. 2068 for (int i=0; i<Toolkit.LONG_BITS; i++) { 2069 // If no bits are set, break out of loop. 2070 if (mask == 0) { 2071 break; 2072 } 2073 if ((mask & 1L) != 0) { // Always test bit 0. 2074 calls[i]++; 2075 } 2076 mask >>>= 1; // Right shift, fill with zeros on left. 2077 } 2078 } 2079 2080 SelectiveAWTEventListener(AWTEventListener l, long mask) { 2081 listener = l; 2082 eventMask = mask; 2083 } 2084 2085 public void eventDispatched(AWTEvent event) { 2086 long eventBit = 0; // Used to save the bit of the event type. 2087 if (((eventBit = eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 && 2088 event.id >= ComponentEvent.COMPONENT_FIRST && 2089 event.id <= ComponentEvent.COMPONENT_LAST) 2090 || ((eventBit = eventMask & AWTEvent.CONTAINER_EVENT_MASK) != 0 && 2091 event.id >= ContainerEvent.CONTAINER_FIRST && 2092 event.id <= ContainerEvent.CONTAINER_LAST) 2093 || ((eventBit = eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 && 2094 event.id >= FocusEvent.FOCUS_FIRST && 2095 event.id <= FocusEvent.FOCUS_LAST) 2096 || ((eventBit = eventMask & AWTEvent.KEY_EVENT_MASK) != 0 && 2097 event.id >= KeyEvent.KEY_FIRST && 2098 event.id <= KeyEvent.KEY_LAST) 2099 || ((eventBit = eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 && 2100 event.id == MouseEvent.MOUSE_WHEEL) 2101 || ((eventBit = eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 && 2102 (event.id == MouseEvent.MOUSE_MOVED || 2103 event.id == MouseEvent.MOUSE_DRAGGED)) 2104 || ((eventBit = eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 && 2105 event.id != MouseEvent.MOUSE_MOVED && 2106 event.id != MouseEvent.MOUSE_DRAGGED && 2107 event.id != MouseEvent.MOUSE_WHEEL && 2108 event.id >= MouseEvent.MOUSE_FIRST && 2109 event.id <= MouseEvent.MOUSE_LAST) 2110 || ((eventBit = eventMask & AWTEvent.WINDOW_EVENT_MASK) != 0 && 2111 (event.id >= WindowEvent.WINDOW_FIRST && 2112 event.id <= WindowEvent.WINDOW_LAST)) 2113 || ((eventBit = eventMask & AWTEvent.ACTION_EVENT_MASK) != 0 && 2114 event.id >= ActionEvent.ACTION_FIRST && 2115 event.id <= ActionEvent.ACTION_LAST) 2116 || ((eventBit = eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0 && 2117 event.id >= AdjustmentEvent.ADJUSTMENT_FIRST && 2118 event.id <= AdjustmentEvent.ADJUSTMENT_LAST) 2119 || ((eventBit = eventMask & AWTEvent.ITEM_EVENT_MASK) != 0 && 2120 event.id >= ItemEvent.ITEM_FIRST && 2121 event.id <= ItemEvent.ITEM_LAST) 2122 || ((eventBit = eventMask & AWTEvent.TEXT_EVENT_MASK) != 0 && 2123 event.id >= TextEvent.TEXT_FIRST && 2124 event.id <= TextEvent.TEXT_LAST) 2125 || ((eventBit = eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 && 2126 event.id >= InputMethodEvent.INPUT_METHOD_FIRST && 2127 event.id <= InputMethodEvent.INPUT_METHOD_LAST) 2128 || ((eventBit = eventMask & AWTEvent.PAINT_EVENT_MASK) != 0 && 2129 event.id >= PaintEvent.PAINT_FIRST && 2130 event.id <= PaintEvent.PAINT_LAST) 2131 || ((eventBit = eventMask & AWTEvent.INVOCATION_EVENT_MASK) != 0 && 2132 event.id >= InvocationEvent.INVOCATION_FIRST && 2133 event.id <= InvocationEvent.INVOCATION_LAST) 2134 || ((eventBit = eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 && 2135 event.id == HierarchyEvent.HIERARCHY_CHANGED) 2136 || ((eventBit = eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 && 2137 (event.id == HierarchyEvent.ANCESTOR_MOVED || 2138 event.id == HierarchyEvent.ANCESTOR_RESIZED)) 2139 || ((eventBit = eventMask & AWTEvent.WINDOW_STATE_EVENT_MASK) != 0 && 2140 event.id == WindowEvent.WINDOW_STATE_CHANGED) 2141 || ((eventBit = eventMask & AWTEvent.WINDOW_FOCUS_EVENT_MASK) != 0 && 2142 (event.id == WindowEvent.WINDOW_GAINED_FOCUS || 2143 event.id == WindowEvent.WINDOW_LOST_FOCUS)) 2144 || ((eventBit = eventMask & sun.awt.SunToolkit.GRAB_EVENT_MASK) != 0 && 2145 (event instanceof sun.awt.UngrabEvent))) { 2146 // Get the index of the call count for this event type. 2147 // Instead of using Math.log(...) we will calculate it with 2148 // bit shifts. That's what previous implementation looked like: 2149 // 2150 // int ci = (int) (Math.log(eventBit)/Math.log(2)); 2151 int ci = 0; 2152 for (long eMask = eventBit; eMask != 0; eMask >>>= 1, ci++) { 2153 } 2154 ci--; 2155 // Call the listener as many times as it was added for this 2156 // event type. 2157 for (int i=0; i<calls[ci]; i++) { 2158 listener.eventDispatched(event); 2159 } 2160 } 2161 } 2162 } 2163 2164 /** 2165 * Returns a map of visual attributes for the abstract level description 2166 * of the given input method highlight, or null if no mapping is found. 2167 * The style field of the input method highlight is ignored. The map 2168 * returned is unmodifiable. 2169 * @param highlight input method highlight 2170 * @return style attribute map, or <code>null</code> 2171 * @exception HeadlessException if 2172 * <code>GraphicsEnvironment.isHeadless</code> returns true 2173 * @see java.awt.GraphicsEnvironment#isHeadless 2174 * @since 1.3 2175 */ 2176 public abstract Map<java.awt.font.TextAttribute,?> 2177 mapInputMethodHighlight(InputMethodHighlight highlight) 2178 throws HeadlessException; 2179 2180 private static PropertyChangeSupport createPropertyChangeSupport(Toolkit toolkit) { 2181 if (toolkit instanceof SunToolkit || toolkit instanceof HeadlessToolkit) { 2182 return new DesktopPropertyChangeSupport(toolkit); 2183 } else { 2184 return new PropertyChangeSupport(toolkit); 2185 } 2186 } 2187 2188 @SuppressWarnings("serial") 2189 private static class DesktopPropertyChangeSupport extends PropertyChangeSupport { 2190 2191 private static final StringBuilder PROP_CHANGE_SUPPORT_KEY = 2192 new StringBuilder("desktop property change support key"); 2193 private final Object source; 2194 2195 public DesktopPropertyChangeSupport(Object sourceBean) { 2196 super(sourceBean); 2197 source = sourceBean; 2198 } 2199 2200 @Override 2201 public synchronized void addPropertyChangeListener( 2202 String propertyName, 2203 PropertyChangeListener listener) 2204 { 2205 PropertyChangeSupport pcs = (PropertyChangeSupport) 2206 AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY); 2207 if (null == pcs) { 2208 pcs = new PropertyChangeSupport(source); 2209 AppContext.getAppContext().put(PROP_CHANGE_SUPPORT_KEY, pcs); 2210 } 2211 pcs.addPropertyChangeListener(propertyName, listener); 2212 } 2213 2214 @Override 2215 public synchronized void removePropertyChangeListener( 2216 String propertyName, 2217 PropertyChangeListener listener) 2218 { 2219 PropertyChangeSupport pcs = (PropertyChangeSupport) 2220 AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY); 2221 if (null != pcs) { 2222 pcs.removePropertyChangeListener(propertyName, listener); 2223 } 2224 } 2225 2226 @Override 2227 public synchronized PropertyChangeListener[] getPropertyChangeListeners() 2228 { 2229 PropertyChangeSupport pcs = (PropertyChangeSupport) 2230 AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY); 2231 if (null != pcs) { 2232 return pcs.getPropertyChangeListeners(); 2233 } else { 2234 return new PropertyChangeListener[0]; 2235 } 2236 } 2237 2238 @Override 2239 public synchronized PropertyChangeListener[] getPropertyChangeListeners(String propertyName) 2240 { 2241 PropertyChangeSupport pcs = (PropertyChangeSupport) 2242 AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY); 2243 if (null != pcs) { 2244 return pcs.getPropertyChangeListeners(propertyName); 2245 } else { 2246 return new PropertyChangeListener[0]; 2247 } 2248 } 2249 2250 @Override 2251 public synchronized void addPropertyChangeListener(PropertyChangeListener listener) { 2252 PropertyChangeSupport pcs = (PropertyChangeSupport) 2253 AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY); 2254 if (null == pcs) { 2255 pcs = new PropertyChangeSupport(source); 2256 AppContext.getAppContext().put(PROP_CHANGE_SUPPORT_KEY, pcs); 2257 } 2258 pcs.addPropertyChangeListener(listener); 2259 } 2260 2261 @Override 2262 public synchronized void removePropertyChangeListener(PropertyChangeListener listener) { 2263 PropertyChangeSupport pcs = (PropertyChangeSupport) 2264 AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY); 2265 if (null != pcs) { 2266 pcs.removePropertyChangeListener(listener); 2267 } 2268 } 2269 2270 /* 2271 * we do expect that all other fireXXX() methods of java.beans.PropertyChangeSupport 2272 * use this method. If this will be changed we will need to change this class. 2273 */ 2274 @Override 2275 public void firePropertyChange(final PropertyChangeEvent evt) { 2276 Object oldValue = evt.getOldValue(); 2277 Object newValue = evt.getNewValue(); 2278 String propertyName = evt.getPropertyName(); 2279 if (oldValue != null && newValue != null && oldValue.equals(newValue)) { 2280 return; 2281 } 2282 Runnable updater = new Runnable() { 2283 public void run() { 2284 PropertyChangeSupport pcs = (PropertyChangeSupport) 2285 AppContext.getAppContext().get(PROP_CHANGE_SUPPORT_KEY); 2286 if (null != pcs) { 2287 pcs.firePropertyChange(evt); 2288 } 2289 } 2290 }; 2291 final AppContext currentAppContext = AppContext.getAppContext(); 2292 for (AppContext appContext : AppContext.getAppContexts()) { 2293 if (null == appContext || appContext.isDisposed()) { 2294 continue; 2295 } 2296 if (currentAppContext == appContext) { 2297 updater.run(); 2298 } else { 2299 final PeerEvent e = new PeerEvent(source, updater, PeerEvent.ULTIMATE_PRIORITY_EVENT); 2300 SunToolkit.postEvent(appContext, e); 2301 } 2302 } 2303 } 2304 } 2305 2306 /** 2307 * Reports whether events from extra mouse buttons are allowed to be processed and posted into 2308 * {@code EventQueue}. 2309 * <br> 2310 * To change the returned value it is necessary to set the {@code sun.awt.enableExtraMouseButtons} 2311 * property before the {@code Toolkit} class initialization. This setting could be done on the application 2312 * startup by the following command: 2313 * <pre> 2314 * java -Dsun.awt.enableExtraMouseButtons=false Application 2315 * </pre> 2316 * Alternatively, the property could be set in the application by using the following code: 2317 * <pre> 2318 * System.setProperty("sun.awt.enableExtraMouseButtons", "true"); 2319 * </pre> 2320 * before the {@code Toolkit} class initialization. 2321 * If not set by the time of the {@code Toolkit} class initialization, this property will be 2322 * initialized with {@code true}. 2323 * Changing this value after the {@code Toolkit} class initialization will have no effect. 2324 * 2325 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true 2326 * @return {@code true} if events from extra mouse buttons are allowed to be processed and posted; 2327 * {@code false} otherwise 2328 * @see System#getProperty(String propertyName) 2329 * @see System#setProperty(String propertyName, String value) 2330 * @see java.awt.EventQueue 2331 * @since 1.7 2332 */ 2333 public boolean areExtraMouseButtonsEnabled() throws HeadlessException { 2334 GraphicsEnvironment.checkHeadless(); 2335 2336 return Toolkit.getDefaultToolkit().areExtraMouseButtonsEnabled(); 2337 } 2338 }