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