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