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