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