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