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