1 /* 2 * Copyright (c) 1997, 2016, 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 sun.awt; 27 28 import java.awt.*; 29 import java.awt.event.InputEvent; 30 import java.awt.event.KeyEvent; 31 import java.awt.event.WindowEvent; 32 import java.awt.image.BufferedImage; 33 import java.awt.image.ColorModel; 34 import java.awt.image.DataBuffer; 35 import java.awt.image.DataBufferInt; 36 import java.awt.image.ImageObserver; 37 import java.awt.image.ImageProducer; 38 import java.awt.image.Raster; 39 import java.awt.peer.FramePeer; 40 import java.awt.peer.KeyboardFocusManagerPeer; 41 import java.awt.peer.MouseInfoPeer; 42 import java.awt.peer.SystemTrayPeer; 43 import java.awt.peer.TrayIconPeer; 44 import java.io.File; 45 import java.io.IOException; 46 import java.io.InputStream; 47 import java.lang.reflect.InvocationTargetException; 48 import java.net.URL; 49 import java.security.AccessController; 50 import java.util.ArrayList; 51 import java.util.Collections; 52 import java.util.Iterator; 53 import java.util.Locale; 54 import java.util.Map; 55 import java.util.Vector; 56 import java.util.WeakHashMap; 57 import java.util.concurrent.TimeUnit; 58 import java.util.concurrent.locks.Condition; 59 import java.util.concurrent.locks.ReentrantLock; 60 61 import sun.awt.im.InputContext; 62 import sun.awt.image.ByteArrayImageSource; 63 import sun.awt.image.FileImageSource; 64 import sun.awt.image.ImageRepresentation; 65 import java.awt.image.MultiResolutionImage; 66 import sun.awt.image.MultiResolutionToolkitImage; 67 import sun.awt.image.ToolkitImage; 68 import sun.awt.image.URLImageSource; 69 import sun.font.FontDesignMetrics; 70 import sun.net.util.URLUtil; 71 import sun.security.action.GetBooleanAction; 72 import sun.security.action.GetPropertyAction; 73 import sun.util.logging.PlatformLogger; 74 75 import static java.awt.RenderingHints.*; 76 77 public abstract class SunToolkit extends Toolkit 78 implements ComponentFactory, InputMethodSupport, KeyboardFocusManagerPeerProvider { 79 80 // 8014718: logging has been removed from SunToolkit 81 82 /* Load debug settings for native code */ 83 static { 84 if (AccessController.doPrivileged(new GetBooleanAction("sun.awt.nativedebug"))) { 85 DebugSettings.init(); 86 } 87 touchKeyboardAutoShowIsEnabled = Boolean.valueOf( 88 GetPropertyAction.privilegedGetProperty( 89 "awt.touchKeyboardAutoShowIsEnabled", "true")); 90 }; 91 92 /** 93 * Special mask for the UngrabEvent events, in addition to the 94 * public masks defined in AWTEvent. Should be used as the mask 95 * value for Toolkit.addAWTEventListener. 96 */ 97 public static final int GRAB_EVENT_MASK = 0x80000000; 98 99 /* The key to put()/get() the PostEventQueue into/from the AppContext. 100 */ 101 private static final String POST_EVENT_QUEUE_KEY = "PostEventQueue"; 102 103 /** 104 * Number of buttons. 105 * By default it's taken from the system. If system value does not 106 * fit into int type range, use our own MAX_BUTTONS_SUPPORT value. 107 */ 108 protected static int numberOfButtons = 0; 109 110 111 /* XFree standard mention 24 buttons as maximum: 112 * http://www.xfree86.org/current/mouse.4.html 113 * We workaround systems supporting more than 24 buttons. 114 * Otherwise, we have to use long type values as masks 115 * which leads to API change. 116 * InputEvent.BUTTON_DOWN_MASK may contain only 21 masks due to 117 * the 4-bytes limit for the int type. (CR 6799099) 118 * One more bit is reserved for FIRST_HIGH_BIT. 119 */ 120 public static final int MAX_BUTTONS_SUPPORTED = 20; 121 122 /** 123 * Creates and initializes EventQueue instance for the specified 124 * AppContext. 125 * Note that event queue must be created from createNewAppContext() 126 * only in order to ensure that EventQueue constructor obtains 127 * the correct AppContext. 128 * @param appContext AppContext to associate with the event queue 129 */ 130 private static void initEQ(AppContext appContext) { 131 EventQueue eventQueue = new EventQueue(); 132 appContext.put(AppContext.EVENT_QUEUE_KEY, eventQueue); 133 134 PostEventQueue postEventQueue = new PostEventQueue(eventQueue); 135 appContext.put(POST_EVENT_QUEUE_KEY, postEventQueue); 136 } 137 138 public SunToolkit() { 139 } 140 141 public boolean useBufferPerWindow() { 142 return false; 143 } 144 145 public abstract FramePeer createLightweightFrame(LightweightFrame target) 146 throws HeadlessException; 147 148 public abstract TrayIconPeer createTrayIcon(TrayIcon target) 149 throws HeadlessException, AWTException; 150 151 public abstract SystemTrayPeer createSystemTray(SystemTray target); 152 153 public abstract boolean isTraySupported(); 154 155 @Override 156 public abstract KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() 157 throws HeadlessException; 158 159 /** 160 * The AWT lock is typically only used on Unix platforms to synchronize 161 * access to Xlib, OpenGL, etc. However, these methods are implemented 162 * in SunToolkit so that they can be called from shared code (e.g. 163 * from the OGL pipeline) or from the X11 pipeline regardless of whether 164 * XToolkit or MToolkit is currently in use. There are native macros 165 * (such as AWT_LOCK) defined in awt.h, so if the implementation of these 166 * methods is changed, make sure it is compatible with the native macros. 167 * 168 * Note: The following methods (awtLock(), awtUnlock(), etc) should be 169 * used in place of: 170 * synchronized (getAWTLock()) { 171 * ... 172 * } 173 * 174 * By factoring these methods out specially, we are able to change the 175 * implementation of these methods (e.g. use more advanced locking 176 * mechanisms) without impacting calling code. 177 * 178 * Sample usage: 179 * private void doStuffWithXlib() { 180 * assert !SunToolkit.isAWTLockHeldByCurrentThread(); 181 * SunToolkit.awtLock(); 182 * try { 183 * ... 184 * XlibWrapper.XDoStuff(); 185 * } finally { 186 * SunToolkit.awtUnlock(); 187 * } 188 * } 189 */ 190 191 private static final ReentrantLock AWT_LOCK = new ReentrantLock(); 192 private static final Condition AWT_LOCK_COND = AWT_LOCK.newCondition(); 193 194 public static final void awtLock() { 195 AWT_LOCK.lock(); 196 } 197 198 public static final boolean awtTryLock() { 199 return AWT_LOCK.tryLock(); 200 } 201 202 public static final void awtUnlock() { 203 AWT_LOCK.unlock(); 204 } 205 206 public static final void awtLockWait() 207 throws InterruptedException 208 { 209 AWT_LOCK_COND.await(); 210 } 211 212 public static final void awtLockWait(long timeout) 213 throws InterruptedException 214 { 215 AWT_LOCK_COND.await(timeout, TimeUnit.MILLISECONDS); 216 } 217 218 public static final void awtLockNotify() { 219 AWT_LOCK_COND.signal(); 220 } 221 222 public static final void awtLockNotifyAll() { 223 AWT_LOCK_COND.signalAll(); 224 } 225 226 public static final boolean isAWTLockHeldByCurrentThread() { 227 return AWT_LOCK.isHeldByCurrentThread(); 228 } 229 230 /* 231 * Create a new AppContext, along with its EventQueue, for a 232 * new ThreadGroup. Browser code, for example, would use this 233 * method to create an AppContext & EventQueue for an Applet. 234 */ 235 public static AppContext createNewAppContext() { 236 ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); 237 return createNewAppContext(threadGroup); 238 } 239 240 static final AppContext createNewAppContext(ThreadGroup threadGroup) { 241 // Create appContext before initialization of EventQueue, so all 242 // the calls to AppContext.getAppContext() from EventQueue ctor 243 // return correct values 244 AppContext appContext = new AppContext(threadGroup); 245 initEQ(appContext); 246 247 return appContext; 248 } 249 250 static void wakeupEventQueue(EventQueue q, boolean isShutdown){ 251 AWTAccessor.getEventQueueAccessor().wakeup(q, isShutdown); 252 } 253 254 /* 255 * Fetch the peer associated with the given target (as specified 256 * in the peer creation method). This can be used to determine 257 * things like what the parent peer is. If the target is null 258 * or the target can't be found (either because the a peer was 259 * never created for it or the peer was disposed), a null will 260 * be returned. 261 */ 262 protected static Object targetToPeer(Object target) { 263 if (target != null && !GraphicsEnvironment.isHeadless()) { 264 return AWTAutoShutdown.getInstance().getPeer(target); 265 } 266 return null; 267 } 268 269 protected static void targetCreatedPeer(Object target, Object peer) { 270 if (target != null && peer != null && 271 !GraphicsEnvironment.isHeadless()) 272 { 273 AWTAutoShutdown.getInstance().registerPeer(target, peer); 274 } 275 } 276 277 protected static void targetDisposedPeer(Object target, Object peer) { 278 if (target != null && peer != null && 279 !GraphicsEnvironment.isHeadless()) 280 { 281 AWTAutoShutdown.getInstance().unregisterPeer(target, peer); 282 } 283 } 284 285 // Maps from non-Component/MenuComponent to AppContext. 286 // WeakHashMap<Component,AppContext> 287 private static final Map<Object, AppContext> appContextMap = 288 Collections.synchronizedMap(new WeakIdentityHashMap<Object, AppContext>()); 289 290 /** 291 * Sets the appContext field of target. If target is not a Component or 292 * MenuComponent, this returns false. 293 */ 294 private static boolean setAppContext(Object target, 295 AppContext context) { 296 if (target instanceof Component) { 297 AWTAccessor.getComponentAccessor(). 298 setAppContext((Component)target, context); 299 } else if (target instanceof MenuComponent) { 300 AWTAccessor.getMenuComponentAccessor(). 301 setAppContext((MenuComponent)target, context); 302 } else { 303 return false; 304 } 305 return true; 306 } 307 308 /** 309 * Returns the appContext field for target. If target is not a 310 * Component or MenuComponent this returns null. 311 */ 312 private static AppContext getAppContext(Object target) { 313 if (target instanceof Component) { 314 return AWTAccessor.getComponentAccessor(). 315 getAppContext((Component)target); 316 } else if (target instanceof MenuComponent) { 317 return AWTAccessor.getMenuComponentAccessor(). 318 getAppContext((MenuComponent)target); 319 } else { 320 return null; 321 } 322 } 323 324 /* 325 * Fetch the AppContext associated with the given target. 326 * This can be used to determine things like which EventQueue 327 * to use for posting events to a Component. If the target is 328 * null or the target can't be found, a null with be returned. 329 */ 330 public static AppContext targetToAppContext(Object target) { 331 if (target == null) { 332 return null; 333 } 334 AppContext context = getAppContext(target); 335 if (context == null) { 336 // target is not a Component/MenuComponent, try the 337 // appContextMap. 338 context = appContextMap.get(target); 339 } 340 return context; 341 } 342 343 /** 344 * Sets the synchronous status of focus requests on lightweight 345 * components in the specified window to the specified value. 346 * If the boolean parameter is {@code true} then the focus 347 * requests on lightweight components will be performed 348 * synchronously, if it is {@code false}, then asynchronously. 349 * By default, all windows have their lightweight request status 350 * set to asynchronous. 351 * <p> 352 * The application can only set the status of lightweight focus 353 * requests to synchronous for any of its windows if it doesn't 354 * perform focus transfers between different heavyweight containers. 355 * In this case the observable focus behaviour is the same as with 356 * asynchronous status. 357 * <p> 358 * If the application performs focus transfer between different 359 * heavyweight containers and sets the lightweight focus request 360 * status to synchronous for any of its windows, then further focus 361 * behaviour is unspecified. 362 * <p> 363 * @param changed the window for which the lightweight focus request 364 * status should be set 365 * @param status the value of lightweight focus request status 366 */ 367 368 public static void setLWRequestStatus(Window changed,boolean status){ 369 AWTAccessor.getWindowAccessor().setLWRequestStatus(changed, status); 370 }; 371 372 public static void checkAndSetPolicy(Container cont) { 373 FocusTraversalPolicy defaultPolicy = KeyboardFocusManager. 374 getCurrentKeyboardFocusManager(). 375 getDefaultFocusTraversalPolicy(); 376 377 cont.setFocusTraversalPolicy(defaultPolicy); 378 } 379 380 /* 381 * Insert a mapping from target to AppContext, for later retrieval 382 * via targetToAppContext() above. 383 */ 384 public static void insertTargetMapping(Object target, AppContext appContext) { 385 if (!setAppContext(target, appContext)) { 386 // Target is not a Component/MenuComponent, use the private Map 387 // instead. 388 appContextMap.put(target, appContext); 389 } 390 } 391 392 /* 393 * Post an AWTEvent to the Java EventQueue, using the PostEventQueue 394 * to avoid possibly calling client code (EventQueueSubclass.postEvent()) 395 * on the toolkit (AWT-Windows/AWT-Motif) thread. This function should 396 * not be called under another lock since it locks the EventQueue. 397 * See bugids 4632918, 4526597. 398 */ 399 public static void postEvent(AppContext appContext, AWTEvent event) { 400 if (event == null) { 401 throw new NullPointerException(); 402 } 403 404 AWTAccessor.SequencedEventAccessor sea = AWTAccessor.getSequencedEventAccessor(); 405 if (sea != null && sea.isSequencedEvent(event)) { 406 AWTEvent nested = sea.getNested(event); 407 if (nested.getID() == WindowEvent.WINDOW_LOST_FOCUS && 408 nested instanceof TimedWindowEvent) 409 { 410 TimedWindowEvent twe = (TimedWindowEvent)nested; 411 ((SunToolkit)Toolkit.getDefaultToolkit()). 412 setWindowDeactivationTime((Window)twe.getSource(), twe.getWhen()); 413 } 414 } 415 416 // All events posted via this method are system-generated. 417 // Placing the following call here reduces considerably the 418 // number of places throughout the toolkit that would 419 // otherwise have to be modified to precisely identify 420 // system-generated events. 421 setSystemGenerated(event); 422 AppContext eventContext = targetToAppContext(event.getSource()); 423 if (eventContext != null && !eventContext.equals(appContext)) { 424 throw new RuntimeException("Event posted on wrong app context : " + event); 425 } 426 PostEventQueue postEventQueue = 427 (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY); 428 if (postEventQueue != null) { 429 postEventQueue.postEvent(event); 430 } 431 } 432 433 /* 434 * Post AWTEvent of high priority. 435 */ 436 public static void postPriorityEvent(final AWTEvent e) { 437 PeerEvent pe = new PeerEvent(Toolkit.getDefaultToolkit(), new Runnable() { 438 @Override 439 public void run() { 440 AWTAccessor.getAWTEventAccessor().setPosted(e); 441 ((Component)e.getSource()).dispatchEvent(e); 442 } 443 }, PeerEvent.ULTIMATE_PRIORITY_EVENT); 444 postEvent(targetToAppContext(e.getSource()), pe); 445 } 446 447 /* 448 * Flush any pending events which haven't been posted to the AWT 449 * EventQueue yet. 450 */ 451 public static void flushPendingEvents() { 452 AppContext appContext = AppContext.getAppContext(); 453 flushPendingEvents(appContext); 454 } 455 456 /* 457 * Flush the PostEventQueue for the right AppContext. 458 * The default flushPendingEvents only flushes the thread-local context, 459 * which is not always correct, c.f. 3746956 460 */ 461 public static void flushPendingEvents(AppContext appContext) { 462 PostEventQueue postEventQueue = 463 (PostEventQueue)appContext.get(POST_EVENT_QUEUE_KEY); 464 if (postEventQueue != null) { 465 postEventQueue.flush(); 466 } 467 } 468 469 /* 470 * Execute a chunk of code on the Java event handler thread for the 471 * given target. Does not wait for the execution to occur before 472 * returning to the caller. 473 */ 474 public static void executeOnEventHandlerThread(Object target, 475 Runnable runnable) { 476 executeOnEventHandlerThread(new PeerEvent(target, runnable, PeerEvent.PRIORITY_EVENT)); 477 } 478 479 /* 480 * Fixed 5064013: the InvocationEvent time should be equals 481 * the time of the ActionEvent 482 */ 483 @SuppressWarnings("serial") 484 public static void executeOnEventHandlerThread(Object target, 485 Runnable runnable, 486 final long when) { 487 executeOnEventHandlerThread( 488 new PeerEvent(target, runnable, PeerEvent.PRIORITY_EVENT) { 489 @Override 490 public long getWhen() { 491 return when; 492 } 493 }); 494 } 495 496 /* 497 * Execute a chunk of code on the Java event handler thread for the 498 * given target. Does not wait for the execution to occur before 499 * returning to the caller. 500 */ 501 public static void executeOnEventHandlerThread(PeerEvent peerEvent) { 502 postEvent(targetToAppContext(peerEvent.getSource()), peerEvent); 503 } 504 505 /* 506 * Execute a chunk of code on the Java event handler thread. The 507 * method takes into account provided AppContext and sets 508 * {@code SunToolkit.getDefaultToolkit()} as a target of the 509 * event. See 6451487 for detailes. 510 * Does not wait for the execution to occur before returning to 511 * the caller. 512 */ 513 public static void invokeLaterOnAppContext( 514 AppContext appContext, Runnable dispatcher) 515 { 516 postEvent(appContext, 517 new PeerEvent(Toolkit.getDefaultToolkit(), dispatcher, 518 PeerEvent.PRIORITY_EVENT)); 519 } 520 521 /* 522 * Execute a chunk of code on the Java event handler thread for the 523 * given target. Waits for the execution to occur before returning 524 * to the caller. 525 */ 526 public static void executeOnEDTAndWait(Object target, Runnable runnable) 527 throws InterruptedException, InvocationTargetException 528 { 529 if (EventQueue.isDispatchThread()) { 530 throw new Error("Cannot call executeOnEDTAndWait from any event dispatcher thread"); 531 } 532 533 class AWTInvocationLock {} 534 Object lock = new AWTInvocationLock(); 535 536 PeerEvent event = new PeerEvent(target, runnable, lock, true, PeerEvent.PRIORITY_EVENT); 537 538 synchronized (lock) { 539 executeOnEventHandlerThread(event); 540 while(!event.isDispatched()) { 541 lock.wait(); 542 } 543 } 544 545 Throwable eventThrowable = event.getThrowable(); 546 if (eventThrowable != null) { 547 throw new InvocationTargetException(eventThrowable); 548 } 549 } 550 551 /* 552 * Returns true if the calling thread is the event dispatch thread 553 * contained within AppContext which associated with the given target. 554 * Use this call to ensure that a given task is being executed 555 * (or not being) on the event dispatch thread for the given target. 556 */ 557 public static boolean isDispatchThreadForAppContext(Object target) { 558 AppContext appContext = targetToAppContext(target); 559 EventQueue eq = (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY); 560 561 AWTAccessor.EventQueueAccessor accessor = AWTAccessor.getEventQueueAccessor(); 562 return accessor.isDispatchThreadImpl(eq); 563 } 564 565 @Override 566 public Dimension getScreenSize() { 567 return GraphicsEnvironment.getLocalGraphicsEnvironment() 568 .getDefaultScreenDevice().getDefaultConfiguration() 569 .getBounds().getSize(); 570 } 571 572 @Override 573 public ColorModel getColorModel() throws HeadlessException { 574 return GraphicsEnvironment.getLocalGraphicsEnvironment() 575 .getDefaultScreenDevice().getDefaultConfiguration() 576 .getColorModel(); 577 } 578 579 @Override 580 @SuppressWarnings("deprecation") 581 public FontMetrics getFontMetrics(Font font) { 582 return FontDesignMetrics.getMetrics(font); 583 } 584 585 @Override 586 @SuppressWarnings("deprecation") 587 public String[] getFontList() { 588 String[] hardwiredFontList = { 589 Font.DIALOG, Font.SANS_SERIF, Font.SERIF, Font.MONOSPACED, 590 Font.DIALOG_INPUT 591 592 // -- Obsolete font names from 1.0.2. It was decided that 593 // -- getFontList should not return these old names: 594 // "Helvetica", "TimesRoman", "Courier", "ZapfDingbats" 595 }; 596 return hardwiredFontList; 597 } 598 599 /** 600 * Disables erasing of background on the canvas before painting if 601 * this is supported by the current toolkit. It is recommended to 602 * call this method early, before the Canvas becomes displayable, 603 * because some Toolkit implementations do not support changing 604 * this property once the Canvas becomes displayable. 605 */ 606 public void disableBackgroundErase(Canvas canvas) { 607 disableBackgroundEraseImpl(canvas); 608 } 609 610 /** 611 * Disables the native erasing of the background on the given 612 * component before painting if this is supported by the current 613 * toolkit. This only has an effect for certain components such as 614 * Canvas, Panel and Window. It is recommended to call this method 615 * early, before the Component becomes displayable, because some 616 * Toolkit implementations do not support changing this property 617 * once the Component becomes displayable. 618 */ 619 public void disableBackgroundErase(Component component) { 620 disableBackgroundEraseImpl(component); 621 } 622 623 private void disableBackgroundEraseImpl(Component component) { 624 AWTAccessor.getComponentAccessor().setBackgroundEraseDisabled(component, true); 625 } 626 627 /** 628 * Returns the value of "sun.awt.noerasebackground" property. Default 629 * value is {@code false}. 630 */ 631 public static boolean getSunAwtNoerasebackground() { 632 return AccessController.doPrivileged(new GetBooleanAction("sun.awt.noerasebackground")); 633 } 634 635 /** 636 * Returns the value of "sun.awt.erasebackgroundonresize" property. Default 637 * value is {@code false}. 638 */ 639 public static boolean getSunAwtErasebackgroundonresize() { 640 return AccessController.doPrivileged(new GetBooleanAction("sun.awt.erasebackgroundonresize")); 641 } 642 643 644 @SuppressWarnings("deprecation") 645 static final SoftCache fileImgCache = new SoftCache(); 646 647 @SuppressWarnings("deprecation") 648 static final SoftCache urlImgCache = new SoftCache(); 649 650 static Image getImageFromHash(Toolkit tk, URL url) { 651 checkPermissions(url); 652 synchronized (urlImgCache) { 653 String key = url.toString(); 654 Image img = (Image)urlImgCache.get(key); 655 if (img == null) { 656 try { 657 img = tk.createImage(new URLImageSource(url)); 658 urlImgCache.put(key, img); 659 } catch (Exception e) { 660 } 661 } 662 return img; 663 } 664 } 665 666 static Image getImageFromHash(Toolkit tk, 667 String filename) { 668 checkPermissions(filename); 669 synchronized (fileImgCache) { 670 Image img = (Image)fileImgCache.get(filename); 671 if (img == null) { 672 try { 673 img = tk.createImage(new FileImageSource(filename)); 674 fileImgCache.put(filename, img); 675 } catch (Exception e) { 676 } 677 } 678 return img; 679 } 680 } 681 682 @Override 683 public Image getImage(String filename) { 684 return getImageFromHash(this, filename); 685 } 686 687 @Override 688 public Image getImage(URL url) { 689 return getImageFromHash(this, url); 690 } 691 692 protected Image getImageWithResolutionVariant(String fileName, 693 String resolutionVariantName) { 694 synchronized (fileImgCache) { 695 Image image = getImageFromHash(this, fileName); 696 if (image instanceof MultiResolutionImage) { 697 return image; 698 } 699 Image resolutionVariant = getImageFromHash(this, resolutionVariantName); 700 image = createImageWithResolutionVariant(image, resolutionVariant); 701 fileImgCache.put(fileName, image); 702 return image; 703 } 704 } 705 706 protected Image getImageWithResolutionVariant(URL url, 707 URL resolutionVariantURL) { 708 synchronized (urlImgCache) { 709 Image image = getImageFromHash(this, url); 710 if (image instanceof MultiResolutionImage) { 711 return image; 712 } 713 Image resolutionVariant = getImageFromHash(this, resolutionVariantURL); 714 image = createImageWithResolutionVariant(image, resolutionVariant); 715 String key = url.toString(); 716 urlImgCache.put(key, image); 717 return image; 718 } 719 } 720 721 722 @Override 723 public Image createImage(String filename) { 724 checkPermissions(filename); 725 return createImage(new FileImageSource(filename)); 726 } 727 728 @Override 729 public Image createImage(URL url) { 730 checkPermissions(url); 731 return createImage(new URLImageSource(url)); 732 } 733 734 @Override 735 public Image createImage(byte[] data, int offset, int length) { 736 return createImage(new ByteArrayImageSource(data, offset, length)); 737 } 738 739 @Override 740 public Image createImage(ImageProducer producer) { 741 return new ToolkitImage(producer); 742 } 743 744 public static Image createImageWithResolutionVariant(Image image, 745 Image resolutionVariant) { 746 return new MultiResolutionToolkitImage(image, resolutionVariant); 747 } 748 749 @Override 750 public int checkImage(Image img, int w, int h, ImageObserver o) { 751 if (!(img instanceof ToolkitImage)) { 752 return ImageObserver.ALLBITS; 753 } 754 755 ToolkitImage tkimg = (ToolkitImage)img; 756 int repbits; 757 if (w == 0 || h == 0) { 758 repbits = ImageObserver.ALLBITS; 759 } else { 760 repbits = tkimg.getImageRep().check(o); 761 } 762 return (tkimg.check(o) | repbits) & checkResolutionVariant(img, w, h, o); 763 } 764 765 @Override 766 public boolean prepareImage(Image img, int w, int h, ImageObserver o) { 767 if (w == 0 || h == 0) { 768 return true; 769 } 770 771 // Must be a ToolkitImage 772 if (!(img instanceof ToolkitImage)) { 773 return true; 774 } 775 776 ToolkitImage tkimg = (ToolkitImage)img; 777 if (tkimg.hasError()) { 778 if (o != null) { 779 o.imageUpdate(img, ImageObserver.ERROR|ImageObserver.ABORT, 780 -1, -1, -1, -1); 781 } 782 return false; 783 } 784 ImageRepresentation ir = tkimg.getImageRep(); 785 return ir.prepare(o) & prepareResolutionVariant(img, w, h, o); 786 } 787 788 private int checkResolutionVariant(Image img, int w, int h, ImageObserver o) { 789 ToolkitImage rvImage = getResolutionVariant(img); 790 int rvw = getRVSize(w); 791 int rvh = getRVSize(h); 792 // Ignore the resolution variant in case of error 793 return (rvImage == null || rvImage.hasError()) ? 0xFFFF : 794 checkImage(rvImage, rvw, rvh, MultiResolutionToolkitImage. 795 getResolutionVariantObserver( 796 img, o, w, h, rvw, rvh, true)); 797 } 798 799 private boolean prepareResolutionVariant(Image img, int w, int h, 800 ImageObserver o) { 801 802 ToolkitImage rvImage = getResolutionVariant(img); 803 int rvw = getRVSize(w); 804 int rvh = getRVSize(h); 805 // Ignore the resolution variant in case of error 806 return rvImage == null || rvImage.hasError() || prepareImage( 807 rvImage, rvw, rvh, 808 MultiResolutionToolkitImage.getResolutionVariantObserver( 809 img, o, w, h, rvw, rvh, true)); 810 } 811 812 private static int getRVSize(int size){ 813 return size == -1 ? -1 : 2 * size; 814 } 815 816 private static ToolkitImage getResolutionVariant(Image image) { 817 if (image instanceof MultiResolutionToolkitImage) { 818 Image resolutionVariant = ((MultiResolutionToolkitImage) image). 819 getResolutionVariant(); 820 if (resolutionVariant instanceof ToolkitImage) { 821 return (ToolkitImage) resolutionVariant; 822 } 823 } 824 return null; 825 } 826 827 protected static boolean imageCached(String fileName) { 828 return fileImgCache.containsKey(fileName); 829 } 830 831 protected static boolean imageCached(URL url) { 832 String key = url.toString(); 833 return urlImgCache.containsKey(key); 834 } 835 836 protected static boolean imageExists(String filename) { 837 if (filename != null) { 838 checkPermissions(filename); 839 return new File(filename).exists(); 840 } 841 return false; 842 } 843 844 @SuppressWarnings("try") 845 protected static boolean imageExists(URL url) { 846 if (url != null) { 847 checkPermissions(url); 848 try (InputStream is = url.openStream()) { 849 return true; 850 }catch(IOException e){ 851 return false; 852 } 853 } 854 return false; 855 } 856 857 private static void checkPermissions(String filename) { 858 SecurityManager security = System.getSecurityManager(); 859 if (security != null) { 860 security.checkRead(filename); 861 } 862 } 863 864 private static void checkPermissions(URL url) { 865 SecurityManager sm = System.getSecurityManager(); 866 if (sm != null) { 867 try { 868 java.security.Permission perm = 869 URLUtil.getConnectPermission(url); 870 if (perm != null) { 871 try { 872 sm.checkPermission(perm); 873 } catch (SecurityException se) { 874 // fallback to checkRead/checkConnect for pre 1.2 875 // security managers 876 if ((perm instanceof java.io.FilePermission) && 877 perm.getActions().indexOf("read") != -1) { 878 sm.checkRead(perm.getName()); 879 } else if ((perm instanceof 880 java.net.SocketPermission) && 881 perm.getActions().indexOf("connect") != -1) { 882 sm.checkConnect(url.getHost(), url.getPort()); 883 } else { 884 throw se; 885 } 886 } 887 } 888 } catch (java.io.IOException ioe) { 889 sm.checkConnect(url.getHost(), url.getPort()); 890 } 891 } 892 } 893 894 /** 895 * Scans {@code imageList} for best-looking image of specified dimensions. 896 * Image can be scaled and/or padded with transparency. 897 */ 898 public static BufferedImage getScaledIconImage(java.util.List<Image> imageList, int width, int height) { 899 if (width == 0 || height == 0) { 900 return null; 901 } 902 java.util.List<Image> multiResAndnormalImages = new ArrayList<>(imageList.size()); 903 for (Image image : imageList) { 904 if ((image instanceof MultiResolutionImage)) { 905 Image im = ((MultiResolutionImage) image).getResolutionVariant(width, height); 906 multiResAndnormalImages.add(im); 907 } else { 908 multiResAndnormalImages.add(image); 909 } 910 } 911 Image bestImage = null; 912 int bestWidth = 0; 913 int bestHeight = 0; 914 double bestSimilarity = 3; //Impossibly high value 915 double bestScaleFactor = 0; 916 for (Iterator<Image> i = multiResAndnormalImages.iterator();i.hasNext();) { 917 //Iterate imageList looking for best matching image. 918 //'Similarity' measure is defined as good scale factor and small insets. 919 //best possible similarity is 0 (no scale, no insets). 920 //It's found while the experiments that good-looking result is achieved 921 //with scale factors x1, x3/4, x2/3, xN, x1/N. 922 Image im = i.next(); 923 if (im == null) { 924 continue; 925 } 926 if (im instanceof ToolkitImage) { 927 ImageRepresentation ir = ((ToolkitImage)im).getImageRep(); 928 ir.reconstruct(ImageObserver.ALLBITS); 929 } 930 int iw; 931 int ih; 932 try { 933 iw = im.getWidth(null); 934 ih = im.getHeight(null); 935 } catch (Exception e){ 936 continue; 937 } 938 if (iw > 0 && ih > 0) { 939 //Calc scale factor 940 double scaleFactor = Math.min((double)width / (double)iw, 941 (double)height / (double)ih); 942 //Calculate scaled image dimensions 943 //adjusting scale factor to nearest "good" value 944 int adjw = 0; 945 int adjh = 0; 946 double scaleMeasure = 1; //0 - best (no) scale, 1 - impossibly bad 947 if (scaleFactor >= 2) { 948 //Need to enlarge image more than twice 949 //Round down scale factor to multiply by integer value 950 scaleFactor = Math.floor(scaleFactor); 951 adjw = iw * (int)scaleFactor; 952 adjh = ih * (int)scaleFactor; 953 scaleMeasure = 1.0 - 0.5 / scaleFactor; 954 } else if (scaleFactor >= 1) { 955 //Don't scale 956 scaleFactor = 1.0; 957 adjw = iw; 958 adjh = ih; 959 scaleMeasure = 0; 960 } else if (scaleFactor >= 0.75) { 961 //Multiply by 3/4 962 scaleFactor = 0.75; 963 adjw = iw * 3 / 4; 964 adjh = ih * 3 / 4; 965 scaleMeasure = 0.3; 966 } else if (scaleFactor >= 0.6666) { 967 //Multiply by 2/3 968 scaleFactor = 0.6666; 969 adjw = iw * 2 / 3; 970 adjh = ih * 2 / 3; 971 scaleMeasure = 0.33; 972 } else { 973 //Multiply size by 1/scaleDivider 974 //where scaleDivider is minimum possible integer 975 //larger than 1/scaleFactor 976 double scaleDivider = Math.ceil(1.0 / scaleFactor); 977 scaleFactor = 1.0 / scaleDivider; 978 adjw = (int)Math.round((double)iw / scaleDivider); 979 adjh = (int)Math.round((double)ih / scaleDivider); 980 scaleMeasure = 1.0 - 1.0 / scaleDivider; 981 } 982 double similarity = ((double)width - (double)adjw) / (double)width + 983 ((double)height - (double)adjh) / (double)height + //Large padding is bad 984 scaleMeasure; //Large rescale is bad 985 if (similarity < bestSimilarity) { 986 bestSimilarity = similarity; 987 bestScaleFactor = scaleFactor; 988 bestImage = im; 989 bestWidth = adjw; 990 bestHeight = adjh; 991 } 992 if (similarity == 0) break; 993 } 994 } 995 if (bestImage == null) { 996 //No images were found, possibly all are broken 997 return null; 998 } 999 BufferedImage bimage = 1000 new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 1001 Graphics2D g = bimage.createGraphics(); 1002 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 1003 RenderingHints.VALUE_INTERPOLATION_BILINEAR); 1004 try { 1005 int x = (width - bestWidth) / 2; 1006 int y = (height - bestHeight) / 2; 1007 g.drawImage(bestImage, x, y, bestWidth, bestHeight, null); 1008 } finally { 1009 g.dispose(); 1010 } 1011 return bimage; 1012 } 1013 1014 public static DataBufferInt getScaledIconData(java.util.List<Image> imageList, int width, int height) { 1015 BufferedImage bimage = getScaledIconImage(imageList, width, height); 1016 if (bimage == null) { 1017 return null; 1018 } 1019 Raster raster = bimage.getRaster(); 1020 DataBuffer buffer = raster.getDataBuffer(); 1021 return (DataBufferInt)buffer; 1022 } 1023 1024 @Override 1025 protected EventQueue getSystemEventQueueImpl() { 1026 return getSystemEventQueueImplPP(); 1027 } 1028 1029 // Package private implementation 1030 static EventQueue getSystemEventQueueImplPP() { 1031 return getSystemEventQueueImplPP(AppContext.getAppContext()); 1032 } 1033 1034 public static EventQueue getSystemEventQueueImplPP(AppContext appContext) { 1035 EventQueue theEventQueue = 1036 (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY); 1037 return theEventQueue; 1038 } 1039 1040 /** 1041 * Give native peers the ability to query the native container 1042 * given a native component (eg the direct parent may be lightweight). 1043 */ 1044 public static Container getNativeContainer(Component c) { 1045 return Toolkit.getNativeContainer(c); 1046 } 1047 1048 /** 1049 * Gives native peers the ability to query the closest HW component. 1050 * If the given component is heavyweight, then it returns this. Otherwise, 1051 * it goes one level up in the hierarchy and tests next component. 1052 */ 1053 public static Component getHeavyweightComponent(Component c) { 1054 while (c != null && AWTAccessor.getComponentAccessor().isLightweight(c)) { 1055 c = AWTAccessor.getComponentAccessor().getParent(c); 1056 } 1057 return c; 1058 } 1059 1060 /** 1061 * Returns key modifiers used by Swing to set up a focus accelerator key stroke. 1062 */ 1063 @SuppressWarnings("deprecation") 1064 public int getFocusAcceleratorKeyMask() { 1065 return InputEvent.ALT_MASK; 1066 } 1067 1068 /** 1069 * Tests whether specified key modifiers mask can be used to enter a printable 1070 * character. This is a default implementation of this method, which reflects 1071 * the way things work on Windows: here, pressing ctrl + alt allows user to enter 1072 * characters from the extended character set (like euro sign or math symbols) 1073 */ 1074 @SuppressWarnings("deprecation") 1075 public boolean isPrintableCharacterModifiersMask(int mods) { 1076 return ((mods & InputEvent.ALT_MASK) == (mods & InputEvent.CTRL_MASK)); 1077 } 1078 1079 /** 1080 * Returns whether popup is allowed to be shown above the task bar. 1081 * This is a default implementation of this method, which checks 1082 * corresponding security permission. 1083 */ 1084 public boolean canPopupOverlapTaskBar() { 1085 boolean result = true; 1086 try { 1087 SecurityManager sm = System.getSecurityManager(); 1088 if (sm != null) { 1089 sm.checkPermission(AWTPermissions.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION); 1090 } 1091 } catch (SecurityException se) { 1092 // There is no permission to show popups over the task bar 1093 result = false; 1094 } 1095 return result; 1096 } 1097 1098 /** 1099 * Returns a new input method window, with behavior as specified in 1100 * {@link java.awt.im.spi.InputMethodContext#createInputMethodWindow}. 1101 * If the inputContext is not null, the window should return it from its 1102 * getInputContext() method. The window needs to implement 1103 * sun.awt.im.InputMethodWindow. 1104 * <p> 1105 * SunToolkit subclasses can override this method to return better input 1106 * method windows. 1107 */ 1108 @Override 1109 public Window createInputMethodWindow(String title, InputContext context) { 1110 return new sun.awt.im.SimpleInputMethodWindow(title, context); 1111 } 1112 1113 /** 1114 * Returns whether enableInputMethods should be set to true for peered 1115 * TextComponent instances on this platform. False by default. 1116 */ 1117 @Override 1118 public boolean enableInputMethodsForTextComponent() { 1119 return false; 1120 } 1121 1122 private static Locale startupLocale = null; 1123 1124 /** 1125 * Returns the locale in which the runtime was started. 1126 */ 1127 public static Locale getStartupLocale() { 1128 if (startupLocale == null) { 1129 String language, region, country, variant; 1130 language = AccessController.doPrivileged( 1131 new GetPropertyAction("user.language", "en")); 1132 // for compatibility, check for old user.region property 1133 region = AccessController.doPrivileged( 1134 new GetPropertyAction("user.region")); 1135 if (region != null) { 1136 // region can be of form country, country_variant, or _variant 1137 int i = region.indexOf('_'); 1138 if (i >= 0) { 1139 country = region.substring(0, i); 1140 variant = region.substring(i + 1); 1141 } else { 1142 country = region; 1143 variant = ""; 1144 } 1145 } else { 1146 country = AccessController.doPrivileged( 1147 new GetPropertyAction("user.country", "")); 1148 variant = AccessController.doPrivileged( 1149 new GetPropertyAction("user.variant", "")); 1150 } 1151 startupLocale = new Locale(language, country, variant); 1152 } 1153 return startupLocale; 1154 } 1155 1156 /** 1157 * Returns the default keyboard locale of the underlying operating system 1158 */ 1159 @Override 1160 public Locale getDefaultKeyboardLocale() { 1161 return getStartupLocale(); 1162 } 1163 1164 /** 1165 * Returns whether default toolkit needs the support of the xembed 1166 * from embedding host(if any). 1167 * @return {@code true}, if XEmbed is needed, {@code false} otherwise 1168 */ 1169 public static boolean needsXEmbed() { 1170 String noxembed = AccessController. 1171 doPrivileged(new GetPropertyAction("sun.awt.noxembed", "false")); 1172 if ("true".equals(noxembed)) { 1173 return false; 1174 } 1175 1176 Toolkit tk = Toolkit.getDefaultToolkit(); 1177 if (tk instanceof SunToolkit) { 1178 // SunToolkit descendants should override this method to specify 1179 // concrete behavior 1180 return ((SunToolkit)tk).needsXEmbedImpl(); 1181 } else { 1182 // Non-SunToolkit doubtly might support XEmbed 1183 return false; 1184 } 1185 } 1186 1187 /** 1188 * Returns whether this toolkit needs the support of the xembed 1189 * from embedding host(if any). 1190 * @return {@code true}, if XEmbed is needed, {@code false} otherwise 1191 */ 1192 protected boolean needsXEmbedImpl() { 1193 return false; 1194 } 1195 1196 private static Dialog.ModalExclusionType DEFAULT_MODAL_EXCLUSION_TYPE = null; 1197 1198 /** 1199 * Returns whether the XEmbed server feature is requested by 1200 * developer. If true, Toolkit should return an 1201 * XEmbed-server-enabled CanvasPeer instead of the ordinary CanvasPeer. 1202 */ 1203 protected final boolean isXEmbedServerRequested() { 1204 return AccessController.doPrivileged(new GetBooleanAction("sun.awt.xembedserver")); 1205 } 1206 1207 /** 1208 * Returns whether the modal exclusion API is supported by the current toolkit. 1209 * When it isn't supported, calling {@code setModalExcluded} has no 1210 * effect, and {@code isModalExcluded} returns false for all windows. 1211 * 1212 * @return true if modal exclusion is supported by the toolkit, false otherwise 1213 * 1214 * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window) 1215 * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window) 1216 * 1217 * @since 1.5 1218 */ 1219 public static boolean isModalExcludedSupported() 1220 { 1221 Toolkit tk = Toolkit.getDefaultToolkit(); 1222 return tk.isModalExclusionTypeSupported(DEFAULT_MODAL_EXCLUSION_TYPE); 1223 } 1224 /* 1225 * Default implementation for isModalExcludedSupportedImpl(), returns false. 1226 * 1227 * @see sun.awt.windows.WToolkit#isModalExcludeSupportedImpl 1228 * @see sun.awt.X11.XToolkit#isModalExcludeSupportedImpl 1229 * 1230 * @since 1.5 1231 */ 1232 protected boolean isModalExcludedSupportedImpl() 1233 { 1234 return false; 1235 } 1236 1237 /* 1238 * Sets this window to be excluded from being modally blocked. When the 1239 * toolkit supports modal exclusion and this method is called, input 1240 * events, focus transfer and z-order will continue to work for the 1241 * window, it's owned windows and child components, even in the 1242 * presence of a modal dialog. 1243 * For details on which {@code Window}s are normally blocked 1244 * by modal dialog, see {@link java.awt.Dialog}. 1245 * Invoking this method when the modal exclusion API is not supported by 1246 * the current toolkit has no effect. 1247 * @param window Window to be marked as not modally blocked 1248 * @see java.awt.Dialog 1249 * @see java.awt.Dialog#setModal(boolean) 1250 * @see sun.awt.SunToolkit#isModalExcludedSupported 1251 * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window) 1252 */ 1253 public static void setModalExcluded(Window window) 1254 { 1255 if (DEFAULT_MODAL_EXCLUSION_TYPE == null) { 1256 DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE; 1257 } 1258 window.setModalExclusionType(DEFAULT_MODAL_EXCLUSION_TYPE); 1259 } 1260 1261 /* 1262 * Returns whether the specified window is blocked by modal dialogs. 1263 * If the modal exclusion API isn't supported by the current toolkit, 1264 * it returns false for all windows. 1265 * 1266 * @param window Window to test for modal exclusion 1267 * 1268 * @return true if the window is modal excluded, false otherwise. If 1269 * the modal exclusion isn't supported by the current Toolkit, false 1270 * is returned 1271 * 1272 * @see sun.awt.SunToolkit#isModalExcludedSupported 1273 * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window) 1274 * 1275 * @since 1.5 1276 */ 1277 public static boolean isModalExcluded(Window window) 1278 { 1279 if (DEFAULT_MODAL_EXCLUSION_TYPE == null) { 1280 DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE; 1281 } 1282 return window.getModalExclusionType().compareTo(DEFAULT_MODAL_EXCLUSION_TYPE) >= 0; 1283 } 1284 1285 /** 1286 * Overridden in XToolkit and WToolkit 1287 */ 1288 @Override 1289 public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) { 1290 return (modalityType == Dialog.ModalityType.MODELESS) || 1291 (modalityType == Dialog.ModalityType.APPLICATION_MODAL); 1292 } 1293 1294 /** 1295 * Overridden in XToolkit and WToolkit 1296 */ 1297 @Override 1298 public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) { 1299 return (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE); 1300 } 1301 1302 /////////////////////////////////////////////////////////////////////////// 1303 // 1304 // The following is used by the Java Plug-in to coordinate dialog modality 1305 // between containing applications (browsers, ActiveX containers etc) and 1306 // the AWT. 1307 // 1308 /////////////////////////////////////////////////////////////////////////// 1309 1310 private ModalityListenerList modalityListeners = new ModalityListenerList(); 1311 1312 public void addModalityListener(ModalityListener listener) { 1313 modalityListeners.add(listener); 1314 } 1315 1316 public void removeModalityListener(ModalityListener listener) { 1317 modalityListeners.remove(listener); 1318 } 1319 1320 public void notifyModalityPushed(Dialog dialog) { 1321 notifyModalityChange(ModalityEvent.MODALITY_PUSHED, dialog); 1322 } 1323 1324 public void notifyModalityPopped(Dialog dialog) { 1325 notifyModalityChange(ModalityEvent.MODALITY_POPPED, dialog); 1326 } 1327 1328 final void notifyModalityChange(int id, Dialog source) { 1329 ModalityEvent ev = new ModalityEvent(source, modalityListeners, id); 1330 ev.dispatch(); 1331 } 1332 1333 static class ModalityListenerList implements ModalityListener { 1334 1335 Vector<ModalityListener> listeners = new Vector<ModalityListener>(); 1336 1337 void add(ModalityListener listener) { 1338 listeners.addElement(listener); 1339 } 1340 1341 void remove(ModalityListener listener) { 1342 listeners.removeElement(listener); 1343 } 1344 1345 @Override 1346 public void modalityPushed(ModalityEvent ev) { 1347 Iterator<ModalityListener> it = listeners.iterator(); 1348 while (it.hasNext()) { 1349 it.next().modalityPushed(ev); 1350 } 1351 } 1352 1353 @Override 1354 public void modalityPopped(ModalityEvent ev) { 1355 Iterator<ModalityListener> it = listeners.iterator(); 1356 while (it.hasNext()) { 1357 it.next().modalityPopped(ev); 1358 } 1359 } 1360 } // end of class ModalityListenerList 1361 1362 /////////////////////////////////////////////////////////////////////////// 1363 // End Plug-in code 1364 /////////////////////////////////////////////////////////////////////////// 1365 1366 public static boolean isLightweightOrUnknown(Component comp) { 1367 if (comp.isLightweight() 1368 || !(getDefaultToolkit() instanceof SunToolkit)) 1369 { 1370 return true; 1371 } 1372 return !(comp instanceof Button 1373 || comp instanceof Canvas 1374 || comp instanceof Checkbox 1375 || comp instanceof Choice 1376 || comp instanceof Label 1377 || comp instanceof java.awt.List 1378 || comp instanceof Panel 1379 || comp instanceof Scrollbar 1380 || comp instanceof ScrollPane 1381 || comp instanceof TextArea 1382 || comp instanceof TextField 1383 || comp instanceof Window); 1384 } 1385 1386 @SuppressWarnings("serial") 1387 public static class OperationTimedOut extends RuntimeException { 1388 public OperationTimedOut(String msg) { 1389 super(msg); 1390 } 1391 public OperationTimedOut() { 1392 } 1393 } 1394 1395 @SuppressWarnings("serial") 1396 public static class InfiniteLoop extends RuntimeException { 1397 } 1398 1399 @SuppressWarnings("serial") 1400 public static class IllegalThreadException extends RuntimeException { 1401 public IllegalThreadException(String msg) { 1402 super(msg); 1403 } 1404 public IllegalThreadException() { 1405 } 1406 } 1407 1408 public static final int DEFAULT_WAIT_TIME = 10000; 1409 private static final int MAX_ITERS = 20; 1410 private static final int MIN_ITERS = 0; 1411 private static final int MINIMAL_EDELAY = 0; 1412 1413 /** 1414 * Parameterless version of realsync which uses default timout (see DEFAUL_WAIT_TIME). 1415 */ 1416 public void realSync() throws OperationTimedOut, InfiniteLoop { 1417 realSync(DEFAULT_WAIT_TIME); 1418 } 1419 1420 /** 1421 * Forces toolkit to synchronize with the native windowing 1422 * sub-system, flushing all pending work and waiting for all the 1423 * events to be processed. This method guarantees that after 1424 * return no additional Java events will be generated, unless 1425 * cause by user. Obviously, the method cannot be used on the 1426 * event dispatch thread (EDT). In case it nevertheless gets 1427 * invoked on this thread, the method throws the 1428 * IllegalThreadException runtime exception. 1429 * 1430 * <p> This method allows to write tests without explicit timeouts 1431 * or wait for some event. Example: 1432 * <pre>{@code 1433 * Frame f = ...; 1434 * f.setVisible(true); 1435 * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); 1436 * }</pre> 1437 * 1438 * <p> After realSync, {@code f} will be completely visible 1439 * on the screen, its getLocationOnScreen will be returning the 1440 * right result and it will be the focus owner. 1441 * 1442 * <p> Another example: 1443 * <pre>{@code 1444 * b.requestFocus(); 1445 * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); 1446 * }</pre> 1447 * 1448 * <p> After realSync, {@code b} will be focus owner. 1449 * 1450 * <p> Notice that realSync isn't guaranteed to work if recurring 1451 * actions occur, such as if during processing of some event 1452 * another request which may generate some events occurs. By 1453 * default, sync tries to perform as much as {@value #MAX_ITERS} 1454 * cycles of event processing, allowing for roughly {@value 1455 * #MAX_ITERS} additional requests. 1456 * 1457 * <p> For example, requestFocus() generates native request, which 1458 * generates one or two Java focus events, which then generate a 1459 * serie of paint events, a serie of Java focus events, which then 1460 * generate a serie of paint events which then are processed - 1461 * three cycles, minimum. 1462 * 1463 * @param timeout the maximum time to wait in milliseconds, negative means "forever". 1464 */ 1465 public void realSync(final long timeout) throws OperationTimedOut, InfiniteLoop 1466 { 1467 if (EventQueue.isDispatchThread()) { 1468 throw new IllegalThreadException("The SunToolkit.realSync() method cannot be used on the event dispatch thread (EDT)."); 1469 } 1470 int bigLoop = 0; 1471 do { 1472 // Let's do sync first 1473 sync(); 1474 1475 // During the wait process, when we were processing incoming 1476 // events, we could have made some new request, which can 1477 // generate new events. Example: MapNotify/XSetInputFocus. 1478 // Therefore, we dispatch them as long as there is something 1479 // to dispatch. 1480 int iters = 0; 1481 while (iters < MIN_ITERS) { 1482 syncNativeQueue(timeout); 1483 iters++; 1484 } 1485 while (syncNativeQueue(timeout) && iters < MAX_ITERS) { 1486 iters++; 1487 } 1488 if (iters >= MAX_ITERS) { 1489 throw new InfiniteLoop(); 1490 } 1491 1492 // native requests were dispatched by X/Window Manager or Windows 1493 // Moreover, we processed them all on Toolkit thread 1494 // Now wait while EDT processes them. 1495 // 1496 // During processing of some events (focus, for example), 1497 // some other events could have been generated. So, after 1498 // waitForIdle, we may end up with full EventQueue 1499 iters = 0; 1500 while (iters < MIN_ITERS) { 1501 waitForIdle(timeout); 1502 iters++; 1503 } 1504 while (waitForIdle(timeout) && iters < MAX_ITERS) { 1505 iters++; 1506 } 1507 if (iters >= MAX_ITERS) { 1508 throw new InfiniteLoop(); 1509 } 1510 1511 bigLoop++; 1512 // Again, for Java events, it was simple to check for new Java 1513 // events by checking event queue, but what if Java events 1514 // resulted in native requests? Therefor, check native events again. 1515 } while ((syncNativeQueue(timeout) || waitForIdle(timeout)) && bigLoop < MAX_ITERS); 1516 } 1517 1518 /** 1519 * Platform toolkits need to implement this method to perform the 1520 * sync of the native queue. The method should wait until native 1521 * requests are processed, all native events are processed and 1522 * corresponding Java events are generated. Should return 1523 * {@code true} if some events were processed, 1524 * {@code false} otherwise. 1525 */ 1526 protected abstract boolean syncNativeQueue(final long timeout); 1527 1528 private boolean eventDispatched; 1529 private boolean queueEmpty; 1530 private final Object waitLock = new Object(); 1531 1532 private boolean isEQEmpty() { 1533 EventQueue queue = getSystemEventQueueImpl(); 1534 return AWTAccessor.getEventQueueAccessor().noEvents(queue); 1535 } 1536 1537 /** 1538 * Waits for the Java event queue to empty. Ensures that all 1539 * events are processed (including paint events), and that if 1540 * recursive events were generated, they are also processed. 1541 * Should return {@code true} if more processing is 1542 * necessary, {@code false} otherwise. 1543 */ 1544 @SuppressWarnings("serial") 1545 protected final boolean waitForIdle(final long timeout) { 1546 flushPendingEvents(); 1547 final boolean queueWasEmpty; 1548 synchronized (waitLock) { 1549 queueWasEmpty = isEQEmpty(); 1550 queueEmpty = false; 1551 eventDispatched = false; 1552 postEvent(AppContext.getAppContext(), 1553 new PeerEvent(getSystemEventQueueImpl(), null, PeerEvent.LOW_PRIORITY_EVENT) { 1554 @Override 1555 public void dispatch() { 1556 // Here we block EDT. It could have some 1557 // events, it should have dispatched them by 1558 // now. So native requests could have been 1559 // generated. First, dispatch them. Then, 1560 // flush Java events again. 1561 int iters = 0; 1562 while (iters < MIN_ITERS) { 1563 syncNativeQueue(timeout); 1564 iters++; 1565 } 1566 while (syncNativeQueue(timeout) && iters < MAX_ITERS) { 1567 iters++; 1568 } 1569 flushPendingEvents(); 1570 1571 synchronized(waitLock) { 1572 queueEmpty = isEQEmpty(); 1573 eventDispatched = true; 1574 waitLock.notifyAll(); 1575 } 1576 } 1577 }); 1578 try { 1579 while (!eventDispatched) { 1580 waitLock.wait(); 1581 } 1582 } catch (InterruptedException ie) { 1583 return false; 1584 } 1585 } 1586 1587 try { 1588 Thread.sleep(MINIMAL_EDELAY); 1589 } catch (InterruptedException ie) { 1590 throw new RuntimeException("Interrupted"); 1591 } 1592 1593 flushPendingEvents(); 1594 1595 // Lock to force write-cache flush for queueEmpty. 1596 synchronized (waitLock) { 1597 return !(queueEmpty && isEQEmpty() && queueWasEmpty); 1598 } 1599 } 1600 1601 /** 1602 * Grabs the mouse input for the given window. The window must be 1603 * visible. The window or its children do not receive any 1604 * additional mouse events besides those targeted to them. All 1605 * other events will be dispatched as before - to the respective 1606 * targets. This Window will receive UngrabEvent when automatic 1607 * ungrab is about to happen. The event can be listened to by 1608 * installing AWTEventListener with WINDOW_EVENT_MASK. See 1609 * UngrabEvent class for the list of conditions when ungrab is 1610 * about to happen. 1611 * @see UngrabEvent 1612 */ 1613 public abstract void grab(Window w); 1614 1615 /** 1616 * Forces ungrab. No event will be sent. 1617 */ 1618 public abstract void ungrab(Window w); 1619 1620 public void showOrHideTouchKeyboard(Component comp, AWTEvent e) {} 1621 1622 private static boolean touchKeyboardAutoShowIsEnabled; 1623 1624 public static boolean isTouchKeyboardAutoShowEnabled() { 1625 return touchKeyboardAutoShowIsEnabled; 1626 } 1627 1628 /** 1629 * Locates the splash screen library in a platform dependent way and closes 1630 * the splash screen. Should be invoked on first top-level frame display. 1631 * @see java.awt.SplashScreen 1632 * @since 1.6 1633 */ 1634 public static native void closeSplashScreen(); 1635 1636 /* The following methods and variables are to support retrieving 1637 * desktop text anti-aliasing settings 1638 */ 1639 1640 /* Need an instance method because setDesktopProperty(..) is protected. */ 1641 private void fireDesktopFontPropertyChanges() { 1642 setDesktopProperty(SunToolkit.DESKTOPFONTHINTS, 1643 SunToolkit.getDesktopFontHints()); 1644 } 1645 1646 private static boolean checkedSystemAAFontSettings; 1647 private static boolean useSystemAAFontSettings; 1648 private static boolean lastExtraCondition = true; 1649 private static RenderingHints desktopFontHints; 1650 1651 /* Since Swing is the reason for this "extra condition" logic its 1652 * worth documenting it in some detail. 1653 * First, a goal is for Swing and applications to both retrieve and 1654 * use the same desktop property value so that there is complete 1655 * consistency between the settings used by JDK's Swing implementation 1656 * and 3rd party custom Swing components, custom L&Fs and any general 1657 * text rendering that wants to be consistent with these. 1658 * But by default on Solaris & Linux Swing will not use AA text over 1659 * remote X11 display (unless Xrender can be used which is TBD and may not 1660 * always be available anyway) as that is a noticeable performance hit. 1661 * So there needs to be a way to express that extra condition so that 1662 * it is seen by all clients of the desktop property API. 1663 * If this were the only condition it could be handled here as it would 1664 * be the same for any L&F and could reasonably be considered to be 1665 * a static behaviour of those systems. 1666 * But GTK currently has an additional test based on locale which is 1667 * not applied by Metal. So mixing GTK in a few locales with Metal 1668 * would mean the last one wins. 1669 * This could be stored per-app context which would work 1670 * for different applets, but wouldn't help for a single application 1671 * using GTK and some other L&F concurrently. 1672 * But it is expected this will be addressed within GTK and the font 1673 * system so is a temporary and somewhat unlikely harmless corner case. 1674 */ 1675 public static void setAAFontSettingsCondition(boolean extraCondition) { 1676 if (extraCondition != lastExtraCondition) { 1677 lastExtraCondition = extraCondition; 1678 if (checkedSystemAAFontSettings) { 1679 /* Someone already asked for this info, under a different 1680 * condition. 1681 * We'll force re-evaluation instead of replicating the 1682 * logic, then notify any listeners of any change. 1683 */ 1684 checkedSystemAAFontSettings = false; 1685 Toolkit tk = Toolkit.getDefaultToolkit(); 1686 if (tk instanceof SunToolkit) { 1687 ((SunToolkit)tk).fireDesktopFontPropertyChanges(); 1688 } 1689 } 1690 } 1691 } 1692 1693 /* "false", "off", ""default" aren't explicitly tested, they 1694 * just fall through to produce a null return which all are equated to 1695 * "false". 1696 */ 1697 private static RenderingHints getDesktopAAHintsByName(String hintname) { 1698 Object aaHint = null; 1699 hintname = hintname.toLowerCase(Locale.ENGLISH); 1700 if (hintname.equals("on")) { 1701 aaHint = VALUE_TEXT_ANTIALIAS_ON; 1702 } else if (hintname.equals("gasp")) { 1703 aaHint = VALUE_TEXT_ANTIALIAS_GASP; 1704 } else if (hintname.equals("lcd") || hintname.equals("lcd_hrgb")) { 1705 aaHint = VALUE_TEXT_ANTIALIAS_LCD_HRGB; 1706 } else if (hintname.equals("lcd_hbgr")) { 1707 aaHint = VALUE_TEXT_ANTIALIAS_LCD_HBGR; 1708 } else if (hintname.equals("lcd_vrgb")) { 1709 aaHint = VALUE_TEXT_ANTIALIAS_LCD_VRGB; 1710 } else if (hintname.equals("lcd_vbgr")) { 1711 aaHint = VALUE_TEXT_ANTIALIAS_LCD_VBGR; 1712 } 1713 if (aaHint != null) { 1714 RenderingHints map = new RenderingHints(null); 1715 map.put(KEY_TEXT_ANTIALIASING, aaHint); 1716 return map; 1717 } else { 1718 return null; 1719 } 1720 } 1721 1722 /* This method determines whether to use the system font settings, 1723 * or ignore them if a L&F has specified they should be ignored, or 1724 * to override both of these with a system property specified value. 1725 * If the toolkit isn't a SunToolkit, (eg may be headless) then that 1726 * system property isn't applied as desktop properties are considered 1727 * to be inapplicable in that case. In that headless case although 1728 * this method will return "true" the toolkit will return a null map. 1729 */ 1730 private static boolean useSystemAAFontSettings() { 1731 if (!checkedSystemAAFontSettings) { 1732 useSystemAAFontSettings = true; /* initially set this true */ 1733 String systemAAFonts = null; 1734 Toolkit tk = Toolkit.getDefaultToolkit(); 1735 if (tk instanceof SunToolkit) { 1736 systemAAFonts = 1737 AccessController.doPrivileged( 1738 new GetPropertyAction("awt.useSystemAAFontSettings")); 1739 } 1740 if (systemAAFonts != null) { 1741 useSystemAAFontSettings = 1742 Boolean.valueOf(systemAAFonts).booleanValue(); 1743 /* If it is anything other than "true", then it may be 1744 * a hint name , or it may be "off, "default", etc. 1745 */ 1746 if (!useSystemAAFontSettings) { 1747 desktopFontHints = getDesktopAAHintsByName(systemAAFonts); 1748 } 1749 } 1750 /* If its still true, apply the extra condition */ 1751 if (useSystemAAFontSettings) { 1752 useSystemAAFontSettings = lastExtraCondition; 1753 } 1754 checkedSystemAAFontSettings = true; 1755 } 1756 return useSystemAAFontSettings; 1757 } 1758 1759 /* A variable defined for the convenience of JDK code */ 1760 public static final String DESKTOPFONTHINTS = "awt.font.desktophints"; 1761 1762 /* Overridden by subclasses to return platform/desktop specific values */ 1763 protected RenderingHints getDesktopAAHints() { 1764 return null; 1765 } 1766 1767 /* Subclass desktop property loading methods call this which 1768 * in turn calls the appropriate subclass implementation of 1769 * getDesktopAAHints() when system settings are being used. 1770 * Its public rather than protected because subclasses may delegate 1771 * to a helper class. 1772 */ 1773 public static RenderingHints getDesktopFontHints() { 1774 if (useSystemAAFontSettings()) { 1775 Toolkit tk = Toolkit.getDefaultToolkit(); 1776 if (tk instanceof SunToolkit) { 1777 Object map = ((SunToolkit)tk).getDesktopAAHints(); 1778 return (RenderingHints)map; 1779 } else { /* Headless Toolkit */ 1780 return null; 1781 } 1782 } else if (desktopFontHints != null) { 1783 /* cloning not necessary as the return value is cloned later, but 1784 * its harmless. 1785 */ 1786 return (RenderingHints)(desktopFontHints.clone()); 1787 } else { 1788 return null; 1789 } 1790 } 1791 1792 1793 public abstract boolean isDesktopSupported(); 1794 public abstract boolean isTaskbarSupported(); 1795 1796 /* 1797 * consumeNextKeyTyped() method is not currently used, 1798 * however Swing could use it in the future. 1799 */ 1800 public static synchronized void consumeNextKeyTyped(KeyEvent keyEvent) { 1801 try { 1802 AWTAccessor.getDefaultKeyboardFocusManagerAccessor().consumeNextKeyTyped( 1803 (DefaultKeyboardFocusManager)KeyboardFocusManager. 1804 getCurrentKeyboardFocusManager(), 1805 keyEvent); 1806 } catch (ClassCastException cce) { 1807 cce.printStackTrace(); 1808 } 1809 } 1810 1811 protected static void dumpPeers(final PlatformLogger aLog) { 1812 AWTAutoShutdown.getInstance().dumpPeers(aLog); 1813 } 1814 1815 /** 1816 * Returns the {@code Window} ancestor of the component {@code comp}. 1817 * @return Window ancestor of the component or component by itself if it is Window; 1818 * null, if component is not a part of window hierarchy 1819 */ 1820 public static Window getContainingWindow(Component comp) { 1821 while (comp != null && !(comp instanceof Window)) { 1822 comp = comp.getParent(); 1823 } 1824 return (Window)comp; 1825 } 1826 1827 private static Boolean sunAwtDisableMixing = null; 1828 1829 /** 1830 * Returns the value of "sun.awt.disableMixing" property. Default 1831 * value is {@code false}. 1832 */ 1833 public static synchronized boolean getSunAwtDisableMixing() { 1834 if (sunAwtDisableMixing == null) { 1835 sunAwtDisableMixing = AccessController.doPrivileged( 1836 new GetBooleanAction("sun.awt.disableMixing")); 1837 } 1838 return sunAwtDisableMixing.booleanValue(); 1839 } 1840 1841 /** 1842 * Returns true if the native GTK libraries are available. The 1843 * default implementation returns false, but UNIXToolkit overrides this 1844 * method to provide a more specific answer. 1845 */ 1846 public boolean isNativeGTKAvailable() { 1847 return false; 1848 } 1849 1850 private static final Object DEACTIVATION_TIMES_MAP_KEY = new Object(); 1851 1852 public synchronized void setWindowDeactivationTime(Window w, long time) { 1853 AppContext ctx = getAppContext(w); 1854 if (ctx == null) { 1855 return; 1856 } 1857 @SuppressWarnings("unchecked") 1858 WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY); 1859 if (map == null) { 1860 map = new WeakHashMap<Window, Long>(); 1861 ctx.put(DEACTIVATION_TIMES_MAP_KEY, map); 1862 } 1863 map.put(w, time); 1864 } 1865 1866 public synchronized long getWindowDeactivationTime(Window w) { 1867 AppContext ctx = getAppContext(w); 1868 if (ctx == null) { 1869 return -1; 1870 } 1871 @SuppressWarnings("unchecked") 1872 WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY); 1873 if (map == null) { 1874 return -1; 1875 } 1876 Long time = map.get(w); 1877 return time == null ? -1 : time; 1878 } 1879 1880 public void updateScreenMenuBarUI() { 1881 } 1882 1883 // Cosntant alpha 1884 public boolean isWindowOpacitySupported() { 1885 return false; 1886 } 1887 1888 // Shaping 1889 public boolean isWindowShapingSupported() { 1890 return false; 1891 } 1892 1893 // Per-pixel alpha 1894 public boolean isWindowTranslucencySupported() { 1895 return false; 1896 } 1897 1898 public boolean isTranslucencyCapable(GraphicsConfiguration gc) { 1899 return false; 1900 } 1901 1902 /** 1903 * Returns true if swing backbuffer should be translucent. 1904 */ 1905 public boolean isSwingBackbufferTranslucencySupported() { 1906 return false; 1907 } 1908 1909 /** 1910 * Returns whether or not a containing top level window for the passed 1911 * component is 1912 * {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT PERPIXEL_TRANSLUCENT}. 1913 * 1914 * @param c a Component which toplevel's to check 1915 * @return {@code true} if the passed component is not null and has a 1916 * containing toplevel window which is opaque (so per-pixel translucency 1917 * is not enabled), {@code false} otherwise 1918 * @see GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT 1919 */ 1920 public static boolean isContainingTopLevelOpaque(Component c) { 1921 Window w = getContainingWindow(c); 1922 return w != null && w.isOpaque(); 1923 } 1924 1925 /** 1926 * Returns whether or not a containing top level window for the passed 1927 * component is 1928 * {@link GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}. 1929 * 1930 * @param c a Component which toplevel's to check 1931 * @return {@code true} if the passed component is not null and has a 1932 * containing toplevel window which has opacity less than 1933 * 1.0f (which means that it is translucent), {@code false} otherwise 1934 * @see GraphicsDevice.WindowTranslucency#TRANSLUCENT 1935 */ 1936 public static boolean isContainingTopLevelTranslucent(Component c) { 1937 Window w = getContainingWindow(c); 1938 return w != null && w.getOpacity() < 1.0f; 1939 } 1940 1941 /** 1942 * Returns whether the native system requires using the peer.updateWindow() 1943 * method to update the contents of a non-opaque window, or if usual 1944 * painting procedures are sufficient. The default return value covers 1945 * the X11 systems. On MS Windows this method is overriden in WToolkit 1946 * to return true. 1947 */ 1948 public boolean needUpdateWindow() { 1949 return false; 1950 } 1951 1952 /** 1953 * Descendants of the SunToolkit should override and put their own logic here. 1954 */ 1955 public int getNumberOfButtons(){ 1956 return 3; 1957 } 1958 1959 /** 1960 * Checks that the given object implements/extends the given 1961 * interface/class. 1962 * 1963 * Note that using the instanceof operator causes a class to be loaded. 1964 * Using this method doesn't load a class and it can be used instead of 1965 * the instanceof operator for performance reasons. 1966 * 1967 * @param obj Object to be checked 1968 * @param type The name of the interface/class. Must be 1969 * fully-qualified interface/class name. 1970 * @return true, if this object implements/extends the given 1971 * interface/class, false, otherwise, or if obj or type is null 1972 */ 1973 public static boolean isInstanceOf(Object obj, String type) { 1974 if (obj == null) return false; 1975 if (type == null) return false; 1976 1977 return isInstanceOf(obj.getClass(), type); 1978 } 1979 1980 private static boolean isInstanceOf(Class<?> cls, String type) { 1981 if (cls == null) return false; 1982 1983 if (cls.getName().equals(type)) { 1984 return true; 1985 } 1986 1987 for (Class<?> c : cls.getInterfaces()) { 1988 if (c.getName().equals(type)) { 1989 return true; 1990 } 1991 } 1992 return isInstanceOf(cls.getSuperclass(), type); 1993 } 1994 1995 protected static LightweightFrame getLightweightFrame(Component c) { 1996 for (; c != null; c = c.getParent()) { 1997 if (c instanceof LightweightFrame) { 1998 return (LightweightFrame)c; 1999 } 2000 if (c instanceof Window) { 2001 // Don't traverse owner windows 2002 return null; 2003 } 2004 } 2005 return null; 2006 } 2007 2008 /////////////////////////////////////////////////////////////////////////// 2009 // 2010 // The following methods help set and identify whether a particular 2011 // AWTEvent object was produced by the system or by user code. As of this 2012 // writing the only consumer is the Java Plug-In, although this information 2013 // could be useful to more clients and probably should be formalized in 2014 // the public API. 2015 // 2016 /////////////////////////////////////////////////////////////////////////// 2017 2018 public static void setSystemGenerated(AWTEvent e) { 2019 AWTAccessor.getAWTEventAccessor().setSystemGenerated(e); 2020 } 2021 2022 public static boolean isSystemGenerated(AWTEvent e) { 2023 return AWTAccessor.getAWTEventAccessor().isSystemGenerated(e); 2024 } 2025 2026 } // class SunToolkit 2027 2028 2029 /* 2030 * PostEventQueue is a Thread that runs in the same AppContext as the 2031 * Java EventQueue. It is a queue of AWTEvents to be posted to the 2032 * Java EventQueue. The toolkit Thread (AWT-Windows/AWT-Motif) posts 2033 * events to this queue, which then calls EventQueue.postEvent(). 2034 * 2035 * We do this because EventQueue.postEvent() may be overridden by client 2036 * code, and we mustn't ever call client code from the toolkit thread. 2037 */ 2038 class PostEventQueue { 2039 private EventQueueItem queueHead = null; 2040 private EventQueueItem queueTail = null; 2041 private final EventQueue eventQueue; 2042 2043 private Thread flushThread = null; 2044 2045 PostEventQueue(EventQueue eq) { 2046 eventQueue = eq; 2047 } 2048 2049 /* 2050 * Continually post pending AWTEvents to the Java EventQueue. The method 2051 * is synchronized to ensure the flush is completed before a new event 2052 * can be posted to this queue. 2053 * 2054 * 7177040: The method couldn't be wholly synchronized because of calls 2055 * of EventQueue.postEvent() that uses pushPopLock, otherwise it could 2056 * potentially lead to deadlock 2057 */ 2058 public void flush() { 2059 2060 Thread newThread = Thread.currentThread(); 2061 2062 try { 2063 EventQueueItem tempQueue; 2064 synchronized (this) { 2065 // Avoid method recursion 2066 if (newThread == flushThread) { 2067 return; 2068 } 2069 // Wait for other threads' flushing 2070 while (flushThread != null) { 2071 wait(); 2072 } 2073 // Skip everything if queue is empty 2074 if (queueHead == null) { 2075 return; 2076 } 2077 // Remember flushing thread 2078 flushThread = newThread; 2079 2080 tempQueue = queueHead; 2081 queueHead = queueTail = null; 2082 } 2083 try { 2084 while (tempQueue != null) { 2085 eventQueue.postEvent(tempQueue.event); 2086 tempQueue = tempQueue.next; 2087 } 2088 } 2089 finally { 2090 // Only the flushing thread can get here 2091 synchronized (this) { 2092 // Forget flushing thread, inform other pending threads 2093 flushThread = null; 2094 notifyAll(); 2095 } 2096 } 2097 } 2098 catch (InterruptedException e) { 2099 // Couldn't allow exception go up, so at least recover the flag 2100 newThread.interrupt(); 2101 } 2102 } 2103 2104 /* 2105 * Enqueue an AWTEvent to be posted to the Java EventQueue. 2106 */ 2107 void postEvent(AWTEvent event) { 2108 EventQueueItem item = new EventQueueItem(event); 2109 2110 synchronized (this) { 2111 if (queueHead == null) { 2112 queueHead = queueTail = item; 2113 } else { 2114 queueTail.next = item; 2115 queueTail = item; 2116 } 2117 } 2118 SunToolkit.wakeupEventQueue(eventQueue, event.getSource() == AWTAutoShutdown.getInstance()); 2119 } 2120 } // class PostEventQueue