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