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