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