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