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