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