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