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