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