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