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