1 /*
   2  * Copyright (c) 2002, 2010, 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 
  26 package sun.awt.X11;
  27 
  28 import java.awt.*;
  29 import java.awt.event.*;
  30 import java.awt.peer.ComponentPeer;
  31 import java.awt.image.ColorModel;
  32 
  33 import java.lang.ref.WeakReference;
  34 
  35 import java.lang.reflect.Field;
  36 import java.lang.reflect.Method;
  37 
  38 import sun.util.logging.PlatformLogger;
  39 
  40 import sun.awt.*;
  41 
  42 import sun.awt.image.PixelConverter;
  43 
  44 import sun.java2d.SunGraphics2D;
  45 import sun.java2d.SurfaceData;
  46 
  47 public class XWindow extends XBaseWindow implements X11ComponentPeer {
  48     private static PlatformLogger log = PlatformLogger.getLogger("sun.awt.X11.XWindow");
  49     private static PlatformLogger insLog = PlatformLogger.getLogger("sun.awt.X11.insets.XWindow");
  50     private static PlatformLogger eventLog = PlatformLogger.getLogger("sun.awt.X11.event.XWindow");
  51     private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.awt.X11.focus.XWindow");
  52     private static PlatformLogger keyEventLog = PlatformLogger.getLogger("sun.awt.X11.kye.XWindow");
  53   /* If a motion comes in while a multi-click is pending,
  54    * allow a smudge factor so that moving the mouse by a small
  55    * amount does not wipe out the multi-click state variables.
  56    */
  57     private final static int AWT_MULTICLICK_SMUDGE = 4;
  58     // ButtonXXX events stuff
  59     static int rbutton = 0;
  60     static int lastX = 0, lastY = 0;
  61     static long lastTime = 0;
  62     static long lastButton = 0;
  63     static WeakReference lastWindowRef = null;
  64     static int clickCount = 0;
  65 
  66     // used to check if we need to re-create surfaceData.
  67     int oldWidth = -1;
  68     int oldHeight = -1;
  69 
  70     protected PropMwmHints mwm_hints;
  71     protected static XAtom wm_protocols;
  72     protected static XAtom wm_delete_window;
  73     protected static XAtom wm_take_focus;
  74 
  75     private boolean stateChanged; // Indicates whether the value on savedState is valid
  76     private int savedState; // Holds last known state of the top-level window
  77 
  78     XWindowAttributesData winAttr;
  79 
  80     protected X11GraphicsConfig graphicsConfig;
  81     protected AwtGraphicsConfigData graphicsConfigData;
  82 
  83     private boolean reparented;
  84 
  85     XWindow parent;
  86 
  87     Component target;
  88 
  89     private static int JAWT_LOCK_ERROR=0x00000001;
  90     private static int JAWT_LOCK_CLIP_CHANGED=0x00000002;
  91     private static int JAWT_LOCK_BOUNDS_CHANGED=0x00000004;
  92     private static int JAWT_LOCK_SURFACE_CHANGED=0x00000008;
  93     private int drawState = JAWT_LOCK_CLIP_CHANGED |
  94     JAWT_LOCK_BOUNDS_CHANGED |
  95     JAWT_LOCK_SURFACE_CHANGED;
  96 
  97     public static final String TARGET = "target",
  98         REPARENTED = "reparented"; // whether it is reparented by default
  99 
 100     SurfaceData surfaceData;
 101 
 102     XRepaintArea paintArea;
 103 
 104     // fallback default font object
 105     private static Font defaultFont;
 106 
 107     static synchronized Font getDefaultFont() {
 108         if (null == defaultFont) {
 109             defaultFont = new Font(Font.DIALOG, Font.PLAIN, 12);
 110         }
 111         return defaultFont;
 112     }
 113 
 114     /* A bitmask keeps the button's numbers as Button1Mask, Button2Mask, Button3Mask
 115      * which are allowed to
 116      * generate the CLICK event after the RELEASE has happened.
 117      * There are conditions that must be true for that sending CLICK event:
 118      * 1) button was initially PRESSED
 119      * 2) no movement or drag has happened until RELEASE
 120     */
 121     private int mouseButtonClickAllowed = 0;
 122 
 123     native int getNativeColor(Color clr, GraphicsConfiguration gc);
 124     native void getWMInsets(long window, long left, long top, long right, long bottom, long border);
 125     native long getTopWindow(long window, long rootWin);
 126     native void getWindowBounds(long window, long x, long y, long width, long height);
 127     private native static void initIDs();
 128 
 129     static {
 130         initIDs();
 131     }
 132 
 133     XWindow(XCreateWindowParams params) {
 134         super(params);
 135     }
 136 
 137     XWindow() {
 138     }
 139 
 140     XWindow(long parentWindow, Rectangle bounds) {
 141         super(new XCreateWindowParams(new Object[] {
 142             BOUNDS, bounds,
 143             PARENT_WINDOW, Long.valueOf(parentWindow)}));
 144     }
 145 
 146     XWindow(Component target, long parentWindow, Rectangle bounds) {
 147         super(new XCreateWindowParams(new Object[] {
 148             BOUNDS, bounds,
 149             PARENT_WINDOW, Long.valueOf(parentWindow),
 150             TARGET, target}));
 151     }
 152 
 153     XWindow(Component target, long parentWindow) {
 154         this(target, parentWindow, new Rectangle(target.getBounds()));
 155     }
 156 
 157     XWindow(Component target) {
 158         this(target, (target.getParent() == null) ? 0 : getParentWindowID(target), new Rectangle(target.getBounds()));
 159     }
 160 
 161     XWindow(Object target) {
 162         this(null, 0, null);
 163     }
 164 
 165     /* This create is used by the XEmbeddedFramePeer since it has to create the window
 166        as a child of the netscape window. This netscape window is passed in as wid */
 167     XWindow(long parentWindow) {
 168         super(new XCreateWindowParams(new Object[] {
 169             PARENT_WINDOW, Long.valueOf(parentWindow),
 170             REPARENTED, Boolean.TRUE,
 171             EMBEDDED, Boolean.TRUE}));
 172     }
 173 
 174     protected void initGraphicsConfiguration() {
 175         graphicsConfig = (X11GraphicsConfig) target.getGraphicsConfiguration();
 176         graphicsConfigData = new AwtGraphicsConfigData(graphicsConfig.getAData());
 177     }
 178 
 179     void preInit(XCreateWindowParams params) {
 180         super.preInit(params);
 181         reparented = Boolean.TRUE.equals(params.get(REPARENTED));
 182 
 183         target = (Component)params.get(TARGET);
 184 
 185         initGraphicsConfiguration();
 186 
 187         AwtGraphicsConfigData gData = getGraphicsConfigurationData();
 188         X11GraphicsConfig config = (X11GraphicsConfig) getGraphicsConfiguration();
 189         XVisualInfo visInfo = gData.get_awt_visInfo();
 190         params.putIfNull(EVENT_MASK, XConstants.KeyPressMask | XConstants.KeyReleaseMask
 191             | XConstants.FocusChangeMask | XConstants.ButtonPressMask | XConstants.ButtonReleaseMask
 192             | XConstants.EnterWindowMask | XConstants.LeaveWindowMask | XConstants.PointerMotionMask
 193             | XConstants.ButtonMotionMask | XConstants.ExposureMask | XConstants.StructureNotifyMask);
 194 
 195         if (target != null) {
 196             params.putIfNull(BOUNDS, new Rectangle(target.getBounds()));
 197         } else {
 198             params.putIfNull(BOUNDS, new Rectangle(0, 0, MIN_SIZE, MIN_SIZE));
 199         }
 200         params.putIfNull(BORDER_PIXEL, Long.valueOf(0));
 201         getColorModel(); // fix 4948833: this call forces the color map to be initialized
 202         params.putIfNull(COLORMAP, gData.get_awt_cmap());
 203         params.putIfNull(DEPTH, gData.get_awt_depth());
 204         params.putIfNull(VISUAL_CLASS, Integer.valueOf((int)XConstants.InputOutput));
 205         params.putIfNull(VISUAL, visInfo.get_visual());
 206         params.putIfNull(VALUE_MASK, XConstants.CWBorderPixel | XConstants.CWEventMask | XConstants.CWColormap);
 207         Long parentWindow = (Long)params.get(PARENT_WINDOW);
 208         if (parentWindow == null || parentWindow.longValue() == 0) {
 209             XToolkit.awtLock();
 210             try {
 211                 int screen = visInfo.get_screen();
 212                 if (screen != -1) {
 213                     params.add(PARENT_WINDOW, XlibWrapper.RootWindow(XToolkit.getDisplay(), screen));
 214                 } else {
 215                     params.add(PARENT_WINDOW, XToolkit.getDefaultRootWindow());
 216                 }
 217             } finally {
 218                 XToolkit.awtUnlock();
 219             }
 220         }
 221 
 222         paintArea = new XRepaintArea();
 223         if (target != null) {
 224             this.parent = getParentXWindowObject(target.getParent());
 225         }
 226 
 227         params.putIfNull(BACKING_STORE, XToolkit.getBackingStoreType());
 228 
 229         XToolkit.awtLock();
 230         try {
 231             if (wm_protocols == null) {
 232                 wm_protocols = XAtom.get("WM_PROTOCOLS");
 233                 wm_delete_window = XAtom.get("WM_DELETE_WINDOW");
 234                 wm_take_focus = XAtom.get("WM_TAKE_FOCUS");
 235             }
 236         }
 237         finally {
 238             XToolkit.awtUnlock();
 239         }
 240         winAttr = new XWindowAttributesData();
 241         savedState = XUtilConstants.WithdrawnState;
 242     }
 243 
 244     void postInit(XCreateWindowParams params) {
 245         super.postInit(params);
 246 
 247         setWMClass(getWMClass());
 248 
 249         surfaceData = graphicsConfig.createSurfaceData(this);
 250         Color c;
 251         if (target != null && (c = target.getBackground()) != null) {
 252             // We need a version of setBackground that does not call repaint !!
 253             // and one that does not get overridden. The problem is that in postInit
 254             // we call setBackground and we dont have all the stuff initialized to
 255             // do a full paint for most peers. So we cannot call setBackground in postInit.
 256             // instead we need to call xSetBackground.
 257             xSetBackground(c);
 258         }
 259     }
 260 
 261     public GraphicsConfiguration getGraphicsConfiguration() {
 262         if (graphicsConfig == null) {
 263             initGraphicsConfiguration();
 264         }
 265         return graphicsConfig;
 266     }
 267 
 268     public AwtGraphicsConfigData getGraphicsConfigurationData() {
 269         if (graphicsConfigData == null) {
 270             initGraphicsConfiguration();
 271         }
 272         return graphicsConfigData;
 273     }
 274 
 275     protected String[] getWMClass() {
 276         return new String[] {XToolkit.getCorrectXIDString(getClass().getName()), XToolkit.getAWTAppClassName()};
 277     }
 278 
 279     void setReparented(boolean newValue) {
 280         reparented = newValue;
 281     }
 282 
 283     boolean isReparented() {
 284         return reparented;
 285     }
 286 
 287     static long getParentWindowID(Component target) {
 288 
 289         ComponentPeer peer = target.getParent().getPeer();
 290         Component temp = target.getParent();
 291         while (!(peer instanceof XWindow))
 292         {
 293             temp = temp.getParent();
 294             peer = temp.getPeer();
 295         }
 296 
 297         if (peer != null && peer instanceof XWindow)
 298             return ((XWindow)peer).getContentWindow();
 299         else return 0;
 300     }
 301 
 302 
 303     static XWindow getParentXWindowObject(Component target) {
 304         if (target == null) return null;
 305         Component temp = target.getParent();
 306         if (temp == null) return null;
 307         ComponentPeer peer = temp.getPeer();
 308         if (peer == null) return null;
 309         while ((peer != null) && !(peer instanceof XWindow))
 310         {
 311             temp = temp.getParent();
 312             peer = temp.getPeer();
 313         }
 314         if (peer != null && peer instanceof XWindow)
 315             return (XWindow) peer;
 316         else return null;
 317     }
 318 
 319 
 320     boolean isParentOf(XWindow win) {
 321         if (!(target instanceof Container) || win == null || win.getTarget() == null) {
 322             return false;
 323         }
 324         Container parent = AWTAccessor.getComponentAccessor().getParent(win.target);
 325         while (parent != null && parent != target) {
 326             parent = AWTAccessor.getComponentAccessor().getParent(parent);
 327         }
 328         return (parent == target);
 329     }
 330 
 331     public Object getTarget() {
 332         return target;
 333     }
 334     public Component getEventSource() {
 335         return target;
 336     }
 337 
 338     public ColorModel getColorModel(int transparency) {
 339         return graphicsConfig.getColorModel (transparency);
 340     }
 341 
 342     public ColorModel getColorModel() {
 343         if (graphicsConfig != null) {
 344             return graphicsConfig.getColorModel ();
 345         }
 346         else {
 347             return XToolkit.getStaticColorModel();
 348         }
 349     }
 350 
 351     Graphics getGraphics(SurfaceData surfData, Color afore, Color aback, Font afont) {
 352         if (surfData == null) return null;
 353 
 354         Component target = (Component) this.target;
 355 
 356         /* Fix for bug 4746122. Color and Font shouldn't be null */
 357         Color bgColor = aback;
 358         if (bgColor == null) {
 359             bgColor = SystemColor.window;
 360         }
 361         Color fgColor = afore;
 362         if (fgColor == null) {
 363             fgColor = SystemColor.windowText;
 364         }
 365         Font font = afont;
 366         if (font == null) {
 367             font = XWindow.getDefaultFont();
 368         }
 369         return new SunGraphics2D(surfData, fgColor, bgColor, font);
 370     }
 371 
 372     public Graphics getGraphics() {
 373         return getGraphics(surfaceData,
 374                            target.getForeground(),
 375                            target.getBackground(),
 376                            target.getFont());
 377     }
 378 
 379     public FontMetrics getFontMetrics(Font font) {
 380         return Toolkit.getDefaultToolkit().getFontMetrics(font);
 381     }
 382 
 383     public Rectangle getTargetBounds() {
 384         return target.getBounds();
 385     }
 386 
 387     /**
 388      * Returns true if the event has been handled and should not be
 389      * posted to Java.
 390      */
 391     boolean prePostEvent(AWTEvent e) {
 392         return false;
 393     }
 394 
 395     static Method m_sendMessage;
 396     static void sendEvent(final AWTEvent e) {
 397         // The uses of this method imply that the incoming event is system-generated
 398         SunToolkit.setSystemGenerated(e);
 399         PeerEvent pe = new PeerEvent(Toolkit.getDefaultToolkit(), new Runnable() {
 400                 public void run() {
 401                     AWTAccessor.getAWTEventAccessor().setPosted(e);
 402                     ((Component)e.getSource()).dispatchEvent(e);
 403                 }
 404             }, PeerEvent.ULTIMATE_PRIORITY_EVENT);
 405         if (focusLog.isLoggable(PlatformLogger.FINER) && (e instanceof FocusEvent)) focusLog.finer("Sending " + e);
 406         XToolkit.postEvent(XToolkit.targetToAppContext(e.getSource()), pe);
 407     }
 408 
 409 
 410 /*
 411  * Post an event to the event queue.
 412  */
 413 // NOTE: This method may be called by privileged threads.
 414 //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 415     void postEvent(AWTEvent event) {
 416         XToolkit.postEvent(XToolkit.targetToAppContext(event.getSource()), event);
 417     }
 418 
 419     static void postEventStatic(AWTEvent event) {
 420         XToolkit.postEvent(XToolkit.targetToAppContext(event.getSource()), event);
 421     }
 422 
 423     public void postEventToEventQueue(final AWTEvent event) {
 424         //fix for 6239938 : Choice drop-down does not disappear when it loses focus, on XToolkit
 425         if (!prePostEvent(event)) {
 426             //event hasn't been handled and must be posted to EventQueue
 427             postEvent(event);
 428         }
 429     }
 430 
 431     // overriden in XCanvasPeer
 432     protected boolean doEraseBackground() {
 433         return true;
 434     }
 435 
 436     // We need a version of setBackground that does not call repaint !!
 437     // and one that does not get overridden. The problem is that in postInit
 438     // we call setBackground and we dont have all the stuff initialized to
 439     // do a full paint for most peers. So we cannot call setBackground in postInit.
 440     final public void xSetBackground(Color c) {
 441         XToolkit.awtLock();
 442         try {
 443             winBackground(c);
 444             // fix for 6558510: handle sun.awt.noerasebackground flag,
 445             // see doEraseBackground() and preInit() methods in XCanvasPeer
 446             if (!doEraseBackground()) {
 447                 return;
 448             }
 449             // 6304250: XAWT: Items in choice show a blue border on OpenGL + Solaris10 when background color is set
 450             // Note: When OGL is enabled, surfaceData.pixelFor() will not
 451             // return a pixel value appropriate for passing to
 452             // XSetWindowBackground().  Therefore, we will use the ColorModel
 453             // for this component in order to calculate a pixel value from
 454             // the given RGB value.
 455             ColorModel cm = getColorModel();
 456             int pixel = PixelConverter.instance.rgbToPixel(c.getRGB(), cm);
 457             XlibWrapper.XSetWindowBackground(XToolkit.getDisplay(), getContentWindow(), pixel);
 458         }
 459         finally {
 460             XToolkit.awtUnlock();
 461         }
 462     }
 463 
 464     public void setBackground(Color c) {
 465         xSetBackground(c);
 466     }
 467 
 468     Color backgroundColor;
 469     void winBackground(Color c) {
 470         backgroundColor = c;
 471     }
 472 
 473     public Color getWinBackground() {
 474         Color c = null;
 475 
 476         if (backgroundColor != null) {
 477             c = backgroundColor;
 478         } else if (parent != null) {
 479             c = parent.getWinBackground();
 480         }
 481 
 482         if (c instanceof SystemColor) {
 483             c = new Color(c.getRGB());
 484         }
 485 
 486         return c;
 487     }
 488 
 489     public boolean isEmbedded() {
 490         return embedded;
 491     }
 492     public  void repaint(int x,int y, int width, int height) {
 493         if (!isVisible() || getWidth() == 0 || getHeight() == 0) {
 494             return;
 495         }
 496         Graphics g = getGraphics();
 497         if (g != null) {
 498             try {
 499                 g.setClip(x,y,width,height);
 500                 paint(g);
 501             } finally {
 502                 g.dispose();
 503             }
 504         }
 505     }
 506     void repaint() {
 507         if (!isVisible() || getWidth() == 0 || getHeight() == 0) {
 508             return;
 509         }
 510         final Graphics g = getGraphics();
 511         if (g != null) {
 512             try {
 513                 paint(g);
 514             } finally {
 515                 g.dispose();
 516             }
 517         }
 518     }
 519     public void paint(final Graphics g) {
 520         // paint peer
 521         paintPeer(g);
 522     }
 523 
 524     void paintPeer(final Graphics g) {
 525     }
 526     //used by Peers to avoid flickering withing paint()
 527     protected void flush(){
 528         XToolkit.awtLock();
 529         try {
 530             XlibWrapper.XFlush(XToolkit.getDisplay());
 531         } finally {
 532             XToolkit.awtUnlock();
 533         }
 534     }
 535 
 536     public void popup(int x, int y, int width, int height) {
 537         // TBD: grab the pointer
 538         xSetBounds(x, y, width, height);
 539     }
 540 
 541     public void handleExposeEvent(XEvent xev) {
 542         super.handleExposeEvent(xev);
 543         XExposeEvent xe = xev.get_xexpose();
 544         if (isEventDisabled(xev)) {
 545             return;
 546         }
 547         int x = xe.get_x();
 548         int y = xe.get_y();
 549         int w = xe.get_width();
 550         int h = xe.get_height();
 551 
 552         Component target = (Component)getEventSource();
 553         AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
 554 
 555         if (!compAccessor.getIgnoreRepaint(target)
 556             && compAccessor.getWidth(target) != 0
 557             && compAccessor.getHeight(target) != 0)
 558         {
 559             handleExposeEvent(target, x, y, w, h);
 560         }
 561     }
 562 
 563     public void handleExposeEvent(Component target, int x, int y, int w, int h) {
 564         PaintEvent event = PaintEventDispatcher.getPaintEventDispatcher().
 565             createPaintEvent(target, x, y, w, h);
 566         if (event != null) {
 567             postEventToEventQueue(event);
 568         }
 569     }
 570 
 571     static int getModifiers(int state, int button, int keyCode) {
 572         return getModifiers(state, button, keyCode, 0,  false);
 573     }
 574 
 575     static int getModifiers(int state, int button, int keyCode, int type, boolean wheel_mouse) {
 576         int modifiers = 0;
 577 
 578         if (((state & XConstants.ShiftMask) != 0) ^ (keyCode == KeyEvent.VK_SHIFT)) {
 579             modifiers |= InputEvent.SHIFT_DOWN_MASK;
 580         }
 581         if (((state & XConstants.ControlMask) != 0) ^ (keyCode == KeyEvent.VK_CONTROL)) {
 582             modifiers |= InputEvent.CTRL_DOWN_MASK;
 583         }
 584         if (((state & XToolkit.metaMask) != 0) ^ (keyCode == KeyEvent.VK_META)) {
 585             modifiers |= InputEvent.META_DOWN_MASK;
 586         }
 587         if (((state & XToolkit.altMask) != 0) ^ (keyCode == KeyEvent.VK_ALT)) {
 588             modifiers |= InputEvent.ALT_DOWN_MASK;
 589         }
 590         if (((state & XToolkit.modeSwitchMask) != 0) ^ (keyCode == KeyEvent.VK_ALT_GRAPH)) {
 591             modifiers |= InputEvent.ALT_GRAPH_DOWN_MASK;
 592         }
 593         //InputEvent.BUTTON_DOWN_MASK array is starting from BUTTON1_DOWN_MASK on index == 0.
 594         // button currently reflects a real button number and starts from 1. (except NOBUTTON which is zero )
 595 
 596         /* this is an attempt to refactor button IDs in : MouseEvent, InputEvent, XlibWrapper and XWindow.*/
 597 
 598         //reflects a button number similar to MouseEvent.BUTTON1, 2, 3 etc.
 599         for (int i = 0; i < XConstants.buttons.length; i ++){
 600             //modifier should be added if :
 601             // 1) current button is now still in PRESSED state (means that user just pressed mouse but not released yet) or
 602             // 2) if Xsystem reports that "state" represents that button was just released. This only happens on RELEASE with 1,2,3 buttons.
 603             // ONLY one of these conditions should be TRUE to add that modifier.
 604             if (((state & XlibUtil.getButtonMask(i + 1)) != 0) != (button == XConstants.buttons[i])){
 605                 //exclude wheel buttons from adding their numbers as modifiers
 606                 if (!wheel_mouse) {
 607                     modifiers |= InputEvent.getMaskForButton(i+1);
 608                 }
 609             }
 610         }
 611         return modifiers;
 612     }
 613 
 614     static int getXModifiers(AWTKeyStroke stroke) {
 615         int mods = stroke.getModifiers();
 616         int res = 0;
 617         if ((mods & (InputEvent.SHIFT_DOWN_MASK | InputEvent.SHIFT_MASK)) != 0) {
 618             res |= XConstants.ShiftMask;
 619         }
 620         if ((mods & (InputEvent.CTRL_DOWN_MASK | InputEvent.CTRL_MASK)) != 0) {
 621             res |= XConstants.ControlMask;
 622         }
 623         if ((mods & (InputEvent.ALT_DOWN_MASK | InputEvent.ALT_MASK)) != 0) {
 624             res |= XToolkit.altMask;
 625         }
 626         if ((mods & (InputEvent.META_DOWN_MASK | InputEvent.META_MASK)) != 0) {
 627             res |= XToolkit.metaMask;
 628         }
 629         if ((mods & (InputEvent.ALT_GRAPH_DOWN_MASK | InputEvent.ALT_GRAPH_MASK)) != 0) {
 630             res |= XToolkit.modeSwitchMask;
 631         }
 632         return res;
 633     }
 634 
 635     /**
 636      * Returns true if this event is disabled and shouldn't be passed to Java.
 637      * Default implementation returns false for all events.
 638      */
 639     static int getRightButtonNumber() {
 640         if (rbutton == 0) { // not initialized yet
 641             XToolkit.awtLock();
 642             try {
 643                 rbutton = XlibWrapper.XGetPointerMapping(XToolkit.getDisplay(), XlibWrapper.ibuffer, 3);
 644             }
 645             finally {
 646                 XToolkit.awtUnlock();
 647             }
 648         }
 649         return rbutton;
 650     }
 651 
 652     static int getMouseMovementSmudge() {
 653         //TODO: It's possible to read corresponding settings
 654         return AWT_MULTICLICK_SMUDGE;
 655     }
 656 
 657     public void handleButtonPressRelease(XEvent xev) {
 658         super.handleButtonPressRelease(xev);
 659         XButtonEvent xbe = xev.get_xbutton();
 660         if (isEventDisabled(xev)) {
 661             return;
 662         }
 663         if (eventLog.isLoggable(PlatformLogger.FINE)) eventLog.fine(xbe.toString());
 664         long when;
 665         int modifiers;
 666         boolean popupTrigger = false;
 667         int button=0;
 668         boolean wheel_mouse = false;
 669         int lbutton = xbe.get_button();
 670         /*
 671          * Ignore the buttons above 20 due to the bit limit for
 672          * InputEvent.BUTTON_DOWN_MASK.
 673          * One more bit is reserved for FIRST_HIGH_BIT.
 674          */
 675         if (lbutton > SunToolkit.MAX_BUTTONS_SUPPORTED) {
 676             return;
 677         }
 678         int type = xev.get_type();
 679         when = xbe.get_time();
 680         long jWhen = XToolkit.nowMillisUTC_offset(when);
 681 
 682         int x = xbe.get_x();
 683         int y = xbe.get_y();
 684         if (xev.get_xany().get_window() != window) {
 685             Point localXY = toLocal(xbe.get_x_root(), xbe.get_y_root());
 686             x = localXY.x;
 687             y = localXY.y;
 688         }
 689 
 690         if (type == XConstants.ButtonPress) {
 691             //Allow this mouse button to generate CLICK event on next ButtonRelease
 692             mouseButtonClickAllowed |= XlibUtil.getButtonMask(lbutton);
 693             XWindow lastWindow = (lastWindowRef != null) ? ((XWindow)lastWindowRef.get()):(null);
 694             /*
 695                multiclick checking
 696             */
 697             if (eventLog.isLoggable(PlatformLogger.FINEST)) eventLog.finest("lastWindow = " + lastWindow + ", lastButton "
 698                                                                    + lastButton + ", lastTime " + lastTime + ", multiClickTime "
 699                                                                    + XToolkit.getMultiClickTime());
 700             if (lastWindow == this && lastButton == lbutton && (when - lastTime) < XToolkit.getMultiClickTime()) {
 701                 clickCount++;
 702             } else {
 703                 clickCount = 1;
 704                 lastWindowRef = new WeakReference(this);
 705                 lastButton = lbutton;
 706                 lastX = x;
 707                 lastY = y;
 708             }
 709             lastTime = when;
 710 
 711 
 712             /*
 713                Check for popup trigger !!
 714             */
 715             if (lbutton == getRightButtonNumber() || lbutton > 2) {
 716                 popupTrigger = true;
 717             } else {
 718                 popupTrigger = false;
 719             }
 720         }
 721 
 722         button = XConstants.buttons[lbutton - 1];
 723         // 4 and 5 buttons are usually considered assigned to a first wheel
 724         if (lbutton == XConstants.buttons[3] ||
 725             lbutton == XConstants.buttons[4]) {
 726             wheel_mouse = true;
 727         }
 728 
 729         // mapping extra buttons to numbers starting from 4.
 730         if ((button > XConstants.buttons[4]) && (!Toolkit.getDefaultToolkit().areExtraMouseButtonsEnabled())){
 731             return;
 732         }
 733 
 734         if (button > XConstants.buttons[4]){
 735             button -= 2;
 736         }
 737         modifiers = getModifiers(xbe.get_state(),button,0, type, wheel_mouse);
 738 
 739         if (!wheel_mouse) {
 740             MouseEvent me = new MouseEvent((Component)getEventSource(),
 741                                            type == XConstants.ButtonPress ? MouseEvent.MOUSE_PRESSED : MouseEvent.MOUSE_RELEASED,
 742                                            jWhen,modifiers, x, y,
 743                                            xbe.get_x_root(),
 744                                            xbe.get_y_root(),
 745                                            clickCount,popupTrigger,button);
 746 
 747             postEventToEventQueue(me);
 748 
 749             if ((type == XConstants.ButtonRelease) &&
 750                 ((mouseButtonClickAllowed & XlibUtil.getButtonMask(lbutton)) != 0) ) // No up-button in the drag-state
 751             {
 752                 postEventToEventQueue(me = new MouseEvent((Component)getEventSource(),
 753                                                      MouseEvent.MOUSE_CLICKED,
 754                                                      jWhen,
 755                                                      modifiers,
 756                                                      x, y,
 757                                                      xbe.get_x_root(),
 758                                                      xbe.get_y_root(),
 759                                                      clickCount,
 760                                                      false, button));
 761             }
 762 
 763         }
 764         else {
 765             if (xev.get_type() == XConstants.ButtonPress) {
 766                 MouseWheelEvent mwe = new MouseWheelEvent((Component)getEventSource(),MouseEvent.MOUSE_WHEEL, jWhen,
 767                                                           modifiers,
 768                                                           x, y,
 769                                                           xbe.get_x_root(),
 770                                                           xbe.get_y_root(),
 771                                                           1,false,MouseWheelEvent.WHEEL_UNIT_SCROLL,
 772                                                           3,button==4 ?  -1 : 1);
 773                 postEventToEventQueue(mwe);
 774             }
 775         }
 776 
 777         /* Update the state variable AFTER the CLICKED event post. */
 778         if (type == XConstants.ButtonRelease) {
 779             /* Exclude this mouse button from allowed list.*/
 780             mouseButtonClickAllowed &= ~ XlibUtil.getButtonMask(lbutton);
 781         }
 782     }
 783 
 784     public void handleMotionNotify(XEvent xev) {
 785         super.handleMotionNotify(xev);
 786         XMotionEvent xme = xev.get_xmotion();
 787         if (isEventDisabled(xev)) {
 788             return;
 789         }
 790 
 791         int mouseKeyState = 0; //(xme.get_state() & (XConstants.buttonsMask[0] | XConstants.buttonsMask[1] | XConstants.buttonsMask[2]));
 792 
 793         //this doesn't work for extra buttons because Xsystem is sending state==0 for every extra button event.
 794         // we can't correct it in MouseEvent class as we done it with modifiers, because exact type (DRAG|MOVE)
 795         // should be passed from XWindow.
 796         final int buttonsNumber = XToolkit.getNumberOfButtonsForMask();
 797 
 798         for (int i = 0; i < buttonsNumber; i++){
 799             // TODO : here is the bug in WM: extra buttons doesn't have state!=0 as they should.
 800             if ((i != 4) && (i != 5)) {
 801                 mouseKeyState = mouseKeyState | (xme.get_state() & XlibUtil.getButtonMask(i + 1));
 802             }
 803         }
 804 
 805         boolean isDragging = (mouseKeyState != 0);
 806         int mouseEventType = 0;
 807 
 808         if (isDragging) {
 809             mouseEventType = MouseEvent.MOUSE_DRAGGED;
 810         } else {
 811             mouseEventType = MouseEvent.MOUSE_MOVED;
 812         }
 813 
 814         /*
 815            Fix for 6176814 .  Add multiclick checking.
 816         */
 817         int x = xme.get_x();
 818         int y = xme.get_y();
 819         XWindow lastWindow = (lastWindowRef != null) ? ((XWindow)lastWindowRef.get()):(null);
 820 
 821         if (!(lastWindow == this &&
 822               (xme.get_time() - lastTime) < XToolkit.getMultiClickTime()  &&
 823               (Math.abs(lastX - x) < AWT_MULTICLICK_SMUDGE &&
 824                Math.abs(lastY - y) < AWT_MULTICLICK_SMUDGE))) {
 825           clickCount = 0;
 826           lastWindowRef = null;
 827           mouseButtonClickAllowed = 0;
 828           lastTime = 0;
 829           lastX = 0;
 830           lastY = 0;
 831         }
 832 
 833         long jWhen = XToolkit.nowMillisUTC_offset(xme.get_time());
 834         int modifiers = getModifiers(xme.get_state(), 0, 0);
 835         boolean popupTrigger = false;
 836 
 837         Component source = (Component)getEventSource();
 838 
 839         if (xme.get_window() != window) {
 840             Point localXY = toLocal(xme.get_x_root(), xme.get_y_root());
 841             x = localXY.x;
 842             y = localXY.y;
 843         }
 844         /* Fix for 5039416.
 845          * According to canvas.c we shouldn't post any MouseEvent if mouse is dragging and clickCount!=0.
 846          */
 847         if ((isDragging && clickCount == 0) || !isDragging) {
 848             MouseEvent mme = new MouseEvent(source, mouseEventType, jWhen,
 849                                             modifiers, x, y, xme.get_x_root(), xme.get_y_root(),
 850                                             clickCount, popupTrigger, MouseEvent.NOBUTTON);
 851             postEventToEventQueue(mme);
 852         }
 853     }
 854 
 855 
 856     // REMIND: need to implement looking for disabled events
 857     public native boolean x11inputMethodLookupString(long event, long [] keysymArray);
 858     native boolean haveCurrentX11InputMethodInstance();
 859 
 860     private boolean mouseAboveMe;
 861 
 862     public boolean isMouseAbove() {
 863         synchronized (getStateLock()) {
 864             return mouseAboveMe;
 865         }
 866     }
 867     protected void setMouseAbove(boolean above) {
 868         synchronized (getStateLock()) {
 869             mouseAboveMe = above;
 870         }
 871     }
 872 
 873     protected void enterNotify(long window) {
 874         if (window == getWindow()) {
 875             setMouseAbove(true);
 876         }
 877     }
 878     protected void leaveNotify(long window) {
 879         if (window == getWindow()) {
 880             setMouseAbove(false);
 881         }
 882     }
 883 
 884     public void handleXCrossingEvent(XEvent xev) {
 885         super.handleXCrossingEvent(xev);
 886         XCrossingEvent xce = xev.get_xcrossing();
 887 
 888         if (eventLog.isLoggable(PlatformLogger.FINEST)) eventLog.finest(xce.toString());
 889 
 890         if (xce.get_type() == XConstants.EnterNotify) {
 891             enterNotify(xce.get_window());
 892         } else { // LeaveNotify:
 893             leaveNotify(xce.get_window());
 894         }
 895 
 896         // Skip event If it was caused by a grab
 897         // This is needed because on displays with focus-follows-mouse on MousePress X system generates
 898         // two XCrossing events with mode != NormalNotify. First of them notifies that the mouse has left
 899         // current component. Second one notifies that it has entered into the same component.
 900         // This looks like the window under the mouse has actually changed and Java handle these  events
 901         // accordingly. This leads to impossibility to make a double click on Component (6404708)
 902         XWindowPeer toplevel = getToplevelXWindow();
 903         if (toplevel != null && !toplevel.isModalBlocked()){
 904             if (xce.get_mode() != XConstants.NotifyNormal) {
 905                 // 6404708 : need update cursor in accordance with skipping Leave/EnterNotify event
 906                 // whereas it doesn't need to handled further.
 907                 if (xce.get_type() == XConstants.EnterNotify) {
 908                     XAwtState.setComponentMouseEntered(getEventSource());
 909                     XGlobalCursorManager.nativeUpdateCursor(getEventSource());
 910                 } else { // LeaveNotify:
 911                     XAwtState.setComponentMouseEntered(null);
 912                 }
 913                 return;
 914             }
 915         }
 916         // X sends XCrossing to all hierarchy so if the edge of child equals to
 917         // ancestor and mouse enters child, the ancestor will get an event too.
 918         // From java point the event is bogus as ancestor is obscured, so if
 919         // the child can get java event itself, we skip it on ancestor.
 920         long childWnd = xce.get_subwindow();
 921         if (childWnd != XConstants.None) {
 922             XBaseWindow child = XToolkit.windowToXWindow(childWnd);
 923             if (child != null && child instanceof XWindow &&
 924                 !child.isEventDisabled(xev))
 925             {
 926                 return;
 927             }
 928         }
 929 
 930         // Remember old component with mouse to have the opportunity to send it MOUSE_EXITED.
 931         final Component compWithMouse = XAwtState.getComponentMouseEntered();
 932         if (toplevel != null) {
 933             if(!toplevel.isModalBlocked()){
 934                 if (xce.get_type() == XConstants.EnterNotify) {
 935                     // Change XAwtState's component mouse entered to the up-to-date one before requesting
 936                     // to update the cursor since XAwtState.getComponentMouseEntered() is used when the
 937                     // cursor is updated (in XGlobalCursorManager.findHeavyweightUnderCursor()).
 938                     XAwtState.setComponentMouseEntered(getEventSource());
 939                     XGlobalCursorManager.nativeUpdateCursor(getEventSource());
 940                 } else { // LeaveNotify:
 941                     XAwtState.setComponentMouseEntered(null);
 942                 }
 943             } else {
 944                 ((XComponentPeer) AWTAccessor.getComponentAccessor().getPeer(target))
 945                     .pSetCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
 946             }
 947         }
 948 
 949         if (isEventDisabled(xev)) {
 950             return;
 951         }
 952 
 953         long jWhen = XToolkit.nowMillisUTC_offset(xce.get_time());
 954         int modifiers = getModifiers(xce.get_state(),0,0);
 955         int clickCount = 0;
 956         boolean popupTrigger = false;
 957         int x = xce.get_x();
 958         int y = xce.get_y();
 959         if (xce.get_window() != window) {
 960             Point localXY = toLocal(xce.get_x_root(), xce.get_y_root());
 961             x = localXY.x;
 962             y = localXY.y;
 963         }
 964 
 965         // This code tracks boundary crossing and ensures MOUSE_ENTER/EXIT
 966         // are posted in alternate pairs
 967         if (compWithMouse != null) {
 968             MouseEvent me = new MouseEvent(compWithMouse,
 969                 MouseEvent.MOUSE_EXITED, jWhen, modifiers, xce.get_x(),
 970                 xce.get_y(), xce.get_x_root(), xce.get_y_root(), clickCount, popupTrigger,
 971                 MouseEvent.NOBUTTON);
 972             postEventToEventQueue(me);
 973             eventLog.finest("Clearing last window ref");
 974             lastWindowRef = null;
 975         }
 976         if (xce.get_type() == XConstants.EnterNotify) {
 977             MouseEvent me = new MouseEvent(getEventSource(), MouseEvent.MOUSE_ENTERED,
 978                 jWhen, modifiers, xce.get_x(), xce.get_y(), xce.get_x_root(), xce.get_y_root(), clickCount,
 979                 popupTrigger, MouseEvent.NOBUTTON);
 980             postEventToEventQueue(me);
 981         }
 982     }
 983 
 984     public void doLayout(int x, int y, int width, int height) {}
 985 
 986     public void handleConfigureNotifyEvent(XEvent xev) {
 987         Rectangle oldBounds = getBounds();
 988 
 989         super.handleConfigureNotifyEvent(xev);
 990         insLog.finer("Configure, {0}, event disabled: {1}",
 991                      xev.get_xconfigure(), isEventDisabled(xev));
 992         if (isEventDisabled(xev)) {
 993             return;
 994         }
 995 
 996 //  if ( Check if it's a resize, a move, or a stacking order change )
 997 //  {
 998         Rectangle bounds = getBounds();
 999         if (!bounds.getSize().equals(oldBounds.getSize())) {
1000             postEventToEventQueue(new ComponentEvent(getEventSource(), ComponentEvent.COMPONENT_RESIZED));
1001         }
1002         if (!bounds.getLocation().equals(oldBounds.getLocation())) {
1003             postEventToEventQueue(new ComponentEvent(getEventSource(), ComponentEvent.COMPONENT_MOVED));
1004         }
1005 //  }
1006     }
1007 
1008     public void handleMapNotifyEvent(XEvent xev) {
1009         super.handleMapNotifyEvent(xev);
1010         log.fine("Mapped {0}", this);
1011         if (isEventDisabled(xev)) {
1012             return;
1013         }
1014         ComponentEvent ce;
1015 
1016         ce = new ComponentEvent(getEventSource(), ComponentEvent.COMPONENT_SHOWN);
1017         postEventToEventQueue(ce);
1018     }
1019 
1020     public void handleUnmapNotifyEvent(XEvent xev) {
1021         super.handleUnmapNotifyEvent(xev);
1022         if (isEventDisabled(xev)) {
1023             return;
1024         }
1025         ComponentEvent ce;
1026 
1027         ce = new ComponentEvent(target, ComponentEvent.COMPONENT_HIDDEN);
1028         postEventToEventQueue(ce);
1029     }
1030 
1031     private void dumpKeysymArray(XKeyEvent ev) {
1032         keyEventLog.fine("  "+Long.toHexString(XlibWrapper.XKeycodeToKeysym(XToolkit.getDisplay(), ev.get_keycode(), 0))+
1033                          "\n        "+Long.toHexString(XlibWrapper.XKeycodeToKeysym(XToolkit.getDisplay(), ev.get_keycode(), 1))+
1034                          "\n        "+Long.toHexString(XlibWrapper.XKeycodeToKeysym(XToolkit.getDisplay(), ev.get_keycode(), 2))+
1035                          "\n        "+Long.toHexString(XlibWrapper.XKeycodeToKeysym(XToolkit.getDisplay(), ev.get_keycode(), 3)));
1036     }
1037     /**
1038        Return unicode character or 0 if no correspondent character found.
1039        Parameter is a keysym basically from keysymdef.h
1040        XXX: how about vendor keys? Is there some with Unicode value and not in the list?
1041     */
1042     int keysymToUnicode( long keysym, int state ) {
1043         return XKeysym.convertKeysym( keysym, state );
1044     }
1045     int keyEventType2Id( int xEventType ) {
1046         return xEventType == XConstants.KeyPress ? java.awt.event.KeyEvent.KEY_PRESSED :
1047                xEventType == XConstants.KeyRelease ? java.awt.event.KeyEvent.KEY_RELEASED : 0;
1048     }
1049     static private long xkeycodeToKeysym(XKeyEvent ev) {
1050         return XKeysym.getKeysym( ev );
1051     }
1052     private long xkeycodeToPrimaryKeysym(XKeyEvent ev) {
1053         return XKeysym.xkeycode2primary_keysym( ev );
1054     }
1055     static private int primaryUnicode2JavaKeycode(int uni) {
1056         return (uni > 0? sun.awt.ExtendedKeyCodes.getExtendedKeyCodeForChar(uni) : 0);
1057         //return (uni > 0? uni + 0x01000000 : 0);
1058     }
1059     void logIncomingKeyEvent(XKeyEvent ev) {
1060         keyEventLog.fine("--XWindow.java:handleKeyEvent:"+ev);
1061         dumpKeysymArray(ev);
1062         keyEventLog.fine("XXXXXXXXXXXXXX javakeycode will be most probably:0x"+ Integer.toHexString(XKeysym.getJavaKeycodeOnly(ev)));
1063     }
1064     public void handleKeyPress(XEvent xev) {
1065         super.handleKeyPress(xev);
1066         XKeyEvent ev = xev.get_xkey();
1067         if (eventLog.isLoggable(PlatformLogger.FINE)) eventLog.fine(ev.toString());
1068         if (isEventDisabled(xev)) {
1069             return;
1070         }
1071         handleKeyPress(ev);
1072     }
1073     // called directly from this package, unlike handleKeyRelease.
1074     // un-final it if you need to override it in a subclass.
1075     final void handleKeyPress(XKeyEvent ev) {
1076         long keysym[] = new long[2];
1077         int unicodeKey = 0;
1078         keysym[0] = XConstants.NoSymbol;
1079 
1080         if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
1081             logIncomingKeyEvent( ev );
1082         }
1083         if ( //TODO check if there's an active input method instance
1084              // without calling a native method. Is it necessary though?
1085             haveCurrentX11InputMethodInstance()) {
1086             if (x11inputMethodLookupString(ev.pData, keysym)) {
1087                 if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
1088                     keyEventLog.fine("--XWindow.java XIM did process event; return; dec keysym processed:"+(keysym[0])+
1089                                    "; hex keysym processed:"+Long.toHexString(keysym[0])
1090                                    );
1091                 }
1092                 return;
1093             }else {
1094                 unicodeKey = keysymToUnicode( keysym[0], ev.get_state() );
1095                 if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
1096                     keyEventLog.fine("--XWindow.java XIM did NOT process event, hex keysym:"+Long.toHexString(keysym[0])+"\n"+
1097                                      "                                         unicode key:"+Integer.toHexString((int)unicodeKey));
1098                 }
1099             }
1100         }else  {
1101             // No input method instance found. For example, there's a Java Input Method.
1102             // Produce do-it-yourself keysym and perhaps unicode character.
1103             keysym[0] = xkeycodeToKeysym(ev);
1104             unicodeKey = keysymToUnicode( keysym[0], ev.get_state() );
1105             if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
1106                 keyEventLog.fine("--XWindow.java XIM is absent;             hex keysym:"+Long.toHexString(keysym[0])+"\n"+
1107                                  "                                         unicode key:"+Integer.toHexString((int)unicodeKey));
1108             }
1109         }
1110         // Keysym should be converted to Unicode, if possible and necessary,
1111         // and Java KeyEvent keycode should be calculated.
1112         // For press we should post pressed & typed Java events.
1113         //
1114         // Press event might be not processed to this time because
1115         //  (1) either XIM could not handle it or
1116         //  (2) it was Latin 1:1 mapping.
1117         //
1118         // Preserve modifiers to get Java key code for dead keys
1119         boolean isDeadKey = isDeadKey(keysym[0]);
1120         XKeysym.Keysym2JavaKeycode jkc = isDeadKey ? XKeysym.getJavaKeycode(keysym[0])
1121                 : XKeysym.getJavaKeycode(ev);
1122         if( jkc == null ) {
1123             jkc = new XKeysym.Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_UNDEFINED, java.awt.event.KeyEvent.KEY_LOCATION_UNKNOWN);
1124         }
1125 
1126         // Take the first keysym from a keysym array associated with the XKeyevent
1127         // and convert it to Unicode. Then, even if a Java keycode for the keystroke
1128         // is undefined, we still have a guess of what has been engraved on a keytop.
1129         int unicodeFromPrimaryKeysym = keysymToUnicode( xkeycodeToPrimaryKeysym(ev) ,0);
1130 
1131         if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
1132             keyEventLog.fine(">>>Fire Event:"+
1133                (ev.get_type() == XConstants.KeyPress ? "KEY_PRESSED; " : "KEY_RELEASED; ")+
1134                "jkeycode:decimal="+jkc.getJavaKeycode()+
1135                ", hex=0x"+Integer.toHexString(jkc.getJavaKeycode())+"; "+
1136                " legacy jkeycode: decimal="+XKeysym.getLegacyJavaKeycodeOnly(ev)+
1137                ", hex=0x"+Integer.toHexString(XKeysym.getLegacyJavaKeycodeOnly(ev))+"; "
1138             );
1139         }
1140 
1141         int jkeyToReturn = XKeysym.getLegacyJavaKeycodeOnly(ev); // someway backward compatible
1142         int jkeyExtended = jkc.getJavaKeycode() == java.awt.event.KeyEvent.VK_UNDEFINED ?
1143                            primaryUnicode2JavaKeycode( unicodeFromPrimaryKeysym ) :
1144                              jkc.getJavaKeycode();
1145         postKeyEvent( java.awt.event.KeyEvent.KEY_PRESSED,
1146                           ev.get_time(),
1147                           isDeadKey ? jkeyExtended : jkeyToReturn,
1148                           (unicodeKey == 0 ? java.awt.event.KeyEvent.CHAR_UNDEFINED : unicodeKey),
1149                           jkc.getKeyLocation(),
1150                           ev.get_state(),ev.getPData(), XKeyEvent.getSize(), (long)(ev.get_keycode()),
1151                           unicodeFromPrimaryKeysym,
1152                           jkeyExtended);
1153 
1154 
1155         if (unicodeKey > 0 && !isDeadKey) {
1156                 keyEventLog.fine("fire _TYPED on "+unicodeKey);
1157                 postKeyEvent( java.awt.event.KeyEvent.KEY_TYPED,
1158                               ev.get_time(),
1159                               java.awt.event.KeyEvent.VK_UNDEFINED,
1160                               unicodeKey,
1161                               java.awt.event.KeyEvent.KEY_LOCATION_UNKNOWN,
1162                               ev.get_state(),ev.getPData(), XKeyEvent.getSize(), (long)0,
1163                               unicodeFromPrimaryKeysym,
1164                               java.awt.event.KeyEvent.VK_UNDEFINED);
1165 
1166         }
1167 
1168 
1169     }
1170 
1171     public void handleKeyRelease(XEvent xev) {
1172         super.handleKeyRelease(xev);
1173         XKeyEvent ev = xev.get_xkey();
1174         if (eventLog.isLoggable(PlatformLogger.FINE)) eventLog.fine(ev.toString());
1175         if (isEventDisabled(xev)) {
1176             return;
1177         }
1178         handleKeyRelease(ev);
1179     }
1180     // un-private it if you need to call it from elsewhere
1181     private void handleKeyRelease(XKeyEvent ev) {
1182         int unicodeKey = 0;
1183 
1184         if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
1185             logIncomingKeyEvent( ev );
1186         }
1187         // Keysym should be converted to Unicode, if possible and necessary,
1188         // and Java KeyEvent keycode should be calculated.
1189         // For release we should post released event.
1190         //
1191         // Preserve modifiers to get Java key code for dead keys
1192         long keysym = xkeycodeToKeysym(ev);
1193         boolean isDeadKey = isDeadKey(keysym);
1194         XKeysym.Keysym2JavaKeycode jkc = isDeadKey ? XKeysym.getJavaKeycode(keysym)
1195                 : XKeysym.getJavaKeycode(ev);
1196         if( jkc == null ) {
1197             jkc = new XKeysym.Keysym2JavaKeycode(java.awt.event.KeyEvent.VK_UNDEFINED, java.awt.event.KeyEvent.KEY_LOCATION_UNKNOWN);
1198         }
1199         if (keyEventLog.isLoggable(PlatformLogger.FINE)) {
1200             keyEventLog.fine(">>>Fire Event:"+
1201                (ev.get_type() == XConstants.KeyPress ? "KEY_PRESSED; " : "KEY_RELEASED; ")+
1202                "jkeycode:decimal="+jkc.getJavaKeycode()+
1203                ", hex=0x"+Integer.toHexString(jkc.getJavaKeycode())+"; "+
1204                " legacy jkeycode: decimal="+XKeysym.getLegacyJavaKeycodeOnly(ev)+
1205                ", hex=0x"+Integer.toHexString(XKeysym.getLegacyJavaKeycodeOnly(ev))+"; "
1206             );
1207         }
1208         // We obtain keysym from IM and derive unicodeKey from it for KeyPress only.
1209         // We used to cache that value and retrieve it on KeyRelease,
1210         // but in case for example of a dead key+vowel pair, a vowel after a deadkey
1211         // might never be cached before.
1212         // Also, switching between keyboard layouts, we might cache a wrong letter.
1213         // That's why we use the same procedure as if there was no IM instance: do-it-yourself unicode.
1214         unicodeKey = keysymToUnicode( xkeycodeToKeysym(ev), ev.get_state() );
1215 
1216         // Take a first keysym from a keysym array associated with the XKeyevent
1217         // and convert it to Unicode. Then, even if Java keycode for the keystroke
1218         // is undefined, we still will have a guess of what was engraved on a keytop.
1219         int unicodeFromPrimaryKeysym = keysymToUnicode( xkeycodeToPrimaryKeysym(ev) ,0);
1220 
1221         int jkeyToReturn = XKeysym.getLegacyJavaKeycodeOnly(ev); // someway backward compatible
1222         int jkeyExtended = jkc.getJavaKeycode() == java.awt.event.KeyEvent.VK_UNDEFINED ?
1223                            primaryUnicode2JavaKeycode( unicodeFromPrimaryKeysym ) :
1224                              jkc.getJavaKeycode();
1225         postKeyEvent(  java.awt.event.KeyEvent.KEY_RELEASED,
1226                           ev.get_time(),
1227                           isDeadKey ? jkeyExtended : jkeyToReturn,
1228                           (unicodeKey == 0 ? java.awt.event.KeyEvent.CHAR_UNDEFINED : unicodeKey),
1229                           jkc.getKeyLocation(),
1230                           ev.get_state(),ev.getPData(), XKeyEvent.getSize(), (long)(ev.get_keycode()),
1231                           unicodeFromPrimaryKeysym,
1232                           jkeyExtended);
1233 
1234 
1235     }
1236 
1237 
1238     private boolean isDeadKey(long keysym){
1239         return XKeySymConstants.XK_dead_grave <= keysym && keysym <= XKeySymConstants.XK_dead_semivoiced_sound;
1240     }
1241 
1242     /*
1243      * XmNiconic and Map/UnmapNotify (that XmNiconic relies on) are
1244      * unreliable, since mapping changes can happen for a virtual desktop
1245      * switch or MacOS style shading that became quite popular under X as
1246      * well.  Yes, it probably should not be this way, as it violates
1247      * ICCCM, but reality is that quite a lot of window managers abuse
1248      * mapping state.
1249      */
1250     int getWMState() {
1251         if (stateChanged) {
1252             stateChanged = false;
1253             WindowPropertyGetter getter =
1254                 new WindowPropertyGetter(window, XWM.XA_WM_STATE, 0, 1, false,
1255                                          XWM.XA_WM_STATE);
1256             try {
1257                 int status = getter.execute();
1258                 if (status != XConstants.Success || getter.getData() == 0) {
1259                     return savedState = XUtilConstants.WithdrawnState;
1260                 }
1261 
1262                 if (getter.getActualType() != XWM.XA_WM_STATE.getAtom() && getter.getActualFormat() != 32) {
1263                     return savedState = XUtilConstants.WithdrawnState;
1264                 }
1265                 savedState = (int)Native.getCard32(getter.getData());
1266             } finally {
1267                 getter.dispose();
1268             }
1269         }
1270         return savedState;
1271     }
1272 
1273     /**
1274      * Override this methods to get notifications when top-level window state changes. The state is
1275      * meant in terms of ICCCM: WithdrawnState, IconicState, NormalState
1276      */
1277     protected void stateChanged(long time, int oldState, int newState) {
1278     }
1279 
1280     @Override
1281     public void handlePropertyNotify(XEvent xev) {
1282         super.handlePropertyNotify(xev);
1283         XPropertyEvent ev = xev.get_xproperty();
1284         if (ev.get_atom() == XWM.XA_WM_STATE.getAtom()) {
1285             // State has changed, invalidate saved value
1286             stateChanged = true;
1287             stateChanged(ev.get_time(), savedState, getWMState());
1288         }
1289     }
1290 
1291     public void reshape(Rectangle bounds) {
1292         reshape(bounds.x, bounds.y, bounds.width, bounds.height);
1293     }
1294 
1295     public void reshape(int x, int y, int width, int height) {
1296         if (width <= 0) {
1297             width = 1;
1298         }
1299         if (height <= 0) {
1300             height = 1;
1301         }
1302         this.x = x;
1303         this.y = y;
1304         this.width = width;
1305         this.height = height;
1306         xSetBounds(x, y, width, height);
1307         // Fixed 6322593, 6304251, 6315137:
1308         // XWindow's SurfaceData should be invalidated and recreated as part
1309         // of the process of resizing the window
1310         // see the evaluation of the bug 6304251 for more information
1311         validateSurface();
1312         layout();
1313     }
1314 
1315     public void layout() {}
1316 
1317     boolean isShowing() {
1318         return visible;
1319     }
1320 
1321     boolean isResizable() {
1322         return true;
1323     }
1324 
1325     boolean isLocationByPlatform() {
1326         return false;
1327     }
1328 
1329     void updateSizeHints() {
1330         updateSizeHints(x, y, width, height);
1331     }
1332 
1333     void updateSizeHints(int x, int y, int width, int height) {
1334         long flags = XUtilConstants.PSize | (isLocationByPlatform() ? 0 : (XUtilConstants.PPosition | XUtilConstants.USPosition));
1335         if (!isResizable()) {
1336             log.finer("Window {0} is not resizable", this);
1337             flags |= XUtilConstants.PMinSize | XUtilConstants.PMaxSize;
1338         } else {
1339             log.finer("Window {0} is resizable", this);
1340         }
1341         setSizeHints(flags, x, y, width, height);
1342     }
1343 
1344     void updateSizeHints(int x, int y) {
1345         long flags = isLocationByPlatform() ? 0 : (XUtilConstants.PPosition | XUtilConstants.USPosition);
1346         if (!isResizable()) {
1347             log.finer("Window {0} is not resizable", this);
1348             flags |= XUtilConstants.PMinSize | XUtilConstants.PMaxSize | XUtilConstants.PSize;
1349         } else {
1350             log.finer("Window {0} is resizable", this);
1351         }
1352         setSizeHints(flags, x, y, width, height);
1353     }
1354 
1355     void validateSurface() {
1356         if ((width != oldWidth) || (height != oldHeight)) {
1357             doValidateSurface();
1358 
1359             oldWidth = width;
1360             oldHeight = height;
1361         }
1362     }
1363 
1364     final void doValidateSurface() {
1365         SurfaceData oldData = surfaceData;
1366         if (oldData != null) {
1367             surfaceData = graphicsConfig.createSurfaceData(this);
1368             oldData.invalidate();
1369         }
1370     }
1371 
1372     public SurfaceData getSurfaceData() {
1373         return surfaceData;
1374     }
1375 
1376     public void dispose() {
1377         SurfaceData oldData = surfaceData;
1378         surfaceData = null;
1379         if (oldData != null) {
1380             oldData.invalidate();
1381         }
1382         XToolkit.targetDisposedPeer(target, this);
1383         destroy();
1384     }
1385 
1386     public Point getLocationOnScreen() {
1387         synchronized (target.getTreeLock()) {
1388             Component comp = target;
1389 
1390             while (comp != null && !(comp instanceof Window)) {
1391                 comp = AWTAccessor.getComponentAccessor().getParent(comp);
1392             }
1393 
1394             // applets, embedded, etc - translate directly
1395             // XXX: override in subclass?
1396             if (comp == null || comp instanceof sun.awt.EmbeddedFrame) {
1397                 return toGlobal(0, 0);
1398             }
1399 
1400             XToolkit.awtLock();
1401             try {
1402                 Object wpeer = XToolkit.targetToPeer(comp);
1403                 if (wpeer == null
1404                     || !(wpeer instanceof XDecoratedPeer)
1405                     || ((XDecoratedPeer)wpeer).configure_seen)
1406                 {
1407                     return toGlobal(0, 0);
1408                 }
1409 
1410                 // wpeer is an XDecoratedPeer not yet fully adopted by WM
1411                 Point pt = toOtherWindow(getContentWindow(),
1412                                          ((XDecoratedPeer)wpeer).getContentWindow(),
1413                                          0, 0);
1414 
1415                 if (pt == null) {
1416                     pt = new Point(((XBaseWindow)wpeer).getAbsoluteX(), ((XBaseWindow)wpeer).getAbsoluteY());
1417                 }
1418                 pt.x += comp.getX();
1419                 pt.y += comp.getY();
1420                 return pt;
1421             } finally {
1422                 XToolkit.awtUnlock();
1423             }
1424         }
1425     }
1426 
1427 
1428     static void setBData(KeyEvent e, byte[] data) {
1429         AWTAccessor.getAWTEventAccessor().setBData(e, data);
1430     }
1431 
1432     public void postKeyEvent(int id, long when, int keyCode, int keyChar,
1433         int keyLocation, int state, long event, int eventSize, long rawCode,
1434         int unicodeFromPrimaryKeysym, int extendedKeyCode)
1435 
1436     {
1437         long jWhen = XToolkit.nowMillisUTC_offset(when);
1438         int modifiers = getModifiers(state, 0, keyCode);
1439 
1440         KeyEvent ke = new KeyEvent((Component)getEventSource(), id, jWhen,
1441                                    modifiers, keyCode, (char)keyChar, keyLocation);
1442         if (event != 0) {
1443             byte[] data = Native.toBytes(event, eventSize);
1444             setBData(ke, data);
1445         }
1446 
1447         AWTAccessor.KeyEventAccessor kea = AWTAccessor.getKeyEventAccessor();
1448         kea.setRawCode(ke, rawCode);
1449         kea.setPrimaryLevelUnicode(ke, (long)unicodeFromPrimaryKeysym);
1450         kea.setExtendedKeyCode(ke, (long)extendedKeyCode);
1451         postEventToEventQueue(ke);
1452     }
1453 
1454     static native int getAWTKeyCodeForKeySym(int keysym);
1455     static native int getKeySymForAWTKeyCode(int keycode);
1456 
1457     /* These two methods are actually applicable to toplevel windows only.
1458      * However, the functionality is required by both the XWindowPeer and
1459      * XWarningWindow, both of which have the XWindow as a common ancestor.
1460      * See XWM.setMotifDecor() for details.
1461      */
1462     public PropMwmHints getMWMHints() {
1463         if (mwm_hints == null) {
1464             mwm_hints = new PropMwmHints();
1465             if (!XWM.XA_MWM_HINTS.getAtomData(getWindow(), mwm_hints.pData, MWMConstants.PROP_MWM_HINTS_ELEMENTS)) {
1466                 mwm_hints.zero();
1467             }
1468         }
1469         return mwm_hints;
1470     }
1471 
1472     public void setMWMHints(PropMwmHints hints) {
1473         mwm_hints = hints;
1474         if (hints != null) {
1475             XWM.XA_MWM_HINTS.setAtomData(getWindow(), mwm_hints.pData, MWMConstants.PROP_MWM_HINTS_ELEMENTS);
1476         }
1477     }
1478 
1479     protected final void initWMProtocols() {
1480         wm_protocols.setAtomListProperty(this, getWMProtocols());
1481     }
1482 
1483     /**
1484      * Returns list of protocols which should be installed on this window.
1485      * Descendants can override this method to add class-specific protocols
1486      */
1487     protected XAtomList getWMProtocols() {
1488         // No protocols on simple window
1489         return new XAtomList();
1490     }
1491 
1492     /**
1493      * Indicates if the window is currently in the FSEM.
1494      * Synchronization: state lock.
1495      */
1496     private boolean fullScreenExclusiveModeState = false;
1497 
1498     // Implementation of the X11ComponentPeer
1499     @Override
1500     public void setFullScreenExclusiveModeState(boolean state) {
1501         synchronized (getStateLock()) {
1502             fullScreenExclusiveModeState = state;
1503         }
1504     }
1505 
1506     public final boolean isFullScreenExclusiveMode() {
1507         synchronized (getStateLock()) {
1508             return fullScreenExclusiveModeState;
1509         }
1510     }
1511 
1512 }