1 /* 2 * Copyright 2002-2009 Sun Microsystems, Inc. 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. Sun designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 22 * CA 95054 USA or visit www.sun.com if you need additional information or 23 * have any questions. 24 */ 25 package sun.awt.X11; 26 27 import java.awt.*; 28 import java.awt.event.InputEvent; 29 import java.awt.event.MouseEvent; 30 import java.awt.event.KeyEvent; 31 import java.awt.datatransfer.Clipboard; 32 import java.awt.dnd.DragSource; 33 import java.awt.dnd.DragGestureListener; 34 import java.awt.dnd.DragGestureEvent; 35 import java.awt.dnd.DragGestureRecognizer; 36 import java.awt.dnd.MouseDragGestureRecognizer; 37 import java.awt.dnd.InvalidDnDOperationException; 38 import java.awt.dnd.peer.DragSourceContextPeer; 39 import java.awt.im.InputMethodHighlight; 40 import java.awt.im.spi.InputMethodDescriptor; 41 import java.awt.image.ColorModel; 42 import java.awt.peer.*; 43 import java.beans.PropertyChangeListener; 44 import java.lang.reflect.InvocationTargetException; 45 import java.lang.reflect.Method; 46 import java.security.AccessController; 47 import java.security.PrivilegedAction; 48 import java.util.*; 49 import javax.swing.LookAndFeel; 50 import javax.swing.UIDefaults; 51 import sun.awt.*; 52 import sun.font.FontConfigManager; 53 import sun.font.FontManager; 54 import sun.misc.PerformanceLogger; 55 import sun.print.PrintJob2D; 56 import sun.security.action.GetBooleanAction; 57 import sun.util.logging.PlatformLogger; 58 59 public final class XToolkit extends UNIXToolkit implements Runnable { 60 private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.X11.XToolkit"); 61 private static final PlatformLogger eventLog = PlatformLogger.getLogger("sun.awt.X11.event.XToolkit"); 62 private static final PlatformLogger timeoutTaskLog = PlatformLogger.getLogger("sun.awt.X11.timeoutTask.XToolkit"); 63 private static final PlatformLogger keyEventLog = PlatformLogger.getLogger("sun.awt.X11.kye.XToolkit"); 64 private static final PlatformLogger backingStoreLog = PlatformLogger.getLogger("sun.awt.X11.backingStore.XToolkit"); 65 66 //There is 400 ms is set by default on Windows and 500 by default on KDE and GNOME. 67 //We use the same hardcoded constant. 68 private final static int AWT_MULTICLICK_DEFAULT_TIME = 500; 69 70 static final boolean PRIMARY_LOOP = false; 71 static final boolean SECONDARY_LOOP = true; 72 73 private static String awtAppClassName = null; 74 75 // the system clipboard - CLIPBOARD selection 76 XClipboard clipboard; 77 // the system selection - PRIMARY selection 78 XClipboard selection; 79 80 // Dynamic Layout Resize client code setting 81 protected static boolean dynamicLayoutSetting = false; 82 83 //Is it allowed to generate events assigned to extra mouse buttons. 84 //Set to true by default. 85 private static boolean areExtraMouseButtonsEnabled = true; 86 87 /** 88 * True when the x settings have been loaded. 89 */ 90 private boolean loadedXSettings; 91 92 /** 93 * XSETTINGS for the default screen. 94 * <p> 95 */ 96 private XSettings xs; 97 98 private FontConfigManager fcManager = new FontConfigManager(); 99 100 static int arrowCursor; 101 static TreeMap winMap = new TreeMap(); 102 static HashMap specialPeerMap = new HashMap(); 103 static HashMap winToDispatcher = new HashMap(); 104 private static long _display; 105 static UIDefaults uidefaults; 106 static X11GraphicsEnvironment localEnv; 107 static X11GraphicsDevice device; 108 static final X11GraphicsConfig config; 109 static int awt_multiclick_time; 110 static boolean securityWarningEnabled; 111 112 private static int screenWidth = -1, screenHeight = -1; // Dimensions of default screen 113 static long awt_defaultFg; // Pixel 114 private static XMouseInfoPeer xPeer; 115 private static Method m_removeSourceEvents; 116 117 static { 118 initSecurityWarning(); 119 if (GraphicsEnvironment.isHeadless()) { 120 config = null; 121 } else { 122 localEnv = (X11GraphicsEnvironment) GraphicsEnvironment 123 .getLocalGraphicsEnvironment(); 124 device = (X11GraphicsDevice) localEnv.getDefaultScreenDevice(); 125 config = (X11GraphicsConfig) (device.getDefaultConfiguration()); 126 if (device != null) { 127 _display = device.getDisplay(); 128 } 129 setupModifierMap(); 130 initIDs(); 131 setBackingStoreType(); 132 } 133 m_removeSourceEvents = SunToolkit.getMethod(EventQueue.class, "removeSourceEvents", new Class[] {Object.class, Boolean.TYPE}) ; 134 135 noisyAwtHandler = AccessController.doPrivileged(new GetBooleanAction("sun.awt.noisyerrorhandler")); 136 } 137 138 //---- ERROR HANDLER CODE ----// 139 140 /* 141 * Error handler at the moment of XToolkit initialization 142 */ 143 private static long saved_error_handler; 144 145 /* 146 * XErrorEvent being handled 147 */ 148 static volatile XErrorEvent saved_error; 149 150 /* 151 * Current error handler or null if no error handler is set 152 */ 153 private static XErrorHandler current_error_handler; 154 155 /* 156 * Value of sun.awt.noisyerrorhandler system property 157 */ 158 private static boolean noisyAwtHandler; 159 160 public static void WITH_XERROR_HANDLER(XErrorHandler handler) { 161 saved_error = null; 162 current_error_handler = handler; 163 } 164 165 public static void RESTORE_XERROR_HANDLER() { 166 // wait until all requests are processed by the X server 167 // and only then uninstall the error handler 168 XSync(); 169 current_error_handler = null; 170 } 171 172 // Should be called under LOCK 173 public static int SAVED_ERROR_HANDLER(long display, XErrorEvent error) { 174 if (saved_error_handler != 0) { 175 // Default XErrorHandler may just terminate the process. Don't call it. 176 // return XlibWrapper.CallErrorHandler(saved_error_handler, display, error.pData); 177 } 178 if (log.isLoggable(PlatformLogger.FINE)) { 179 log.fine("Unhandled XErrorEvent: " + 180 "id=" + error.get_resourceid() + ", " + 181 "serial=" + error.get_serial() + ", " + 182 "ec=" + error.get_error_code() + ", " + 183 "rc=" + error.get_request_code() + ", " + 184 "mc=" + error.get_minor_code()); 185 } 186 return 0; 187 } 188 189 // Called from the native code when an error occurs 190 private static int globalErrorHandler(long display, long event_ptr) { 191 if (noisyAwtHandler) { 192 XlibWrapper.PrintXErrorEvent(display, event_ptr); 193 } 194 XErrorEvent event = new XErrorEvent(event_ptr); 195 saved_error = event; 196 try { 197 if (current_error_handler != null) { 198 return current_error_handler.handleError(display, event); 199 } else { 200 return SAVED_ERROR_HANDLER(display, event); 201 } 202 } catch (Throwable z) { 203 log.fine("Error in GlobalErrorHandler", z); 204 } 205 return 0; 206 } 207 208 //---- END OF ERROR HANDLER CODE ----// 209 210 private native static void initIDs(); 211 native static void waitForEvents(long nextTaskTime); 212 static Thread toolkitThread; 213 static boolean isToolkitThread() { 214 return Thread.currentThread() == toolkitThread; 215 } 216 217 static void initSecurityWarning() { 218 // Enable warning only for internal builds 219 String runtime = getSystemProperty("java.runtime.version"); 220 securityWarningEnabled = (runtime != null && runtime.contains("internal")); 221 } 222 223 static boolean isSecurityWarningEnabled() { 224 return securityWarningEnabled; 225 } 226 227 static native void awt_output_flush(); 228 229 static final void awtFUnlock() { 230 awtUnlock(); 231 awt_output_flush(); 232 } 233 234 235 public native void nativeLoadSystemColors(int[] systemColors); 236 237 static UIDefaults getUIDefaults() { 238 if (uidefaults == null) { 239 initUIDefaults(); 240 } 241 return uidefaults; 242 } 243 244 public void loadSystemColors(int[] systemColors) { 245 nativeLoadSystemColors(systemColors); 246 MotifColorUtilities.loadSystemColors(systemColors); 247 } 248 249 250 251 static void initUIDefaults() { 252 try { 253 // Load Defaults from MotifLookAndFeel 254 255 // This dummy load is necessary to get SystemColor initialized. !!!!!! 256 Color c = SystemColor.text; 257 258 LookAndFeel lnf = new XAWTLookAndFeel(); 259 uidefaults = lnf.getDefaults(); 260 } 261 catch (Exception e) 262 { 263 e.printStackTrace(); 264 } 265 } 266 267 static Object displayLock = new Object(); 268 269 public static long getDisplay() { 270 return _display; 271 } 272 273 public static long getDefaultRootWindow() { 274 awtLock(); 275 try { 276 long res = XlibWrapper.RootWindow(XToolkit.getDisplay(), 277 XlibWrapper.DefaultScreen(XToolkit.getDisplay())); 278 279 if (res == 0) { 280 throw new IllegalStateException("Root window must not be null"); 281 } 282 return res; 283 } finally { 284 awtUnlock(); 285 } 286 } 287 288 void init() { 289 awtLock(); 290 try { 291 XlibWrapper.XSupportsLocale(); 292 if (XlibWrapper.XSetLocaleModifiers("") == null) { 293 log.finer("X locale modifiers are not supported, using default"); 294 } 295 tryXKB(); 296 297 AwtScreenData defaultScreen = new AwtScreenData(XToolkit.getDefaultScreenData()); 298 awt_defaultFg = defaultScreen.get_blackpixel(); 299 300 arrowCursor = XlibWrapper.XCreateFontCursor(XToolkit.getDisplay(), 301 XCursorFontConstants.XC_arrow); 302 areExtraMouseButtonsEnabled = Boolean.parseBoolean(System.getProperty("sun.awt.enableExtraMouseButtons", "true")); 303 //set system property if not yet assigned 304 System.setProperty("sun.awt.enableExtraMouseButtons", ""+areExtraMouseButtonsEnabled); 305 306 saved_error_handler = XlibWrapper.SetToolkitErrorHandler(); 307 } finally { 308 awtUnlock(); 309 } 310 PrivilegedAction<Void> a = new PrivilegedAction<Void>() { 311 public Void run() { 312 ThreadGroup mainTG = Thread.currentThread().getThreadGroup(); 313 ThreadGroup parentTG = mainTG.getParent(); 314 while (parentTG != null) { 315 mainTG = parentTG; 316 parentTG = mainTG.getParent(); 317 } 318 Thread shutdownThread = new Thread(mainTG, "XToolkt-Shutdown-Thread") { 319 public void run() { 320 XSystemTrayPeer peer = XSystemTrayPeer.getPeerInstance(); 321 if (peer != null) { 322 peer.dispose(); 323 } 324 if (xs != null) { 325 ((XAWTXSettings)xs).dispose(); 326 } 327 freeXKB(); 328 if (log.isLoggable(PlatformLogger.FINE)) { 329 dumpPeers(); 330 } 331 } 332 }; 333 shutdownThread.setContextClassLoader(null); 334 Runtime.getRuntime().addShutdownHook(shutdownThread); 335 return null; 336 } 337 }; 338 AccessController.doPrivileged(a); 339 } 340 341 static String getCorrectXIDString(String val) { 342 if (val != null) { 343 return val.replace('.', '-'); 344 } else { 345 return val; 346 } 347 } 348 349 static native String getEnv(String key); 350 351 352 static String getAWTAppClassName() { 353 return awtAppClassName; 354 } 355 356 static final String DATA_TRANSFERER_CLASS_NAME = "sun.awt.X11.XDataTransferer"; 357 358 public XToolkit() { 359 super(); 360 if (PerformanceLogger.loggingEnabled()) { 361 PerformanceLogger.setTime("XToolkit construction"); 362 } 363 364 if (!GraphicsEnvironment.isHeadless()) { 365 String mainClassName = null; 366 367 StackTraceElement trace[] = (new Throwable()).getStackTrace(); 368 int bottom = trace.length - 1; 369 if (bottom >= 0) { 370 mainClassName = trace[bottom].getClassName(); 371 } 372 if (mainClassName == null || mainClassName.equals("")) { 373 mainClassName = "AWT"; 374 } 375 awtAppClassName = getCorrectXIDString(mainClassName); 376 377 init(); 378 XWM.init(); 379 SunToolkit.setDataTransfererClassName(DATA_TRANSFERER_CLASS_NAME); 380 toolkitThread = new Thread(this, "AWT-XAWT"); 381 toolkitThread.setPriority(Thread.NORM_PRIORITY + 1); 382 toolkitThread.setDaemon(true); 383 ThreadGroup mainTG = (ThreadGroup)AccessController.doPrivileged( 384 new PrivilegedAction() { 385 public Object run() { 386 ThreadGroup currentTG = 387 Thread.currentThread().getThreadGroup(); 388 ThreadGroup parentTG = currentTG.getParent(); 389 while (parentTG != null) { 390 currentTG = parentTG; 391 parentTG = currentTG.getParent(); 392 } 393 return currentTG; 394 } 395 }); 396 toolkitThread.start(); 397 } 398 } 399 400 public ButtonPeer createButton(Button target) { 401 ButtonPeer peer = new XButtonPeer(target); 402 targetCreatedPeer(target, peer); 403 return peer; 404 } 405 406 public FramePeer createFrame(Frame target) { 407 FramePeer peer = new XFramePeer(target); 408 targetCreatedPeer(target, peer); 409 return peer; 410 } 411 412 static void addToWinMap(long window, XBaseWindow xwin) 413 { 414 synchronized(winMap) { 415 winMap.put(Long.valueOf(window),xwin); 416 } 417 } 418 419 static void removeFromWinMap(long window, XBaseWindow xwin) { 420 synchronized(winMap) { 421 winMap.remove(Long.valueOf(window)); 422 } 423 } 424 static XBaseWindow windowToXWindow(long window) { 425 synchronized(winMap) { 426 return (XBaseWindow) winMap.get(Long.valueOf(window)); 427 } 428 } 429 430 static void addEventDispatcher(long window, XEventDispatcher dispatcher) { 431 synchronized(winToDispatcher) { 432 Long key = Long.valueOf(window); 433 Collection dispatchers = (Collection)winToDispatcher.get(key); 434 if (dispatchers == null) { 435 dispatchers = new Vector(); 436 winToDispatcher.put(key, dispatchers); 437 } 438 dispatchers.add(dispatcher); 439 } 440 } 441 static void removeEventDispatcher(long window, XEventDispatcher dispatcher) { 442 synchronized(winToDispatcher) { 443 Long key = Long.valueOf(window); 444 Collection dispatchers = (Collection)winToDispatcher.get(key); 445 if (dispatchers != null) { 446 dispatchers.remove(dispatcher); 447 } 448 } 449 } 450 451 private Point lastCursorPos; 452 453 /** 454 * Returns whether there is last remembered cursor position. The 455 * position is remembered from X mouse events on our peers. The 456 * position is stored in <code>p</code>. 457 * @return true, if there is remembered last cursor position, 458 * false otherwise 459 */ 460 boolean getLastCursorPos(Point p) { 461 awtLock(); 462 try { 463 if (lastCursorPos == null) { 464 return false; 465 } 466 p.setLocation(lastCursorPos); 467 return true; 468 } finally { 469 awtUnlock(); 470 } 471 } 472 473 private void processGlobalMotionEvent(XEvent e) { 474 // Only our windows guaranteely generate MotionNotify, so we 475 // should track enter/leave, to catch the moment when to 476 // switch to XQueryPointer 477 if (e.get_type() == XConstants.MotionNotify) { 478 XMotionEvent ev = e.get_xmotion(); 479 awtLock(); 480 try { 481 if (lastCursorPos == null) { 482 lastCursorPos = new Point(ev.get_x_root(), ev.get_y_root()); 483 } else { 484 lastCursorPos.setLocation(ev.get_x_root(), ev.get_y_root()); 485 } 486 } finally { 487 awtUnlock(); 488 } 489 } else if (e.get_type() == XConstants.LeaveNotify) { 490 // Leave from our window 491 awtLock(); 492 try { 493 lastCursorPos = null; 494 } finally { 495 awtUnlock(); 496 } 497 } else if (e.get_type() == XConstants.EnterNotify) { 498 // Entrance into our window 499 XCrossingEvent ev = e.get_xcrossing(); 500 awtLock(); 501 try { 502 if (lastCursorPos == null) { 503 lastCursorPos = new Point(ev.get_x_root(), ev.get_y_root()); 504 } else { 505 lastCursorPos.setLocation(ev.get_x_root(), ev.get_y_root()); 506 } 507 } finally { 508 awtUnlock(); 509 } 510 } 511 } 512 513 public interface XEventListener { 514 public void eventProcessed(XEvent e); 515 } 516 517 private Collection<XEventListener> listeners = new LinkedList<XEventListener>(); 518 519 public void addXEventListener(XEventListener listener) { 520 synchronized (listeners) { 521 listeners.add(listener); 522 } 523 } 524 525 private void notifyListeners(XEvent xev) { 526 synchronized (listeners) { 527 if (listeners.size() == 0) return; 528 529 XEvent copy = xev.clone(); 530 try { 531 for (XEventListener listener : listeners) { 532 listener.eventProcessed(copy); 533 } 534 } finally { 535 copy.dispose(); 536 } 537 } 538 } 539 540 private void dispatchEvent(XEvent ev) { 541 final XAnyEvent xany = ev.get_xany(); 542 543 if (windowToXWindow(xany.get_window()) != null && 544 (ev.get_type() == XConstants.MotionNotify || ev.get_type() == XConstants.EnterNotify || ev.get_type() == XConstants.LeaveNotify)) 545 { 546 processGlobalMotionEvent(ev); 547 } 548 549 if( ev.get_type() == XConstants.MappingNotify ) { 550 // The 'window' field in this event is unused. 551 // This application itself does nothing to initiate such an event 552 // (no calls of XChangeKeyboardMapping etc.). 553 // SunRay server sends this event to the application once on every 554 // keyboard (not just layout) change which means, quite seldom. 555 XlibWrapper.XRefreshKeyboardMapping(ev.pData); 556 resetKeyboardSniffer(); 557 setupModifierMap(); 558 } 559 XBaseWindow.dispatchToWindow(ev); 560 561 Collection dispatchers = null; 562 synchronized(winToDispatcher) { 563 Long key = Long.valueOf(xany.get_window()); 564 dispatchers = (Collection)winToDispatcher.get(key); 565 if (dispatchers != null) { // Clone it to avoid synchronization during dispatching 566 dispatchers = new Vector(dispatchers); 567 } 568 } 569 if (dispatchers != null) { 570 Iterator iter = dispatchers.iterator(); 571 while (iter.hasNext()) { 572 XEventDispatcher disp = (XEventDispatcher)iter.next(); 573 disp.dispatchEvent(ev); 574 } 575 } 576 notifyListeners(ev); 577 } 578 579 static void processException(Throwable thr) { 580 if (log.isLoggable(PlatformLogger.WARNING)) { 581 log.warning("Exception on Toolkit thread", thr); 582 } 583 } 584 585 static native void awt_toolkit_init(); 586 587 public void run() { 588 awt_toolkit_init(); 589 run(PRIMARY_LOOP); 590 } 591 592 public void run(boolean loop) 593 { 594 XEvent ev = new XEvent(); 595 while(true) { 596 // Fix for 6829923: we should gracefully handle toolkit thread interruption 597 if (Thread.currentThread().isInterrupted()) { 598 // We expect interruption from the AppContext.dispose() method only. 599 // If the thread is interrupted from another place, let's skip it 600 // for compatibility reasons. Probably some time later we'll remove 601 // the check for AppContext.isDisposed() and will unconditionally 602 // break the loop here. 603 if (AppContext.getAppContext().isDisposed()) { 604 break; 605 } 606 } 607 awtLock(); 608 try { 609 if (loop == SECONDARY_LOOP) { 610 // In the secondary loop we may have already aquired awt_lock 611 // several times, so waitForEvents() might be unable to release 612 // the awt_lock and this causes lock up. 613 // For now, we just avoid waitForEvents in the secondary loop. 614 if (!XlibWrapper.XNextSecondaryLoopEvent(getDisplay(),ev.pData)) { 615 break; 616 } 617 } else { 618 callTimeoutTasks(); 619 // If no events are queued, waitForEvents() causes calls to 620 // awtUnlock(), awtJNI_ThreadYield, poll, awtLock(), 621 // so it spends most of its time in poll, without holding the lock. 622 while ((XlibWrapper.XEventsQueued(getDisplay(), XConstants.QueuedAfterReading) == 0) && 623 (XlibWrapper.XEventsQueued(getDisplay(), XConstants.QueuedAfterFlush) == 0)) { 624 callTimeoutTasks(); 625 waitForEvents(getNextTaskTime()); 626 } 627 XlibWrapper.XNextEvent(getDisplay(),ev.pData); 628 } 629 630 if (ev.get_type() != XConstants.NoExpose) { 631 eventNumber++; 632 } 633 if (awt_UseXKB_Calls && ev.get_type() == awt_XKBBaseEventCode) { 634 processXkbChanges(ev); 635 } 636 637 if (XDropTargetEventProcessor.processEvent(ev) || 638 XDragSourceContextPeer.processEvent(ev)) { 639 continue; 640 } 641 642 if (eventLog.isLoggable(PlatformLogger.FINER)) { 643 eventLog.finer("{0}", ev); 644 } 645 646 // Check if input method consumes the event 647 long w = 0; 648 if (windowToXWindow(ev.get_xany().get_window()) != null) { 649 Component owner = 650 XKeyboardFocusManagerPeer.getCurrentNativeFocusOwner(); 651 if (owner != null) { 652 XWindow ownerWindow = (XWindow) AWTAccessor.getComponentAccessor().getPeer(owner); 653 if (ownerWindow != null) { 654 w = ownerWindow.getContentWindow(); 655 } 656 } 657 } 658 if( keyEventLog.isLoggable(PlatformLogger.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) { 659 keyEventLog.fine("before XFilterEvent:"+ev); 660 } 661 if (XlibWrapper.XFilterEvent(ev.getPData(), w)) { 662 continue; 663 } 664 if( keyEventLog.isLoggable(PlatformLogger.FINE) && (ev.get_type() == XConstants.KeyPress || ev.get_type() == XConstants.KeyRelease) ) { 665 keyEventLog.fine("after XFilterEvent:"+ev); // IS THIS CORRECT? 666 } 667 668 dispatchEvent(ev); 669 } catch (ThreadDeath td) { 670 XBaseWindow.ungrabInput(); 671 return; 672 } catch (Throwable thr) { 673 XBaseWindow.ungrabInput(); 674 processException(thr); 675 } finally { 676 awtUnlock(); 677 } 678 } 679 } 680 681 static int getDefaultScreenWidth() { 682 if (screenWidth == -1) { 683 long display = getDisplay(); 684 awtLock(); 685 try { 686 screenWidth = (int) XlibWrapper.DisplayWidth(display, XlibWrapper.DefaultScreen(display)); 687 } finally { 688 awtUnlock(); 689 } 690 } 691 return screenWidth; 692 } 693 694 static int getDefaultScreenHeight() { 695 if (screenHeight == -1) { 696 long display = getDisplay(); 697 awtLock(); 698 try { 699 screenHeight = (int) XlibWrapper.DisplayHeight(display, XlibWrapper.DefaultScreen(display)); 700 } finally { 701 awtUnlock(); 702 } 703 } 704 return screenHeight; 705 } 706 707 protected int getScreenWidth() { 708 return getDefaultScreenWidth(); 709 } 710 711 protected int getScreenHeight() { 712 return getDefaultScreenHeight(); 713 } 714 715 private static Rectangle getWorkArea(long root) 716 { 717 XAtom XA_NET_WORKAREA = XAtom.get("_NET_WORKAREA"); 718 719 long native_ptr = Native.allocateLongArray(4); 720 try 721 { 722 boolean workareaPresent = XA_NET_WORKAREA.getAtomData(root, 723 XAtom.XA_CARDINAL, native_ptr, 4); 724 if (workareaPresent) 725 { 726 int rootX = (int)Native.getLong(native_ptr, 0); 727 int rootY = (int)Native.getLong(native_ptr, 1); 728 int rootWidth = (int)Native.getLong(native_ptr, 2); 729 int rootHeight = (int)Native.getLong(native_ptr, 3); 730 731 return new Rectangle(rootX, rootY, rootWidth, rootHeight); 732 } 733 } 734 finally 735 { 736 XlibWrapper.unsafe.freeMemory(native_ptr); 737 } 738 739 return null; 740 } 741 742 /* 743 * If we're running in non-Xinerama environment and the current 744 * window manager supports _NET protocol then the screen insets 745 * are calculated using _NET_WM_WORKAREA property of the root 746 * window. 747 * Otherwise, i. e. if Xinerama is on or _NET_WM_WORKAREA is 748 * not set, we try to calculate the insets ourselves using 749 * getScreenInsetsManually method. 750 */ 751 public Insets getScreenInsets(GraphicsConfiguration gc) 752 { 753 XNETProtocol netProto = XWM.getWM().getNETProtocol(); 754 if ((netProto == null) || !netProto.active()) 755 { 756 return super.getScreenInsets(gc); 757 } 758 759 XToolkit.awtLock(); 760 try 761 { 762 X11GraphicsConfig x11gc = (X11GraphicsConfig)gc; 763 X11GraphicsDevice x11gd = (X11GraphicsDevice)x11gc.getDevice(); 764 long root = XlibUtil.getRootWindow(x11gd.getScreen()); 765 Rectangle rootBounds = XlibUtil.getWindowGeometry(root); 766 767 X11GraphicsEnvironment x11ge = (X11GraphicsEnvironment) 768 GraphicsEnvironment.getLocalGraphicsEnvironment(); 769 if (!x11ge.runningXinerama()) 770 { 771 Rectangle workArea = XToolkit.getWorkArea(root); 772 if (workArea != null) 773 { 774 return new Insets(workArea.y, 775 workArea.x, 776 rootBounds.height - workArea.height - workArea.y, 777 rootBounds.width - workArea.width - workArea.x); 778 } 779 } 780 781 return getScreenInsetsManually(root, rootBounds, gc.getBounds()); 782 } 783 finally 784 { 785 XToolkit.awtUnlock(); 786 } 787 } 788 789 /* 790 * Manual calculation of screen insets: get all the windows with 791 * _NET_WM_STRUT/_NET_WM_STRUT_PARTIAL hints and add these 792 * hints' values to screen insets. 793 * 794 * This method should be called under XToolkit.awtLock() 795 */ 796 private Insets getScreenInsetsManually(long root, Rectangle rootBounds, Rectangle screenBounds) 797 { 798 /* 799 * During the manual calculation of screen insets we iterate 800 * all the X windows hierarchy starting from root window. This 801 * constant is the max level inspected in this hierarchy. 802 * 3 is a heuristic value: I suppose any the toolbar-like 803 * window is a child of either root or desktop window. 804 */ 805 final int MAX_NESTED_LEVEL = 3; 806 807 XAtom XA_NET_WM_STRUT = XAtom.get("_NET_WM_STRUT"); 808 XAtom XA_NET_WM_STRUT_PARTIAL = XAtom.get("_NET_WM_STRUT_PARTIAL"); 809 810 Insets insets = new Insets(0, 0, 0, 0); 811 812 java.util.List search = new LinkedList(); 813 search.add(root); 814 search.add(0); 815 while (!search.isEmpty()) 816 { 817 long window = (Long)search.remove(0); 818 int windowLevel = (Integer)search.remove(0); 819 820 /* 821 * Note that most of the modern window managers unmap 822 * application window if it is iconified. Thus, any 823 * _NET_WM_STRUT[_PARTIAL] hints for iconified windows 824 * are not included to the screen insets. 825 */ 826 if (XlibUtil.getWindowMapState(window) == XConstants.IsUnmapped) 827 { 828 continue; 829 } 830 831 long native_ptr = Native.allocateLongArray(4); 832 try 833 { 834 // first, check if _NET_WM_STRUT or _NET_WM_STRUT_PARTIAL are present 835 // if both are set on the window, _NET_WM_STRUT_PARTIAL is used (see _NET spec) 836 boolean strutPresent = XA_NET_WM_STRUT_PARTIAL.getAtomData(window, XAtom.XA_CARDINAL, native_ptr, 4); 837 if (!strutPresent) 838 { 839 strutPresent = XA_NET_WM_STRUT.getAtomData(window, XAtom.XA_CARDINAL, native_ptr, 4); 840 } 841 if (strutPresent) 842 { 843 // second, verify that window is located on the proper screen 844 Rectangle windowBounds = XlibUtil.getWindowGeometry(window); 845 if (windowLevel > 1) 846 { 847 windowBounds = XlibUtil.translateCoordinates(window, root, windowBounds); 848 } 849 // if _NET_WM_STRUT_PARTIAL is present, we should use its values to detect 850 // if the struts area intersects with screenBounds, however some window 851 // managers don't set this hint correctly, so we just get intersection with windowBounds 852 if (windowBounds.intersects(screenBounds)) 853 { 854 insets.left = Math.max((int)Native.getLong(native_ptr, 0), insets.left); 855 insets.right = Math.max((int)Native.getLong(native_ptr, 1), insets.right); 856 insets.top = Math.max((int)Native.getLong(native_ptr, 2), insets.top); 857 insets.bottom = Math.max((int)Native.getLong(native_ptr, 3), insets.bottom); 858 } 859 } 860 } 861 finally 862 { 863 XlibWrapper.unsafe.freeMemory(native_ptr); 864 } 865 866 if (windowLevel < MAX_NESTED_LEVEL) 867 { 868 Set<Long> children = XlibUtil.getChildWindows(window); 869 for (long child : children) 870 { 871 search.add(child); 872 search.add(windowLevel + 1); 873 } 874 } 875 } 876 877 return insets; 878 } 879 880 /* 881 * The current implementation of disabling background erasing for 882 * canvases is that we don't set any native background color 883 * (with XSetWindowBackground) for the canvas window. However, 884 * this color is set in the peer constructor - see 885 * XWindow.postInit() for details. That's why this method from 886 * SunToolkit is not overridden in XToolkit: it's too late to 887 * disable background erasing :( 888 */ 889 /* 890 @Override 891 public void disableBackgroundErase(Canvas canvas) { 892 XCanvasPeer peer = (XCanvasPeer)canvas.getPeer(); 893 if (peer == null) { 894 throw new IllegalStateException("Canvas must have a valid peer"); 895 } 896 peer.disableBackgroundErase(); 897 } 898 */ 899 900 // Need this for XMenuItemPeer. 901 protected static final Object targetToPeer(Object target) { 902 Object p=null; 903 if (target != null && !GraphicsEnvironment.isHeadless()) { 904 p = specialPeerMap.get(target); 905 } 906 if (p != null) return p; 907 else 908 return SunToolkit.targetToPeer(target); 909 } 910 911 // Need this for XMenuItemPeer. 912 protected static final void targetDisposedPeer(Object target, Object peer) { 913 SunToolkit.targetDisposedPeer(target, peer); 914 } 915 916 public RobotPeer createRobot(Robot target, GraphicsDevice screen) { 917 return new XRobotPeer(screen.getDefaultConfiguration()); 918 } 919 920 921 /* 922 * On X, support for dynamic layout on resizing is governed by the 923 * window manager. If the window manager supports it, it happens 924 * automatically. The setter method for this property is 925 * irrelevant on X. 926 */ 927 public void setDynamicLayout(boolean b) { 928 dynamicLayoutSetting = b; 929 } 930 931 protected boolean isDynamicLayoutSet() { 932 return dynamicLayoutSetting; 933 } 934 935 /* Called from isDynamicLayoutActive() and from 936 * lazilyLoadDynamicLayoutSupportedProperty() 937 */ 938 protected boolean isDynamicLayoutSupported() { 939 return XWM.getWM().supportsDynamicLayout(); 940 } 941 942 public boolean isDynamicLayoutActive() { 943 return isDynamicLayoutSupported(); 944 } 945 946 947 public FontPeer getFontPeer(String name, int style){ 948 return new XFontPeer(name, style); 949 } 950 951 public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException { 952 return XDragSourceContextPeer.createDragSourceContextPeer(dge); 953 } 954 955 public <T extends DragGestureRecognizer> T 956 createDragGestureRecognizer(Class<T> recognizerClass, 957 DragSource ds, 958 Component c, 959 int srcActions, 960 DragGestureListener dgl) 961 { 962 if (MouseDragGestureRecognizer.class.equals(recognizerClass)) 963 return (T)new XMouseDragGestureRecognizer(ds, c, srcActions, dgl); 964 else 965 return null; 966 } 967 968 public CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target) { 969 XCheckboxMenuItemPeer peer = new XCheckboxMenuItemPeer(target); 970 //vb157120: looks like we don't need to map menu items 971 //in new menus implementation 972 //targetCreatedPeer(target, peer); 973 return peer; 974 } 975 976 public MenuItemPeer createMenuItem(MenuItem target) { 977 XMenuItemPeer peer = new XMenuItemPeer(target); 978 //vb157120: looks like we don't need to map menu items 979 //in new menus implementation 980 //targetCreatedPeer(target, peer); 981 return peer; 982 } 983 984 public TextFieldPeer createTextField(TextField target) { 985 TextFieldPeer peer = new XTextFieldPeer(target); 986 targetCreatedPeer(target, peer); 987 return peer; 988 } 989 990 public LabelPeer createLabel(Label target) { 991 LabelPeer peer = new XLabelPeer(target); 992 targetCreatedPeer(target, peer); 993 return peer; 994 } 995 996 public ListPeer createList(java.awt.List target) { 997 ListPeer peer = new XListPeer(target); 998 targetCreatedPeer(target, peer); 999 return peer; 1000 } 1001 1002 public CheckboxPeer createCheckbox(Checkbox target) { 1003 CheckboxPeer peer = new XCheckboxPeer(target); 1004 targetCreatedPeer(target, peer); 1005 return peer; 1006 } 1007 1008 public ScrollbarPeer createScrollbar(Scrollbar target) { 1009 XScrollbarPeer peer = new XScrollbarPeer(target); 1010 targetCreatedPeer(target, peer); 1011 return peer; 1012 } 1013 1014 public ScrollPanePeer createScrollPane(ScrollPane target) { 1015 XScrollPanePeer peer = new XScrollPanePeer(target); 1016 targetCreatedPeer(target, peer); 1017 return peer; 1018 } 1019 1020 public TextAreaPeer createTextArea(TextArea target) { 1021 TextAreaPeer peer = new XTextAreaPeer(target); 1022 targetCreatedPeer(target, peer); 1023 return peer; 1024 } 1025 1026 public ChoicePeer createChoice(Choice target) { 1027 XChoicePeer peer = new XChoicePeer(target); 1028 targetCreatedPeer(target, peer); 1029 return peer; 1030 } 1031 1032 public CanvasPeer createCanvas(Canvas target) { 1033 XCanvasPeer peer = (isXEmbedServerRequested() ? new XEmbedCanvasPeer(target) : new XCanvasPeer(target)); 1034 targetCreatedPeer(target, peer); 1035 return peer; 1036 } 1037 1038 public PanelPeer createPanel(Panel target) { 1039 PanelPeer peer = new XPanelPeer(target); 1040 targetCreatedPeer(target, peer); 1041 return peer; 1042 } 1043 1044 public WindowPeer createWindow(Window target) { 1045 WindowPeer peer = new XWindowPeer(target); 1046 targetCreatedPeer(target, peer); 1047 return peer; 1048 } 1049 1050 public DialogPeer createDialog(Dialog target) { 1051 DialogPeer peer = new XDialogPeer(target); 1052 targetCreatedPeer(target, peer); 1053 return peer; 1054 } 1055 1056 public FileDialogPeer createFileDialog(FileDialog target) { 1057 // The current GtkFileChooser is available from GTK+ 2.4 1058 FileDialogPeer peer = checkGtkVersion(2, 4, 0) ? new GtkFileDialogPeer( 1059 target) : new XFileDialogPeer(target); 1060 targetCreatedPeer(target, peer); 1061 return peer; 1062 } 1063 1064 public MenuBarPeer createMenuBar(MenuBar target) { 1065 XMenuBarPeer peer = new XMenuBarPeer(target); 1066 targetCreatedPeer(target, peer); 1067 return peer; 1068 } 1069 1070 public MenuPeer createMenu(Menu target) { 1071 XMenuPeer peer = new XMenuPeer(target); 1072 //vb157120: looks like we don't need to map menu items 1073 //in new menus implementation 1074 //targetCreatedPeer(target, peer); 1075 return peer; 1076 } 1077 1078 public PopupMenuPeer createPopupMenu(PopupMenu target) { 1079 XPopupMenuPeer peer = new XPopupMenuPeer(target); 1080 targetCreatedPeer(target, peer); 1081 return peer; 1082 } 1083 1084 public synchronized MouseInfoPeer getMouseInfoPeer() { 1085 if (xPeer == null) { 1086 xPeer = new XMouseInfoPeer(); 1087 } 1088 return xPeer; 1089 } 1090 1091 public XEmbeddedFramePeer createEmbeddedFrame(XEmbeddedFrame target) 1092 { 1093 XEmbeddedFramePeer peer = new XEmbeddedFramePeer(target); 1094 targetCreatedPeer(target, peer); 1095 return peer; 1096 } 1097 1098 XEmbedChildProxyPeer createEmbedProxy(XEmbedChildProxy target) { 1099 XEmbedChildProxyPeer peer = new XEmbedChildProxyPeer(target); 1100 targetCreatedPeer(target, peer); 1101 return peer; 1102 } 1103 1104 public KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager manager) throws HeadlessException { 1105 XKeyboardFocusManagerPeer peer = new XKeyboardFocusManagerPeer(manager); 1106 return peer; 1107 } 1108 1109 /** 1110 * Returns a new custom cursor. 1111 */ 1112 public Cursor createCustomCursor(Image cursor, Point hotSpot, String name) 1113 throws IndexOutOfBoundsException { 1114 return new XCustomCursor(cursor, hotSpot, name); 1115 } 1116 1117 public TrayIconPeer createTrayIcon(TrayIcon target) 1118 throws HeadlessException, AWTException 1119 { 1120 TrayIconPeer peer = new XTrayIconPeer(target); 1121 targetCreatedPeer(target, peer); 1122 return peer; 1123 } 1124 1125 public SystemTrayPeer createSystemTray(SystemTray target) throws HeadlessException { 1126 SystemTrayPeer peer = new XSystemTrayPeer(target); 1127 return peer; 1128 } 1129 1130 public boolean isTraySupported() { 1131 XSystemTrayPeer peer = XSystemTrayPeer.getPeerInstance(); 1132 if (peer != null) { 1133 return peer.isAvailable(); 1134 } 1135 return false; 1136 } 1137 1138 /** 1139 * Returns the supported cursor size 1140 */ 1141 public Dimension getBestCursorSize(int preferredWidth, int preferredHeight) { 1142 return XCustomCursor.getBestCursorSize( 1143 java.lang.Math.max(1,preferredWidth), java.lang.Math.max(1,preferredHeight)); 1144 } 1145 1146 1147 public int getMaximumCursorColors() { 1148 return 2; // Black and white. 1149 } 1150 1151 public Map mapInputMethodHighlight(InputMethodHighlight highlight) { 1152 return XInputMethod.mapInputMethodHighlight(highlight); 1153 } 1154 @Override 1155 public boolean getLockingKeyState(int key) { 1156 if (! (key == KeyEvent.VK_CAPS_LOCK || key == KeyEvent.VK_NUM_LOCK || 1157 key == KeyEvent.VK_SCROLL_LOCK || key == KeyEvent.VK_KANA_LOCK)) { 1158 throw new IllegalArgumentException("invalid key for Toolkit.getLockingKeyState"); 1159 } 1160 awtLock(); 1161 try { 1162 return getModifierState( key ); 1163 } finally { 1164 awtUnlock(); 1165 } 1166 } 1167 1168 public Clipboard getSystemClipboard() { 1169 SecurityManager security = System.getSecurityManager(); 1170 if (security != null) { 1171 security.checkSystemClipboardAccess(); 1172 } 1173 synchronized (this) { 1174 if (clipboard == null) { 1175 clipboard = new XClipboard("System", "CLIPBOARD"); 1176 } 1177 } 1178 return clipboard; 1179 } 1180 1181 public Clipboard getSystemSelection() { 1182 SecurityManager security = System.getSecurityManager(); 1183 if (security != null) { 1184 security.checkSystemClipboardAccess(); 1185 } 1186 synchronized (this) { 1187 if (selection == null) { 1188 selection = new XClipboard("Selection", "PRIMARY"); 1189 } 1190 } 1191 return selection; 1192 } 1193 1194 public void beep() { 1195 awtLock(); 1196 try { 1197 XlibWrapper.XBell(getDisplay(), 0); 1198 XlibWrapper.XFlush(getDisplay()); 1199 } finally { 1200 awtUnlock(); 1201 } 1202 } 1203 1204 static String getSystemProperty(final String name) { 1205 return (String)AccessController.doPrivileged(new PrivilegedAction() { 1206 public Object run() { 1207 return System.getProperty(name); 1208 } 1209 }); 1210 } 1211 1212 public PrintJob getPrintJob(final Frame frame, final String doctitle, 1213 final Properties props) { 1214 1215 if (GraphicsEnvironment.isHeadless()) { 1216 throw new IllegalArgumentException(); 1217 } 1218 1219 PrintJob2D printJob = new PrintJob2D(frame, doctitle, props); 1220 1221 if (printJob.printDialog() == false) { 1222 printJob = null; 1223 } 1224 return printJob; 1225 } 1226 1227 public PrintJob getPrintJob(final Frame frame, final String doctitle, 1228 final JobAttributes jobAttributes, 1229 final PageAttributes pageAttributes) { 1230 1231 1232 if (GraphicsEnvironment.isHeadless()) { 1233 throw new IllegalArgumentException(); 1234 } 1235 1236 PrintJob2D printJob = new PrintJob2D(frame, doctitle, 1237 jobAttributes, pageAttributes); 1238 1239 if (printJob.printDialog() == false) { 1240 printJob = null; 1241 } 1242 1243 return printJob; 1244 } 1245 1246 static void XSync() { 1247 awtLock(); 1248 try { 1249 XlibWrapper.XSync(getDisplay(),0); 1250 } finally { 1251 awtUnlock(); 1252 } 1253 } 1254 1255 public int getScreenResolution() { 1256 long display = getDisplay(); 1257 awtLock(); 1258 try { 1259 return (int) ((XlibWrapper.DisplayWidth(display, 1260 XlibWrapper.DefaultScreen(display)) * 25.4) / 1261 XlibWrapper.DisplayWidthMM(display, 1262 XlibWrapper.DefaultScreen(display))); 1263 } finally { 1264 awtUnlock(); 1265 } 1266 } 1267 1268 static native long getDefaultXColormap(); 1269 static native long getDefaultScreenData(); 1270 1271 static ColorModel screenmodel; 1272 1273 static ColorModel getStaticColorModel() { 1274 if (screenmodel == null) { 1275 screenmodel = config.getColorModel (); 1276 } 1277 return screenmodel; 1278 } 1279 1280 public ColorModel getColorModel() { 1281 return getStaticColorModel(); 1282 } 1283 1284 /** 1285 * Returns a new input method adapter descriptor for native input methods. 1286 */ 1287 public InputMethodDescriptor getInputMethodAdapterDescriptor() throws AWTException { 1288 return new XInputMethodDescriptor(); 1289 } 1290 1291 static int getMultiClickTime() { 1292 if (awt_multiclick_time == 0) { 1293 initializeMultiClickTime(); 1294 } 1295 return awt_multiclick_time; 1296 } 1297 static void initializeMultiClickTime() { 1298 awtLock(); 1299 try { 1300 try { 1301 String multiclick_time_query = XlibWrapper.XGetDefault(XToolkit.getDisplay(), "*", "multiClickTime"); 1302 if (multiclick_time_query != null) { 1303 awt_multiclick_time = (int)Long.parseLong(multiclick_time_query); 1304 } else { 1305 multiclick_time_query = XlibWrapper.XGetDefault(XToolkit.getDisplay(), 1306 "OpenWindows", "MultiClickTimeout"); 1307 if (multiclick_time_query != null) { 1308 /* Note: OpenWindows.MultiClickTimeout is in tenths of 1309 a second, so we need to multiply by 100 to convert to 1310 milliseconds */ 1311 awt_multiclick_time = (int)Long.parseLong(multiclick_time_query) * 100; 1312 } else { 1313 awt_multiclick_time = AWT_MULTICLICK_DEFAULT_TIME; 1314 } 1315 } 1316 } catch (NumberFormatException nf) { 1317 awt_multiclick_time = AWT_MULTICLICK_DEFAULT_TIME; 1318 } catch (NullPointerException npe) { 1319 awt_multiclick_time = AWT_MULTICLICK_DEFAULT_TIME; 1320 } 1321 } finally { 1322 awtUnlock(); 1323 } 1324 if (awt_multiclick_time == 0) { 1325 awt_multiclick_time = AWT_MULTICLICK_DEFAULT_TIME; 1326 } 1327 } 1328 1329 public boolean isFrameStateSupported(int state) 1330 throws HeadlessException 1331 { 1332 if (state == Frame.NORMAL || state == Frame.ICONIFIED) { 1333 return true; 1334 } else { 1335 return XWM.getWM().supportsExtendedState(state); 1336 } 1337 } 1338 1339 static void dumpPeers() { 1340 if (log.isLoggable(PlatformLogger.FINE)) { 1341 log.fine("Mapped windows:"); 1342 Iterator iter = winMap.entrySet().iterator(); 1343 while (iter.hasNext()) { 1344 Map.Entry entry = (Map.Entry)iter.next(); 1345 log.fine(entry.getKey() + "->" + entry.getValue()); 1346 if (entry.getValue() instanceof XComponentPeer) { 1347 Component target = (Component)((XComponentPeer)entry.getValue()).getTarget(); 1348 log.fine("\ttarget: " + target); 1349 } 1350 } 1351 1352 SunToolkit.dumpPeers(log); 1353 1354 log.fine("Mapped special peers:"); 1355 iter = specialPeerMap.entrySet().iterator(); 1356 while (iter.hasNext()) { 1357 Map.Entry entry = (Map.Entry)iter.next(); 1358 log.fine(entry.getKey() + "->" + entry.getValue()); 1359 } 1360 1361 log.fine("Mapped dispatchers:"); 1362 iter = winToDispatcher.entrySet().iterator(); 1363 while (iter.hasNext()) { 1364 Map.Entry entry = (Map.Entry)iter.next(); 1365 log.fine(entry.getKey() + "->" + entry.getValue()); 1366 } 1367 } 1368 } 1369 1370 /* Protected with awt_lock. */ 1371 private static boolean initialized; 1372 private static boolean timeStampUpdated; 1373 private static long timeStamp; 1374 1375 private static final XEventDispatcher timeFetcher = 1376 new XEventDispatcher() { 1377 public void dispatchEvent(XEvent ev) { 1378 switch (ev.get_type()) { 1379 case XConstants.PropertyNotify: 1380 XPropertyEvent xpe = ev.get_xproperty(); 1381 1382 awtLock(); 1383 try { 1384 timeStamp = xpe.get_time(); 1385 timeStampUpdated = true; 1386 awtLockNotifyAll(); 1387 } finally { 1388 awtUnlock(); 1389 } 1390 1391 break; 1392 } 1393 } 1394 }; 1395 1396 private static XAtom _XA_JAVA_TIME_PROPERTY_ATOM; 1397 1398 static long getCurrentServerTime() { 1399 awtLock(); 1400 try { 1401 try { 1402 if (!initialized) { 1403 XToolkit.addEventDispatcher(XBaseWindow.getXAWTRootWindow().getWindow(), 1404 timeFetcher); 1405 _XA_JAVA_TIME_PROPERTY_ATOM = XAtom.get("_SUNW_JAVA_AWT_TIME"); 1406 initialized = true; 1407 } 1408 timeStampUpdated = false; 1409 XlibWrapper.XChangeProperty(XToolkit.getDisplay(), 1410 XBaseWindow.getXAWTRootWindow().getWindow(), 1411 _XA_JAVA_TIME_PROPERTY_ATOM.getAtom(), XAtom.XA_ATOM, 32, 1412 XConstants.PropModeAppend, 1413 0, 0); 1414 XlibWrapper.XFlush(XToolkit.getDisplay()); 1415 1416 if (isToolkitThread()) { 1417 XEvent event = new XEvent(); 1418 try { 1419 XlibWrapper.XWindowEvent(XToolkit.getDisplay(), 1420 XBaseWindow.getXAWTRootWindow().getWindow(), 1421 XConstants.PropertyChangeMask, 1422 event.pData); 1423 timeFetcher.dispatchEvent(event); 1424 } 1425 finally { 1426 event.dispose(); 1427 } 1428 } 1429 else { 1430 while (!timeStampUpdated) { 1431 awtLockWait(); 1432 } 1433 } 1434 } catch (InterruptedException ie) { 1435 // Note: the returned timeStamp can be incorrect in this case. 1436 if (log.isLoggable(PlatformLogger.FINE)) log.fine("Catched exception, timeStamp may not be correct (ie = " + ie + ")"); 1437 } 1438 } finally { 1439 awtUnlock(); 1440 } 1441 return timeStamp; 1442 } 1443 protected void initializeDesktopProperties() { 1444 desktopProperties.put("DnD.Autoscroll.initialDelay", 1445 Integer.valueOf(50)); 1446 desktopProperties.put("DnD.Autoscroll.interval", 1447 Integer.valueOf(50)); 1448 desktopProperties.put("DnD.Autoscroll.cursorHysteresis", 1449 Integer.valueOf(5)); 1450 desktopProperties.put("Shell.shellFolderManager", 1451 "sun.awt.shell.ShellFolderManager"); 1452 // Don't want to call getMultiClickTime() if we are headless 1453 if (!GraphicsEnvironment.isHeadless()) { 1454 desktopProperties.put("awt.multiClickInterval", 1455 Integer.valueOf(getMultiClickTime())); 1456 desktopProperties.put("awt.mouse.numButtons", 1457 Integer.valueOf(getNumberOfButtons())); 1458 } 1459 } 1460 1461 /** 1462 * This method runs through the XPointer and XExtendedPointer array. 1463 * XExtendedPointer has priority because on some systems XPointer 1464 * (which is assigned to the virtual pointer) reports the maximum 1465 * capabilities of the mouse pointer (i.e. 32 physical buttons). 1466 */ 1467 private native int getNumberOfButtonsImpl(); 1468 1469 @Override 1470 public int getNumberOfButtons(){ 1471 awtLock(); 1472 try { 1473 if (numberOfButtons == 0) { 1474 numberOfButtons = getNumberOfButtonsImpl(); 1475 } 1476 return (numberOfButtons > MAX_BUTTONS_SUPPORTED)? MAX_BUTTONS_SUPPORTED : numberOfButtons; 1477 } finally { 1478 awtUnlock(); 1479 } 1480 } 1481 1482 private final static String prefix = "DnD.Cursor."; 1483 private final static String postfix = ".32x32"; 1484 private static final String dndPrefix = "DnD."; 1485 1486 protected Object lazilyLoadDesktopProperty(String name) { 1487 if (name.startsWith(prefix)) { 1488 String cursorName = name.substring(prefix.length(), name.length()) + postfix; 1489 1490 try { 1491 return Cursor.getSystemCustomCursor(cursorName); 1492 } catch (AWTException awte) { 1493 throw new RuntimeException("cannot load system cursor: " + cursorName, awte); 1494 } 1495 } 1496 1497 if (name.equals("awt.dynamicLayoutSupported")) { 1498 return Boolean.valueOf(isDynamicLayoutSupported()); 1499 } 1500 1501 if (initXSettingsIfNeeded(name)) { 1502 return desktopProperties.get(name); 1503 } 1504 1505 return super.lazilyLoadDesktopProperty(name); 1506 } 1507 1508 public synchronized void addPropertyChangeListener(String name, PropertyChangeListener pcl) { 1509 initXSettingsIfNeeded(name); 1510 super.addPropertyChangeListener(name, pcl); 1511 } 1512 1513 /** 1514 * Initializes XAWTXSettings if a property for a given property name is provided by 1515 * XSettings and they are not initialized yet. 1516 * 1517 * @return true if the method has initialized XAWTXSettings. 1518 */ 1519 private boolean initXSettingsIfNeeded(final String propName) { 1520 if (!loadedXSettings && 1521 (propName.startsWith("gnome.") || 1522 propName.equals(SunToolkit.DESKTOPFONTHINTS) || 1523 propName.startsWith(dndPrefix))) 1524 { 1525 loadedXSettings = true; 1526 if (!GraphicsEnvironment.isHeadless()) { 1527 loadXSettings(); 1528 /* If no desktop font hint could be retrieved, check for 1529 * KDE running KWin and retrieve settings from fontconfig. 1530 * If that isn't found let SunToolkit will see if there's a 1531 * system property set by a user. 1532 */ 1533 if (desktopProperties.get(SunToolkit.DESKTOPFONTHINTS) == null) { 1534 if (XWM.isKDE2()) { 1535 Object hint = fcManager.getFontConfigAAHint(); 1536 if (hint != null) { 1537 /* set the fontconfig/KDE property so that 1538 * getDesktopHints() below will see it 1539 * and set the public property. 1540 */ 1541 desktopProperties.put(UNIXToolkit.FONTCONFIGAAHINT, 1542 hint); 1543 } 1544 } 1545 desktopProperties.put(SunToolkit.DESKTOPFONTHINTS, 1546 SunToolkit.getDesktopFontHints()); 1547 } 1548 1549 return true; 1550 } 1551 } 1552 return false; 1553 } 1554 1555 private void loadXSettings() { 1556 xs = new XAWTXSettings(); 1557 } 1558 1559 /** 1560 * Callback from the native side indicating some, or all, of the 1561 * desktop properties have changed and need to be reloaded. 1562 * <code>data</code> is the byte array directly from the x server and 1563 * may be in little endian format. 1564 * <p> 1565 * NB: This could be called from any thread if triggered by 1566 * <code>loadXSettings</code>. It is called from the System EDT 1567 * if triggered by an XSETTINGS change. 1568 */ 1569 void parseXSettings(int screen_XXX_ignored,Map updatedSettings) { 1570 1571 if (updatedSettings == null || updatedSettings.isEmpty()) { 1572 return; 1573 } 1574 1575 Iterator i = updatedSettings.entrySet().iterator(); 1576 while (i.hasNext()) { 1577 Map.Entry e = (Map.Entry)i.next(); 1578 String name = (String)e.getKey(); 1579 1580 name = "gnome." + name; 1581 setDesktopProperty(name, e.getValue()); 1582 log.fine("name = " + name + " value = " + e.getValue()); 1583 1584 // XXX: we probably want to do something smarter. In 1585 // particular, "Net" properties are of interest to the 1586 // "core" AWT itself. E.g. 1587 // 1588 // Net/DndDragThreshold -> ??? 1589 // Net/DoubleClickTime -> awt.multiClickInterval 1590 } 1591 1592 setDesktopProperty(SunToolkit.DESKTOPFONTHINTS, 1593 SunToolkit.getDesktopFontHints()); 1594 1595 Integer dragThreshold = null; 1596 synchronized (this) { 1597 dragThreshold = (Integer)desktopProperties.get("gnome.Net/DndDragThreshold"); 1598 } 1599 if (dragThreshold != null) { 1600 setDesktopProperty("DnD.gestureMotionThreshold", dragThreshold); 1601 } 1602 1603 } 1604 1605 1606 1607 static int altMask; 1608 static int metaMask; 1609 static int numLockMask; 1610 static int modeSwitchMask; 1611 static int modLockIsShiftLock; 1612 1613 /* Like XKeysymToKeycode, but ensures that keysym is the primary 1614 * symbol on the keycode returned. Returns zero otherwise. 1615 */ 1616 static int keysymToPrimaryKeycode(long sym) { 1617 awtLock(); 1618 try { 1619 int code = XlibWrapper.XKeysymToKeycode(getDisplay(), sym); 1620 if (code == 0) { 1621 return 0; 1622 } 1623 long primary = XlibWrapper.XKeycodeToKeysym(getDisplay(), code, 0); 1624 if (sym != primary) { 1625 return 0; 1626 } 1627 return code; 1628 } finally { 1629 awtUnlock(); 1630 } 1631 } 1632 static boolean getModifierState( int jkc ) { 1633 int iKeyMask = 0; 1634 long ks = XKeysym.javaKeycode2Keysym( jkc ); 1635 int kc = XlibWrapper.XKeysymToKeycode(getDisplay(), ks); 1636 if (kc == 0) { 1637 return false; 1638 } 1639 awtLock(); 1640 try { 1641 XModifierKeymap modmap = new XModifierKeymap( 1642 XlibWrapper.XGetModifierMapping(getDisplay())); 1643 1644 int nkeys = modmap.get_max_keypermod(); 1645 1646 long map_ptr = modmap.get_modifiermap(); 1647 for( int k = 0; k < 8; k++ ) { 1648 for (int i = 0; i < nkeys; ++i) { 1649 int keycode = Native.getUByte(map_ptr, k * nkeys + i); 1650 if (keycode == 0) { 1651 continue; // ignore zero keycode 1652 } 1653 if (kc == keycode) { 1654 iKeyMask = 1 << k; 1655 break; 1656 } 1657 } 1658 if( iKeyMask != 0 ) { 1659 break; 1660 } 1661 } 1662 XlibWrapper.XFreeModifiermap(modmap.pData); 1663 if (iKeyMask == 0 ) { 1664 return false; 1665 } 1666 // Now we know to which modifier is assigned the keycode 1667 // correspondent to the keysym correspondent to the java 1668 // keycode. We are going to check a state of this modifier. 1669 // If a modifier is a weird one, we cannot help it. 1670 long window = 0; 1671 try{ 1672 // get any application window 1673 window = ((Long)(winMap.firstKey())).longValue(); 1674 }catch(NoSuchElementException nex) { 1675 // get root window 1676 window = getDefaultRootWindow(); 1677 } 1678 boolean res = XlibWrapper.XQueryPointer(getDisplay(), window, 1679 XlibWrapper.larg1, //root 1680 XlibWrapper.larg2, //child 1681 XlibWrapper.larg3, //root_x 1682 XlibWrapper.larg4, //root_y 1683 XlibWrapper.larg5, //child_x 1684 XlibWrapper.larg6, //child_y 1685 XlibWrapper.larg7);//mask 1686 int mask = Native.getInt(XlibWrapper.larg7); 1687 return ((mask & iKeyMask) != 0); 1688 } finally { 1689 awtUnlock(); 1690 } 1691 } 1692 1693 /* Assign meaning - alt, meta, etc. - to X modifiers mod1 ... mod5. 1694 * Only consider primary symbols on keycodes attached to modifiers. 1695 */ 1696 static void setupModifierMap() { 1697 final int metaL = keysymToPrimaryKeycode(XKeySymConstants.XK_Meta_L); 1698 final int metaR = keysymToPrimaryKeycode(XKeySymConstants.XK_Meta_R); 1699 final int altL = keysymToPrimaryKeycode(XKeySymConstants.XK_Alt_L); 1700 final int altR = keysymToPrimaryKeycode(XKeySymConstants.XK_Alt_R); 1701 final int numLock = keysymToPrimaryKeycode(XKeySymConstants.XK_Num_Lock); 1702 final int modeSwitch = keysymToPrimaryKeycode(XKeySymConstants.XK_Mode_switch); 1703 final int shiftLock = keysymToPrimaryKeycode(XKeySymConstants.XK_Shift_Lock); 1704 final int capsLock = keysymToPrimaryKeycode(XKeySymConstants.XK_Caps_Lock); 1705 1706 final int modmask[] = { XConstants.ShiftMask, XConstants.LockMask, XConstants.ControlMask, XConstants.Mod1Mask, 1707 XConstants.Mod2Mask, XConstants.Mod3Mask, XConstants.Mod4Mask, XConstants.Mod5Mask }; 1708 1709 log.fine("In setupModifierMap"); 1710 awtLock(); 1711 try { 1712 XModifierKeymap modmap = new XModifierKeymap( 1713 XlibWrapper.XGetModifierMapping(getDisplay())); 1714 1715 int nkeys = modmap.get_max_keypermod(); 1716 1717 long map_ptr = modmap.get_modifiermap(); 1718 1719 for (int modn = XConstants.Mod1MapIndex; 1720 modn <= XConstants.Mod5MapIndex; 1721 ++modn) 1722 { 1723 for (int i = 0; i < nkeys; ++i) { 1724 /* for each keycode attached to this modifier */ 1725 int keycode = Native.getUByte(map_ptr, modn * nkeys + i); 1726 1727 if (keycode == 0) { 1728 break; 1729 } 1730 if (metaMask == 0 && 1731 (keycode == metaL || keycode == metaR)) 1732 { 1733 metaMask = modmask[modn]; 1734 break; 1735 } 1736 if (altMask == 0 && (keycode == altL || keycode == altR)) { 1737 altMask = modmask[modn]; 1738 break; 1739 } 1740 if (numLockMask == 0 && keycode == numLock) { 1741 numLockMask = modmask[modn]; 1742 break; 1743 } 1744 if (modeSwitchMask == 0 && keycode == modeSwitch) { 1745 modeSwitchMask = modmask[modn]; 1746 break; 1747 } 1748 continue; 1749 } 1750 } 1751 modLockIsShiftLock = 0; 1752 for (int j = 0; j < nkeys; ++j) { 1753 int keycode = Native.getUByte(map_ptr, XConstants.LockMapIndex * nkeys + j); 1754 if (keycode == 0) { 1755 break; 1756 } 1757 if (keycode == shiftLock) { 1758 modLockIsShiftLock = 1; 1759 break; 1760 } 1761 if (keycode == capsLock) { 1762 break; 1763 } 1764 } 1765 XlibWrapper.XFreeModifiermap(modmap.pData); 1766 } finally { 1767 awtUnlock(); 1768 } 1769 if (log.isLoggable(PlatformLogger.FINE)) { 1770 log.fine("metaMask = " + metaMask); 1771 log.fine("altMask = " + altMask); 1772 log.fine("numLockMask = " + numLockMask); 1773 log.fine("modeSwitchMask = " + modeSwitchMask); 1774 log.fine("modLockIsShiftLock = " + modLockIsShiftLock); 1775 } 1776 } 1777 1778 1779 private static SortedMap timeoutTasks; 1780 1781 /** 1782 * Removed the task from the list of waiting-to-be called tasks. 1783 * If the task has been scheduled several times removes only first one. 1784 */ 1785 static void remove(Runnable task) { 1786 if (task == null) { 1787 throw new NullPointerException("task is null"); 1788 } 1789 awtLock(); 1790 try { 1791 if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) { 1792 timeoutTaskLog.finer("Removing task " + task); 1793 } 1794 if (timeoutTasks == null) { 1795 if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) { 1796 timeoutTaskLog.finer("Task is not scheduled"); 1797 } 1798 return; 1799 } 1800 Collection values = timeoutTasks.values(); 1801 Iterator iter = values.iterator(); 1802 while (iter.hasNext()) { 1803 java.util.List list = (java.util.List)iter.next(); 1804 boolean removed = false; 1805 if (list.contains(task)) { 1806 list.remove(task); 1807 if (list.isEmpty()) { 1808 iter.remove(); 1809 } 1810 break; 1811 } 1812 } 1813 } finally { 1814 awtUnlock(); 1815 } 1816 } 1817 1818 static native void wakeup_poll(); 1819 1820 /** 1821 * Registers a Runnable which <code>run()</code> method will be called 1822 * once on the toolkit thread when a specified interval of time elapses. 1823 * 1824 * @param task a Runnable which <code>run</code> method will be called 1825 * on the toolkit thread when <code>interval</code> milliseconds 1826 * elapse 1827 * @param interval an interal in milliseconds 1828 * 1829 * @throws NullPointerException if <code>task</code> is <code>null</code> 1830 * @throws IllegalArgumentException if <code>interval</code> is not positive 1831 */ 1832 static void schedule(Runnable task, long interval) { 1833 if (task == null) { 1834 throw new NullPointerException("task is null"); 1835 } 1836 if (interval <= 0) { 1837 throw new IllegalArgumentException("interval " + interval + " is not positive"); 1838 } 1839 1840 awtLock(); 1841 try { 1842 if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) { 1843 timeoutTaskLog.finer("XToolkit.schedule(): current time={0}" + 1844 "; interval={1}" + 1845 "; task being added={2}" + "; tasks before addition={3}", 1846 Long.valueOf(System.currentTimeMillis()), Long.valueOf(interval), task, timeoutTasks); 1847 } 1848 1849 if (timeoutTasks == null) { 1850 timeoutTasks = new TreeMap(); 1851 } 1852 1853 Long time = Long.valueOf(System.currentTimeMillis() + interval); 1854 java.util.List tasks = (java.util.List)timeoutTasks.get(time); 1855 if (tasks == null) { 1856 tasks = new ArrayList(1); 1857 timeoutTasks.put(time, tasks); 1858 } 1859 tasks.add(task); 1860 1861 1862 if (timeoutTasks.get(timeoutTasks.firstKey()) == tasks && tasks.size() == 1) { 1863 // Added task became first task - poll won't know 1864 // about it so we need to wake it up 1865 wakeup_poll(); 1866 } 1867 } finally { 1868 awtUnlock(); 1869 } 1870 } 1871 1872 private long getNextTaskTime() { 1873 awtLock(); 1874 try { 1875 if (timeoutTasks == null || timeoutTasks.isEmpty()) { 1876 return -1L; 1877 } 1878 return (Long)timeoutTasks.firstKey(); 1879 } finally { 1880 awtUnlock(); 1881 } 1882 } 1883 1884 /** 1885 * Executes mature timeout tasks registered with schedule(). 1886 * Called from run() under awtLock. 1887 */ 1888 private static void callTimeoutTasks() { 1889 if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) { 1890 timeoutTaskLog.finer("XToolkit.callTimeoutTasks(): current time={0}" + 1891 "; tasks={1}", Long.valueOf(System.currentTimeMillis()), timeoutTasks); 1892 } 1893 1894 if (timeoutTasks == null || timeoutTasks.isEmpty()) { 1895 return; 1896 } 1897 1898 Long currentTime = Long.valueOf(System.currentTimeMillis()); 1899 Long time = (Long)timeoutTasks.firstKey(); 1900 1901 while (time.compareTo(currentTime) <= 0) { 1902 java.util.List tasks = (java.util.List)timeoutTasks.remove(time); 1903 1904 for (Iterator iter = tasks.iterator(); iter.hasNext();) { 1905 Runnable task = (Runnable)iter.next(); 1906 1907 if (timeoutTaskLog.isLoggable(PlatformLogger.FINER)) { 1908 timeoutTaskLog.finer("XToolkit.callTimeoutTasks(): current time={0}" + 1909 "; about to run task={1}", Long.valueOf(currentTime), task); 1910 } 1911 1912 try { 1913 task.run(); 1914 } catch (ThreadDeath td) { 1915 throw td; 1916 } catch (Throwable thr) { 1917 processException(thr); 1918 } 1919 } 1920 1921 if (timeoutTasks.isEmpty()) { 1922 break; 1923 } 1924 time = (Long)timeoutTasks.firstKey(); 1925 } 1926 } 1927 1928 static long getAwtDefaultFg() { 1929 return awt_defaultFg; 1930 } 1931 1932 static boolean isLeftMouseButton(MouseEvent me) { 1933 switch (me.getID()) { 1934 case MouseEvent.MOUSE_PRESSED: 1935 case MouseEvent.MOUSE_RELEASED: 1936 return (me.getButton() == MouseEvent.BUTTON1); 1937 case MouseEvent.MOUSE_ENTERED: 1938 case MouseEvent.MOUSE_EXITED: 1939 case MouseEvent.MOUSE_CLICKED: 1940 case MouseEvent.MOUSE_DRAGGED: 1941 return ((me.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK) != 0); 1942 } 1943 return false; 1944 } 1945 1946 static boolean isRightMouseButton(MouseEvent me) { 1947 int numButtons = ((Integer)getDefaultToolkit().getDesktopProperty("awt.mouse.numButtons")).intValue(); 1948 switch (me.getID()) { 1949 case MouseEvent.MOUSE_PRESSED: 1950 case MouseEvent.MOUSE_RELEASED: 1951 return ((numButtons == 2 && me.getButton() == MouseEvent.BUTTON2) || 1952 (numButtons > 2 && me.getButton() == MouseEvent.BUTTON3)); 1953 case MouseEvent.MOUSE_ENTERED: 1954 case MouseEvent.MOUSE_EXITED: 1955 case MouseEvent.MOUSE_CLICKED: 1956 case MouseEvent.MOUSE_DRAGGED: 1957 return ((numButtons == 2 && (me.getModifiersEx() & InputEvent.BUTTON2_DOWN_MASK) != 0) || 1958 (numButtons > 2 && (me.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)); 1959 } 1960 return false; 1961 } 1962 1963 static long reset_time_utc; 1964 static final long WRAP_TIME_MILLIS = Integer.MAX_VALUE; 1965 1966 /* 1967 * This function converts between the X server time (number of milliseconds 1968 * since the last server reset) and the UTC time for the 'when' field of an 1969 * InputEvent (or another event type with a timestamp). 1970 */ 1971 static long nowMillisUTC_offset(long server_offset) { 1972 // ported from awt_util.c 1973 /* 1974 * Because Time is of type 'unsigned long', it is possible that Time will 1975 * never wrap when using 64-bit Xlib. However, if a 64-bit client 1976 * connects to a 32-bit server, I suspect the values will still wrap. So 1977 * we should not attempt to remove the wrap checking even if _LP64 is 1978 * true. 1979 */ 1980 1981 long current_time_utc = System.currentTimeMillis(); 1982 if (log.isLoggable(PlatformLogger.FINER)) { 1983 log.finer("reset_time=" + reset_time_utc + ", current_time=" + current_time_utc 1984 + ", server_offset=" + server_offset + ", wrap_time=" + WRAP_TIME_MILLIS); 1985 } 1986 1987 if ((current_time_utc - reset_time_utc) > WRAP_TIME_MILLIS) { 1988 reset_time_utc = System.currentTimeMillis() - getCurrentServerTime(); 1989 } 1990 1991 if (log.isLoggable(PlatformLogger.FINER)) { 1992 log.finer("result = " + (reset_time_utc + server_offset)); 1993 } 1994 return reset_time_utc + server_offset; 1995 } 1996 1997 /** 1998 * @see sun.awt.SunToolkit#needsXEmbedImpl 1999 */ 2000 protected boolean needsXEmbedImpl() { 2001 // XToolkit implements supports for XEmbed-client protocol and 2002 // requires the supports from the embedding host for it to work. 2003 return true; 2004 } 2005 2006 public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) { 2007 return (modalityType == null) || 2008 (modalityType == Dialog.ModalityType.MODELESS) || 2009 (modalityType == Dialog.ModalityType.DOCUMENT_MODAL) || 2010 (modalityType == Dialog.ModalityType.APPLICATION_MODAL) || 2011 (modalityType == Dialog.ModalityType.TOOLKIT_MODAL); 2012 } 2013 2014 public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) { 2015 return (exclusionType == null) || 2016 (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE) || 2017 (exclusionType == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) || 2018 (exclusionType == Dialog.ModalExclusionType.TOOLKIT_EXCLUDE); 2019 } 2020 2021 static EventQueue getEventQueue(Object target) { 2022 AppContext appContext = targetToAppContext(target); 2023 if (appContext != null) { 2024 return (EventQueue)appContext.get(AppContext.EVENT_QUEUE_KEY); 2025 } 2026 return null; 2027 } 2028 2029 static void removeSourceEvents(EventQueue queue, Object source, boolean removeAllEvents) { 2030 try { 2031 m_removeSourceEvents.invoke(queue, source, removeAllEvents); 2032 } 2033 catch (IllegalAccessException e) 2034 { 2035 e.printStackTrace(); 2036 } 2037 catch (InvocationTargetException e) { 2038 e.printStackTrace(); 2039 } 2040 } 2041 2042 public boolean isAlwaysOnTopSupported() { 2043 for (XLayerProtocol proto : XWM.getWM().getProtocols(XLayerProtocol.class)) { 2044 if (proto.supportsLayer(XLayerProtocol.LAYER_ALWAYS_ON_TOP)) { 2045 return true; 2046 } 2047 } 2048 return false; 2049 } 2050 2051 public boolean useBufferPerWindow() { 2052 return XToolkit.getBackingStoreType() == XConstants.NotUseful; 2053 } 2054 2055 /** 2056 * Returns one of XConstants: NotUseful, WhenMapped or Always. 2057 * If backing store is not available on at least one screen, or 2058 * java2d uses DGA(which conflicts with backing store) on at least one screen, 2059 * or the string system property "sun.awt.backingStore" is neither "Always" 2060 * nor "WhenMapped", then the method returns XConstants.NotUseful. 2061 * Otherwise, if the system property "sun.awt.backingStore" is "WhenMapped", 2062 * then the method returns XConstants.WhenMapped. 2063 * Otherwise (i.e., if the system property "sun.awt.backingStore" is "Always"), 2064 * the method returns XConstants.Always. 2065 */ 2066 static int getBackingStoreType() { 2067 return backingStoreType; 2068 } 2069 2070 private static void setBackingStoreType() { 2071 String prop = (String)AccessController.doPrivileged( 2072 new sun.security.action.GetPropertyAction("sun.awt.backingStore")); 2073 2074 if (prop == null) { 2075 backingStoreType = XConstants.NotUseful; 2076 if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) { 2077 backingStoreLog.config("The system property sun.awt.backingStore is not set" + 2078 ", by default backingStore=NotUseful"); 2079 } 2080 return; 2081 } 2082 2083 if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) { 2084 backingStoreLog.config("The system property sun.awt.backingStore is " + prop); 2085 } 2086 prop = prop.toLowerCase(); 2087 if (prop.equals("always")) { 2088 backingStoreType = XConstants.Always; 2089 } else if (prop.equals("whenmapped")) { 2090 backingStoreType = XConstants.WhenMapped; 2091 } else { 2092 backingStoreType = XConstants.NotUseful; 2093 } 2094 2095 if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) { 2096 backingStoreLog.config("backingStore(as provided by the system property)=" + 2097 ( backingStoreType == XConstants.NotUseful ? "NotUseful" 2098 : backingStoreType == XConstants.WhenMapped ? 2099 "WhenMapped" : "Always") ); 2100 } 2101 2102 if (sun.java2d.x11.X11SurfaceData.isDgaAvailable()) { 2103 backingStoreType = XConstants.NotUseful; 2104 2105 if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) { 2106 backingStoreLog.config("DGA is available, backingStore=NotUseful"); 2107 } 2108 2109 return; 2110 } 2111 2112 awtLock(); 2113 try { 2114 int screenCount = XlibWrapper.ScreenCount(getDisplay()); 2115 for (int i = 0; i < screenCount; i++) { 2116 if (XlibWrapper.DoesBackingStore(XlibWrapper.ScreenOfDisplay(getDisplay(), i)) 2117 == XConstants.NotUseful) { 2118 backingStoreType = XConstants.NotUseful; 2119 2120 if (backingStoreLog.isLoggable(PlatformLogger.CONFIG)) { 2121 backingStoreLog.config("Backing store is not available on the screen " + 2122 i + ", backingStore=NotUseful"); 2123 } 2124 2125 return; 2126 } 2127 } 2128 } finally { 2129 awtUnlock(); 2130 } 2131 } 2132 2133 /** 2134 * One of XConstants: NotUseful, WhenMapped or Always. 2135 */ 2136 private static int backingStoreType; 2137 2138 static final int XSUN_KP_BEHAVIOR = 1; 2139 static final int XORG_KP_BEHAVIOR = 2; 2140 static final int IS_SUN_KEYBOARD = 1; 2141 static final int IS_NONSUN_KEYBOARD = 2; 2142 static final int IS_KANA_KEYBOARD = 1; 2143 static final int IS_NONKANA_KEYBOARD = 2; 2144 2145 2146 static int awt_IsXsunKPBehavior = 0; 2147 static boolean awt_UseXKB = false; 2148 static boolean awt_UseXKB_Calls = false; 2149 static int awt_XKBBaseEventCode = 0; 2150 static int awt_XKBEffectiveGroup = 0; // so far, I don't use it leaving all calculations 2151 // to XkbTranslateKeyCode 2152 static long awt_XKBDescPtr = 0; 2153 2154 /** 2155 * Check for Xsun convention regarding numpad keys. 2156 * Xsun and some other servers (i.e. derived from Xsun) 2157 * under certain conditions process numpad keys unlike Xorg. 2158 */ 2159 static boolean isXsunKPBehavior() { 2160 awtLock(); 2161 try { 2162 if( awt_IsXsunKPBehavior == 0 ) { 2163 if( XlibWrapper.IsXsunKPBehavior(getDisplay()) ) { 2164 awt_IsXsunKPBehavior = XSUN_KP_BEHAVIOR; 2165 }else{ 2166 awt_IsXsunKPBehavior = XORG_KP_BEHAVIOR; 2167 } 2168 } 2169 return awt_IsXsunKPBehavior == XSUN_KP_BEHAVIOR ? true : false; 2170 } finally { 2171 awtUnlock(); 2172 } 2173 } 2174 2175 static int sunOrNotKeyboard = 0; 2176 static int kanaOrNotKeyboard = 0; 2177 static void resetKeyboardSniffer() { 2178 sunOrNotKeyboard = 0; 2179 kanaOrNotKeyboard = 0; 2180 } 2181 static boolean isSunKeyboard() { 2182 if( sunOrNotKeyboard == 0 ) { 2183 if( XlibWrapper.IsSunKeyboard( getDisplay() )) { 2184 sunOrNotKeyboard = IS_SUN_KEYBOARD; 2185 }else{ 2186 sunOrNotKeyboard = IS_NONSUN_KEYBOARD; 2187 } 2188 } 2189 return (sunOrNotKeyboard == IS_SUN_KEYBOARD); 2190 } 2191 static boolean isKanaKeyboard() { 2192 if( kanaOrNotKeyboard == 0 ) { 2193 if( XlibWrapper.IsKanaKeyboard( getDisplay() )) { 2194 kanaOrNotKeyboard = IS_KANA_KEYBOARD; 2195 }else{ 2196 kanaOrNotKeyboard = IS_NONKANA_KEYBOARD; 2197 } 2198 } 2199 return (kanaOrNotKeyboard == IS_KANA_KEYBOARD); 2200 } 2201 static boolean isXKBenabled() { 2202 awtLock(); 2203 try { 2204 return awt_UseXKB; 2205 } finally { 2206 awtUnlock(); 2207 } 2208 } 2209 2210 /** 2211 Query XKEYBOARD extension. 2212 If possible, initialize xkb library. 2213 */ 2214 static boolean tryXKB() { 2215 awtLock(); 2216 try { 2217 String name = "XKEYBOARD"; 2218 // First, if there is extension at all. 2219 awt_UseXKB = XlibWrapper.XQueryExtension( getDisplay(), name, XlibWrapper.larg1, XlibWrapper.larg2, XlibWrapper.larg3); 2220 if( awt_UseXKB ) { 2221 // There is a keyboard extension. Check if a client library is compatible. 2222 // If not, don't use xkb calls. 2223 // In this case we still may be Xkb-capable application. 2224 awt_UseXKB_Calls = XlibWrapper.XkbLibraryVersion( XlibWrapper.larg1, XlibWrapper.larg2); 2225 if( awt_UseXKB_Calls ) { 2226 awt_UseXKB_Calls = XlibWrapper.XkbQueryExtension( getDisplay(), XlibWrapper.larg1, XlibWrapper.larg2, 2227 XlibWrapper.larg3, XlibWrapper.larg4, XlibWrapper.larg5); 2228 if( awt_UseXKB_Calls ) { 2229 awt_XKBBaseEventCode = Native.getInt(XlibWrapper.larg2); 2230 XlibWrapper.XkbSelectEvents (getDisplay(), 2231 XConstants.XkbUseCoreKbd, 2232 XConstants.XkbNewKeyboardNotifyMask | 2233 XConstants.XkbMapNotifyMask ,//| 2234 //XConstants.XkbStateNotifyMask, 2235 XConstants.XkbNewKeyboardNotifyMask | 2236 XConstants.XkbMapNotifyMask );//| 2237 //XConstants.XkbStateNotifyMask); 2238 2239 XlibWrapper.XkbSelectEventDetails(getDisplay(), XConstants.XkbUseCoreKbd, 2240 XConstants.XkbStateNotify, 2241 XConstants.XkbGroupStateMask, 2242 XConstants.XkbGroupStateMask); 2243 //XXX ? XkbGroupLockMask last, XkbAllStateComponentsMask before last? 2244 awt_XKBDescPtr = XlibWrapper.XkbGetMap(getDisplay(), 2245 XConstants.XkbKeyTypesMask | 2246 XConstants.XkbKeySymsMask | 2247 XConstants.XkbModifierMapMask | 2248 XConstants.XkbVirtualModsMask, 2249 XConstants.XkbUseCoreKbd); 2250 } 2251 } 2252 } 2253 return awt_UseXKB; 2254 } finally { 2255 awtUnlock(); 2256 } 2257 } 2258 static boolean canUseXKBCalls() { 2259 awtLock(); 2260 try { 2261 return awt_UseXKB_Calls; 2262 } finally { 2263 awtUnlock(); 2264 } 2265 } 2266 static int getXKBEffectiveGroup() { 2267 awtLock(); 2268 try { 2269 return awt_XKBEffectiveGroup; 2270 } finally { 2271 awtUnlock(); 2272 } 2273 } 2274 static int getXKBBaseEventCode() { 2275 awtLock(); 2276 try { 2277 return awt_XKBBaseEventCode; 2278 } finally { 2279 awtUnlock(); 2280 } 2281 } 2282 static long getXKBKbdDesc() { 2283 awtLock(); 2284 try { 2285 return awt_XKBDescPtr; 2286 } finally { 2287 awtUnlock(); 2288 } 2289 } 2290 void freeXKB() { 2291 awtLock(); 2292 try { 2293 if (awt_UseXKB_Calls && awt_XKBDescPtr != 0) { 2294 XlibWrapper.XkbFreeKeyboard(awt_XKBDescPtr, 0xFF, true); 2295 awt_XKBDescPtr = 0; 2296 } 2297 } finally { 2298 awtUnlock(); 2299 } 2300 } 2301 private void processXkbChanges(XEvent ev) { 2302 // mapping change --> refresh kbd map 2303 // state change --> get a new effective group; do I really need it 2304 // or that should be left for XkbTranslateKeyCode? 2305 XkbEvent xke = new XkbEvent( ev.getPData() ); 2306 int xkb_type = xke.get_any().get_xkb_type(); 2307 switch( xkb_type ) { 2308 case XConstants.XkbNewKeyboardNotify : 2309 if( awt_XKBDescPtr != 0 ) { 2310 freeXKB(); 2311 } 2312 awt_XKBDescPtr = XlibWrapper.XkbGetMap(getDisplay(), 2313 XConstants.XkbKeyTypesMask | 2314 XConstants.XkbKeySymsMask | 2315 XConstants.XkbModifierMapMask | 2316 XConstants.XkbVirtualModsMask, 2317 XConstants.XkbUseCoreKbd); 2318 //System.out.println("XkbNewKeyboard:"+(xke.get_new_kbd())); 2319 break; 2320 case XConstants.XkbMapNotify : 2321 //TODO: provide a simple unit test. 2322 XlibWrapper.XkbGetUpdatedMap(getDisplay(), 2323 XConstants.XkbKeyTypesMask | 2324 XConstants.XkbKeySymsMask | 2325 XConstants.XkbModifierMapMask | 2326 XConstants.XkbVirtualModsMask, 2327 awt_XKBDescPtr); 2328 //System.out.println("XkbMap:"+(xke.get_map())); 2329 break; 2330 case XConstants.XkbStateNotify : 2331 // May use it later e.g. to obtain an effective group etc. 2332 //System.out.println("XkbState:"+(xke.get_state())); 2333 break; 2334 default: 2335 //System.out.println("XkbEvent of xkb_type "+xkb_type); 2336 break; 2337 } 2338 } 2339 2340 private static long eventNumber; 2341 public static long getEventNumber() { 2342 awtLock(); 2343 try { 2344 return eventNumber; 2345 } finally { 2346 awtUnlock(); 2347 } 2348 } 2349 2350 private static XEventDispatcher oops_waiter; 2351 private static boolean oops_updated; 2352 private static boolean oops_failed; 2353 private XAtom oops; 2354 private static final long WORKAROUND_SLEEP = 100; 2355 2356 /** 2357 * @inheritDoc 2358 */ 2359 protected boolean syncNativeQueue(final long timeout) { 2360 XBaseWindow win = XBaseWindow.getXAWTRootWindow(); 2361 2362 if (oops_waiter == null) { 2363 oops_waiter = new XEventDispatcher() { 2364 public void dispatchEvent(XEvent e) { 2365 if (e.get_type() == XConstants.SelectionNotify) { 2366 XSelectionEvent pe = e.get_xselection(); 2367 if (pe.get_property() == oops.getAtom()) { 2368 oops_updated = true; 2369 awtLockNotifyAll(); 2370 } else if (pe.get_selection() == XAtom.get("WM_S0").getAtom() && 2371 pe.get_target() == XAtom.get("VERSION").getAtom() && 2372 pe.get_property() == 0 && 2373 XlibWrapper.XGetSelectionOwner(getDisplay(), XAtom.get("WM_S0").getAtom()) == 0) 2374 { 2375 // WM forgot to acquire selection or there is no WM 2376 oops_failed = true; 2377 awtLockNotifyAll(); 2378 } 2379 2380 } 2381 } 2382 }; 2383 } 2384 2385 if (oops == null) { 2386 oops = XAtom.get("OOPS"); 2387 } 2388 2389 awtLock(); 2390 try { 2391 addEventDispatcher(win.getWindow(), oops_waiter); 2392 2393 oops_updated = false; 2394 oops_failed = false; 2395 // Wait for selection notify for oops on win 2396 long event_number = getEventNumber(); 2397 XAtom atom = XAtom.get("WM_S0"); 2398 eventLog.finer("WM_S0 selection owner {0}", XlibWrapper.XGetSelectionOwner(getDisplay(), atom.getAtom())); 2399 XlibWrapper.XConvertSelection(getDisplay(), atom.getAtom(), 2400 XAtom.get("VERSION").getAtom(), oops.getAtom(), 2401 win.getWindow(), XConstants.CurrentTime); 2402 XSync(); 2403 2404 2405 eventLog.finer("Requested OOPS"); 2406 2407 long start = System.currentTimeMillis(); 2408 while (!oops_updated && !oops_failed) { 2409 try { 2410 awtLockWait(timeout); 2411 } catch (InterruptedException e) { 2412 throw new RuntimeException(e); 2413 } 2414 // This "while" is a protection from spurious 2415 // wake-ups. However, we shouldn't wait for too long 2416 if ((System.currentTimeMillis() - start > timeout) && timeout >= 0) { 2417 throw new OperationTimedOut(Long.toString(System.currentTimeMillis() - start)); 2418 } 2419 } 2420 if (oops_failed && getEventNumber() - event_number == 1) { 2421 // If selection update failed we can simply wait some time 2422 // hoping some events will arrive 2423 awtUnlock(); 2424 eventLog.finest("Emergency sleep"); 2425 try { 2426 Thread.sleep(WORKAROUND_SLEEP); 2427 } catch (InterruptedException ie) { 2428 throw new RuntimeException(ie); 2429 } finally { 2430 awtLock(); 2431 } 2432 } 2433 return getEventNumber() - event_number > 2; 2434 } finally { 2435 removeEventDispatcher(win.getWindow(), oops_waiter); 2436 eventLog.finer("Exiting syncNativeQueue"); 2437 awtUnlock(); 2438 } 2439 } 2440 public void grab(Window w) { 2441 if (w.getPeer() != null) { 2442 ((XWindowPeer)w.getPeer()).setGrab(true); 2443 } 2444 } 2445 2446 public void ungrab(Window w) { 2447 if (w.getPeer() != null) { 2448 ((XWindowPeer)w.getPeer()).setGrab(false); 2449 } 2450 } 2451 /** 2452 * Returns if the java.awt.Desktop class is supported on the current 2453 * desktop. 2454 * <p> 2455 * The methods of java.awt.Desktop class are supported on the Gnome desktop. 2456 * Check if the running desktop is Gnome by checking the window manager. 2457 */ 2458 public boolean isDesktopSupported(){ 2459 return XDesktopPeer.isDesktopSupported(); 2460 } 2461 2462 public DesktopPeer createDesktopPeer(Desktop target){ 2463 return new XDesktopPeer(); 2464 } 2465 2466 public boolean areExtraMouseButtonsEnabled() throws HeadlessException { 2467 return areExtraMouseButtonsEnabled; 2468 } 2469 2470 @Override 2471 public boolean isWindowOpacitySupported() { 2472 XNETProtocol net_protocol = XWM.getWM().getNETProtocol(); 2473 2474 if (net_protocol == null) { 2475 return false; 2476 } 2477 2478 return net_protocol.doOpacityProtocol(); 2479 } 2480 2481 @Override 2482 public boolean isWindowShapingSupported() { 2483 return XlibUtil.isShapingSupported(); 2484 } 2485 2486 @Override 2487 public boolean isWindowTranslucencySupported() { 2488 //NOTE: it may not be supported. The actual check is being performed 2489 // at com.sun.awt.AWTUtilities(). In X11 we need to check 2490 // whether there's any translucency-capable GC available. 2491 return true; 2492 } 2493 2494 @Override 2495 public boolean isTranslucencyCapable(GraphicsConfiguration gc) { 2496 if (!(gc instanceof X11GraphicsConfig)) { 2497 return false; 2498 } 2499 return ((X11GraphicsConfig)gc).isTranslucencyCapable(); 2500 } 2501 2502 /** 2503 * Returns the value of "sun.awt.disablegrab" property. Default 2504 * value is {@code false}. 2505 */ 2506 public static boolean getSunAwtDisableGrab() { 2507 return AccessController.doPrivileged(new GetBooleanAction("sun.awt.disablegrab")); 2508 } 2509 }