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