1 /*
   2  * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package sun.awt.X11;
  26 
  27 import java.awt.*;
  28 
  29 import java.awt.event.ComponentEvent;
  30 import java.awt.event.FocusEvent;
  31 import java.awt.event.WindowEvent;
  32 import java.awt.geom.AffineTransform;
  33 
  34 import java.awt.peer.ComponentPeer;
  35 import java.awt.peer.WindowPeer;
  36 
  37 import java.io.UnsupportedEncodingException;
  38 
  39 import java.security.AccessController;
  40 import java.security.PrivilegedAction;
  41 
  42 import java.util.ArrayList;
  43 import java.util.HashSet;
  44 import java.util.Iterator;
  45 import java.util.Set;
  46 import java.util.Vector;
  47 
  48 import java.util.concurrent.atomic.AtomicBoolean;
  49 
  50 import sun.awt.AWTAccessor.ComponentAccessor;
  51 import sun.util.logging.PlatformLogger;
  52 
  53 import sun.awt.AWTAccessor;
  54 import sun.awt.DisplayChangedListener;
  55 import sun.awt.SunToolkit;
  56 import sun.awt.X11GraphicsDevice;
  57 import sun.awt.X11GraphicsEnvironment;
  58 import sun.awt.IconInfo;
  59 
  60 import sun.java2d.pipe.Region;
  61 
  62 class XWindowPeer extends XPanelPeer implements WindowPeer,
  63                                                 DisplayChangedListener {
  64 
  65     private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.X11.XWindowPeer");
  66     private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.awt.X11.focus.XWindowPeer");
  67     private static final PlatformLogger insLog = PlatformLogger.getLogger("sun.awt.X11.insets.XWindowPeer");
  68     private static final PlatformLogger grabLog = PlatformLogger.getLogger("sun.awt.X11.grab.XWindowPeer");
  69     private static final PlatformLogger iconLog = PlatformLogger.getLogger("sun.awt.X11.icon.XWindowPeer");
  70 
  71     // should be synchronized on awtLock
  72     private static Set<XWindowPeer> windows = new HashSet<XWindowPeer>();
  73 
  74 
  75     private boolean cachedFocusableWindow;
  76     XWarningWindow warningWindow;
  77 
  78     private boolean alwaysOnTop;
  79     private boolean locationByPlatform;
  80 
  81     Dialog modalBlocker;
  82     boolean delayedModalBlocking = false;
  83     Dimension targetMinimumSize = null;
  84 
  85     private XWindowPeer ownerPeer;
  86 
  87     // used for modal blocking to keep existing z-order
  88     protected XWindowPeer prevTransientFor, nextTransientFor;
  89     // value of WM_TRANSIENT_FOR hint set on this window
  90     private XBaseWindow curRealTransientFor;
  91 
  92     private boolean grab = false; // Whether to do a grab during showing
  93 
  94     private boolean isMapped = false; // Is this window mapped or not
  95     private boolean mustControlStackPosition = false; // Am override-redirect not on top
  96     private XEventDispatcher rootPropertyEventDispatcher = null;
  97 
  98     private static final AtomicBoolean isStartupNotificationRemoved = new AtomicBoolean();
  99 
 100     /*
 101      * Focus related flags
 102      */
 103     private boolean isUnhiding = false;             // Is the window unhiding.
 104     private boolean isBeforeFirstMapNotify = false; // Is the window (being shown) between
 105                                                     //    setVisible(true) & handleMapNotify().
 106 
 107     /**
 108      * The type of the window.
 109      *
 110      * The type is supposed to be immutable while the peer object exists.
 111      * The value gets initialized in the preInit() method.
 112      */
 113     private Window.Type windowType = Window.Type.NORMAL;
 114 
 115     public final Window.Type getWindowType() {
 116         return windowType;
 117     }
 118 
 119     // It need to be accessed from XFramePeer.
 120     protected Vector <ToplevelStateListener> toplevelStateListeners = new Vector<ToplevelStateListener>();
 121     XWindowPeer(XCreateWindowParams params) {
 122         super(params.putIfNull(PARENT_WINDOW, Long.valueOf(0)));
 123     }
 124 
 125     XWindowPeer(Window target) {
 126         super(new XCreateWindowParams(new Object[] {
 127             TARGET, target,
 128             PARENT_WINDOW, Long.valueOf(0)}));
 129     }
 130 
 131     /*
 132      * This constant defines icon size recommended for using.
 133      * Apparently, we should use XGetIconSizes which should
 134      * return icon sizes would be most appreciated by the WM.
 135      * However, XGetIconSizes always returns 0 for some reason.
 136      * So the constant has been introduced.
 137      */
 138     private static final int PREFERRED_SIZE_FOR_ICON = 128;
 139 
 140     /*
 141      * Sometimes XChangeProperty(_NET_WM_ICON) doesn't work if
 142      * image buffer is too large. This constant holds maximum
 143      * length of buffer which can be used with _NET_WM_ICON hint.
 144      * It holds int's value.
 145      */
 146     private static final int MAXIMUM_BUFFER_LENGTH_NET_WM_ICON = (2<<15) - 1;
 147 
 148     void preInit(XCreateWindowParams params) {
 149         target = (Component)params.get(TARGET);
 150         windowType = ((Window)target).getType();
 151         params.put(REPARENTED,
 152                    Boolean.valueOf(isOverrideRedirect() || isSimpleWindow()));
 153         super.preInit(params);
 154         params.putIfNull(BIT_GRAVITY, Integer.valueOf(XConstants.NorthWestGravity));
 155 
 156         long eventMask = 0;
 157         if (params.containsKey(EVENT_MASK)) {
 158             eventMask = ((Long)params.get(EVENT_MASK));
 159         }
 160         eventMask |= XConstants.VisibilityChangeMask;
 161         params.put(EVENT_MASK, eventMask);
 162 
 163         XA_NET_WM_STATE = XAtom.get("_NET_WM_STATE");
 164 
 165 
 166         params.put(OVERRIDE_REDIRECT, Boolean.valueOf(isOverrideRedirect()));
 167 
 168         SunToolkit.awtLock();
 169         try {
 170             windows.add(this);
 171         } finally {
 172             SunToolkit.awtUnlock();
 173         }
 174 
 175         cachedFocusableWindow = isFocusableWindow();
 176 
 177         if (!target.isFontSet()) {
 178                target.setFont(XWindow.getDefaultFont());
 179                // we should not call setFont because it will call a repaint
 180                // which the peer may not be ready to do yet.
 181         }
 182         if (!target.isBackgroundSet()) {
 183                target.setBackground(SystemColor.window);
 184                // we should not call setBackGround because it will call a repaint
 185                // which the peer may not be ready to do yet.
 186 
 187         }
 188         if (!target.isForegroundSet()) {
 189                target.setForeground(SystemColor.windowText);
 190                // we should not call setForeGround because it will call a repaint
 191                // which the peer may not be ready to do yet.
 192         }
 193 
 194 
 195         alwaysOnTop = ((Window)target).isAlwaysOnTop() && ((Window)target).isAlwaysOnTopSupported();
 196 
 197         GraphicsConfiguration gc = getGraphicsConfiguration();
 198         ((X11GraphicsDevice)gc.getDevice()).addDisplayChangedListener(this);
 199     }
 200 
 201     protected String getWMName() {
 202         String name = target.getName();
 203         if (name == null || name.trim().equals("")) {
 204             name = " ";
 205         }
 206         return name;
 207     }
 208 
 209     private static native String getLocalHostname();
 210     private static native int getJvmPID();
 211 
 212     @SuppressWarnings("deprecation")
 213     void postInit(XCreateWindowParams params) {
 214         super.postInit(params);
 215 
 216         // Init WM_PROTOCOLS atom
 217         initWMProtocols();
 218 
 219         // Set _NET_WM_PID and WM_CLIENT_MACHINE using this JVM
 220         XAtom.get("WM_CLIENT_MACHINE").setProperty(getWindow(), getLocalHostname());
 221         XAtom.get("_NET_WM_PID").setCard32Property(getWindow(), getJvmPID());
 222 
 223         // Set WM_TRANSIENT_FOR and group_leader
 224         Window t_window = (Window)target;
 225         Window owner = t_window.getOwner();
 226         if (owner != null) {
 227             ownerPeer = AWTAccessor.getComponentAccessor().getPeer(owner);
 228             if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {
 229                 focusLog.finer("Owner is " + owner);
 230                 focusLog.finer("Owner peer is " + ownerPeer);
 231                 focusLog.finer("Owner X window " + Long.toHexString(ownerPeer.getWindow()));
 232                 focusLog.finer("Owner content X window " + Long.toHexString(ownerPeer.getContentWindow()));
 233             }
 234             // as owner window may be an embedded window, we must get a toplevel window
 235             // to set as TRANSIENT_FOR hint
 236             long ownerWindow = ownerPeer.getWindow();
 237             if (ownerWindow != 0) {
 238                 XToolkit.awtLock();
 239                 try {
 240                     // Set WM_TRANSIENT_FOR
 241                     if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
 242                         focusLog.fine("Setting transient on " + Long.toHexString(getWindow())
 243                                       + " for " + Long.toHexString(ownerWindow));
 244                     }
 245                     setToplevelTransientFor(this, ownerPeer, false, true);
 246 
 247                     // Set group leader
 248                     XWMHints hints = getWMHints();
 249                     hints.set_flags(hints.get_flags() | (int)XUtilConstants.WindowGroupHint);
 250                     hints.set_window_group(ownerWindow);
 251                     XlibWrapper.XSetWMHints(XToolkit.getDisplay(), getWindow(), hints.pData);
 252                 }
 253                 finally {
 254                     XToolkit.awtUnlock();
 255                 }
 256             }
 257         }
 258 
 259         if (owner != null || isSimpleWindow()) {
 260             XNETProtocol protocol = XWM.getWM().getNETProtocol();
 261             if (protocol != null && protocol.active()) {
 262                 XToolkit.awtLock();
 263                 try {
 264                     XAtomList net_wm_state = getNETWMState();
 265                     net_wm_state.add(protocol.XA_NET_WM_STATE_SKIP_TASKBAR);
 266                     setNETWMState(net_wm_state);
 267                 } finally {
 268                     XToolkit.awtUnlock();
 269                 }
 270 
 271             }
 272         }
 273 
 274          // Init warning window(for applets)
 275         if (((Window)target).getWarningString() != null) {
 276             // accessSystemTray permission allows to display TrayIcon, TrayIcon tooltip
 277             // and TrayIcon balloon windows without a warning window.
 278             if (!AWTAccessor.getWindowAccessor().isTrayIconWindow((Window)target)) {
 279                 warningWindow = new XWarningWindow((Window)target, getWindow(), this);
 280             }
 281         }
 282 
 283         setSaveUnder(true);
 284 
 285         updateIconImages();
 286 
 287         updateShape();
 288         updateOpacity();
 289         // no need in updateOpaque() as it is no-op
 290     }
 291 
 292     public void updateIconImages() {
 293         Window target = (Window)this.target;
 294         java.util.List<Image> iconImages = target.getIconImages();
 295         XWindowPeer ownerPeer = getOwnerPeer();
 296         winAttr.icons = new ArrayList<IconInfo>();
 297         if (iconImages.size() != 0) {
 298             //read icon images from target
 299             winAttr.iconsInherited = false;
 300             for (Iterator<Image> i = iconImages.iterator(); i.hasNext(); ) {
 301                 Image image = i.next();
 302                 if (image == null) {
 303                     if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 304                         log.finest("XWindowPeer.updateIconImages: Skipping the image passed into Java because it's null.");
 305                     }
 306                     continue;
 307                 }
 308                 IconInfo iconInfo;
 309                 try {
 310                     iconInfo = new IconInfo(image);
 311                 } catch (Exception e){
 312                     if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 313                         log.finest("XWindowPeer.updateIconImages: Perhaps the image passed into Java is broken. Skipping this icon.");
 314                     }
 315                     continue;
 316                 }
 317                 if (iconInfo.isValid()) {
 318                     winAttr.icons.add(iconInfo);
 319                 }
 320             }
 321         }
 322 
 323         // Fix for CR#6425089
 324         winAttr.icons = normalizeIconImages(winAttr.icons);
 325 
 326         if (winAttr.icons.size() == 0) {
 327             //target.icons is empty or all icon images are broken
 328             if (ownerPeer != null) {
 329                 //icon is inherited from parent
 330                 winAttr.iconsInherited = true;
 331                 winAttr.icons = ownerPeer.getIconInfo();
 332             } else {
 333                 //default icon is used
 334                 winAttr.iconsInherited = false;
 335                 winAttr.icons = getDefaultIconInfo();
 336             }
 337         }
 338         recursivelySetIcon(winAttr.icons);
 339     }
 340 
 341     /*
 342      * Sometimes XChangeProperty(_NET_WM_ICON) doesn't work if
 343      * image buffer is too large. This function help us accommodate
 344      * initial list of the icon images to certainly-acceptable.
 345      * It does scale some of these icons to appropriate size
 346      * if it's necessary.
 347      */
 348     static java.util.List<IconInfo> normalizeIconImages(java.util.List<IconInfo> icons) {
 349         java.util.List<IconInfo> result = new ArrayList<IconInfo>();
 350         int totalLength = 0;
 351         boolean haveLargeIcon = false;
 352 
 353         for (IconInfo icon : icons) {
 354             int width = icon.getWidth();
 355             int height = icon.getHeight();
 356             int length = icon.getRawLength();
 357 
 358             if (width > PREFERRED_SIZE_FOR_ICON || height > PREFERRED_SIZE_FOR_ICON) {
 359                 if (haveLargeIcon) {
 360                     continue;
 361                 }
 362                 int scaledWidth = width;
 363                 int scaledHeight = height;
 364                 while (scaledWidth > PREFERRED_SIZE_FOR_ICON ||
 365                        scaledHeight > PREFERRED_SIZE_FOR_ICON) {
 366                     scaledWidth = scaledWidth / 2;
 367                     scaledHeight = scaledHeight / 2;
 368                 }
 369 
 370                 icon.setScaledSize(scaledWidth, scaledHeight);
 371                 length = icon.getRawLength();
 372             }
 373 
 374             if (totalLength + length <= MAXIMUM_BUFFER_LENGTH_NET_WM_ICON) {
 375                 totalLength += length;
 376                 result.add(icon);
 377                 if (width > PREFERRED_SIZE_FOR_ICON || height > PREFERRED_SIZE_FOR_ICON) {
 378                     haveLargeIcon = true;
 379                 }
 380             }
 381         }
 382 
 383         if (iconLog.isLoggable(PlatformLogger.Level.FINEST)) {
 384             iconLog.finest(">>> Length_ of buffer of icons data: " + totalLength +
 385                            ", maximum length: " + MAXIMUM_BUFFER_LENGTH_NET_WM_ICON);
 386         }
 387 
 388         return result;
 389     }
 390 
 391     /*
 392      * Dumps each icon from the list
 393      */
 394     static void dumpIcons(java.util.List<IconInfo> icons) {
 395         if (iconLog.isLoggable(PlatformLogger.Level.FINEST)) {
 396             iconLog.finest(">>> Sizes of icon images:");
 397             for (Iterator<IconInfo> i = icons.iterator(); i.hasNext(); ) {
 398                 iconLog.finest("    {0}", i.next());
 399             }
 400         }
 401     }
 402 
 403     public void recursivelySetIcon(java.util.List<IconInfo> icons) {
 404         dumpIcons(winAttr.icons);
 405         setIconHints(icons);
 406         Window target = (Window)this.target;
 407         Window[] children = target.getOwnedWindows();
 408         int cnt = children.length;
 409         final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
 410         for (int i = 0; i < cnt; i++) {
 411             final ComponentPeer childPeer = acc.getPeer(children[i]);
 412             if (childPeer != null && childPeer instanceof XWindowPeer) {
 413                 if (((XWindowPeer)childPeer).winAttr.iconsInherited) {
 414                     ((XWindowPeer)childPeer).winAttr.icons = icons;
 415                     ((XWindowPeer)childPeer).recursivelySetIcon(icons);
 416                 }
 417             }
 418         }
 419     }
 420 
 421     java.util.List<IconInfo> getIconInfo() {
 422         return winAttr.icons;
 423     }
 424     void setIconHints(java.util.List<IconInfo> icons) {
 425         //This does nothing for XWindowPeer,
 426         //It's overriden in XDecoratedPeer
 427     }
 428 
 429     private static ArrayList<IconInfo> defaultIconInfo;
 430     protected static synchronized java.util.List<IconInfo> getDefaultIconInfo() {
 431         if (defaultIconInfo == null) {
 432             defaultIconInfo = new ArrayList<IconInfo>();
 433             if (XlibWrapper.dataModel == 32) {
 434                 defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon32_java_icon16_png.java_icon16_png));
 435                 defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon32_java_icon24_png.java_icon24_png));
 436                 defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon32_java_icon32_png.java_icon32_png));
 437                 defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon32_java_icon48_png.java_icon48_png));
 438             } else {
 439                 defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon64_java_icon16_png.java_icon16_png));
 440                 defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon64_java_icon24_png.java_icon24_png));
 441                 defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon64_java_icon32_png.java_icon32_png));
 442                 defaultIconInfo.add(new IconInfo(sun.awt.AWTIcon64_java_icon48_png.java_icon48_png));
 443             }
 444         }
 445         return defaultIconInfo;
 446     }
 447 
 448     private void updateShape() {
 449         // Shape shape = ((Window)target).getShape();
 450         Shape shape = AWTAccessor.getWindowAccessor().getShape((Window)target);
 451         if (shape != null) {
 452             applyShape(Region.getInstance(shape, null));
 453         }
 454     }
 455 
 456     private void updateOpacity() {
 457         // float opacity = ((Window)target).getOpacity();
 458         float opacity = AWTAccessor.getWindowAccessor().getOpacity((Window)target);
 459         if (opacity < 1.0f) {
 460             setOpacity(opacity);
 461         }
 462     }
 463 
 464     public void updateMinimumSize() {
 465         //This function only saves minimumSize value in XWindowPeer
 466         //Setting WMSizeHints is implemented in XDecoratedPeer
 467         targetMinimumSize = (target.isMinimumSizeSet()) ?
 468             target.getMinimumSize() : null;
 469     }
 470 
 471     public Dimension getTargetMinimumSize() {
 472         return (targetMinimumSize == null) ? null : new Dimension(targetMinimumSize);
 473     }
 474 
 475     public XWindowPeer getOwnerPeer() {
 476         return ownerPeer;
 477     }
 478 
 479     //Fix for 6318144: PIT:Setting Min Size bigger than current size enlarges
 480     //the window but fails to revalidate, Sol-CDE
 481     //This bug is regression for
 482     //5025858: Resizing a decorated frame triggers componentResized event twice.
 483     //Since events are not posted from Component.setBounds we need to send them here.
 484     //Note that this function is overriden in XDecoratedPeer so event
 485     //posting is not changing for decorated peers
 486     public void setBounds(int x, int y, int width, int height, int op) {
 487         XToolkit.awtLock();
 488         try {
 489             Rectangle oldBounds = getBounds();
 490 
 491             super.setBounds(x, y, width, height, op);
 492 
 493             Rectangle bounds = getBounds();
 494 
 495             XSizeHints hints = getHints();
 496             setSizeHints(hints.get_flags() | XUtilConstants.PPosition | XUtilConstants.PSize,
 497                              bounds.x, bounds.y, bounds.width, bounds.height);
 498             XWM.setMotifDecor(this, false, 0, 0);
 499 
 500             boolean isResized = !bounds.getSize().equals(oldBounds.getSize());
 501             boolean isMoved = !bounds.getLocation().equals(oldBounds.getLocation());
 502             if (isMoved || isResized) {
 503                 repositionSecurityWarning();
 504             }
 505             if (isResized) {
 506                 postEventToEventQueue(new ComponentEvent(getEventSource(), ComponentEvent.COMPONENT_RESIZED));
 507             }
 508             if (isMoved) {
 509                 postEventToEventQueue(new ComponentEvent(getEventSource(), ComponentEvent.COMPONENT_MOVED));
 510             }
 511         } finally {
 512             XToolkit.awtUnlock();
 513         }
 514     }
 515 
 516     void updateFocusability() {
 517         updateFocusableWindowState();
 518         XToolkit.awtLock();
 519         try {
 520             XWMHints hints = getWMHints();
 521             hints.set_flags(hints.get_flags() | (int)XUtilConstants.InputHint);
 522             hints.set_input(false/*isNativelyNonFocusableWindow() ? (0):(1)*/);
 523             XlibWrapper.XSetWMHints(XToolkit.getDisplay(), getWindow(), hints.pData);
 524         }
 525         finally {
 526             XToolkit.awtUnlock();
 527         }
 528     }
 529 
 530     public Insets getInsets() {
 531         return new Insets(0, 0, 0, 0);
 532     }
 533 
 534     // NOTE: This method may be called by privileged threads.
 535     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 536     public void handleIconify() {
 537         postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_ICONIFIED));
 538     }
 539 
 540     // NOTE: This method may be called by privileged threads.
 541     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 542     public void handleDeiconify() {
 543         postEvent(new WindowEvent((Window)target, WindowEvent.WINDOW_DEICONIFIED));
 544     }
 545 
 546     // NOTE: This method may be called by privileged threads.
 547     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 548     public void handleStateChange(int oldState, int newState) {
 549         postEvent(new WindowEvent((Window)target,
 550                                   WindowEvent.WINDOW_STATE_CHANGED,
 551                                   oldState, newState));
 552     }
 553 
 554     /**
 555      * DEPRECATED:  Replaced by getInsets().
 556      */
 557     public Insets insets() {
 558         return getInsets();
 559     }
 560 
 561     boolean isAutoRequestFocus() {
 562         if (XToolkit.isToolkitThread()) {
 563             return AWTAccessor.getWindowAccessor().isAutoRequestFocus((Window)target);
 564         } else {
 565             return ((Window)target).isAutoRequestFocus();
 566         }
 567     }
 568 
 569     /*
 570      * Retrives real native focused window and converts it into Java peer.
 571      */
 572     static XWindowPeer getNativeFocusedWindowPeer() {
 573         XBaseWindow baseWindow = XToolkit.windowToXWindow(xGetInputFocus());
 574         return (baseWindow instanceof XWindowPeer) ? (XWindowPeer)baseWindow :
 575                (baseWindow instanceof XFocusProxyWindow) ?
 576                ((XFocusProxyWindow)baseWindow).getOwner() : null;
 577     }
 578 
 579     /*
 580      * Retrives real native focused window and converts it into Java window.
 581      */
 582     static Window getNativeFocusedWindow() {
 583         XWindowPeer peer = getNativeFocusedWindowPeer();
 584         return peer != null ? (Window)peer.target : null;
 585     }
 586 
 587     boolean isFocusableWindow() {
 588         if (XToolkit.isToolkitThread() || SunToolkit.isAWTLockHeldByCurrentThread())
 589         {
 590             return cachedFocusableWindow;
 591         } else {
 592             return ((Window)target).isFocusableWindow();
 593         }
 594     }
 595 
 596     /* WARNING: don't call client code in this method! */
 597     boolean isFocusedWindowModalBlocker() {
 598         return false;
 599     }
 600 
 601     long getFocusTargetWindow() {
 602         return getContentWindow();
 603     }
 604 
 605     /**
 606      * Returns whether or not this window peer has native X window
 607      * configured as non-focusable window. It might happen if:
 608      * - Java window is non-focusable
 609      * - Java window is simple Window(not Frame or Dialog)
 610      */
 611     boolean isNativelyNonFocusableWindow() {
 612         if (XToolkit.isToolkitThread() || SunToolkit.isAWTLockHeldByCurrentThread())
 613         {
 614             return isSimpleWindow() || !cachedFocusableWindow;
 615         } else {
 616             return isSimpleWindow() || !(((Window)target).isFocusableWindow());
 617         }
 618     }
 619 
 620     public void handleWindowFocusIn_Dispatch() {
 621         if (EventQueue.isDispatchThread()) {
 622             XKeyboardFocusManagerPeer.getInstance().setCurrentFocusedWindow((Window) target);
 623             WindowEvent we = new WindowEvent((Window)target, WindowEvent.WINDOW_GAINED_FOCUS);
 624             SunToolkit.setSystemGenerated(we);
 625             target.dispatchEvent(we);
 626         }
 627     }
 628 
 629     public void handleWindowFocusInSync(long serial) {
 630         WindowEvent we = new WindowEvent((Window)target, WindowEvent.WINDOW_GAINED_FOCUS);
 631         XKeyboardFocusManagerPeer.getInstance().setCurrentFocusedWindow((Window) target);
 632         sendEvent(we);
 633     }
 634     // NOTE: This method may be called by privileged threads.
 635     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 636     public void handleWindowFocusIn(long serial) {
 637         WindowEvent we = new WindowEvent((Window)target, WindowEvent.WINDOW_GAINED_FOCUS);
 638         /* wrap in Sequenced, then post*/
 639         XKeyboardFocusManagerPeer.getInstance().setCurrentFocusedWindow((Window) target);
 640         postEvent(wrapInSequenced((AWTEvent) we));
 641     }
 642 
 643     // NOTE: This method may be called by privileged threads.
 644     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
 645     public void handleWindowFocusOut(Window oppositeWindow, long serial) {
 646         WindowEvent we = new WindowEvent((Window)target, WindowEvent.WINDOW_LOST_FOCUS, oppositeWindow);
 647         XKeyboardFocusManagerPeer.getInstance().setCurrentFocusedWindow(null);
 648         XKeyboardFocusManagerPeer.getInstance().setCurrentFocusOwner(null);
 649         /* wrap in Sequenced, then post*/
 650         postEvent(wrapInSequenced((AWTEvent) we));
 651     }
 652     public void handleWindowFocusOutSync(Window oppositeWindow, long serial) {
 653         WindowEvent we = new WindowEvent((Window)target, WindowEvent.WINDOW_LOST_FOCUS, oppositeWindow);
 654         XKeyboardFocusManagerPeer.getInstance().setCurrentFocusedWindow(null);
 655         XKeyboardFocusManagerPeer.getInstance().setCurrentFocusOwner(null);
 656         sendEvent(we);
 657     }
 658 
 659 /* --- DisplayChangedListener Stuff --- */
 660 
 661     /* Xinerama
 662      * called to check if we've been moved onto a different screen
 663      * Based on checkNewXineramaScreen() in awt_GraphicsEnv.c
 664      */
 665     public void checkIfOnNewScreen(Rectangle newBounds) {
 666         if (!XToolkit.localEnv.runningXinerama()) {
 667             return;
 668         }
 669 
 670         if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 671             log.finest("XWindowPeer: Check if we've been moved to a new screen since we're running in Xinerama mode");
 672         }
 673 
 674         int area = newBounds.width * newBounds.height;
 675         int intAmt, vertAmt, horizAmt;
 676         int largestAmt = 0;
 677         int curScreenNum = ((X11GraphicsDevice)getGraphicsConfiguration().getDevice()).getScreen();
 678         int newScreenNum = 0;
 679         GraphicsDevice gds[] = XToolkit.localEnv.getScreenDevices();
 680         GraphicsConfiguration newGC = null;
 681         Rectangle screenBounds;
 682 
 683         XToolkit.awtUnlock();
 684         try {
 685             for (int i = 0; i < gds.length; i++) {
 686                 screenBounds = gds[i].getDefaultConfiguration().getBounds();
 687                 if (newBounds.intersects(screenBounds)) {
 688                     horizAmt = Math.min(newBounds.x + newBounds.width,
 689                                         screenBounds.x + screenBounds.width) -
 690                                Math.max(newBounds.x, screenBounds.x);
 691                     vertAmt = Math.min(newBounds.y + newBounds.height,
 692                                        screenBounds.y + screenBounds.height)-
 693                               Math.max(newBounds.y, screenBounds.y);
 694                     intAmt = horizAmt * vertAmt;
 695                     if (intAmt == area) {
 696                         // Completely on this screen - done!
 697                         newScreenNum = i;
 698                         newGC = gds[i].getDefaultConfiguration();
 699                         break;
 700                     }
 701                     if (intAmt > largestAmt) {
 702                         largestAmt = intAmt;
 703                         newScreenNum = i;
 704                         newGC = gds[i].getDefaultConfiguration();
 705                     }
 706                 }
 707             }
 708         } finally {
 709             XToolkit.awtLock();
 710         }
 711         if (newScreenNum != curScreenNum) {
 712             if (log.isLoggable(PlatformLogger.Level.FINEST)) {
 713                 log.finest("XWindowPeer: Moved to a new screen");
 714             }
 715             executeDisplayChangedOnEDT(newGC);
 716         }
 717     }
 718 
 719     /**
 720      * Helper method that executes the displayChanged(screen) method on
 721      * the event dispatch thread.  This method is used in the Xinerama case
 722      * and after display mode change events.
 723      */
 724     private void executeDisplayChangedOnEDT(final GraphicsConfiguration gc) {
 725         Runnable dc = new Runnable() {
 726             public void run() {
 727                 AWTAccessor.getComponentAccessor().
 728                     setGraphicsConfiguration(target, gc);
 729             }
 730         };
 731         SunToolkit.executeOnEventHandlerThread(target, dc);
 732     }
 733 
 734     /**
 735      * From the DisplayChangedListener interface; called from
 736      * X11GraphicsDevice when the display mode has been changed.
 737      */
 738     public void displayChanged() {
 739         executeDisplayChangedOnEDT(getGraphicsConfiguration());
 740     }
 741 
 742     /**
 743      * From the DisplayChangedListener interface; top-levels do not need
 744      * to react to this event.
 745      */
 746     public void paletteChanged() {
 747     }
 748 
 749     private Point queryXLocation()
 750     {
 751         return XlibUtil.translateCoordinates(getContentWindow(), XlibWrapper
 752                                              .RootWindow(XToolkit.getDisplay(),
 753                                              getScreenNumber()),
 754                                              new Point(0, 0), getScale());
 755     }
 756 
 757     protected Point getNewLocation(XConfigureEvent xe, int leftInset, int topInset) {
 758         // Bounds of the window
 759         Rectangle targetBounds = AWTAccessor.getComponentAccessor().getBounds(target);
 760 
 761         int runningWM = XWM.getWMID();
 762         Point newLocation = targetBounds.getLocation();
 763         if (xe.get_send_event() || runningWM == XWM.NO_WM || XWM.isNonReparentingWM()) {
 764             // Location, Client size + insets
 765             newLocation = new Point(scaleDown(xe.get_x()) - leftInset,
 766                                     scaleDown(xe.get_y()) - topInset);
 767         } else {
 768             // ICCCM 4.1.5 states that a real ConfigureNotify will be sent when
 769             // a window is resized but the client can not tell if the window was
 770             // moved or not. The client should consider the position as unkown
 771             // and use TranslateCoordinates to find the actual position.
 772             //
 773             // TODO this should be the default for every case.
 774             switch (runningWM) {
 775                 case XWM.CDE_WM:
 776                 case XWM.MOTIF_WM:
 777                 case XWM.METACITY_WM:
 778                 case XWM.MUTTER_WM:
 779                 case XWM.SAWFISH_WM:
 780                 {
 781                     Point xlocation = queryXLocation();
 782                     if (log.isLoggable(PlatformLogger.Level.FINE)) {
 783                         log.fine("New X location: {0}", xlocation);
 784                     }
 785                     if (xlocation != null) {
 786                         newLocation = xlocation;
 787                     }
 788                     break;
 789                 }
 790                 default:
 791                     break;
 792             }
 793         }
 794         return newLocation;
 795     }
 796 
 797     /*
 798      * Overridden to check if we need to update our GraphicsDevice/Config
 799      * Added for 4934052.
 800      */
 801     @Override
 802     public void handleConfigureNotifyEvent(XEvent xev) {
 803         assert (SunToolkit.isAWTLockHeldByCurrentThread());
 804         XConfigureEvent xe = xev.get_xconfigure();
 805         if (insLog.isLoggable(PlatformLogger.Level.FINE)) {
 806             insLog.fine(xe.toString());
 807         }
 808         checkIfOnNewScreen(toGlobal(new Rectangle(scaleDown(xe.get_x()),
 809                 scaleDown(xe.get_y()),
 810                 scaleDown(xe.get_width()),
 811                 scaleDown(xe.get_height()))));
 812 
 813         Rectangle oldBounds = getBounds();
 814 
 815         x = scaleDown(xe.get_x());
 816         y = scaleDown(xe.get_y());
 817         width = scaleDown(xe.get_width());
 818         height = scaleDown(xe.get_height());
 819 
 820         if (!getBounds().getSize().equals(oldBounds.getSize())) {
 821             AWTAccessor.getComponentAccessor().setSize(target, width, height);
 822             postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_RESIZED));
 823         }
 824         if (!getBounds().getLocation().equals(oldBounds.getLocation())) {
 825             AWTAccessor.getComponentAccessor().setLocation(target, x, y);
 826             postEvent(new ComponentEvent(target, ComponentEvent.COMPONENT_MOVED));
 827         }
 828         repositionSecurityWarning();
 829     }
 830 
 831     final void requestXFocus(long time) {
 832         requestXFocus(time, true);
 833     }
 834 
 835     final void requestXFocus() {
 836         requestXFocus(0, false);
 837     }
 838 
 839     /**
 840      * Requests focus to this top-level. Descendants should override to provide
 841      * implementations based on a class of top-level.
 842      */
 843     protected void requestXFocus(long time, boolean timeProvided) {
 844         // Since in XAWT focus is synthetic and all basic Windows are
 845         // override_redirect all we can do is check whether our parent
 846         // is active. If it is - we can freely synthesize focus transfer.
 847         // Luckily, this logic is already implemented in requestWindowFocus.
 848         if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
 849             focusLog.fine("Requesting window focus");
 850         }
 851         requestWindowFocus(time, timeProvided);
 852     }
 853 
 854     public final boolean focusAllowedFor() {
 855         if (isNativelyNonFocusableWindow()) {
 856             return false;
 857         }
 858 /*
 859         Window target = (Window)this.target;
 860         if (!target.isVisible() ||
 861             !target.isEnabled() ||
 862             !target.isFocusable())
 863         {
 864             return false;
 865         }
 866 */
 867         if (isModalBlocked()) {
 868             return false;
 869         }
 870         return true;
 871     }
 872 
 873     public void handleFocusEvent(XEvent xev) {
 874         XFocusChangeEvent xfe = xev.get_xfocus();
 875         FocusEvent fe;
 876         if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
 877             focusLog.fine("{0}", xfe);
 878         }
 879         if (isEventDisabled(xev)) {
 880             return;
 881         }
 882         if (xev.get_type() == XConstants.FocusIn)
 883         {
 884             // If this window is non-focusable don't post any java focus event
 885             if (focusAllowedFor()) {
 886                 if (xfe.get_mode() == XConstants.NotifyNormal // Normal notify
 887                     || xfe.get_mode() == XConstants.NotifyWhileGrabbed) // Alt-Tab notify
 888                 {
 889                     handleWindowFocusIn(xfe.get_serial());
 890                 }
 891             }
 892         }
 893         else
 894         {
 895             if (xfe.get_mode() == XConstants.NotifyNormal // Normal notify
 896                 || xfe.get_mode() == XConstants.NotifyWhileGrabbed) // Alt-Tab notify
 897             {
 898                 // If this window is non-focusable don't post any java focus event
 899                 if (!isNativelyNonFocusableWindow()) {
 900                     XWindowPeer oppositeXWindow = getNativeFocusedWindowPeer();
 901                     Object oppositeTarget = (oppositeXWindow!=null)? oppositeXWindow.getTarget() : null;
 902                     Window oppositeWindow = null;
 903                     if (oppositeTarget instanceof Window) {
 904                         oppositeWindow = (Window) oppositeTarget;
 905                     }
 906                     // Check if opposite window is non-focusable. In that case we don't want to
 907                     // post any event.
 908                     if (oppositeXWindow != null && oppositeXWindow.isNativelyNonFocusableWindow()) {
 909                         return;
 910                     }
 911                     if (this == oppositeXWindow) {
 912                         oppositeWindow = null;
 913                     } else if (oppositeXWindow instanceof XDecoratedPeer) {
 914                         if (((XDecoratedPeer) oppositeXWindow).actualFocusedWindow != null) {
 915                             oppositeXWindow = ((XDecoratedPeer) oppositeXWindow).actualFocusedWindow;
 916                             oppositeTarget = oppositeXWindow.getTarget();
 917                             if (oppositeTarget instanceof Window
 918                                 && oppositeXWindow.isVisible()
 919                                 && oppositeXWindow.isNativelyNonFocusableWindow())
 920                             {
 921                                 oppositeWindow = ((Window) oppositeTarget);
 922                             }
 923                         }
 924                     }
 925                     handleWindowFocusOut(oppositeWindow, xfe.get_serial());
 926                 }
 927             }
 928         }
 929     }
 930 
 931     void setSaveUnder(boolean state) {}
 932 
 933     public void toFront() {
 934         if (isOverrideRedirect() && mustControlStackPosition) {
 935             mustControlStackPosition = false;
 936             removeRootPropertyEventDispatcher();
 937         }
 938         if (isVisible()) {
 939             super.toFront();
 940             if (isFocusableWindow() && isAutoRequestFocus() &&
 941                 !isModalBlocked() && !isWithdrawn())
 942             {
 943                 requestInitialFocus();
 944             }
 945         } else {
 946             setVisible(true);
 947         }
 948     }
 949 
 950     public void toBack() {
 951         XToolkit.awtLock();
 952         try {
 953             if(!isOverrideRedirect()) {
 954                 XlibWrapper.XLowerWindow(XToolkit.getDisplay(), getWindow());
 955             }else{
 956                 lowerOverrideRedirect();
 957             }
 958         }
 959         finally {
 960             XToolkit.awtUnlock();
 961         }
 962     }
 963     private void lowerOverrideRedirect() {
 964         //
 965         // make new hash of toplevels of all windows from 'windows' hash.
 966         // FIXME: do not call them "toplevel" as it is misleading.
 967         //
 968         HashSet<Long> toplevels = new HashSet<>();
 969         long topl = 0, mytopl = 0;
 970 
 971         for (XWindowPeer xp : windows) {
 972             topl = getToplevelWindow( xp.getWindow() );
 973             if( xp.equals( this ) ) {
 974                 mytopl = topl;
 975             }
 976             if( topl > 0 )
 977                 toplevels.add( Long.valueOf( topl ) );
 978         }
 979 
 980         //
 981         // find in the root's tree:
 982         // (1) my toplevel, (2) lowest java toplevel, (3) desktop
 983         // We must enforce (3), (1), (2) order, upward;
 984         // note that nautilus on the next restacking will do (1),(3),(2).
 985         //
 986         long laux,     wDesktop = -1, wBottom = -1;
 987         int  iMy = -1, iDesktop = -1, iBottom = -1;
 988         int i = 0;
 989         XQueryTree xqt = new XQueryTree(XToolkit.getDefaultRootWindow());
 990         try {
 991             if( xqt.execute() > 0 ) {
 992                 int nchildren = xqt.get_nchildren();
 993                 long children = xqt.get_children();
 994                 for(i = 0; i < nchildren; i++) {
 995                     laux = Native.getWindow(children, i);
 996                     if( laux == mytopl ) {
 997                         iMy = i;
 998                     }else if( isDesktopWindow( laux ) ) {
 999                         // we need topmost desktop of them all.
1000                         iDesktop = i;
1001                         wDesktop = laux;
1002                     }else if(iBottom < 0 &&
1003                              toplevels.contains( Long.valueOf(laux) ) &&
1004                              laux != mytopl) {
1005                         iBottom = i;
1006                         wBottom = laux;
1007                     }
1008                 }
1009             }
1010 
1011             if( (iMy < iBottom || iBottom < 0 )&& iDesktop < iMy)
1012                 return; // no action necessary
1013 
1014             long to_restack = Native.allocateLongArray(2);
1015             Native.putLong(to_restack, 0, wBottom);
1016             Native.putLong(to_restack, 1,  mytopl);
1017             XlibWrapper.XRestackWindows(XToolkit.getDisplay(), to_restack, 2);
1018             XlibWrapper.unsafe.freeMemory(to_restack);
1019 
1020 
1021             if( !mustControlStackPosition ) {
1022                 mustControlStackPosition = true;
1023                 // add root window property listener:
1024                 // somebody (eg nautilus desktop) may obscure us
1025                 addRootPropertyEventDispatcher();
1026             }
1027         } finally {
1028             xqt.dispose();
1029         }
1030     }
1031     /**
1032         Get XID of closest to root window in a given window hierarchy.
1033         FIXME: do not call it "toplevel" as it is misleading.
1034         On error return 0.
1035     */
1036     private long getToplevelWindow( long w ) {
1037         long wi = w, ret, root;
1038         do {
1039             ret = wi;
1040             XQueryTree qt = new XQueryTree(wi);
1041             try {
1042                 if (qt.execute() == 0) {
1043                     return 0;
1044                 }
1045                 root = qt.get_root();
1046                 wi = qt.get_parent();
1047             } finally {
1048                 qt.dispose();
1049             }
1050 
1051         } while (wi != root);
1052 
1053         return ret;
1054     }
1055 
1056     private static boolean isDesktopWindow( long wi ) {
1057         return XWM.getWM().isDesktopWindow( wi );
1058     }
1059 
1060     private void updateAlwaysOnTop() {
1061         if (log.isLoggable(PlatformLogger.Level.FINE)) {
1062             log.fine("Promoting always-on-top state {0}", Boolean.valueOf(alwaysOnTop));
1063         }
1064         XWM.getWM().setLayer(this,
1065                 alwaysOnTop ?
1066                         XLayerProtocol.LAYER_ALWAYS_ON_TOP :
1067                         XLayerProtocol.LAYER_NORMAL);
1068     }
1069 
1070     public void updateAlwaysOnTopState() {
1071         this.alwaysOnTop = ((Window) this.target).isAlwaysOnTop();
1072         if (ownerPeer != null) {
1073             XToolkit.awtLock();
1074             try {
1075                 restoreTransientFor(this);
1076                 applyWindowType();
1077             }
1078             finally {
1079                 XToolkit.awtUnlock();
1080             }
1081         }
1082         updateAlwaysOnTop();
1083     }
1084 
1085     boolean isLocationByPlatform() {
1086         return locationByPlatform;
1087     }
1088 
1089     private void promoteDefaultPosition() {
1090         this.locationByPlatform = ((Window)target).isLocationByPlatform();
1091         if (locationByPlatform) {
1092             XToolkit.awtLock();
1093             try {
1094                 Rectangle bounds = getBounds();
1095                 XSizeHints hints = getHints();
1096                 setSizeHints(hints.get_flags() & ~(XUtilConstants.USPosition | XUtilConstants.PPosition),
1097                              bounds.x, bounds.y, bounds.width, bounds.height);
1098             } finally {
1099                 XToolkit.awtUnlock();
1100             }
1101         }
1102     }
1103 
1104     public void setVisible(boolean vis) {
1105         if (!isVisible() && vis) {
1106             isBeforeFirstMapNotify = true;
1107             winAttr.initialFocus = isAutoRequestFocus();
1108             if (!winAttr.initialFocus) {
1109                 /*
1110                  * It's easier and safer to temporary suppress WM_TAKE_FOCUS
1111                  * protocol itself than to ignore WM_TAKE_FOCUS client message.
1112                  * Because we will have to make the difference between
1113                  * the message come after showing and the message come after
1114                  * activation. Also, on Metacity, for some reason, we have _two_
1115                  * WM_TAKE_FOCUS client messages when showing a frame/dialog.
1116                  */
1117                 suppressWmTakeFocus(true);
1118             }
1119         }
1120         updateFocusability();
1121         promoteDefaultPosition();
1122         if (!vis && warningWindow != null) {
1123             warningWindow.setSecurityWarningVisible(false, false);
1124         }
1125         boolean refreshChildsTransientFor = isVisible() != vis;
1126         super.setVisible(vis);
1127         if (refreshChildsTransientFor) {
1128             for (Window child : ((Window) target).getOwnedWindows()) {
1129                 XToolkit.awtLock();
1130                 try {
1131                     if(!child.isLightweight() && child.isVisible()) {
1132                         ComponentPeer childPeer = AWTAccessor.
1133                                 getComponentAccessor().getPeer(child);
1134                         if(childPeer instanceof XWindowPeer) {
1135                             XWindowPeer windowPeer = (XWindowPeer) childPeer;
1136                             restoreTransientFor(windowPeer);
1137                             windowPeer.applyWindowType();
1138                         }
1139                     }
1140                 }
1141                 finally {
1142                     XToolkit.awtUnlock();
1143                 }
1144             }
1145         }
1146         if (!vis && !isWithdrawn()) {
1147             // ICCCM, 4.1.4. Changing Window State:
1148             // "Iconic -> Withdrawn - The client should unmap the window and follow it
1149             // with a synthetic UnmapNotify event as described later in this section."
1150             // The same is true for Normal -> Withdrawn
1151             XToolkit.awtLock();
1152             try {
1153                 XUnmapEvent unmap = new XUnmapEvent();
1154                 unmap.set_window(window);
1155                 unmap.set_event(XToolkit.getDefaultRootWindow());
1156                 unmap.set_type(XConstants.UnmapNotify);
1157                 unmap.set_from_configure(false);
1158                 XlibWrapper.XSendEvent(XToolkit.getDisplay(), XToolkit.getDefaultRootWindow(),
1159                         false, XConstants.SubstructureNotifyMask | XConstants.SubstructureRedirectMask,
1160                         unmap.pData);
1161                 unmap.dispose();
1162             }
1163             finally {
1164                 XToolkit.awtUnlock();
1165             }
1166         }
1167         // method called somewhere in parent does not generate configure-notify
1168         // event for override-redirect.
1169         // Ergo, no reshape and bugs like 5085647 in case setBounds was
1170         // called before setVisible.
1171         if (isOverrideRedirect() && vis) {
1172             updateChildrenSizes();
1173         }
1174         repositionSecurityWarning();
1175     }
1176 
1177     protected void suppressWmTakeFocus(boolean doSuppress) {
1178     }
1179 
1180     final boolean isSimpleWindow() {
1181         return !(target instanceof Frame || target instanceof Dialog);
1182     }
1183     boolean hasWarningWindow() {
1184         return ((Window)target).getWarningString() != null;
1185     }
1186 
1187     // The height of menu bar window
1188     int getMenuBarHeight() {
1189         return 0;
1190     }
1191 
1192     // Called when shell changes its size and requires children windows
1193     // to update their sizes appropriately
1194     void updateChildrenSizes() {
1195     }
1196 
1197     public void repositionSecurityWarning() {
1198         // NOTE: On KWin if the window/border snapping option is enabled,
1199         // the Java window may be swinging while it's being moved.
1200         // This doesn't make the application unusable though looks quite ugly.
1201         // Probobly we need to find some hint to assign to our Security
1202         // Warning window in order to exclude it from the snapping option.
1203         // We are not currently aware of existance of such a property.
1204         if (warningWindow != null) {
1205             // We can't use the coordinates stored in the XBaseWindow since
1206             // they are zeros for decorated frames.
1207             ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
1208             int x = compAccessor.getX(target);
1209             int y = compAccessor.getY(target);
1210             int width = compAccessor.getWidth(target);
1211             int height = compAccessor.getHeight(target);
1212             warningWindow.reposition(x, y, width, height);
1213         }
1214     }
1215 
1216     @Override
1217     protected void setMouseAbove(boolean above) {
1218         super.setMouseAbove(above);
1219         updateSecurityWarningVisibility();
1220     }
1221 
1222     @Override
1223     public void setFullScreenExclusiveModeState(boolean state) {
1224         super.setFullScreenExclusiveModeState(state);
1225         updateSecurityWarningVisibility();
1226     }
1227 
1228     public void updateSecurityWarningVisibility() {
1229         if (warningWindow == null) {
1230             return;
1231         }
1232 
1233         if (!isVisible()) {
1234             return; // The warning window should already be hidden.
1235         }
1236 
1237         boolean show = false;
1238 
1239         if (!isFullScreenExclusiveMode()) {
1240             int state = getWMState();
1241 
1242             // getWMState() always returns 0 (Withdrawn) for simple windows. Hence
1243             // we ignore the state for such windows.
1244             if (isVisible() && (state == XUtilConstants.NormalState || isSimpleWindow())) {
1245                 if (XKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow() ==
1246                         getTarget())
1247                 {
1248                     show = true;
1249                 }
1250 
1251                 if (isMouseAbove() || warningWindow.isMouseAbove())
1252                 {
1253                     show = true;
1254                 }
1255             }
1256         }
1257 
1258         warningWindow.setSecurityWarningVisible(show, true);
1259     }
1260 
1261     boolean isOverrideRedirect() {
1262         return XWM.getWMID() == XWM.OPENLOOK_WM ||
1263             Window.Type.POPUP.equals(getWindowType());
1264     }
1265 
1266     final boolean isOLWMDecorBug() {
1267         return XWM.getWMID() == XWM.OPENLOOK_WM &&
1268             winAttr.nativeDecor == false;
1269     }
1270 
1271     public void dispose() {
1272         if (isGrabbed()) {
1273             if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
1274                 grabLog.fine("Generating UngrabEvent on {0} because of the window disposal", this);
1275             }
1276             postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
1277         }
1278 
1279         SunToolkit.awtLock();
1280 
1281         try {
1282             windows.remove(this);
1283         } finally {
1284             SunToolkit.awtUnlock();
1285         }
1286 
1287         if (warningWindow != null) {
1288             warningWindow.destroy();
1289         }
1290 
1291         removeRootPropertyEventDispatcher();
1292         mustControlStackPosition = false;
1293         super.dispose();
1294 
1295         /*
1296          * Fix for 6457980.
1297          * When disposing an owned Window we should implicitly
1298          * return focus to its decorated owner because it won't
1299          * receive WM_TAKE_FOCUS.
1300          */
1301         if (isSimpleWindow()) {
1302             if (target == XKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow()) {
1303                 Window owner = getDecoratedOwner((Window)target);
1304                 ((XWindowPeer)AWTAccessor.getComponentAccessor().getPeer(owner)).requestWindowFocus();
1305             }
1306         }
1307     }
1308 
1309     boolean isResizable() {
1310         return winAttr.isResizable;
1311     }
1312 
1313     public void handleVisibilityEvent(XEvent xev) {
1314         super.handleVisibilityEvent(xev);
1315         XVisibilityEvent ve = xev.get_xvisibility();
1316         winAttr.visibilityState = ve.get_state();
1317 //         if (ve.get_state() == XlibWrapper.VisibilityUnobscured) {
1318 //             // raiseInputMethodWindow
1319 //         }
1320         repositionSecurityWarning();
1321     }
1322 
1323     void handleRootPropertyNotify(XEvent xev) {
1324         XPropertyEvent ev = xev.get_xproperty();
1325         if( mustControlStackPosition &&
1326             ev.get_atom() == XAtom.get("_NET_CLIENT_LIST_STACKING").getAtom()){
1327             // Restore stack order unhadled/spoiled by WM or some app (nautilus).
1328             // As of now, don't use any generic machinery: just
1329             // do toBack() again.
1330             if(isOverrideRedirect()) {
1331                 toBack();
1332             }
1333         }
1334     }
1335 
1336     private void removeStartupNotification() {
1337         if (isStartupNotificationRemoved.getAndSet(true)) {
1338             return;
1339         }
1340 
1341         final String desktopStartupId = AccessController.doPrivileged(new PrivilegedAction<String>() {
1342             public String run() {
1343                 return XToolkit.getEnv("DESKTOP_STARTUP_ID");
1344             }
1345         });
1346         if (desktopStartupId == null) {
1347             return;
1348         }
1349 
1350         final StringBuilder messageBuilder = new StringBuilder("remove: ID=");
1351         messageBuilder.append('"');
1352         for (int i = 0; i < desktopStartupId.length(); i++) {
1353             if (desktopStartupId.charAt(i) == '"' || desktopStartupId.charAt(i) == '\\') {
1354                 messageBuilder.append('\\');
1355             }
1356             messageBuilder.append(desktopStartupId.charAt(i));
1357         }
1358         messageBuilder.append('"');
1359         messageBuilder.append('\0');
1360         final byte[] message;
1361         try {
1362             message = messageBuilder.toString().getBytes("UTF-8");
1363         } catch (UnsupportedEncodingException cannotHappen) {
1364             return;
1365         }
1366 
1367         XClientMessageEvent req = null;
1368 
1369         XToolkit.awtLock();
1370         try {
1371             final XAtom netStartupInfoBeginAtom = XAtom.get("_NET_STARTUP_INFO_BEGIN");
1372             final XAtom netStartupInfoAtom = XAtom.get("_NET_STARTUP_INFO");
1373 
1374             req = new XClientMessageEvent();
1375             req.set_type(XConstants.ClientMessage);
1376             req.set_window(getWindow());
1377             req.set_message_type(netStartupInfoBeginAtom.getAtom());
1378             req.set_format(8);
1379 
1380             for (int pos = 0; pos < message.length; pos += 20) {
1381                 final int msglen = Math.min(message.length - pos, 20);
1382                 int i = 0;
1383                 for (; i < msglen; i++) {
1384                     XlibWrapper.unsafe.putByte(req.get_data() + i, message[pos + i]);
1385                 }
1386                 for (; i < 20; i++) {
1387                     XlibWrapper.unsafe.putByte(req.get_data() + i, (byte)0);
1388                 }
1389                 XlibWrapper.XSendEvent(XToolkit.getDisplay(),
1390                     XlibWrapper.RootWindow(XToolkit.getDisplay(), getScreenNumber()),
1391                     false,
1392                     XConstants.PropertyChangeMask,
1393                     req.pData);
1394                 req.set_message_type(netStartupInfoAtom.getAtom());
1395             }
1396         } finally {
1397             XToolkit.awtUnlock();
1398             if (req != null) {
1399                 req.dispose();
1400             }
1401         }
1402     }
1403 
1404     public void handleMapNotifyEvent(XEvent xev) {
1405         removeStartupNotification();
1406 
1407         // See 6480534.
1408         isUnhiding |= isWMStateNetHidden();
1409 
1410         super.handleMapNotifyEvent(xev);
1411         if (!winAttr.initialFocus) {
1412             suppressWmTakeFocus(false); // restore the protocol.
1413             /*
1414              * For some reason, on Metacity, a frame/dialog being shown
1415              * without WM_TAKE_FOCUS protocol doesn't get moved to the front.
1416              * So, we do it evidently.
1417              */
1418             XToolkit.awtLock();
1419             try {
1420                 XlibWrapper.XRaiseWindow(XToolkit.getDisplay(), getWindow());
1421             } finally {
1422                 XToolkit.awtUnlock();
1423             }
1424         }
1425         if (shouldFocusOnMapNotify()) {
1426             focusLog.fine("Automatically request focus on window");
1427             requestInitialFocus();
1428         }
1429         isUnhiding = false;
1430         isBeforeFirstMapNotify = false;
1431         updateAlwaysOnTop();
1432 
1433         synchronized (getStateLock()) {
1434             if (!isMapped) {
1435                 isMapped = true;
1436             }
1437         }
1438     }
1439 
1440     public void handleUnmapNotifyEvent(XEvent xev) {
1441         super.handleUnmapNotifyEvent(xev);
1442 
1443         // On Metacity UnmapNotify comes before PropertyNotify (for _NET_WM_STATE_HIDDEN).
1444         // So we also check for the property later in MapNotify. See 6480534.
1445         isUnhiding |= isWMStateNetHidden();
1446 
1447         synchronized (getStateLock()) {
1448             if (isMapped) {
1449                 isMapped = false;
1450             }
1451         }
1452     }
1453 
1454     private boolean shouldFocusOnMapNotify() {
1455         boolean res = false;
1456 
1457         if (isBeforeFirstMapNotify) {
1458             res = (winAttr.initialFocus ||          // Window.autoRequestFocus
1459                    isFocusedWindowModalBlocker());
1460         } else {
1461             res = isUnhiding;                       // Unhiding
1462         }
1463         res = res &&
1464             isFocusableWindow() &&                  // General focusability
1465             !isModalBlocked();                      // Modality
1466 
1467         return res;
1468     }
1469 
1470     protected boolean isWMStateNetHidden() {
1471         XNETProtocol protocol = XWM.getWM().getNETProtocol();
1472         return (protocol != null && protocol.isWMStateNetHidden(this));
1473     }
1474 
1475     protected void requestInitialFocus() {
1476         requestXFocus();
1477     }
1478 
1479     public void addToplevelStateListener(ToplevelStateListener l){
1480         toplevelStateListeners.add(l);
1481     }
1482 
1483     public void removeToplevelStateListener(ToplevelStateListener l){
1484         toplevelStateListeners.remove(l);
1485     }
1486 
1487     /**
1488      * Override this methods to get notifications when top-level window state changes. The state is
1489      * meant in terms of ICCCM: WithdrawnState, IconicState, NormalState
1490      */
1491     @Override
1492     protected void stateChanged(long time, int oldState, int newState) {
1493         // Fix for 6401700, 6412803
1494         // If this window is modal blocked, it is put into the transient_for
1495         // chain using prevTransientFor and nextTransientFor hints. However,
1496         // the real WM_TRANSIENT_FOR hint shouldn't be set for windows in
1497         // different WM states (except for owner-window relationship), so
1498         // if the window changes its state, its real WM_TRANSIENT_FOR hint
1499         // should be updated accordingly.
1500         updateTransientFor();
1501 
1502         for (ToplevelStateListener topLevelListenerTmp : toplevelStateListeners) {
1503             topLevelListenerTmp.stateChangedICCCM(oldState, newState);
1504         }
1505 
1506         updateSecurityWarningVisibility();
1507     }
1508 
1509     boolean isWithdrawn() {
1510         return getWMState() == XUtilConstants.WithdrawnState;
1511     }
1512 
1513     boolean hasDecorations(int decor) {
1514         if (!winAttr.nativeDecor) {
1515             return false;
1516         }
1517         else {
1518             int myDecor = winAttr.decorations;
1519             boolean hasBits = ((myDecor & decor) == decor);
1520             if ((myDecor & XWindowAttributesData.AWT_DECOR_ALL) != 0)
1521                 return !hasBits;
1522             else
1523                 return hasBits;
1524         }
1525     }
1526 
1527     void setReparented(boolean newValue) {
1528         super.setReparented(newValue);
1529         XToolkit.awtLock();
1530         try {
1531             if (isReparented() && delayedModalBlocking) {
1532                 addToTransientFors(AWTAccessor.getComponentAccessor().getPeer(modalBlocker));
1533                 delayedModalBlocking = false;
1534             }
1535         } finally {
1536             XToolkit.awtUnlock();
1537         }
1538     }
1539 
1540     /*
1541      * Returns a Vector of all Java top-level windows,
1542      * sorted by their current Z-order
1543      */
1544     static Vector<XWindowPeer> collectJavaToplevels() {
1545         Vector<XWindowPeer> javaToplevels = new Vector<XWindowPeer>();
1546         Vector<Long> v = new Vector<Long>();
1547         X11GraphicsEnvironment ge =
1548             (X11GraphicsEnvironment)GraphicsEnvironment.getLocalGraphicsEnvironment();
1549         GraphicsDevice[] gds = ge.getScreenDevices();
1550         if (!ge.runningXinerama() && (gds.length > 1)) {
1551             for (GraphicsDevice gd : gds) {
1552                 int screen = ((X11GraphicsDevice)gd).getScreen();
1553                 long rootWindow = XlibWrapper.RootWindow(XToolkit.getDisplay(), screen);
1554                 v.add(rootWindow);
1555             }
1556         } else {
1557             v.add(XToolkit.getDefaultRootWindow());
1558         }
1559         final int windowsCount = windows.size();
1560         while ((v.size() > 0) && (javaToplevels.size() < windowsCount)) {
1561             long win = v.remove(0);
1562             XQueryTree qt = new XQueryTree(win);
1563             try {
1564                 if (qt.execute() != 0) {
1565                     int nchildren = qt.get_nchildren();
1566                     long children = qt.get_children();
1567                     // XQueryTree returns window children ordered by z-order
1568                     for (int i = 0; i < nchildren; i++) {
1569                         long child = Native.getWindow(children, i);
1570                         XBaseWindow childWindow = XToolkit.windowToXWindow(child);
1571                         // filter out Java non-toplevels
1572                         if ((childWindow != null) && !(childWindow instanceof XWindowPeer)) {
1573                             continue;
1574                         } else {
1575                             v.add(child);
1576                         }
1577                         if (childWindow instanceof XWindowPeer) {
1578                             XWindowPeer np = (XWindowPeer)childWindow;
1579                             javaToplevels.add(np);
1580                             // XQueryTree returns windows sorted by their z-order. However,
1581                             // if WM has not handled transient for hint for a child window,
1582                             // it may appear in javaToplevels before its owner. Move such
1583                             // children after their owners.
1584                             int k = 0;
1585                             XWindowPeer toCheck = javaToplevels.get(k);
1586                             while (toCheck != np) {
1587                                 XWindowPeer toCheckOwnerPeer = toCheck.getOwnerPeer();
1588                                 if (toCheckOwnerPeer == np) {
1589                                     javaToplevels.remove(k);
1590                                     javaToplevels.add(toCheck);
1591                                 } else {
1592                                     k++;
1593                                 }
1594                                 toCheck = javaToplevels.get(k);
1595                             }
1596                         }
1597                     }
1598                 }
1599             } finally {
1600                 qt.dispose();
1601             }
1602         }
1603         return javaToplevels;
1604     }
1605 
1606     public void setModalBlocked(Dialog d, boolean blocked) {
1607         setModalBlocked(d, blocked, null);
1608     }
1609     public void setModalBlocked(Dialog d, boolean blocked,
1610                                 Vector<XWindowPeer> javaToplevels)
1611     {
1612         XToolkit.awtLock();
1613         try {
1614             // State lock should always be after awtLock
1615             synchronized(getStateLock()) {
1616                 XDialogPeer blockerPeer = AWTAccessor.getComponentAccessor().getPeer(d);
1617                 if (blocked) {
1618                     if (log.isLoggable(PlatformLogger.Level.FINE)) {
1619                         log.fine("{0} is blocked by {1}", this, blockerPeer);
1620                     }
1621                     modalBlocker = d;
1622 
1623                     if (isReparented() || XWM.isNonReparentingWM()) {
1624                         addToTransientFors(blockerPeer, javaToplevels);
1625                     } else {
1626                         delayedModalBlocking = true;
1627                     }
1628                 } else {
1629                     if (d != modalBlocker) {
1630                         throw new IllegalStateException("Trying to unblock window blocked by another dialog");
1631                     }
1632                     modalBlocker = null;
1633 
1634                     if (isReparented() || XWM.isNonReparentingWM()) {
1635                         removeFromTransientFors();
1636                     } else {
1637                         delayedModalBlocking = false;
1638                     }
1639                 }
1640 
1641                 updateTransientFor();
1642             }
1643         } finally {
1644             XToolkit.awtUnlock();
1645         }
1646     }
1647 
1648     /*
1649      * Sets the TRANSIENT_FOR hint to the given top-level window. This
1650      *  method is used when a window is modal blocked/unblocked or
1651      *  changed its state from/to NormalState to/from other states.
1652      * If window or transientForWindow are embedded frames, the containing
1653      *  top-level windows are used.
1654      *
1655      * @param window specifies the top-level window that the hint
1656      *  is to be set to
1657      * @param transientForWindow the top-level window
1658      * @param updateChain specifies if next/prevTransientFor fields are
1659      *  to be updated
1660      * @param allStates if set to {@code true} then TRANSIENT_FOR hint
1661      *  is set regardless of the state of window and transientForWindow,
1662      *  otherwise it is set only if both are in the same state
1663      */
1664     static void setToplevelTransientFor(XWindowPeer window, XWindowPeer transientForWindow,
1665                                                 boolean updateChain, boolean allStates)
1666     {
1667         if ((window == null) || (transientForWindow == null)) {
1668             return;
1669         }
1670         if (updateChain) {
1671             window.prevTransientFor = transientForWindow;
1672             transientForWindow.nextTransientFor = window;
1673         }
1674         if (!allStates && (window.getWMState() != transientForWindow.getWMState())) {
1675             return;
1676         }
1677         if (window.getScreenNumber() != transientForWindow.getScreenNumber()) {
1678             return;
1679         }
1680         long bpw = window.getWindow();
1681         while (!XlibUtil.isToplevelWindow(bpw) && !XlibUtil.isXAWTToplevelWindow(bpw)) {
1682             bpw = XlibUtil.getParentWindow(bpw);
1683         }
1684         long tpw = transientForWindow.getWindow();
1685         XBaseWindow parent = transientForWindow;
1686         while (tpw != 0 && ((!XlibUtil.isToplevelWindow(tpw) &&
1687                 !XlibUtil.isXAWTToplevelWindow(tpw)) || !parent.isVisible())) {
1688             tpw = XlibUtil.getParentWindow(tpw);
1689             parent = XToolkit.windowToXWindow(tpw);
1690         }
1691         XlibWrapper.XSetTransientFor(XToolkit.getDisplay(), bpw, tpw);
1692         window.curRealTransientFor = parent;
1693     }
1694 
1695     /*
1696      * This method does nothing if this window is not blocked by any modal dialog.
1697      * For modal blocked windows this method looks up for the nearest
1698      *  prevTransiendFor window that is in the same state (Normal/Iconified/Withdrawn)
1699      *  as this one and makes this window transient for it. The same operation is
1700      *  performed for nextTransientFor window.
1701      * Values of prevTransientFor and nextTransientFor fields are not changed.
1702      */
1703     void updateTransientFor() {
1704         int state = getWMState();
1705         XWindowPeer p = prevTransientFor;
1706         while ((p != null) && ((p.getWMState() != state) || (p.getScreenNumber() != getScreenNumber()))) {
1707             p = p.prevTransientFor;
1708         }
1709         if (p != null) {
1710             setToplevelTransientFor(this, p, false, false);
1711         } else {
1712             restoreTransientFor(this);
1713         }
1714         XWindowPeer n = nextTransientFor;
1715         while ((n != null) && ((n.getWMState() != state) || (n.getScreenNumber() != getScreenNumber()))) {
1716             n = n.nextTransientFor;
1717         }
1718         if (n != null) {
1719             setToplevelTransientFor(n, this, false, false);
1720         }
1721     }
1722 
1723     /*
1724      * Removes the TRANSIENT_FOR hint from the given top-level window.
1725      * If window or transientForWindow are embedded frames, the containing
1726      *  top-level windows are used.
1727      *
1728      * @param window specifies the top-level window that the hint
1729      *  is to be removed from
1730      */
1731     private static void removeTransientForHint(XWindowPeer window) {
1732         XAtom XA_WM_TRANSIENT_FOR = XAtom.get(XAtom.XA_WM_TRANSIENT_FOR);
1733         long bpw = window.getWindow();
1734         while (!XlibUtil.isToplevelWindow(bpw) && !XlibUtil.isXAWTToplevelWindow(bpw)) {
1735             bpw = XlibUtil.getParentWindow(bpw);
1736         }
1737         XlibWrapper.XDeleteProperty(XToolkit.getDisplay(), bpw, XA_WM_TRANSIENT_FOR.getAtom());
1738         window.curRealTransientFor = null;
1739     }
1740 
1741     /*
1742      * When a modal dialog is shown, all its blocked windows are lined up into
1743      *  a chain in such a way that each window is a transient_for window for
1744      *  the next one. That allows us to keep the modal dialog above all its
1745      *  blocked windows (even if there are some another modal dialogs between
1746      *  them).
1747      * This method adds this top-level window to the chain of the given modal
1748      *  dialog. To keep the current relative z-order, we should use the
1749      *  XQueryTree to find the place to insert this window to. As each window
1750      *  can be blocked by only one modal dialog (such checks are performed in
1751      *  shared code), both this and blockerPeer are on the top of their chains
1752      *  (chains may be empty).
1753      * If this window is a modal dialog and has its own chain, these chains are
1754      *  merged according to the current z-order (XQueryTree is used again).
1755      *  Below are some simple examples (z-order is from left to right, -- is
1756      *  modal blocking).
1757      *
1758      * Example 0:
1759      *     T (current chain of this, no windows are blocked by this)
1760      *  W1---B (current chain of blockerPeer, W2 is blocked by blockerPeer)
1761      *  Result is:
1762      *  W1-T-B (merged chain, all the windows are blocked by blockerPeer)
1763      *
1764      * Example 1:
1765      *  W1-T (current chain of this, W1 is blocked by this)
1766      *       W2-B (current chain of blockerPeer, W2 is blocked by blockerPeer)
1767      *  Result is:
1768      *  W1-T-W2-B (merged chain, all the windows are blocked by blockerPeer)
1769      *
1770      * Example 2:
1771      *  W1----T (current chain of this, W1 is blocked by this)
1772      *     W2---B (current chain of blockerPeer, W2 is blocked by blockerPeer)
1773      *  Result is:
1774      *  W1-W2-T-B (merged chain, all the windows are blocked by blockerPeer)
1775      *
1776      * This method should be called under the AWT lock.
1777      *
1778      * @see #removeFromTransientFors
1779      * @see #setModalBlocked
1780      */
1781     private void addToTransientFors(XDialogPeer blockerPeer) {
1782         addToTransientFors(blockerPeer, null);
1783     }
1784 
1785     private void addToTransientFors(XDialogPeer blockerPeer, Vector<XWindowPeer> javaToplevels)
1786     {
1787         // blockerPeer chain iterator
1788         XWindowPeer blockerChain = blockerPeer;
1789         while (blockerChain.prevTransientFor != null) {
1790             blockerChain = blockerChain.prevTransientFor;
1791         }
1792         // this window chain iterator
1793         // each window can be blocked no more than once, so this window
1794         //   is on top of its chain
1795         XWindowPeer thisChain = this;
1796         while (thisChain.prevTransientFor != null) {
1797             thisChain = thisChain.prevTransientFor;
1798         }
1799         // if there are no windows blocked by modalBlocker, simply add this window
1800         //  and its chain to blocker's chain
1801         if (blockerChain == blockerPeer) {
1802             setToplevelTransientFor(blockerPeer, this, true, false);
1803         } else {
1804             // Collect all the Java top-levels, if required
1805             if (javaToplevels == null) {
1806                 javaToplevels = collectJavaToplevels();
1807             }
1808             // merged chain tail
1809             XWindowPeer mergedChain = null;
1810             for (XWindowPeer w : javaToplevels) {
1811                 XWindowPeer prevMergedChain = mergedChain;
1812                 if (w == thisChain) {
1813                     if (thisChain == this) {
1814                         if (prevMergedChain != null) {
1815                             setToplevelTransientFor(this, prevMergedChain, true, false);
1816                         }
1817                         setToplevelTransientFor(blockerChain, this, true, false);
1818                         break;
1819                     } else {
1820                         mergedChain = thisChain;
1821                         thisChain = thisChain.nextTransientFor;
1822                     }
1823                 } else if (w == blockerChain) {
1824                     mergedChain = blockerChain;
1825                     blockerChain = blockerChain.nextTransientFor;
1826                 } else {
1827                     continue;
1828                 }
1829                 if (prevMergedChain == null) {
1830                     mergedChain.prevTransientFor = null;
1831                 } else {
1832                     setToplevelTransientFor(mergedChain, prevMergedChain, true, false);
1833                     mergedChain.updateTransientFor();
1834                 }
1835                 if (blockerChain == blockerPeer) {
1836                     setToplevelTransientFor(thisChain, mergedChain, true, false);
1837                     setToplevelTransientFor(blockerChain, this, true, false);
1838                     break;
1839                 }
1840             }
1841         }
1842 
1843         XToolkit.XSync();
1844     }
1845 
1846     static void restoreTransientFor(XWindowPeer window) {
1847         XWindowPeer ownerPeer = window.getOwnerPeer();
1848         if (ownerPeer != null) {
1849             setToplevelTransientFor(window, ownerPeer, false, true);
1850         } else {
1851             removeTransientForHint(window);
1852         }
1853     }
1854 
1855     /*
1856      * When a window is modally unblocked, it should be removed from its blocker
1857      *  chain, see {@link #addToTransientFor addToTransientFors} method for the
1858      *  chain definition.
1859      * The problem is that we cannot simply restore window's original
1860      *  TRANSIENT_FOR hint (if any) and link prevTransientFor and
1861      *  nextTransientFor together as the whole chain could be created as a merge
1862      *  of two other chains in addToTransientFors. In that case, if this window is
1863      *  a modal dialog, it would lost all its own chain, if we simply exclude it
1864      *  from the chain.
1865      * The correct behaviour of this method should be to split the chain, this
1866      *  window is currently in, into two chains. First chain is this window own
1867      *  chain (i. e. all the windows blocked by this one, directly or indirectly),
1868      *  if any, and the rest windows from the current chain.
1869      *
1870      * Example:
1871      *  Original state:
1872      *   W1-B1 (window W1 is blocked by B1)
1873      *   W2-B2 (window W2 is blocked by B2)
1874      *  B3 is shown and blocks B1 and B2:
1875      *   W1-W2-B1-B2-B3 (a single chain after B1.addToTransientFors() and B2.addToTransientFors())
1876      *  If we then unblock B1, the state should be:
1877      *   W1-B1 (window W1 is blocked by B1)
1878      *   W2-B2-B3 (window W2 is blocked by B2 and B2 is blocked by B3)
1879      *
1880      * This method should be called under the AWT lock.
1881      *
1882      * @see #addToTransientFors
1883      * @see #setModalBlocked
1884      */
1885     private void removeFromTransientFors() {
1886         // the head of the chain of this window
1887         XWindowPeer thisChain = this;
1888         // the head of the current chain
1889         // nextTransientFor is always not null as this window is in the chain
1890         XWindowPeer otherChain = nextTransientFor;
1891         // the set of blockers in this chain: if this dialog blocks some other
1892         // modal dialogs, their blocked windows should stay in this dialog's chain
1893         Set<XWindowPeer> thisChainBlockers = new HashSet<XWindowPeer>();
1894         thisChainBlockers.add(this);
1895         // current chain iterator in the order from next to prev
1896         XWindowPeer chainToSplit = prevTransientFor;
1897         while (chainToSplit != null) {
1898             XWindowPeer blocker = AWTAccessor.getComponentAccessor().getPeer(chainToSplit.modalBlocker);
1899             if (thisChainBlockers.contains(blocker)) {
1900                 // add to this dialog's chain
1901                 setToplevelTransientFor(thisChain, chainToSplit, true, false);
1902                 thisChain = chainToSplit;
1903                 thisChainBlockers.add(chainToSplit);
1904             } else {
1905                 // leave in the current chain
1906                 setToplevelTransientFor(otherChain, chainToSplit, true, false);
1907                 otherChain = chainToSplit;
1908             }
1909             chainToSplit = chainToSplit.prevTransientFor;
1910         }
1911         restoreTransientFor(thisChain);
1912         thisChain.prevTransientFor = null;
1913         restoreTransientFor(otherChain);
1914         otherChain.prevTransientFor = null;
1915         nextTransientFor = null;
1916 
1917         XToolkit.XSync();
1918     }
1919 
1920     boolean isModalBlocked() {
1921         return modalBlocker != null;
1922     }
1923 
1924     static Window getDecoratedOwner(Window window) {
1925         while ((null != window) && !(window instanceof Frame || window instanceof Dialog)) {
1926             window = (Window) AWTAccessor.getComponentAccessor().getParent(window);
1927         }
1928         return window;
1929     }
1930 
1931     public boolean requestWindowFocus(XWindowPeer actualFocusedWindow) {
1932         setActualFocusedWindow(actualFocusedWindow);
1933         return requestWindowFocus();
1934     }
1935 
1936     public boolean requestWindowFocus() {
1937         return requestWindowFocus(0, false);
1938     }
1939 
1940     public boolean requestWindowFocus(long time, boolean timeProvided) {
1941         focusLog.fine("Request for window focus");
1942         // If this is Frame or Dialog we can't assure focus request success - but we still can try
1943         // If this is Window and its owner Frame is active we can be sure request succedded.
1944         Window ownerWindow  = XWindowPeer.getDecoratedOwner((Window)target);
1945         Window focusedWindow = XKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow();
1946         Window activeWindow = XWindowPeer.getDecoratedOwner(focusedWindow);
1947 
1948         if (isWMStateNetHidden()) {
1949             focusLog.fine("The window is unmapped, so rejecting the request");
1950             return false;
1951         }
1952         if (activeWindow == ownerWindow) {
1953             focusLog.fine("Parent window is active - generating focus for this window");
1954             handleWindowFocusInSync(-1);
1955             return true;
1956         }
1957         focusLog.fine("Parent window is not active");
1958 
1959         XDecoratedPeer wpeer = AWTAccessor.getComponentAccessor().getPeer(ownerWindow);
1960         if (wpeer != null && wpeer.requestWindowFocus(this, time, timeProvided)) {
1961             focusLog.fine("Parent window accepted focus request - generating focus for this window");
1962             return true;
1963         }
1964         focusLog.fine("Denied - parent window is not active and didn't accept focus request");
1965         return false;
1966     }
1967 
1968     // This method is to be overriden in XDecoratedPeer.
1969     void setActualFocusedWindow(XWindowPeer actualFocusedWindow) {
1970     }
1971 
1972     /**
1973      * Applies the current window type.
1974      */
1975     private void applyWindowType() {
1976         XNETProtocol protocol = XWM.getWM().getNETProtocol();
1977         if (protocol == null) {
1978             return;
1979         }
1980 
1981         XAtom typeAtom = null;
1982 
1983         switch (getWindowType())
1984         {
1985             case NORMAL:
1986                 typeAtom = curRealTransientFor == null ?
1987                                protocol.XA_NET_WM_WINDOW_TYPE_NORMAL :
1988                                protocol.XA_NET_WM_WINDOW_TYPE_DIALOG;
1989                 break;
1990             case UTILITY:
1991                 typeAtom = protocol.XA_NET_WM_WINDOW_TYPE_UTILITY;
1992                 break;
1993             case POPUP:
1994                 typeAtom = protocol.XA_NET_WM_WINDOW_TYPE_POPUP_MENU;
1995                 break;
1996         }
1997 
1998         if (typeAtom != null) {
1999             XAtomList wtype = new XAtomList();
2000             wtype.add(typeAtom);
2001             protocol.XA_NET_WM_WINDOW_TYPE.
2002                 setAtomListProperty(getWindow(), wtype);
2003         } else {
2004             protocol.XA_NET_WM_WINDOW_TYPE.
2005                 DeleteProperty(getWindow());
2006         }
2007     }
2008 
2009     @Override
2010     public void xSetVisible(boolean visible) {
2011         if (log.isLoggable(PlatformLogger.Level.FINE)) {
2012             log.fine("Setting visible on " + this + " to " + visible);
2013         }
2014         XToolkit.awtLock();
2015         try {
2016             this.visible = visible;
2017             if (visible) {
2018                 applyWindowType();
2019                 XlibWrapper.XMapRaised(XToolkit.getDisplay(), getWindow());
2020             } else {
2021                 XlibWrapper.XUnmapWindow(XToolkit.getDisplay(), getWindow());
2022             }
2023             XlibWrapper.XFlush(XToolkit.getDisplay());
2024         }
2025         finally {
2026             XToolkit.awtUnlock();
2027         }
2028     }
2029 
2030     // should be synchronized on awtLock
2031     private int dropTargetCount = 0;
2032 
2033     public void addDropTarget() {
2034         XToolkit.awtLock();
2035         try {
2036             if (dropTargetCount == 0) {
2037                 long window = getWindow();
2038                 if (window != 0) {
2039                     XDropTargetRegistry.getRegistry().registerDropSite(window);
2040                 }
2041             }
2042             dropTargetCount++;
2043         } finally {
2044             XToolkit.awtUnlock();
2045         }
2046     }
2047 
2048     public void removeDropTarget() {
2049         XToolkit.awtLock();
2050         try {
2051             dropTargetCount--;
2052             if (dropTargetCount == 0) {
2053                 long window = getWindow();
2054                 if (window != 0) {
2055                     XDropTargetRegistry.getRegistry().unregisterDropSite(window);
2056                 }
2057             }
2058         } finally {
2059             XToolkit.awtUnlock();
2060         }
2061     }
2062     void addRootPropertyEventDispatcher() {
2063         if( rootPropertyEventDispatcher == null ) {
2064             rootPropertyEventDispatcher = new XEventDispatcher() {
2065                 public void dispatchEvent(XEvent ev) {
2066                     if( ev.get_type() == XConstants.PropertyNotify ) {
2067                         handleRootPropertyNotify( ev );
2068                     }
2069                 }
2070             };
2071             XlibWrapper.XSelectInput( XToolkit.getDisplay(),
2072                                       XToolkit.getDefaultRootWindow(),
2073                                       XConstants.PropertyChangeMask);
2074             XToolkit.addEventDispatcher(XToolkit.getDefaultRootWindow(),
2075                                                 rootPropertyEventDispatcher);
2076         }
2077     }
2078     void removeRootPropertyEventDispatcher() {
2079         if( rootPropertyEventDispatcher != null ) {
2080             XToolkit.removeEventDispatcher(XToolkit.getDefaultRootWindow(),
2081                                                 rootPropertyEventDispatcher);
2082             rootPropertyEventDispatcher = null;
2083         }
2084     }
2085     public void updateFocusableWindowState() {
2086         cachedFocusableWindow = isFocusableWindow();
2087     }
2088 
2089     XAtom XA_NET_WM_STATE;
2090     XAtomList net_wm_state;
2091     public XAtomList getNETWMState() {
2092         if (net_wm_state == null) {
2093             net_wm_state = XA_NET_WM_STATE.getAtomListPropertyList(this);
2094         }
2095         return net_wm_state;
2096     }
2097 
2098     public void setNETWMState(XAtomList state) {
2099         net_wm_state = state;
2100         if (state != null) {
2101             XA_NET_WM_STATE.setAtomListProperty(this, state);
2102         }
2103     }
2104 
2105     public PropMwmHints getMWMHints() {
2106         if (mwm_hints == null) {
2107             mwm_hints = new PropMwmHints();
2108             if (!XWM.XA_MWM_HINTS.getAtomData(getWindow(), mwm_hints.pData, MWMConstants.PROP_MWM_HINTS_ELEMENTS)) {
2109                 mwm_hints.zero();
2110             }
2111         }
2112         return mwm_hints;
2113     }
2114 
2115     public void setMWMHints(PropMwmHints hints) {
2116         mwm_hints = hints;
2117         if (hints != null) {
2118             XWM.XA_MWM_HINTS.setAtomData(getWindow(), mwm_hints.pData, MWMConstants.PROP_MWM_HINTS_ELEMENTS);
2119         }
2120     }
2121 
2122     protected void updateDropTarget() {
2123         XToolkit.awtLock();
2124         try {
2125             if (dropTargetCount > 0) {
2126                 long window = getWindow();
2127                 if (window != 0) {
2128                     XDropTargetRegistry.getRegistry().unregisterDropSite(window);
2129                     XDropTargetRegistry.getRegistry().registerDropSite(window);
2130                 }
2131             }
2132         } finally {
2133             XToolkit.awtUnlock();
2134         }
2135     }
2136 
2137     public void setGrab(boolean grab) {
2138         this.grab = grab;
2139         if (grab) {
2140             pressTarget = this;
2141             grabInput();
2142         } else {
2143             ungrabInput();
2144         }
2145     }
2146 
2147     public boolean isGrabbed() {
2148         return grab && XAwtState.getGrabWindow() == this;
2149     }
2150 
2151     public void handleXCrossingEvent(XEvent xev) {
2152         XCrossingEvent xce = xev.get_xcrossing();
2153         if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
2154             grabLog.fine("{0}, when grabbed {1}, contains {2}",
2155                          xce, isGrabbed(),
2156                          containsGlobal(scaleDown(xce.get_x_root()),
2157                                         scaleDown(xce.get_y_root())));
2158         }
2159         if (isGrabbed()) {
2160             // When window is grabbed, all events are dispatched to
2161             // it.  Retarget them to the corresponding windows (notice
2162             // that XBaseWindow.dispatchEvent does the opposite
2163             // translation)
2164             // Note that we need to retarget XCrossingEvents to content window
2165             // since it generates MOUSE_ENTERED/MOUSE_EXITED for frame and dialog.
2166             // (fix for 6390326)
2167             XBaseWindow target = XToolkit.windowToXWindow(xce.get_window());
2168             if (grabLog.isLoggable(PlatformLogger.Level.FINER)) {
2169                 grabLog.finer("  -  Grab event target {0}", target);
2170             }
2171             if (target != null && target != this) {
2172                 target.dispatchEvent(xev);
2173                 return;
2174             }
2175         }
2176         super.handleXCrossingEvent(xev);
2177     }
2178 
2179     public void handleMotionNotify(XEvent xev) {
2180         XMotionEvent xme = xev.get_xmotion();
2181         if (grabLog.isLoggable(PlatformLogger.Level.FINER)) {
2182             grabLog.finer("{0}, when grabbed {1}, contains {2}",
2183                           xme, isGrabbed(),
2184                           containsGlobal(scaleDown(xme.get_x_root()),
2185                                          scaleDown(xme.get_y_root())));
2186         }
2187         if (isGrabbed()) {
2188             boolean dragging = false;
2189             final int buttonsNumber = XToolkit.getNumberOfButtonsForMask();
2190 
2191             for (int i = 0; i < buttonsNumber; i++){
2192                 // here is the bug in WM: extra buttons doesn't have state!=0 as they should.
2193                 if ((i != 4) && (i != 5)){
2194                     dragging = dragging || ((xme.get_state() & XlibUtil.getButtonMask(i + 1)) != 0);
2195                 }
2196             }
2197             // When window is grabbed, all events are dispatched to
2198             // it.  Retarget them to the corresponding windows (notice
2199             // that XBaseWindow.dispatchEvent does the opposite
2200             // translation)
2201             XBaseWindow target = XToolkit.windowToXWindow(xme.get_window());
2202             if (dragging && pressTarget != target) {
2203                 // for some reasons if we grab input MotionNotify for drag is reported with target
2204                 // to underlying window, not to window on which we have initiated drag
2205                 // so we need to retarget them.  Here I use simplified logic which retarget all
2206                 // such events to source of mouse press (or the grabber).  It helps with fix for 6390326.
2207                 // So, I do not want to implement complicated logic for better retargeting.
2208                 target = pressTarget.isVisible() ? pressTarget : this;
2209                 xme.set_window(target.getWindow());
2210                 Point localCoord = target.toLocal(scaleDown(xme.get_x_root()),
2211                                                   scaleDown(xme.get_y_root()));
2212                 xme.set_x(scaleUp(localCoord.x));
2213                 xme.set_y(scaleUp(localCoord.y));
2214             }
2215             if (grabLog.isLoggable(PlatformLogger.Level.FINER)) {
2216                 grabLog.finer("  -  Grab event target {0}", target);
2217             }
2218             if (target != null) {
2219                 if (target != getContentXWindow() && target != this) {
2220                     target.dispatchEvent(xev);
2221                     return;
2222                 }
2223             }
2224 
2225             // note that we need to pass dragging events to the grabber (6390326)
2226             // see comment above for more inforamtion.
2227             if (!containsGlobal(scaleDown(xme.get_x_root()),
2228                                 scaleDown(xme.get_y_root()))
2229                     && !dragging) {
2230                 // Outside of Java
2231                 return;
2232             }
2233         }
2234         super.handleMotionNotify(xev);
2235     }
2236 
2237     // we use it to retarget mouse drag and mouse release during grab.
2238     private XBaseWindow pressTarget = this;
2239 
2240     public void handleButtonPressRelease(XEvent xev) {
2241         XButtonEvent xbe = xev.get_xbutton();
2242         /*
2243          * Ignore the buttons above 20 due to the bit limit for
2244          * InputEvent.BUTTON_DOWN_MASK.
2245          * One more bit is reserved for FIRST_HIGH_BIT.
2246          */
2247         if (xbe.get_button() > SunToolkit.MAX_BUTTONS_SUPPORTED) {
2248             return;
2249         }
2250         if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
2251             grabLog.fine("{0}, when grabbed {1}, contains {2} ({3}, {4}, {5}x{6})",
2252                          xbe, isGrabbed(),
2253                          containsGlobal(scaleDown(xbe.get_x_root()),
2254                                         scaleDown(xbe.get_y_root())),
2255                          getAbsoluteX(), getAbsoluteY(),
2256                          getWidth(), getHeight());
2257         }
2258         if (isGrabbed()) {
2259             // When window is grabbed, all events are dispatched to
2260             // it.  Retarget them to the corresponding windows (notice
2261             // that XBaseWindow.dispatchEvent does the opposite
2262             // translation)
2263             XBaseWindow target = XToolkit.windowToXWindow(xbe.get_window());
2264             try {
2265                 if (grabLog.isLoggable(PlatformLogger.Level.FINER)) {
2266                     grabLog.finer("  -  Grab event target {0} (press target {1})", target, pressTarget);
2267                 }
2268                 if (xbe.get_type() == XConstants.ButtonPress
2269                     && xbe.get_button() == XConstants.buttons[0])
2270                 {
2271                     // need to keep it to retarget mouse release
2272                     pressTarget = target;
2273                 } else if (xbe.get_type() == XConstants.ButtonRelease
2274                            && xbe.get_button() == XConstants.buttons[0]
2275                            && pressTarget != target)
2276                 {
2277                     // during grab we do receive mouse release on different component (not on the source
2278                     // of mouse press).  So we need to retarget it.
2279                     // see 6390326 for more information.
2280                     target = pressTarget.isVisible() ? pressTarget : this;
2281                     xbe.set_window(target.getWindow());
2282                     Point localCoord = target.toLocal(scaleDown(xbe.get_x_root()),
2283                                                       scaleDown(xbe.get_y_root()));
2284                     xbe.set_x(scaleUp(localCoord.x));
2285                     xbe.set_y(scaleUp(localCoord.y));
2286                     pressTarget = this;
2287                 }
2288                 if (target != null && target != getContentXWindow() && target != this) {
2289                     target.dispatchEvent(xev);
2290                     return;
2291                 }
2292             } finally {
2293                 if (target != null) {
2294                     // Target is either us or our content window -
2295                     // check that event is inside.  'Us' in case of
2296                     // shell will mean that this will also filter out press on title
2297                     if ((target == this || target == getContentXWindow())
2298                             && !containsGlobal(scaleDown(xbe.get_x_root()),
2299                                                scaleDown(xbe.get_y_root())))
2300                     {
2301                         // Outside this toplevel hierarchy
2302                         // According to the specification of UngrabEvent, post it
2303                         // when press occurs outside of the window and not on its owned windows
2304                         if (xbe.get_type() == XConstants.ButtonPress) {
2305                             if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
2306                                 grabLog.fine("Generating UngrabEvent on {0} because not inside of shell", this);
2307                             }
2308                             postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
2309                             return;
2310                         }
2311                     }
2312                     // First, get the toplevel
2313                     XWindowPeer toplevel = target.getToplevelXWindow();
2314                     if (toplevel != null) {
2315                         Window w = (Window)toplevel.target;
2316                         while (w != null && toplevel != this && !(toplevel instanceof XDialogPeer)) {
2317                             w = (Window) AWTAccessor.getComponentAccessor().getParent(w);
2318                             if (w != null) {
2319                                 toplevel = AWTAccessor.getComponentAccessor().getPeer(w);
2320                             }
2321                         }
2322                         if (w == null || (w != this.target && w instanceof Dialog)) {
2323                             // toplevel == null - outside of
2324                             // hierarchy, toplevel is Dialog - should
2325                             // send ungrab (but shouldn't for Window)
2326                             if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
2327                                 grabLog.fine("Generating UngrabEvent on {0} because hierarchy ended", this);
2328                             }
2329                             postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
2330                         }
2331                     } else {
2332                         // toplevel is null - outside of hierarchy
2333                         if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
2334                             grabLog.fine("Generating UngrabEvent on {0} because toplevel is null", this);
2335                         }
2336                         postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
2337                         return;
2338                     }
2339                 } else {
2340                     // target doesn't map to XAWT window - outside of hierarchy
2341                     if (grabLog.isLoggable(PlatformLogger.Level.FINE)) {
2342                         grabLog.fine("Generating UngrabEvent on because target is null {0}", this);
2343                     }
2344                     postEventToEventQueue(new sun.awt.UngrabEvent(getEventSource()));
2345                     return;
2346                 }
2347             }
2348         }
2349         super.handleButtonPressRelease(xev);
2350     }
2351 
2352     public void print(Graphics g) {
2353         // We assume we print the whole frame,
2354         // so we expect no clip was set previously
2355         Shape shape = AWTAccessor.getWindowAccessor().getShape((Window)target);
2356         if (shape != null) {
2357             g.setClip(shape);
2358         }
2359         super.print(g);
2360     }
2361 
2362     @Override
2363     public void setOpacity(float opacity) {
2364         final long maxOpacity = 0xffffffffl;
2365         long iOpacity = (long)(opacity * maxOpacity);
2366         if (iOpacity < 0) {
2367             iOpacity = 0;
2368         }
2369         if (iOpacity > maxOpacity) {
2370             iOpacity = maxOpacity;
2371         }
2372 
2373         XAtom netWmWindowOpacityAtom = XAtom.get("_NET_WM_WINDOW_OPACITY");
2374 
2375         if (iOpacity == maxOpacity) {
2376             netWmWindowOpacityAtom.DeleteProperty(getWindow());
2377         } else {
2378             netWmWindowOpacityAtom.setCard32Property(getWindow(), iOpacity);
2379         }
2380     }
2381 
2382     @Override
2383     public void setOpaque(boolean isOpaque) {
2384         // no-op
2385     }
2386 
2387     @Override
2388     public void updateWindow() {
2389         // no-op
2390     }
2391 }