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