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