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.Collections; 50 import java.util.Iterator; 51 import java.util.Locale; 52 import java.util.Map; 53 import java.util.Vector; 54 import java.util.WeakHashMap; 55 import java.util.concurrent.TimeUnit; 56 import java.util.concurrent.locks.Condition; 57 import java.util.concurrent.locks.ReentrantLock; 58 59 import sun.awt.im.InputContext; 60 import sun.awt.image.ByteArrayImageSource; 61 import sun.awt.image.FileImageSource; 62 import sun.awt.image.ImageRepresentation; 63 import java.awt.image.MultiResolutionImage; 64 import sun.awt.image.MultiResolutionToolkitImage; 65 import sun.awt.image.ToolkitImage; 66 import sun.awt.image.URLImageSource; 67 import sun.font.FontDesignMetrics; 68 import sun.misc.SoftCache; 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 private static FocusTraversalPolicy createLayoutPolicy() { 377 FocusTraversalPolicy policy = null; 378 try { 379 @SuppressWarnings("deprecation") 380 Object layoutPolicyObject = 381 Class.forName("javax.swing.LayoutFocusTraversalPolicy").newInstance(); 382 policy = (FocusTraversalPolicy)layoutPolicyObject; 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, resolutionVariant); 757 } 758 759 @Override 760 public int checkImage(Image img, int w, int h, ImageObserver o) { 761 if (!(img instanceof ToolkitImage)) { 762 return ImageObserver.ALLBITS; 763 } 764 765 ToolkitImage tkimg = (ToolkitImage)img; 766 int repbits; 767 if (w == 0 || h == 0) { 768 repbits = ImageObserver.ALLBITS; 769 } else { 770 repbits = tkimg.getImageRep().check(o); 771 } 772 return (tkimg.check(o) | repbits) & checkResolutionVariant(img, w, h, o); 773 } 774 775 @Override 776 public boolean prepareImage(Image img, int w, int h, ImageObserver o) { 777 if (w == 0 || h == 0) { 778 return true; 779 } 780 781 // Must be a ToolkitImage 782 if (!(img instanceof ToolkitImage)) { 783 return true; 784 } 785 786 ToolkitImage tkimg = (ToolkitImage)img; 787 if (tkimg.hasError()) { 788 if (o != null) { 789 o.imageUpdate(img, ImageObserver.ERROR|ImageObserver.ABORT, 790 -1, -1, -1, -1); 791 } 792 return false; 793 } 794 ImageRepresentation ir = tkimg.getImageRep(); 795 return ir.prepare(o) & prepareResolutionVariant(img, w, h, o); 796 } 797 798 private int checkResolutionVariant(Image img, int w, int h, ImageObserver o) { 799 ToolkitImage rvImage = getResolutionVariant(img); 800 int rvw = getRVSize(w); 801 int rvh = getRVSize(h); 802 // Ignore the resolution variant in case of error 803 return (rvImage == null || rvImage.hasError()) ? 0xFFFF : 804 checkImage(rvImage, rvw, rvh, MultiResolutionToolkitImage. 805 getResolutionVariantObserver( 806 img, o, w, h, rvw, rvh, true)); 807 } 808 809 private boolean prepareResolutionVariant(Image img, int w, int h, 810 ImageObserver o) { 811 812 ToolkitImage rvImage = getResolutionVariant(img); 813 int rvw = getRVSize(w); 814 int rvh = getRVSize(h); 815 // Ignore the resolution variant in case of error 816 return rvImage == null || rvImage.hasError() || prepareImage( 817 rvImage, rvw, rvh, 818 MultiResolutionToolkitImage.getResolutionVariantObserver( 819 img, o, w, h, rvw, rvh, true)); 820 } 821 822 private static int getRVSize(int size){ 823 return size == -1 ? -1 : 2 * size; 824 } 825 826 private static ToolkitImage getResolutionVariant(Image image) { 827 if (image instanceof MultiResolutionToolkitImage) { 828 Image resolutionVariant = ((MultiResolutionToolkitImage) image). 829 getResolutionVariant(); 830 if (resolutionVariant instanceof ToolkitImage) { 831 return (ToolkitImage) resolutionVariant; 832 } 833 } 834 return null; 835 } 836 837 protected static boolean imageCached(String fileName) { 838 return fileImgCache.containsKey(fileName); 839 } 840 841 protected static boolean imageCached(URL url) { 842 String key = url.toString(); 843 return urlImgCache.containsKey(key); 844 } 845 846 protected static boolean imageExists(String filename) { 847 if (filename != null) { 848 checkPermissions(filename); 849 return new File(filename).exists(); 850 } 851 return false; 852 } 853 854 @SuppressWarnings("try") 855 protected static boolean imageExists(URL url) { 856 if (url != null) { 857 checkPermissions(url); 858 try (InputStream is = url.openStream()) { 859 return true; 860 }catch(IOException e){ 861 return false; 862 } 863 } 864 return false; 865 } 866 867 private static void checkPermissions(String filename) { 868 SecurityManager security = System.getSecurityManager(); 869 if (security != null) { 870 security.checkRead(filename); 871 } 872 } 873 874 private static void checkPermissions(URL url) { 875 SecurityManager sm = System.getSecurityManager(); 876 if (sm != null) { 877 try { 878 java.security.Permission perm = 879 URLUtil.getConnectPermission(url); 880 if (perm != null) { 881 try { 882 sm.checkPermission(perm); 883 } catch (SecurityException se) { 884 // fallback to checkRead/checkConnect for pre 1.2 885 // security managers 886 if ((perm instanceof java.io.FilePermission) && 887 perm.getActions().indexOf("read") != -1) { 888 sm.checkRead(perm.getName()); 889 } else if ((perm instanceof 890 java.net.SocketPermission) && 891 perm.getActions().indexOf("connect") != -1) { 892 sm.checkConnect(url.getHost(), url.getPort()); 893 } else { 894 throw se; 895 } 896 } 897 } 898 } catch (java.io.IOException ioe) { 899 sm.checkConnect(url.getHost(), url.getPort()); 900 } 901 } 902 } 903 904 /** 905 * Scans {@code imageList} for best-looking image of specified dimensions. 906 * Image can be scaled and/or padded with transparency. 907 */ 908 public static BufferedImage getScaledIconImage(java.util.List<Image> imageList, int width, int height) { 909 if (width == 0 || height == 0) { 910 return null; 911 } 912 Image bestImage = null; 913 int bestWidth = 0; 914 int bestHeight = 0; 915 double bestSimilarity = 3; //Impossibly high value 916 double bestScaleFactor = 0; 917 for (Iterator<Image> i = imageList.iterator();i.hasNext();) { 918 //Iterate imageList looking for best matching image. 919 //'Similarity' measure is defined as good scale factor and small insets. 920 //best possible similarity is 0 (no scale, no insets). 921 //It's found while the experiments that good-looking result is achieved 922 //with scale factors x1, x3/4, x2/3, xN, x1/N. 923 Image im = i.next(); 924 if (im == null) { 925 continue; 926 } 927 if (im instanceof ToolkitImage) { 928 ImageRepresentation ir = ((ToolkitImage)im).getImageRep(); 929 ir.reconstruct(ImageObserver.ALLBITS); 930 } 931 int iw; 932 int ih; 933 try { 934 iw = im.getWidth(null); 935 ih = im.getHeight(null); 936 } catch (Exception e){ 937 continue; 938 } 939 if (iw > 0 && ih > 0) { 940 //Calc scale factor 941 double scaleFactor = Math.min((double)width / (double)iw, 942 (double)height / (double)ih); 943 //Calculate scaled image dimensions 944 //adjusting scale factor to nearest "good" value 945 int adjw = 0; 946 int adjh = 0; 947 double scaleMeasure = 1; //0 - best (no) scale, 1 - impossibly bad 948 if (scaleFactor >= 2) { 949 //Need to enlarge image more than twice 950 //Round down scale factor to multiply by integer value 951 scaleFactor = Math.floor(scaleFactor); 952 adjw = iw * (int)scaleFactor; 953 adjh = ih * (int)scaleFactor; 954 scaleMeasure = 1.0 - 0.5 / scaleFactor; 955 } else if (scaleFactor >= 1) { 956 //Don't scale 957 scaleFactor = 1.0; 958 adjw = iw; 959 adjh = ih; 960 scaleMeasure = 0; 961 } else if (scaleFactor >= 0.75) { 962 //Multiply by 3/4 963 scaleFactor = 0.75; 964 adjw = iw * 3 / 4; 965 adjh = ih * 3 / 4; 966 scaleMeasure = 0.3; 967 } else if (scaleFactor >= 0.6666) { 968 //Multiply by 2/3 969 scaleFactor = 0.6666; 970 adjw = iw * 2 / 3; 971 adjh = ih * 2 / 3; 972 scaleMeasure = 0.33; 973 } else { 974 //Multiply size by 1/scaleDivider 975 //where scaleDivider is minimum possible integer 976 //larger than 1/scaleFactor 977 double scaleDivider = Math.ceil(1.0 / scaleFactor); 978 scaleFactor = 1.0 / scaleDivider; 979 adjw = (int)Math.round((double)iw / scaleDivider); 980 adjh = (int)Math.round((double)ih / scaleDivider); 981 scaleMeasure = 1.0 - 1.0 / scaleDivider; 982 } 983 double similarity = ((double)width - (double)adjw) / (double)width + 984 ((double)height - (double)adjh) / (double)height + //Large padding is bad 985 scaleMeasure; //Large rescale is bad 986 if (similarity < bestSimilarity) { 987 bestSimilarity = similarity; 988 bestScaleFactor = scaleFactor; 989 bestImage = im; 990 bestWidth = adjw; 991 bestHeight = adjh; 992 } 993 if (similarity == 0) break; 994 } 995 } 996 if (bestImage == null) { 997 //No images were found, possibly all are broken 998 return null; 999 } 1000 BufferedImage bimage = 1001 new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 1002 Graphics2D g = bimage.createGraphics(); 1003 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 1004 RenderingHints.VALUE_INTERPOLATION_BILINEAR); 1005 try { 1006 int x = (width - bestWidth) / 2; 1007 int y = (height - bestHeight) / 2; 1008 g.drawImage(bestImage, x, y, bestWidth, bestHeight, null); 1009 } finally { 1010 g.dispose(); 1011 } 1012 return bimage; 1013 } 1014 1015 public static DataBufferInt getScaledIconData(java.util.List<Image> imageList, int width, int height) { 1016 BufferedImage bimage = getScaledIconImage(imageList, width, height); 1017 if (bimage == null) { 1018 return null; 1019 } 1020 Raster raster = bimage.getRaster(); 1021 DataBuffer buffer = raster.getDataBuffer(); 1022 return (DataBufferInt)buffer; 1023 } 1024 1025 @Override 1026 protected EventQueue getSystemEventQueueImpl() { 1027 return getSystemEventQueueImplPP(); 1028 } 1029 1030 // Package private implementation 1031 static EventQueue getSystemEventQueueImplPP() { 1032 return getSystemEventQueueImplPP(AppContext.getAppContext()); 1033 } 1034 1035 public static EventQueue getSystemEventQueueImplPP(AppContext appContext) { 1036 EventQueue theEventQueue = 1037 (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY); 1038 return theEventQueue; 1039 } 1040 1041 /** 1042 * Give native peers the ability to query the native container 1043 * given a native component (eg the direct parent may be lightweight). 1044 */ 1045 public static Container getNativeContainer(Component c) { 1046 return Toolkit.getNativeContainer(c); 1047 } 1048 1049 /** 1050 * Gives native peers the ability to query the closest HW component. 1051 * If the given component is heavyweight, then it returns this. Otherwise, 1052 * it goes one level up in the hierarchy and tests next component. 1053 */ 1054 public static Component getHeavyweightComponent(Component c) { 1055 while (c != null && AWTAccessor.getComponentAccessor().isLightweight(c)) { 1056 c = AWTAccessor.getComponentAccessor().getParent(c); 1057 } 1058 return c; 1059 } 1060 1061 /** 1062 * Returns key modifiers used by Swing to set up a focus accelerator key stroke. 1063 */ 1064 public int getFocusAcceleratorKeyMask() { 1065 return InputEvent.ALT_MASK; 1066 } 1067 1068 /** 1069 * Tests whether specified key modifiers mask can be used to enter a printable 1070 * character. This is a default implementation of this method, which reflects 1071 * the way things work on Windows: here, pressing ctrl + alt allows user to enter 1072 * characters from the extended character set (like euro sign or math symbols) 1073 */ 1074 public boolean isPrintableCharacterModifiersMask(int mods) { 1075 return ((mods & InputEvent.ALT_MASK) == (mods & InputEvent.CTRL_MASK)); 1076 } 1077 1078 /** 1079 * Returns whether popup is allowed to be shown above the task bar. 1080 * This is a default implementation of this method, which checks 1081 * corresponding security permission. 1082 */ 1083 public boolean canPopupOverlapTaskBar() { 1084 boolean result = true; 1085 try { 1086 SecurityManager sm = System.getSecurityManager(); 1087 if (sm != null) { 1088 sm.checkPermission(AWTPermissions.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION); 1089 } 1090 } catch (SecurityException se) { 1091 // There is no permission to show popups over the task bar 1092 result = false; 1093 } 1094 return result; 1095 } 1096 1097 /** 1098 * Returns a new input method window, with behavior as specified in 1099 * {@link java.awt.im.spi.InputMethodContext#createInputMethodWindow}. 1100 * If the inputContext is not null, the window should return it from its 1101 * getInputContext() method. The window needs to implement 1102 * sun.awt.im.InputMethodWindow. 1103 * <p> 1104 * SunToolkit subclasses can override this method to return better input 1105 * method windows. 1106 */ 1107 @Override 1108 public Window createInputMethodWindow(String title, InputContext context) { 1109 return new sun.awt.im.SimpleInputMethodWindow(title, context); 1110 } 1111 1112 /** 1113 * Returns whether enableInputMethods should be set to true for peered 1114 * TextComponent instances on this platform. False by default. 1115 */ 1116 @Override 1117 public boolean enableInputMethodsForTextComponent() { 1118 return false; 1119 } 1120 1121 private static Locale startupLocale = null; 1122 1123 /** 1124 * Returns the locale in which the runtime was started. 1125 */ 1126 public static Locale getStartupLocale() { 1127 if (startupLocale == null) { 1128 String language, region, country, variant; 1129 language = AccessController.doPrivileged( 1130 new GetPropertyAction("user.language", "en")); 1131 // for compatibility, check for old user.region property 1132 region = AccessController.doPrivileged( 1133 new GetPropertyAction("user.region")); 1134 if (region != null) { 1135 // region can be of form country, country_variant, or _variant 1136 int i = region.indexOf('_'); 1137 if (i >= 0) { 1138 country = region.substring(0, i); 1139 variant = region.substring(i + 1); 1140 } else { 1141 country = region; 1142 variant = ""; 1143 } 1144 } else { 1145 country = AccessController.doPrivileged( 1146 new GetPropertyAction("user.country", "")); 1147 variant = AccessController.doPrivileged( 1148 new GetPropertyAction("user.variant", "")); 1149 } 1150 startupLocale = new Locale(language, country, variant); 1151 } 1152 return startupLocale; 1153 } 1154 1155 /** 1156 * Returns the default keyboard locale of the underlying operating system 1157 */ 1158 @Override 1159 public Locale getDefaultKeyboardLocale() { 1160 return getStartupLocale(); 1161 } 1162 1163 /** 1164 * Returns whether default toolkit needs the support of the xembed 1165 * from embedding host(if any). 1166 * @return {@code true}, if XEmbed is needed, {@code false} otherwise 1167 */ 1168 public static boolean needsXEmbed() { 1169 String noxembed = AccessController. 1170 doPrivileged(new GetPropertyAction("sun.awt.noxembed", "false")); 1171 if ("true".equals(noxembed)) { 1172 return false; 1173 } 1174 1175 Toolkit tk = Toolkit.getDefaultToolkit(); 1176 if (tk instanceof SunToolkit) { 1177 // SunToolkit descendants should override this method to specify 1178 // concrete behavior 1179 return ((SunToolkit)tk).needsXEmbedImpl(); 1180 } else { 1181 // Non-SunToolkit doubtly might support XEmbed 1182 return false; 1183 } 1184 } 1185 1186 /** 1187 * Returns whether this toolkit needs the support of the xembed 1188 * from embedding host(if any). 1189 * @return {@code true}, if XEmbed is needed, {@code false} otherwise 1190 */ 1191 protected boolean needsXEmbedImpl() { 1192 return false; 1193 } 1194 1195 private static Dialog.ModalExclusionType DEFAULT_MODAL_EXCLUSION_TYPE = null; 1196 1197 /** 1198 * Returns whether the XEmbed server feature is requested by 1199 * developer. If true, Toolkit should return an 1200 * XEmbed-server-enabled CanvasPeer instead of the ordinary CanvasPeer. 1201 */ 1202 protected final boolean isXEmbedServerRequested() { 1203 return AccessController.doPrivileged(new GetBooleanAction("sun.awt.xembedserver")); 1204 } 1205 1206 /** 1207 * Returns whether the modal exclusion API is supported by the current toolkit. 1208 * When it isn't supported, calling {@code setModalExcluded} has no 1209 * effect, and {@code isModalExcluded} returns false for all windows. 1210 * 1211 * @return true if modal exclusion is supported by the toolkit, false otherwise 1212 * 1213 * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window) 1214 * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window) 1215 * 1216 * @since 1.5 1217 */ 1218 public static boolean isModalExcludedSupported() 1219 { 1220 Toolkit tk = Toolkit.getDefaultToolkit(); 1221 return tk.isModalExclusionTypeSupported(DEFAULT_MODAL_EXCLUSION_TYPE); 1222 } 1223 /* 1224 * Default implementation for isModalExcludedSupportedImpl(), returns false. 1225 * 1226 * @see sun.awt.windows.WToolkit#isModalExcludeSupportedImpl 1227 * @see sun.awt.X11.XToolkit#isModalExcludeSupportedImpl 1228 * 1229 * @since 1.5 1230 */ 1231 protected boolean isModalExcludedSupportedImpl() 1232 { 1233 return false; 1234 } 1235 1236 /* 1237 * Sets this window to be excluded from being modally blocked. When the 1238 * toolkit supports modal exclusion and this method is called, input 1239 * events, focus transfer and z-order will continue to work for the 1240 * window, it's owned windows and child components, even in the 1241 * presence of a modal dialog. 1242 * For details on which {@code Window}s are normally blocked 1243 * by modal dialog, see {@link java.awt.Dialog}. 1244 * Invoking this method when the modal exclusion API is not supported by 1245 * the current toolkit has no effect. 1246 * @param window Window to be marked as not modally blocked 1247 * @see java.awt.Dialog 1248 * @see java.awt.Dialog#setModal(boolean) 1249 * @see sun.awt.SunToolkit#isModalExcludedSupported 1250 * @see sun.awt.SunToolkit#isModalExcluded(java.awt.Window) 1251 */ 1252 public static void setModalExcluded(Window window) 1253 { 1254 if (DEFAULT_MODAL_EXCLUSION_TYPE == null) { 1255 DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE; 1256 } 1257 window.setModalExclusionType(DEFAULT_MODAL_EXCLUSION_TYPE); 1258 } 1259 1260 /* 1261 * Returns whether the specified window is blocked by modal dialogs. 1262 * If the modal exclusion API isn't supported by the current toolkit, 1263 * it returns false for all windows. 1264 * 1265 * @param window Window to test for modal exclusion 1266 * 1267 * @return true if the window is modal excluded, false otherwise. If 1268 * the modal exclusion isn't supported by the current Toolkit, false 1269 * is returned 1270 * 1271 * @see sun.awt.SunToolkit#isModalExcludedSupported 1272 * @see sun.awt.SunToolkit#setModalExcluded(java.awt.Window) 1273 * 1274 * @since 1.5 1275 */ 1276 public static boolean isModalExcluded(Window window) 1277 { 1278 if (DEFAULT_MODAL_EXCLUSION_TYPE == null) { 1279 DEFAULT_MODAL_EXCLUSION_TYPE = Dialog.ModalExclusionType.APPLICATION_EXCLUDE; 1280 } 1281 return window.getModalExclusionType().compareTo(DEFAULT_MODAL_EXCLUSION_TYPE) >= 0; 1282 } 1283 1284 /** 1285 * Overridden in XToolkit and WToolkit 1286 */ 1287 @Override 1288 public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) { 1289 return (modalityType == Dialog.ModalityType.MODELESS) || 1290 (modalityType == Dialog.ModalityType.APPLICATION_MODAL); 1291 } 1292 1293 /** 1294 * Overridden in XToolkit and WToolkit 1295 */ 1296 @Override 1297 public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) { 1298 return (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE); 1299 } 1300 1301 /////////////////////////////////////////////////////////////////////////// 1302 // 1303 // The following is used by the Java Plug-in to coordinate dialog modality 1304 // between containing applications (browsers, ActiveX containers etc) and 1305 // the AWT. 1306 // 1307 /////////////////////////////////////////////////////////////////////////// 1308 1309 private ModalityListenerList modalityListeners = new ModalityListenerList(); 1310 1311 public void addModalityListener(ModalityListener listener) { 1312 modalityListeners.add(listener); 1313 } 1314 1315 public void removeModalityListener(ModalityListener listener) { 1316 modalityListeners.remove(listener); 1317 } 1318 1319 public void notifyModalityPushed(Dialog dialog) { 1320 notifyModalityChange(ModalityEvent.MODALITY_PUSHED, dialog); 1321 } 1322 1323 public void notifyModalityPopped(Dialog dialog) { 1324 notifyModalityChange(ModalityEvent.MODALITY_POPPED, dialog); 1325 } 1326 1327 final void notifyModalityChange(int id, Dialog source) { 1328 ModalityEvent ev = new ModalityEvent(source, modalityListeners, id); 1329 ev.dispatch(); 1330 } 1331 1332 static class ModalityListenerList implements ModalityListener { 1333 1334 Vector<ModalityListener> listeners = new Vector<ModalityListener>(); 1335 1336 void add(ModalityListener listener) { 1337 listeners.addElement(listener); 1338 } 1339 1340 void remove(ModalityListener listener) { 1341 listeners.removeElement(listener); 1342 } 1343 1344 @Override 1345 public void modalityPushed(ModalityEvent ev) { 1346 Iterator<ModalityListener> it = listeners.iterator(); 1347 while (it.hasNext()) { 1348 it.next().modalityPushed(ev); 1349 } 1350 } 1351 1352 @Override 1353 public void modalityPopped(ModalityEvent ev) { 1354 Iterator<ModalityListener> it = listeners.iterator(); 1355 while (it.hasNext()) { 1356 it.next().modalityPopped(ev); 1357 } 1358 } 1359 } // end of class ModalityListenerList 1360 1361 /////////////////////////////////////////////////////////////////////////// 1362 // End Plug-in code 1363 /////////////////////////////////////////////////////////////////////////// 1364 1365 public static boolean isLightweightOrUnknown(Component comp) { 1366 if (comp.isLightweight() 1367 || !(getDefaultToolkit() instanceof SunToolkit)) 1368 { 1369 return true; 1370 } 1371 return !(comp instanceof Button 1372 || comp instanceof Canvas 1373 || comp instanceof Checkbox 1374 || comp instanceof Choice 1375 || comp instanceof Label 1376 || comp instanceof java.awt.List 1377 || comp instanceof Panel 1378 || comp instanceof Scrollbar 1379 || comp instanceof ScrollPane 1380 || comp instanceof TextArea 1381 || comp instanceof TextField 1382 || comp instanceof Window); 1383 } 1384 1385 @SuppressWarnings("serial") 1386 public static class OperationTimedOut extends RuntimeException { 1387 public OperationTimedOut(String msg) { 1388 super(msg); 1389 } 1390 public OperationTimedOut() { 1391 } 1392 } 1393 1394 @SuppressWarnings("serial") 1395 public static class InfiniteLoop extends RuntimeException { 1396 } 1397 1398 @SuppressWarnings("serial") 1399 public static class IllegalThreadException extends RuntimeException { 1400 public IllegalThreadException(String msg) { 1401 super(msg); 1402 } 1403 public IllegalThreadException() { 1404 } 1405 } 1406 1407 public static final int DEFAULT_WAIT_TIME = 10000; 1408 private static final int MAX_ITERS = 20; 1409 private static final int MIN_ITERS = 0; 1410 private static final int MINIMAL_EDELAY = 0; 1411 1412 /** 1413 * Parameterless version of realsync which uses default timout (see DEFAUL_WAIT_TIME). 1414 */ 1415 public void realSync() throws OperationTimedOut, InfiniteLoop { 1416 realSync(DEFAULT_WAIT_TIME); 1417 } 1418 1419 /** 1420 * Forces toolkit to synchronize with the native windowing 1421 * sub-system, flushing all pending work and waiting for all the 1422 * events to be processed. This method guarantees that after 1423 * return no additional Java events will be generated, unless 1424 * cause by user. Obviously, the method cannot be used on the 1425 * event dispatch thread (EDT). In case it nevertheless gets 1426 * invoked on this thread, the method throws the 1427 * IllegalThreadException runtime exception. 1428 * 1429 * <p> This method allows to write tests without explicit timeouts 1430 * or wait for some event. Example: 1431 * <pre>{@code 1432 * Frame f = ...; 1433 * f.setVisible(true); 1434 * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); 1435 * }</pre> 1436 * 1437 * <p> After realSync, {@code f} will be completely visible 1438 * on the screen, its getLocationOnScreen will be returning the 1439 * right result and it will be the focus owner. 1440 * 1441 * <p> Another example: 1442 * <pre>{@code 1443 * b.requestFocus(); 1444 * ((SunToolkit)Toolkit.getDefaultToolkit()).realSync(); 1445 * }</pre> 1446 * 1447 * <p> After realSync, {@code b} will be focus owner. 1448 * 1449 * <p> Notice that realSync isn't guaranteed to work if recurring 1450 * actions occur, such as if during processing of some event 1451 * another request which may generate some events occurs. By 1452 * default, sync tries to perform as much as {@value #MAX_ITERS} 1453 * cycles of event processing, allowing for roughly {@value 1454 * #MAX_ITERS} additional requests. 1455 * 1456 * <p> For example, requestFocus() generates native request, which 1457 * generates one or two Java focus events, which then generate a 1458 * serie of paint events, a serie of Java focus events, which then 1459 * generate a serie of paint events which then are processed - 1460 * three cycles, minimum. 1461 * 1462 * @param timeout the maximum time to wait in milliseconds, negative means "forever". 1463 */ 1464 public void realSync(final long timeout) throws OperationTimedOut, InfiniteLoop 1465 { 1466 if (EventQueue.isDispatchThread()) { 1467 throw new IllegalThreadException("The SunToolkit.realSync() method cannot be used on the event dispatch thread (EDT)."); 1468 } 1469 int bigLoop = 0; 1470 do { 1471 // Let's do sync first 1472 sync(); 1473 1474 // During the wait process, when we were processing incoming 1475 // events, we could have made some new request, which can 1476 // generate new events. Example: MapNotify/XSetInputFocus. 1477 // Therefore, we dispatch them as long as there is something 1478 // to dispatch. 1479 int iters = 0; 1480 while (iters < MIN_ITERS) { 1481 syncNativeQueue(timeout); 1482 iters++; 1483 } 1484 while (syncNativeQueue(timeout) && iters < MAX_ITERS) { 1485 iters++; 1486 } 1487 if (iters >= MAX_ITERS) { 1488 throw new InfiniteLoop(); 1489 } 1490 1491 // native requests were dispatched by X/Window Manager or Windows 1492 // Moreover, we processed them all on Toolkit thread 1493 // Now wait while EDT processes them. 1494 // 1495 // During processing of some events (focus, for example), 1496 // some other events could have been generated. So, after 1497 // waitForIdle, we may end up with full EventQueue 1498 iters = 0; 1499 while (iters < MIN_ITERS) { 1500 waitForIdle(timeout); 1501 iters++; 1502 } 1503 while (waitForIdle(timeout) && iters < MAX_ITERS) { 1504 iters++; 1505 } 1506 if (iters >= MAX_ITERS) { 1507 throw new InfiniteLoop(); 1508 } 1509 1510 bigLoop++; 1511 // Again, for Java events, it was simple to check for new Java 1512 // events by checking event queue, but what if Java events 1513 // resulted in native requests? Therefor, check native events again. 1514 } while ((syncNativeQueue(timeout) || waitForIdle(timeout)) && bigLoop < MAX_ITERS); 1515 } 1516 1517 /** 1518 * Platform toolkits need to implement this method to perform the 1519 * sync of the native queue. The method should wait until native 1520 * requests are processed, all native events are processed and 1521 * corresponding Java events are generated. Should return 1522 * {@code true} if some events were processed, 1523 * {@code false} otherwise. 1524 */ 1525 protected abstract boolean syncNativeQueue(final long timeout); 1526 1527 private boolean eventDispatched = false; 1528 private boolean queueEmpty = false; 1529 private final Object waitLock = "Wait Lock"; 1530 1531 private boolean isEQEmpty() { 1532 EventQueue queue = getSystemEventQueueImpl(); 1533 return AWTAccessor.getEventQueueAccessor().noEvents(queue); 1534 } 1535 1536 /** 1537 * Waits for the Java event queue to empty. Ensures that all 1538 * events are processed (including paint events), and that if 1539 * recursive events were generated, they are also processed. 1540 * Should return {@code true} if more processing is 1541 * necessary, {@code false} otherwise. 1542 */ 1543 @SuppressWarnings("serial") 1544 protected final boolean waitForIdle(final long timeout) { 1545 flushPendingEvents(); 1546 boolean queueWasEmpty = isEQEmpty(); 1547 queueEmpty = false; 1548 eventDispatched = false; 1549 synchronized(waitLock) { 1550 postEvent(AppContext.getAppContext(), 1551 new PeerEvent(getSystemEventQueueImpl(), null, PeerEvent.LOW_PRIORITY_EVENT) { 1552 @Override 1553 public void dispatch() { 1554 // Here we block EDT. It could have some 1555 // events, it should have dispatched them by 1556 // now. So native requests could have been 1557 // generated. First, dispatch them. Then, 1558 // flush Java events again. 1559 int iters = 0; 1560 while (iters < MIN_ITERS) { 1561 syncNativeQueue(timeout); 1562 iters++; 1563 } 1564 while (syncNativeQueue(timeout) && iters < MAX_ITERS) { 1565 iters++; 1566 } 1567 flushPendingEvents(); 1568 1569 synchronized(waitLock) { 1570 queueEmpty = isEQEmpty(); 1571 eventDispatched = true; 1572 waitLock.notifyAll(); 1573 } 1574 } 1575 }); 1576 try { 1577 while (!eventDispatched) { 1578 waitLock.wait(); 1579 } 1580 } catch (InterruptedException ie) { 1581 return false; 1582 } 1583 } 1584 1585 try { 1586 Thread.sleep(MINIMAL_EDELAY); 1587 } catch (InterruptedException ie) { 1588 throw new RuntimeException("Interrupted"); 1589 } 1590 1591 flushPendingEvents(); 1592 1593 // Lock to force write-cache flush for queueEmpty. 1594 synchronized (waitLock) { 1595 return !(queueEmpty && isEQEmpty() && queueWasEmpty); 1596 } 1597 } 1598 1599 /** 1600 * Grabs the mouse input for the given window. The window must be 1601 * visible. The window or its children do not receive any 1602 * additional mouse events besides those targeted to them. All 1603 * other events will be dispatched as before - to the respective 1604 * targets. This Window will receive UngrabEvent when automatic 1605 * ungrab is about to happen. The event can be listened to by 1606 * installing AWTEventListener with WINDOW_EVENT_MASK. See 1607 * UngrabEvent class for the list of conditions when ungrab is 1608 * about to happen. 1609 * @see UngrabEvent 1610 */ 1611 public abstract void grab(Window w); 1612 1613 /** 1614 * Forces ungrab. No event will be sent. 1615 */ 1616 public abstract void ungrab(Window w); 1617 1618 1619 /** 1620 * Locates the splash screen library in a platform dependent way and closes 1621 * the splash screen. Should be invoked on first top-level frame display. 1622 * @see java.awt.SplashScreen 1623 * @since 1.6 1624 */ 1625 public static native void closeSplashScreen(); 1626 1627 /* The following methods and variables are to support retrieving 1628 * desktop text anti-aliasing settings 1629 */ 1630 1631 /* Need an instance method because setDesktopProperty(..) is protected. */ 1632 private void fireDesktopFontPropertyChanges() { 1633 setDesktopProperty(SunToolkit.DESKTOPFONTHINTS, 1634 SunToolkit.getDesktopFontHints()); 1635 } 1636 1637 private static boolean checkedSystemAAFontSettings; 1638 private static boolean useSystemAAFontSettings; 1639 private static boolean lastExtraCondition = true; 1640 private static RenderingHints desktopFontHints; 1641 1642 /* Since Swing is the reason for this "extra condition" logic its 1643 * worth documenting it in some detail. 1644 * First, a goal is for Swing and applications to both retrieve and 1645 * use the same desktop property value so that there is complete 1646 * consistency between the settings used by JDK's Swing implementation 1647 * and 3rd party custom Swing components, custom L&Fs and any general 1648 * text rendering that wants to be consistent with these. 1649 * But by default on Solaris & Linux Swing will not use AA text over 1650 * remote X11 display (unless Xrender can be used which is TBD and may not 1651 * always be available anyway) as that is a noticeable performance hit. 1652 * So there needs to be a way to express that extra condition so that 1653 * it is seen by all clients of the desktop property API. 1654 * If this were the only condition it could be handled here as it would 1655 * be the same for any L&F and could reasonably be considered to be 1656 * a static behaviour of those systems. 1657 * But GTK currently has an additional test based on locale which is 1658 * not applied by Metal. So mixing GTK in a few locales with Metal 1659 * would mean the last one wins. 1660 * This could be stored per-app context which would work 1661 * for different applets, but wouldn't help for a single application 1662 * using GTK and some other L&F concurrently. 1663 * But it is expected this will be addressed within GTK and the font 1664 * system so is a temporary and somewhat unlikely harmless corner case. 1665 */ 1666 public static void setAAFontSettingsCondition(boolean extraCondition) { 1667 if (extraCondition != lastExtraCondition) { 1668 lastExtraCondition = extraCondition; 1669 if (checkedSystemAAFontSettings) { 1670 /* Someone already asked for this info, under a different 1671 * condition. 1672 * We'll force re-evaluation instead of replicating the 1673 * logic, then notify any listeners of any change. 1674 */ 1675 checkedSystemAAFontSettings = false; 1676 Toolkit tk = Toolkit.getDefaultToolkit(); 1677 if (tk instanceof SunToolkit) { 1678 ((SunToolkit)tk).fireDesktopFontPropertyChanges(); 1679 } 1680 } 1681 } 1682 } 1683 1684 /* "false", "off", ""default" aren't explicitly tested, they 1685 * just fall through to produce a null return which all are equated to 1686 * "false". 1687 */ 1688 private static RenderingHints getDesktopAAHintsByName(String hintname) { 1689 Object aaHint = null; 1690 hintname = hintname.toLowerCase(Locale.ENGLISH); 1691 if (hintname.equals("on")) { 1692 aaHint = VALUE_TEXT_ANTIALIAS_ON; 1693 } else if (hintname.equals("gasp")) { 1694 aaHint = VALUE_TEXT_ANTIALIAS_GASP; 1695 } else if (hintname.equals("lcd") || hintname.equals("lcd_hrgb")) { 1696 aaHint = VALUE_TEXT_ANTIALIAS_LCD_HRGB; 1697 } else if (hintname.equals("lcd_hbgr")) { 1698 aaHint = VALUE_TEXT_ANTIALIAS_LCD_HBGR; 1699 } else if (hintname.equals("lcd_vrgb")) { 1700 aaHint = VALUE_TEXT_ANTIALIAS_LCD_VRGB; 1701 } else if (hintname.equals("lcd_vbgr")) { 1702 aaHint = VALUE_TEXT_ANTIALIAS_LCD_VBGR; 1703 } 1704 if (aaHint != null) { 1705 RenderingHints map = new RenderingHints(null); 1706 map.put(KEY_TEXT_ANTIALIASING, aaHint); 1707 return map; 1708 } else { 1709 return null; 1710 } 1711 } 1712 1713 /* This method determines whether to use the system font settings, 1714 * or ignore them if a L&F has specified they should be ignored, or 1715 * to override both of these with a system property specified value. 1716 * If the toolkit isn't a SunToolkit, (eg may be headless) then that 1717 * system property isn't applied as desktop properties are considered 1718 * to be inapplicable in that case. In that headless case although 1719 * this method will return "true" the toolkit will return a null map. 1720 */ 1721 private static boolean useSystemAAFontSettings() { 1722 if (!checkedSystemAAFontSettings) { 1723 useSystemAAFontSettings = true; /* initially set this true */ 1724 String systemAAFonts = null; 1725 Toolkit tk = Toolkit.getDefaultToolkit(); 1726 if (tk instanceof SunToolkit) { 1727 systemAAFonts = 1728 AccessController.doPrivileged( 1729 new GetPropertyAction("awt.useSystemAAFontSettings")); 1730 } 1731 if (systemAAFonts != null) { 1732 useSystemAAFontSettings = 1733 Boolean.valueOf(systemAAFonts).booleanValue(); 1734 /* If it is anything other than "true", then it may be 1735 * a hint name , or it may be "off, "default", etc. 1736 */ 1737 if (!useSystemAAFontSettings) { 1738 desktopFontHints = getDesktopAAHintsByName(systemAAFonts); 1739 } 1740 } 1741 /* If its still true, apply the extra condition */ 1742 if (useSystemAAFontSettings) { 1743 useSystemAAFontSettings = lastExtraCondition; 1744 } 1745 checkedSystemAAFontSettings = true; 1746 } 1747 return useSystemAAFontSettings; 1748 } 1749 1750 /* A variable defined for the convenience of JDK code */ 1751 public static final String DESKTOPFONTHINTS = "awt.font.desktophints"; 1752 1753 /* Overridden by subclasses to return platform/desktop specific values */ 1754 protected RenderingHints getDesktopAAHints() { 1755 return null; 1756 } 1757 1758 /* Subclass desktop property loading methods call this which 1759 * in turn calls the appropriate subclass implementation of 1760 * getDesktopAAHints() when system settings are being used. 1761 * Its public rather than protected because subclasses may delegate 1762 * to a helper class. 1763 */ 1764 public static RenderingHints getDesktopFontHints() { 1765 if (useSystemAAFontSettings()) { 1766 Toolkit tk = Toolkit.getDefaultToolkit(); 1767 if (tk instanceof SunToolkit) { 1768 Object map = ((SunToolkit)tk).getDesktopAAHints(); 1769 return (RenderingHints)map; 1770 } else { /* Headless Toolkit */ 1771 return null; 1772 } 1773 } else if (desktopFontHints != null) { 1774 /* cloning not necessary as the return value is cloned later, but 1775 * its harmless. 1776 */ 1777 return (RenderingHints)(desktopFontHints.clone()); 1778 } else { 1779 return null; 1780 } 1781 } 1782 1783 1784 public abstract boolean isDesktopSupported(); 1785 public abstract boolean isTaskbarSupported(); 1786 1787 /* 1788 * consumeNextKeyTyped() method is not currently used, 1789 * however Swing could use it in the future. 1790 */ 1791 public static synchronized void consumeNextKeyTyped(KeyEvent keyEvent) { 1792 try { 1793 AWTAccessor.getDefaultKeyboardFocusManagerAccessor().consumeNextKeyTyped( 1794 (DefaultKeyboardFocusManager)KeyboardFocusManager. 1795 getCurrentKeyboardFocusManager(), 1796 keyEvent); 1797 } catch (ClassCastException cce) { 1798 cce.printStackTrace(); 1799 } 1800 } 1801 1802 protected static void dumpPeers(final PlatformLogger aLog) { 1803 AWTAutoShutdown.getInstance().dumpPeers(aLog); 1804 } 1805 1806 /** 1807 * Returns the {@code Window} ancestor of the component {@code comp}. 1808 * @return Window ancestor of the component or component by itself if it is Window; 1809 * null, if component is not a part of window hierarchy 1810 */ 1811 public static Window getContainingWindow(Component comp) { 1812 while (comp != null && !(comp instanceof Window)) { 1813 comp = comp.getParent(); 1814 } 1815 return (Window)comp; 1816 } 1817 1818 private static Boolean sunAwtDisableMixing = null; 1819 1820 /** 1821 * Returns the value of "sun.awt.disableMixing" property. Default 1822 * value is {@code false}. 1823 */ 1824 public static synchronized boolean getSunAwtDisableMixing() { 1825 if (sunAwtDisableMixing == null) { 1826 sunAwtDisableMixing = AccessController.doPrivileged( 1827 new GetBooleanAction("sun.awt.disableMixing")); 1828 } 1829 return sunAwtDisableMixing.booleanValue(); 1830 } 1831 1832 /** 1833 * Returns true if the native GTK libraries are available. The 1834 * default implementation returns false, but UNIXToolkit overrides this 1835 * method to provide a more specific answer. 1836 */ 1837 public boolean isNativeGTKAvailable() { 1838 return false; 1839 } 1840 1841 private static final Object DEACTIVATION_TIMES_MAP_KEY = new Object(); 1842 1843 public synchronized void setWindowDeactivationTime(Window w, long time) { 1844 AppContext ctx = getAppContext(w); 1845 if (ctx == null) { 1846 return; 1847 } 1848 @SuppressWarnings("unchecked") 1849 WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY); 1850 if (map == null) { 1851 map = new WeakHashMap<Window, Long>(); 1852 ctx.put(DEACTIVATION_TIMES_MAP_KEY, map); 1853 } 1854 map.put(w, time); 1855 } 1856 1857 public synchronized long getWindowDeactivationTime(Window w) { 1858 AppContext ctx = getAppContext(w); 1859 if (ctx == null) { 1860 return -1; 1861 } 1862 @SuppressWarnings("unchecked") 1863 WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY); 1864 if (map == null) { 1865 return -1; 1866 } 1867 Long time = map.get(w); 1868 return time == null ? -1 : time; 1869 } 1870 1871 // Cosntant alpha 1872 public boolean isWindowOpacitySupported() { 1873 return false; 1874 } 1875 1876 // Shaping 1877 public boolean isWindowShapingSupported() { 1878 return false; 1879 } 1880 1881 // Per-pixel alpha 1882 public boolean isWindowTranslucencySupported() { 1883 return false; 1884 } 1885 1886 public boolean isTranslucencyCapable(GraphicsConfiguration gc) { 1887 return false; 1888 } 1889 1890 /** 1891 * Returns true if swing backbuffer should be translucent. 1892 */ 1893 public boolean isSwingBackbufferTranslucencySupported() { 1894 return false; 1895 } 1896 1897 /** 1898 * Returns whether or not a containing top level window for the passed 1899 * component is 1900 * {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT PERPIXEL_TRANSLUCENT}. 1901 * 1902 * @param c a Component which toplevel's to check 1903 * @return {@code true} if the passed component is not null and has a 1904 * containing toplevel window which is opaque (so per-pixel translucency 1905 * is not enabled), {@code false} otherwise 1906 * @see GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT 1907 */ 1908 public static boolean isContainingTopLevelOpaque(Component c) { 1909 Window w = getContainingWindow(c); 1910 return w != null && w.isOpaque(); 1911 } 1912 1913 /** 1914 * Returns whether or not a containing top level window for the passed 1915 * component is 1916 * {@link GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}. 1917 * 1918 * @param c a Component which toplevel's to check 1919 * @return {@code true} if the passed component is not null and has a 1920 * containing toplevel window which has opacity less than 1921 * 1.0f (which means that it is translucent), {@code false} otherwise 1922 * @see GraphicsDevice.WindowTranslucency#TRANSLUCENT 1923 */ 1924 public static boolean isContainingTopLevelTranslucent(Component c) { 1925 Window w = getContainingWindow(c); 1926 return w != null && w.getOpacity() < 1.0f; 1927 } 1928 1929 /** 1930 * Returns whether the native system requires using the peer.updateWindow() 1931 * method to update the contents of a non-opaque window, or if usual 1932 * painting procedures are sufficient. The default return value covers 1933 * the X11 systems. On MS Windows this method is overriden in WToolkit 1934 * to return true. 1935 */ 1936 public boolean needUpdateWindow() { 1937 return false; 1938 } 1939 1940 /** 1941 * Descendants of the SunToolkit should override and put their own logic here. 1942 */ 1943 public int getNumberOfButtons(){ 1944 return 3; 1945 } 1946 1947 /** 1948 * Checks that the given object implements/extends the given 1949 * interface/class. 1950 * 1951 * Note that using the instanceof operator causes a class to be loaded. 1952 * Using this method doesn't load a class and it can be used instead of 1953 * the instanceof operator for performance reasons. 1954 * 1955 * @param obj Object to be checked 1956 * @param type The name of the interface/class. Must be 1957 * fully-qualified interface/class name. 1958 * @return true, if this object implements/extends the given 1959 * interface/class, false, otherwise, or if obj or type is null 1960 */ 1961 public static boolean isInstanceOf(Object obj, String type) { 1962 if (obj == null) return false; 1963 if (type == null) return false; 1964 1965 return isInstanceOf(obj.getClass(), type); 1966 } 1967 1968 private static boolean isInstanceOf(Class<?> cls, String type) { 1969 if (cls == null) return false; 1970 1971 if (cls.getName().equals(type)) { 1972 return true; 1973 } 1974 1975 for (Class<?> c : cls.getInterfaces()) { 1976 if (c.getName().equals(type)) { 1977 return true; 1978 } 1979 } 1980 return isInstanceOf(cls.getSuperclass(), type); 1981 } 1982 1983 protected static LightweightFrame getLightweightFrame(Component c) { 1984 for (; c != null; c = c.getParent()) { 1985 if (c instanceof LightweightFrame) { 1986 return (LightweightFrame)c; 1987 } 1988 if (c instanceof Window) { 1989 // Don't traverse owner windows 1990 return null; 1991 } 1992 } 1993 return null; 1994 } 1995 1996 /////////////////////////////////////////////////////////////////////////// 1997 // 1998 // The following methods help set and identify whether a particular 1999 // AWTEvent object was produced by the system or by user code. As of this 2000 // writing the only consumer is the Java Plug-In, although this information 2001 // could be useful to more clients and probably should be formalized in 2002 // the public API. 2003 // 2004 /////////////////////////////////////////////////////////////////////////// 2005 2006 public static void setSystemGenerated(AWTEvent e) { 2007 AWTAccessor.getAWTEventAccessor().setSystemGenerated(e); 2008 } 2009 2010 public static boolean isSystemGenerated(AWTEvent e) { 2011 return AWTAccessor.getAWTEventAccessor().isSystemGenerated(e); 2012 } 2013 2014 } // class SunToolkit 2015 2016 2017 /* 2018 * PostEventQueue is a Thread that runs in the same AppContext as the 2019 * Java EventQueue. It is a queue of AWTEvents to be posted to the 2020 * Java EventQueue. The toolkit Thread (AWT-Windows/AWT-Motif) posts 2021 * events to this queue, which then calls EventQueue.postEvent(). 2022 * 2023 * We do this because EventQueue.postEvent() may be overridden by client 2024 * code, and we mustn't ever call client code from the toolkit thread. 2025 */ 2026 class PostEventQueue { 2027 private EventQueueItem queueHead = null; 2028 private EventQueueItem queueTail = null; 2029 private final EventQueue eventQueue; 2030 2031 private Thread flushThread = null; 2032 2033 PostEventQueue(EventQueue eq) { 2034 eventQueue = eq; 2035 } 2036 2037 /* 2038 * Continually post pending AWTEvents to the Java EventQueue. The method 2039 * is synchronized to ensure the flush is completed before a new event 2040 * can be posted to this queue. 2041 * 2042 * 7177040: The method couldn't be wholly synchronized because of calls 2043 * of EventQueue.postEvent() that uses pushPopLock, otherwise it could 2044 * potentially lead to deadlock 2045 */ 2046 public void flush() { 2047 2048 Thread newThread = Thread.currentThread(); 2049 2050 try { 2051 EventQueueItem tempQueue; 2052 synchronized (this) { 2053 // Avoid method recursion 2054 if (newThread == flushThread) { 2055 return; 2056 } 2057 // Wait for other threads' flushing 2058 while (flushThread != null) { 2059 wait(); 2060 } 2061 // Skip everything if queue is empty 2062 if (queueHead == null) { 2063 return; 2064 } 2065 // Remember flushing thread 2066 flushThread = newThread; 2067 2068 tempQueue = queueHead; 2069 queueHead = queueTail = null; 2070 } 2071 try { 2072 while (tempQueue != null) { 2073 eventQueue.postEvent(tempQueue.event); 2074 tempQueue = tempQueue.next; 2075 } 2076 } 2077 finally { 2078 // Only the flushing thread can get here 2079 synchronized (this) { 2080 // Forget flushing thread, inform other pending threads 2081 flushThread = null; 2082 notifyAll(); 2083 } 2084 } 2085 } 2086 catch (InterruptedException e) { 2087 // Couldn't allow exception go up, so at least recover the flag 2088 newThread.interrupt(); 2089 } 2090 } 2091 2092 /* 2093 * Enqueue an AWTEvent to be posted to the Java EventQueue. 2094 */ 2095 void postEvent(AWTEvent event) { 2096 EventQueueItem item = new EventQueueItem(event); 2097 2098 synchronized (this) { 2099 if (queueHead == null) { 2100 queueHead = queueTail = item; 2101 } else { 2102 queueTail.next = item; 2103 queueTail = item; 2104 } 2105 } 2106 SunToolkit.wakeupEventQueue(eventQueue, event.getSource() == AWTAutoShutdown.getInstance()); 2107 } 2108 } // class PostEventQueue