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