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