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