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