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