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