1 /*
   2  * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.lwawt;
  27 
  28 import java.awt.*;
  29 import java.awt.event.*;
  30 import java.awt.peer.*;
  31 import java.util.List;
  32 
  33 import javax.swing.*;
  34 
  35 import sun.awt.*;
  36 import sun.awt.AWTAccessor.ComponentAccessor;
  37 import sun.java2d.*;
  38 import sun.java2d.loops.Blit;
  39 import sun.java2d.loops.CompositeType;
  40 import sun.java2d.pipe.Region;
  41 import sun.util.logging.PlatformLogger;
  42 
  43 public class LWWindowPeer
  44     extends LWContainerPeer<Window, JComponent>
  45     implements FramePeer, DialogPeer, FullScreenCapable, DisplayChangedListener, PlatformEventNotifier
  46 {
  47     public enum PeerType {
  48         SIMPLEWINDOW,
  49         FRAME,
  50         DIALOG,
  51         EMBEDDED_FRAME,
  52         VIEW_EMBEDDED_FRAME,
  53         LW_FRAME
  54     }
  55 
  56     private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.lwawt.focus.LWWindowPeer");
  57 
  58     private final PlatformWindow platformWindow;
  59 
  60     private static final int MINIMUM_WIDTH = 1;
  61     private static final int MINIMUM_HEIGHT = 1;
  62 
  63     private Insets insets = new Insets(0, 0, 0, 0);
  64 
  65     private GraphicsDevice graphicsDevice;
  66     private GraphicsConfiguration graphicsConfig;
  67 
  68     private SurfaceData surfaceData;
  69     private final Object surfaceDataLock = new Object();
  70 
  71     private volatile int windowState = Frame.NORMAL;
  72 
  73     // check that the mouse is over the window
  74     private volatile boolean isMouseOver = false;
  75 
  76     // A peer where the last mouse event came to. Used by cursor manager to
  77     // find the component under cursor
  78     private static volatile LWComponentPeer<?, ?> lastCommonMouseEventPeer;
  79 
  80     // A peer where the last mouse event came to. Used to generate
  81     // MOUSE_ENTERED/EXITED notifications
  82     private volatile LWComponentPeer<?, ?> lastMouseEventPeer;
  83 
  84     // Peers where all dragged/released events should come to,
  85     // depending on what mouse button is being dragged according to Cocoa
  86     private static final LWComponentPeer<?, ?>[] mouseDownTarget = new LWComponentPeer<?, ?>[3];
  87 
  88     // A bitmask that indicates what mouse buttons produce MOUSE_CLICKED events
  89     // on MOUSE_RELEASE. Click events are only generated if there were no drag
  90     // events between MOUSE_PRESSED and MOUSE_RELEASED for particular button
  91     private static int mouseClickButtons = 0;
  92 
  93     private volatile boolean isOpaque = true;
  94 
  95     private static final Font DEFAULT_FONT = new Font("Lucida Grande", Font.PLAIN, 13);
  96 
  97     private static LWWindowPeer grabbingWindow;
  98 
  99     private volatile boolean skipNextFocusChange;
 100 
 101     private static final Color nonOpaqueBackground = new Color(0, 0, 0, 0);
 102 
 103     private volatile boolean textured;
 104 
 105     private final PeerType peerType;
 106 
 107     private final SecurityWarningWindow warningWindow;
 108 
 109     private volatile boolean targetFocusable;
 110 
 111     /**
 112      * Current modal blocker or null.
 113      *
 114      * Synchronization: peerTreeLock.
 115      */
 116     private LWWindowPeer blocker;
 117 
 118     public LWWindowPeer(Window target, PlatformComponent platformComponent,
 119                         PlatformWindow platformWindow, PeerType peerType)
 120     {
 121         super(target, platformComponent);
 122         this.platformWindow = platformWindow;
 123         this.peerType = peerType;
 124 
 125         Window owner = target.getOwner();
 126         LWWindowPeer ownerPeer = owner == null ? null :
 127              (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(owner);
 128         PlatformWindow ownerDelegate = (ownerPeer != null) ? ownerPeer.getPlatformWindow() : null;
 129 
 130         // The delegate.initialize() needs a non-null GC on X11.
 131         GraphicsConfiguration gc = getTarget().getGraphicsConfiguration();
 132         synchronized (getStateLock()) {
 133             // graphicsConfig should be updated according to the real window
 134             // bounds when the window is shown, see 4868278
 135             this.graphicsConfig = gc;
 136         }
 137 
 138         if (!target.isFontSet()) {
 139             target.setFont(DEFAULT_FONT);
 140         }
 141 
 142         if (!target.isBackgroundSet()) {
 143             target.setBackground(SystemColor.window);
 144         } else {
 145             // first we check if user provided alpha for background. This is
 146             // similar to what Apple's Java do.
 147             // Since JDK7 we should rely on setOpacity() only.
 148             // this.opacity = c.getAlpha();
 149         }
 150 
 151         if (!target.isForegroundSet()) {
 152             target.setForeground(SystemColor.windowText);
 153             // we should not call setForeground because it will call a repaint
 154             // which the peer may not be ready to do yet.
 155         }
 156 
 157         platformWindow.initialize(target, this, ownerDelegate);
 158 
 159         // Init warning window(for applets)
 160         SecurityWarningWindow warn = null;
 161         if (target.getWarningString() != null) {
 162             // accessSystemTray permission allows to display TrayIcon, TrayIcon tooltip
 163             // and TrayIcon balloon windows without a warning window.
 164             if (!AWTAccessor.getWindowAccessor().isTrayIconWindow(target)) {
 165                 LWToolkit toolkit = (LWToolkit)Toolkit.getDefaultToolkit();
 166                 warn = toolkit.createSecurityWarning(target, this);
 167             }
 168         }
 169 
 170         warningWindow = warn;
 171     }
 172 
 173     @Override
 174     void initializeImpl() {
 175         super.initializeImpl();
 176 
 177 
 178         if (getTarget() instanceof Frame) {
 179             setTitle(((Frame) getTarget()).getTitle());
 180             setState(((Frame) getTarget()).getExtendedState());
 181         } else if (getTarget() instanceof Dialog) {
 182             setTitle(((Dialog) getTarget()).getTitle());
 183         }
 184 
 185         updateAlwaysOnTopState();
 186         updateMinimumSize();
 187 
 188         final Shape shape = getTarget().getShape();
 189         if (shape != null) {
 190             applyShape(Region.getInstance(shape, null));
 191         }
 192 
 193         final float opacity = getTarget().getOpacity();
 194         if (opacity < 1.0f) {
 195             setOpacity(opacity);
 196         }
 197 
 198         setOpaque(getTarget().isOpaque());
 199 
 200         updateInsets(platformWindow.getInsets());
 201         if (getSurfaceData() == null) {
 202             replaceSurfaceData(false);
 203         }
 204         activateDisplayListener();
 205     }
 206 
 207     // Just a helper method
 208     @Override
 209     public PlatformWindow getPlatformWindow() {
 210         return platformWindow;
 211     }
 212 
 213     @Override
 214     protected LWWindowPeer getWindowPeerOrSelf() {
 215         return this;
 216     }
 217 
 218     // ---- PEER METHODS ---- //
 219 
 220     @Override
 221     protected void disposeImpl() {
 222         deactivateDisplayListener();
 223         SurfaceData oldData = getSurfaceData();
 224         synchronized (surfaceDataLock){
 225             surfaceData = null;
 226         }
 227         if (oldData != null) {
 228             oldData.invalidate();
 229         }
 230         if (isGrabbing()) {
 231             ungrab();
 232         }
 233         if (warningWindow != null) {
 234             warningWindow.dispose();
 235         }
 236 
 237         platformWindow.dispose();
 238         super.disposeImpl();
 239     }
 240 
 241     @Override
 242     protected void setVisibleImpl(final boolean visible) {
 243         if (!visible && warningWindow != null) {
 244             warningWindow.setVisible(false, false);
 245         }
 246         updateFocusableWindowState();
 247         super.setVisibleImpl(visible);
 248         // TODO: update graphicsConfig, see 4868278
 249         platformWindow.setVisible(visible);
 250         if (isSimpleWindow()) {
 251             KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
 252             if (visible) {
 253                 if (!getTarget().isAutoRequestFocus()) {
 254                     return;
 255                 } else {
 256                     requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
 257                 }
 258             // Focus the owner in case this window is focused.
 259             } else if (kfmPeer.getCurrentFocusedWindow() == getTarget()) {
 260                 // Transfer focus to the owner.
 261                 LWWindowPeer owner = getOwnerFrameDialog(LWWindowPeer.this);
 262                 if (owner != null) {
 263                     owner.requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
 264                 }
 265             }
 266         }
 267     }
 268 
 269     @Override
 270     public final GraphicsConfiguration getGraphicsConfiguration() {
 271         synchronized (getStateLock()) {
 272             return graphicsConfig;
 273         }
 274     }
 275 
 276     @Override
 277     public boolean updateGraphicsData(GraphicsConfiguration gc) {
 278         setGraphicsConfig(gc);
 279         return false;
 280     }
 281 
 282     protected final Graphics getOnscreenGraphics(Color fg, Color bg, Font f) {
 283         if (getSurfaceData() == null) {
 284             return null;
 285         }
 286         if (fg == null) {
 287             fg = SystemColor.windowText;
 288         }
 289         if (bg == null) {
 290             bg = SystemColor.window;
 291         }
 292         if (f == null) {
 293             f = DEFAULT_FONT;
 294         }
 295         return platformWindow.transformGraphics(new SunGraphics2D(getSurfaceData(), fg, bg, f));
 296     }
 297 
 298     @Override
 299     public void setBounds(int x, int y, int w, int h, int op) {
 300 
 301         if((op & NO_EMBEDDED_CHECK) == 0 && getPeerType() == PeerType.VIEW_EMBEDDED_FRAME) {
 302             return;
 303         }
 304 
 305         if ((op & SET_CLIENT_SIZE) != 0) {
 306             // SET_CLIENT_SIZE is only applicable to window peers, so handle it here
 307             // instead of pulling 'insets' field up to LWComponentPeer
 308             // no need to add insets since Window's notion of width and height includes insets.
 309             op &= ~SET_CLIENT_SIZE;
 310             op |= SET_SIZE;
 311         }
 312 
 313         // Don't post ComponentMoved/Resized and Paint events
 314         // until we've got a notification from the delegate
 315         Rectangle cb = constrainBounds(x, y, w, h);
 316 
 317         Rectangle newBounds = new Rectangle(getBounds());
 318         if ((op & (SET_LOCATION | SET_BOUNDS)) != 0) {
 319             newBounds.x = cb.x;
 320             newBounds.y = cb.y;
 321         }
 322         if ((op & (SET_SIZE | SET_BOUNDS)) != 0) {
 323             newBounds.width = cb.width;
 324             newBounds.height = cb.height;
 325         }
 326         // Native system could constraint bounds, so the peer wold be updated in the callback
 327         platformWindow.setBounds(newBounds.x, newBounds.y, newBounds.width, newBounds.height);
 328     }
 329 
 330     public Rectangle constrainBounds(Rectangle bounds) {
 331         return constrainBounds(bounds.x, bounds.y, bounds.width, bounds.height);
 332     }
 333 
 334     public Rectangle constrainBounds(int x, int y, int w, int h) {
 335 
 336         if (w < MINIMUM_WIDTH) {
 337             w = MINIMUM_WIDTH;
 338         }
 339 
 340         if (h < MINIMUM_HEIGHT) {
 341             h = MINIMUM_HEIGHT;
 342         }
 343 
 344         final int maxW = getLWGC().getMaxTextureWidth();
 345         final int maxH = getLWGC().getMaxTextureHeight();
 346 
 347         if (w > maxW) {
 348             w = maxW;
 349         }
 350         if (h > maxH) {
 351             h = maxH;
 352         }
 353 
 354         return new Rectangle(x, y, w, h);
 355     }
 356 
 357     @Override
 358     public Point getLocationOnScreen() {
 359         return platformWindow.getLocationOnScreen();
 360     }
 361 
 362     /**
 363      * Overridden from LWContainerPeer to return the correct insets.
 364      * Insets are queried from the delegate and are kept up to date by
 365      * requiering when needed (i.e. when the window geometry is changed).
 366      */
 367     @Override
 368     public Insets getInsets() {
 369         synchronized (getStateLock()) {
 370             return insets;
 371         }
 372     }
 373 
 374     @Override
 375     public FontMetrics getFontMetrics(Font f) {
 376         // TODO: check for "use platform metrics" settings
 377         return platformWindow.getFontMetrics(f);
 378     }
 379 
 380     @Override
 381     public void toFront() {
 382         platformWindow.toFront();
 383     }
 384 
 385     @Override
 386     public void toBack() {
 387         platformWindow.toBack();
 388     }
 389 
 390     @Override
 391     public void setZOrder(ComponentPeer above) {
 392         throw new RuntimeException("not implemented");
 393     }
 394 
 395     @Override
 396     public void updateAlwaysOnTopState() {
 397         platformWindow.setAlwaysOnTop(getTarget().isAlwaysOnTop());
 398     }
 399 
 400     @Override
 401     public void updateFocusableWindowState() {
 402         targetFocusable = getTarget().isFocusableWindow();
 403         platformWindow.updateFocusableWindowState();
 404     }
 405 
 406     @Override
 407     public void setModalBlocked(Dialog blocker, boolean blocked) {
 408         synchronized (getPeerTreeLock()) {
 409             ComponentPeer peer =  AWTAccessor.getComponentAccessor().getPeer(blocker);
 410             if (blocked && (peer instanceof LWWindowPeer)) {
 411                 this.blocker = (LWWindowPeer) peer;
 412             } else {
 413                 this.blocker = null;
 414             }
 415         }
 416 
 417         platformWindow.setModalBlocked(blocked);
 418     }
 419 
 420     @Override
 421     public void updateMinimumSize() {
 422         final Dimension min;
 423         if (getTarget().isMinimumSizeSet()) {
 424             min = getTarget().getMinimumSize();
 425             min.width = Math.max(min.width, MINIMUM_WIDTH);
 426             min.height = Math.max(min.height, MINIMUM_HEIGHT);
 427         } else {
 428             min = new Dimension(MINIMUM_WIDTH, MINIMUM_HEIGHT);
 429         }
 430 
 431         final Dimension max;
 432         if (getTarget().isMaximumSizeSet()) {
 433             max = getTarget().getMaximumSize();
 434             max.width = Math.min(max.width, getLWGC().getMaxTextureWidth());
 435             max.height = Math.min(max.height, getLWGC().getMaxTextureHeight());
 436         } else {
 437             max = new Dimension(getLWGC().getMaxTextureWidth(),
 438                                 getLWGC().getMaxTextureHeight());
 439         }
 440 
 441         platformWindow.setSizeConstraints(min.width, min.height, max.width, max.height);
 442     }
 443 
 444     @Override
 445     public void updateIconImages() {
 446         getPlatformWindow().updateIconImages();
 447     }
 448 
 449     @Override
 450     public void setBackground(final Color c) {
 451         super.setBackground(c);
 452         updateOpaque();
 453     }
 454 
 455     @Override
 456     public void setOpacity(float opacity) {
 457         getPlatformWindow().setOpacity(opacity);
 458         repaintPeer();
 459     }
 460 
 461     @Override
 462     public final void setOpaque(final boolean isOpaque) {
 463         if (this.isOpaque != isOpaque) {
 464             this.isOpaque = isOpaque;
 465             updateOpaque();
 466         }
 467     }
 468 
 469     private void updateOpaque() {
 470         getPlatformWindow().setOpaque(!isTranslucent());
 471         replaceSurfaceData(false);
 472         repaintPeer();
 473     }
 474 
 475     @Override
 476     public void updateWindow() {
 477     }
 478 
 479     public final boolean isTextured() {
 480         return textured;
 481     }
 482 
 483     public final void setTextured(final boolean isTextured) {
 484         textured = isTextured;
 485     }
 486 
 487     @Override
 488     public final boolean isTranslucent() {
 489         synchronized (getStateLock()) {
 490             /*
 491              * Textured window is a special case of translucent window.
 492              * The difference is only in nswindow background. So when we set
 493              * texture property our peer became fully translucent. It doesn't
 494              * fill background, create non opaque backbuffers and layer etc.
 495              */
 496             return !isOpaque || isShaped() || isTextured();
 497         }
 498     }
 499 
 500     @Override
 501     final void applyShapeImpl(final Region shape) {
 502         super.applyShapeImpl(shape);
 503         updateOpaque();
 504     }
 505 
 506     @Override
 507     public void repositionSecurityWarning() {
 508         if (warningWindow != null) {
 509             ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
 510             Window target = getTarget();
 511             int x = compAccessor.getX(target);
 512             int y = compAccessor.getY(target);
 513             int width = compAccessor.getWidth(target);
 514             int height = compAccessor.getHeight(target);
 515             warningWindow.reposition(x, y, width, height);
 516         }
 517     }
 518 
 519     // ---- FRAME PEER METHODS ---- //
 520 
 521     @Override // FramePeer and DialogPeer
 522     public void setTitle(String title) {
 523         platformWindow.setTitle(title == null ? "" : title);
 524     }
 525 
 526     @Override
 527     public void setMenuBar(MenuBar mb) {
 528          platformWindow.setMenuBar(mb);
 529     }
 530 
 531     @Override // FramePeer and DialogPeer
 532     public void setResizable(boolean resizable) {
 533         platformWindow.setResizable(resizable);
 534     }
 535 
 536     @Override
 537     public void setState(int state) {
 538         platformWindow.setWindowState(state);
 539     }
 540 
 541     @Override
 542     public int getState() {
 543         return windowState;
 544     }
 545 
 546     @Override
 547     public void setMaximizedBounds(Rectangle bounds) {
 548         // TODO: not implemented
 549     }
 550 
 551     @Override
 552     public void setBoundsPrivate(int x, int y, int width, int height) {
 553         setBounds(x, y, width, height, SET_BOUNDS | NO_EMBEDDED_CHECK);
 554     }
 555 
 556     @Override
 557     public Rectangle getBoundsPrivate() {
 558         throw new RuntimeException("not implemented");
 559     }
 560 
 561     // ---- DIALOG PEER METHODS ---- //
 562 
 563     @Override
 564     public void blockWindows(List<Window> windows) {
 565         //TODO: LWX will probably need some collectJavaToplevels to speed this up
 566         for (Window w : windows) {
 567             WindowPeer wp = AWTAccessor.getComponentAccessor().getPeer(w);
 568             if (wp != null) {
 569                 wp.setModalBlocked((Dialog)getTarget(), true);
 570             }
 571         }
 572     }
 573 
 574     // ---- PEER NOTIFICATIONS ---- //
 575 
 576     @Override
 577     public void notifyIconify(boolean iconify) {
 578         //The toplevel target is Frame and states are applicable to it.
 579         //Otherwise, the target is Window and it don't have state property.
 580         //Hopefully, no such events are posted in the queue so consider the
 581         //target as Frame in all cases.
 582 
 583         // REMIND: should we send it anyway if the state not changed since last
 584         // time?
 585         WindowEvent iconifyEvent = new WindowEvent(getTarget(),
 586                 iconify ? WindowEvent.WINDOW_ICONIFIED
 587                         : WindowEvent.WINDOW_DEICONIFIED);
 588         postEvent(iconifyEvent);
 589 
 590         int newWindowState = iconify ? Frame.ICONIFIED : Frame.NORMAL;
 591         postWindowStateChangedEvent(newWindowState);
 592 
 593         // REMIND: RepaintManager doesn't repaint iconified windows and
 594         // hence ignores any repaint request during deiconification.
 595         // So, we need to repaint window explicitly when it becomes normal.
 596         if (!iconify) {
 597             repaintPeer();
 598         }
 599     }
 600 
 601     @Override
 602     public void notifyZoom(boolean isZoomed) {
 603         int newWindowState = isZoomed ? Frame.MAXIMIZED_BOTH : Frame.NORMAL;
 604         postWindowStateChangedEvent(newWindowState);
 605     }
 606 
 607     /**
 608      * Called by the {@code PlatformWindow} when any part of the window should
 609      * be repainted.
 610      */
 611     @Override
 612     public void notifyExpose(final Rectangle r) {
 613         repaintPeer(r);
 614     }
 615 
 616     /**
 617      * Called by the {@code PlatformWindow} when this window is moved/resized by
 618      * user or window insets are changed. There's no notifyReshape() in
 619      * LWComponentPeer as the only components which could be resized by user are
 620      * top-level windows.
 621      */
 622     @Override
 623     public void notifyReshape(int x, int y, int w, int h) {
 624         Rectangle oldBounds = getBounds();
 625         final boolean invalid = updateInsets(platformWindow.getInsets());
 626         final boolean moved = (x != oldBounds.x) || (y != oldBounds.y);
 627         final boolean resized = (w != oldBounds.width) || (h != oldBounds.height);
 628 
 629         // Check if anything changed
 630         if (!moved && !resized && !invalid) {
 631             return;
 632         }
 633         // First, update peer's bounds
 634         setBounds(x, y, w, h, SET_BOUNDS, false, false);
 635 
 636         // Second, update the graphics config and surface data
 637         final boolean isNewDevice = updateGraphicsDevice();
 638         if (resized || isNewDevice) {
 639             replaceSurfaceData();
 640             updateMinimumSize();
 641         }
 642 
 643         // Third, COMPONENT_MOVED/COMPONENT_RESIZED/PAINT events
 644         if (moved || invalid) {
 645             handleMove(x, y, true);
 646         }
 647         if (resized || invalid || isNewDevice) {
 648             handleResize(w, h, true);
 649             repaintPeer();
 650         }
 651 
 652         repositionSecurityWarning();
 653     }
 654 
 655     private void clearBackground(final int w, final int h) {
 656         final Graphics g = getOnscreenGraphics(getForeground(), getBackground(),
 657                                                getFont());
 658         if (g != null) {
 659             try {
 660                 if (g instanceof Graphics2D) {
 661                     ((Graphics2D) g).setComposite(AlphaComposite.Src);
 662                 }
 663                 if (isTranslucent()) {
 664                     g.setColor(nonOpaqueBackground);
 665                     g.fillRect(0, 0, w, h);
 666                 }
 667                 if (!isTextured()) {
 668                     if (g instanceof SunGraphics2D) {
 669                         ((SunGraphics2D) g).constrain(0, 0, w, h, getRegion());
 670                     }
 671                     g.setColor(getBackground());
 672                     g.fillRect(0, 0, w, h);
 673                 }
 674             } finally {
 675                 g.dispose();
 676             }
 677         }
 678     }
 679 
 680     @Override
 681     public void notifyUpdateCursor() {
 682         getLWToolkit().getCursorManager().updateCursorLater(this);
 683     }
 684 
 685     @Override
 686     public void notifyActivation(boolean activation, LWWindowPeer opposite) {
 687         Window oppositeWindow = (opposite == null)? null : opposite.getTarget();
 688         changeFocusedWindow(activation, oppositeWindow);
 689     }
 690 
 691     // MouseDown in non-client area
 692     @Override
 693     public void notifyNCMouseDown() {
 694         // Ungrab except for a click on a Dialog with the grabbing owner
 695         if (grabbingWindow != null &&
 696             !grabbingWindow.isOneOfOwnersOf(this))
 697         {
 698             grabbingWindow.ungrab();
 699         }
 700     }
 701 
 702     // ---- EVENTS ---- //
 703 
 704     /*
 705      * Called by the delegate to dispatch the event to Java. Event
 706      * coordinates are relative to non-client window are, i.e. the top-left
 707      * point of the client area is (insets.top, insets.left).
 708      */
 709     @Override
 710     public void notifyMouseEvent(int id, long when, int button,
 711                                  int x, int y, int screenX, int screenY,
 712                                  int modifiers, int clickCount, boolean popupTrigger,
 713                                  byte[] bdata)
 714     {
 715         // TODO: fill "bdata" member of AWTEvent
 716         Rectangle r = getBounds();
 717         // findPeerAt() expects parent coordinates
 718         LWComponentPeer<?, ?> targetPeer = findPeerAt(r.x + x, r.y + y);
 719 
 720         if (id == MouseEvent.MOUSE_EXITED) {
 721             isMouseOver = false;
 722             if (lastMouseEventPeer != null) {
 723                 if (lastMouseEventPeer.isEnabled()) {
 724                     Point lp = lastMouseEventPeer.windowToLocal(x, y,
 725                             this);
 726                     Component target = lastMouseEventPeer.getTarget();
 727                     postMouseExitedEvent(target, when, modifiers, lp,
 728                             screenX, screenY, clickCount, popupTrigger, button);
 729                 }
 730 
 731                 // Sometimes we may get MOUSE_EXITED after lastCommonMouseEventPeer is switched
 732                 // to a peer from another window. So we must first check if this peer is
 733                 // the same as lastWindowPeer
 734                 if (lastCommonMouseEventPeer != null && lastCommonMouseEventPeer.getWindowPeerOrSelf() == this) {
 735                     lastCommonMouseEventPeer = null;
 736                 }
 737                 lastMouseEventPeer = null;
 738             }
 739         } else if(id == MouseEvent.MOUSE_ENTERED) {
 740             isMouseOver = true;
 741             if (targetPeer != null) {
 742                 if (targetPeer.isEnabled()) {
 743                     Point lp = targetPeer.windowToLocal(x, y, this);
 744                     Component target = targetPeer.getTarget();
 745                     postMouseEnteredEvent(target, when, modifiers, lp,
 746                             screenX, screenY, clickCount, popupTrigger, button);
 747                 }
 748                 lastCommonMouseEventPeer = targetPeer;
 749                 lastMouseEventPeer = targetPeer;
 750             }
 751         } else {
 752             PlatformWindow topmostPlatforWindow =
 753                     platformWindow.getTopmostPlatformWindowUnderMouse();
 754 
 755             LWWindowPeer topmostWindowPeer =
 756                     topmostPlatforWindow != null ? topmostPlatforWindow.getPeer() : null;
 757 
 758             // topmostWindowPeer == null condition is added for the backward
 759             // compatibility with applets. It can be removed when the
 760             // getTopmostPlatformWindowUnderMouse() method will be properly
 761             // implemented in CPlatformEmbeddedFrame class
 762             if (topmostWindowPeer == this || topmostWindowPeer == null) {
 763                 generateMouseEnterExitEventsForComponents(when, button, x, y,
 764                         screenX, screenY, modifiers, clickCount, popupTrigger,
 765                         targetPeer);
 766             } else {
 767                 LWComponentPeer<?, ?> topmostTargetPeer =
 768                         topmostWindowPeer != null ? topmostWindowPeer.findPeerAt(r.x + x, r.y + y) : null;
 769                 topmostWindowPeer.generateMouseEnterExitEventsForComponents(when, button, x, y,
 770                         screenX, screenY, modifiers, clickCount, popupTrigger,
 771                         topmostTargetPeer);
 772             }
 773 
 774             // TODO: fill "bdata" member of AWTEvent
 775 
 776             int eventButtonMask = (button > 0)? MouseEvent.getMaskForButton(button) : 0;
 777             int otherButtonsPressed = modifiers & ~eventButtonMask;
 778 
 779             // For pressed/dragged/released events OS X treats other
 780             // mouse buttons as if they were BUTTON2, so we do the same
 781             int targetIdx = (button > 3) ? MouseEvent.BUTTON2 - 1 : button - 1;
 782 
 783             // MOUSE_ENTERED/EXITED are generated for the components strictly under
 784             // mouse even when dragging. That's why we first update lastMouseEventPeer
 785             // based on initial targetPeer value and only then recalculate targetPeer
 786             // for MOUSE_DRAGGED/RELEASED events
 787             if (id == MouseEvent.MOUSE_PRESSED) {
 788 
 789                 // Ungrab only if this window is not an owned window of the grabbing one.
 790                 if (!isGrabbing() && grabbingWindow != null &&
 791                     !grabbingWindow.isOneOfOwnersOf(this))
 792                 {
 793                     grabbingWindow.ungrab();
 794                 }
 795                 if (otherButtonsPressed == 0) {
 796                     mouseClickButtons = eventButtonMask;
 797                 } else {
 798                     mouseClickButtons |= eventButtonMask;
 799                 }
 800 
 801                 // The window should be focused on mouse click. If it gets activated by the native platform,
 802                 // this request will be no op. It will take effect when:
 803                 // 1. A simple not focused window is clicked.
 804                 // 2. An active but not focused owner frame/dialog is clicked.
 805                 // The mouse event then will trigger a focus request "in window" to the component, so the window
 806                 // should gain focus before.
 807                 requestWindowFocus(CausedFocusEvent.Cause.MOUSE_EVENT);
 808 
 809                 mouseDownTarget[targetIdx] = targetPeer;
 810             } else if (id == MouseEvent.MOUSE_DRAGGED) {
 811                 // Cocoa dragged event has the information about which mouse
 812                 // button is being dragged. Use it to determine the peer that
 813                 // should receive the dragged event.
 814                 targetPeer = mouseDownTarget[targetIdx];
 815                 mouseClickButtons &= ~modifiers;
 816             } else if (id == MouseEvent.MOUSE_RELEASED) {
 817                 // TODO: currently, mouse released event goes to the same component
 818                 // that received corresponding mouse pressed event. For most cases,
 819                 // it's OK, however, we need to make sure that our behavior is consistent
 820                 // with 1.6 for cases where component in question have been
 821                 // hidden/removed in between of mouse pressed/released events.
 822                 targetPeer = mouseDownTarget[targetIdx];
 823 
 824                 if ((modifiers & eventButtonMask) == 0) {
 825                     mouseDownTarget[targetIdx] = null;
 826                 }
 827 
 828                 // mouseClickButtons is updated below, after MOUSE_CLICK is sent
 829             }
 830 
 831             if (targetPeer == null) {
 832                 //TODO This can happen if this window is invisible. this is correct behavior in this case?
 833                 targetPeer = this;
 834             }
 835 
 836 
 837             Point lp = targetPeer.windowToLocal(x, y, this);
 838             if (targetPeer.isEnabled()) {
 839                 MouseEvent event = new MouseEvent(targetPeer.getTarget(), id,
 840                                                   when, modifiers, lp.x, lp.y,
 841                                                   screenX, screenY, clickCount,
 842                                                   popupTrigger, button);
 843                 postEvent(event);
 844             }
 845 
 846             if (id == MouseEvent.MOUSE_RELEASED) {
 847                 if ((mouseClickButtons & eventButtonMask) != 0
 848                     && targetPeer.isEnabled()) {
 849                     postEvent(new MouseEvent(targetPeer.getTarget(),
 850                                              MouseEvent.MOUSE_CLICKED,
 851                                              when, modifiers,
 852                                              lp.x, lp.y, screenX, screenY,
 853                                              clickCount, popupTrigger, button));
 854                 }
 855                 mouseClickButtons &= ~eventButtonMask;
 856             }
 857         }
 858         notifyUpdateCursor();
 859     }
 860 
 861     private void generateMouseEnterExitEventsForComponents(long when,
 862             int button, int x, int y, int screenX, int screenY,
 863             int modifiers, int clickCount, boolean popupTrigger,
 864             final LWComponentPeer<?, ?> targetPeer) {
 865 
 866         if (!isMouseOver || targetPeer == lastMouseEventPeer) {
 867             return;
 868         }
 869 
 870         // Generate Mouse Exit for components
 871         if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
 872             Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
 873             Component target = lastMouseEventPeer.getTarget();
 874             postMouseExitedEvent(target, when, modifiers, oldp, screenX, screenY,
 875                     clickCount, popupTrigger, button);
 876         }
 877         lastCommonMouseEventPeer = targetPeer;
 878         lastMouseEventPeer = targetPeer;
 879 
 880         // Generate Mouse Enter for components
 881         if (targetPeer != null && targetPeer.isEnabled()) {
 882             Point newp = targetPeer.windowToLocal(x, y, this);
 883             Component target = targetPeer.getTarget();
 884             postMouseEnteredEvent(target, when, modifiers, newp, screenX, screenY, clickCount, popupTrigger, button);
 885         }
 886     }
 887 
 888     private void postMouseEnteredEvent(Component target, long when, int modifiers,
 889                                        Point loc, int xAbs, int yAbs,
 890                                        int clickCount, boolean popupTrigger, int button) {
 891 
 892         updateSecurityWarningVisibility();
 893 
 894         postEvent(new MouseEvent(target,
 895                 MouseEvent.MOUSE_ENTERED,
 896                 when, modifiers,
 897                 loc.x, loc.y, xAbs, yAbs,
 898                 clickCount, popupTrigger, button));
 899     }
 900 
 901     private void postMouseExitedEvent(Component target, long when, int modifiers,
 902                                       Point loc, int xAbs, int yAbs,
 903                                       int clickCount, boolean popupTrigger, int button) {
 904 
 905         updateSecurityWarningVisibility();
 906 
 907         postEvent(new MouseEvent(target,
 908                 MouseEvent.MOUSE_EXITED,
 909                 when, modifiers,
 910                 loc.x, loc.y, xAbs, yAbs,
 911                 clickCount, popupTrigger, button));
 912     }
 913 
 914     @Override
 915     public void notifyMouseWheelEvent(long when, int x, int y, int modifiers,
 916                                       int scrollType, int scrollAmount,
 917                                       int wheelRotation, double preciseWheelRotation,
 918                                       byte[] bdata)
 919     {
 920         // TODO: could we just use the last mouse event target here?
 921         Rectangle r = getBounds();
 922         // findPeerAt() expects parent coordinates
 923         final LWComponentPeer<?, ?> targetPeer = findPeerAt(r.x + x, r.y + y);
 924         if (targetPeer == null || !targetPeer.isEnabled()) {
 925             return;
 926         }
 927 
 928         Point lp = targetPeer.windowToLocal(x, y, this);
 929         // TODO: fill "bdata" member of AWTEvent
 930         // TODO: screenX/screenY
 931         postEvent(new MouseWheelEvent(targetPeer.getTarget(),
 932                                       MouseEvent.MOUSE_WHEEL,
 933                                       when, modifiers,
 934                                       lp.x, lp.y,
 935                                       0, 0, /* screenX, Y */
 936                                       0 /* clickCount */, false /* popupTrigger */,
 937                                       scrollType, scrollAmount,
 938                                       wheelRotation, preciseWheelRotation));
 939     }
 940 
 941     /*
 942      * Called by the delegate when a key is pressed.
 943      */
 944     @Override
 945     public void notifyKeyEvent(int id, long when, int modifiers,
 946                                int keyCode, char keyChar, int keyLocation)
 947     {
 948         LWKeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
 949         Component focusOwner = kfmPeer.getCurrentFocusOwner();
 950 
 951         if (focusOwner == null) {
 952             focusOwner = kfmPeer.getCurrentFocusedWindow();
 953             if (focusOwner == null) {
 954                 focusOwner = this.getTarget();
 955             }
 956         }
 957 
 958         KeyEvent keyEvent = new KeyEvent(focusOwner, id, when, modifiers,
 959             keyCode, keyChar, keyLocation);
 960         AWTAccessor.getKeyEventAccessor().setExtendedKeyCode(keyEvent,
 961                 (keyChar == KeyEvent.CHAR_UNDEFINED) ? keyCode
 962                 : ExtendedKeyCodes.getExtendedKeyCodeForChar(keyChar));
 963         postEvent(keyEvent);
 964     }
 965 
 966     // ---- UTILITY METHODS ---- //
 967 
 968     private void activateDisplayListener() {
 969         final GraphicsEnvironment ge =
 970                 GraphicsEnvironment.getLocalGraphicsEnvironment();
 971         ((SunGraphicsEnvironment) ge).addDisplayChangedListener(this);
 972     }
 973 
 974     private void deactivateDisplayListener() {
 975         final GraphicsEnvironment ge =
 976                 GraphicsEnvironment.getLocalGraphicsEnvironment();
 977         ((SunGraphicsEnvironment) ge).removeDisplayChangedListener(this);
 978     }
 979 
 980     private void postWindowStateChangedEvent(int newWindowState) {
 981         if (getTarget() instanceof Frame) {
 982             AWTAccessor.getFrameAccessor().setExtendedState(
 983                     (Frame)getTarget(), newWindowState);
 984         }
 985 
 986         WindowEvent stateChangedEvent = new WindowEvent(getTarget(),
 987                 WindowEvent.WINDOW_STATE_CHANGED,
 988                 windowState, newWindowState);
 989         postEvent(stateChangedEvent);
 990         windowState = newWindowState;
 991 
 992         updateSecurityWarningVisibility();
 993     }
 994 
 995     private static int getGraphicsConfigScreen(GraphicsConfiguration gc) {
 996         // TODO: this method can be implemented in a more
 997         // efficient way by forwarding to the delegate
 998         GraphicsDevice gd = gc.getDevice();
 999         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
1000         GraphicsDevice[] gds = ge.getScreenDevices();
1001         for (int i = 0; i < gds.length; i++) {
1002             if (gds[i] == gd) {
1003                 return i;
1004             }
1005         }
1006         // Should never happen if gc is a screen device config
1007         return 0;
1008     }
1009 
1010     /*
1011      * This method is called when window's graphics config is changed from
1012      * the app code (e.g. when the window is made non-opaque) or when
1013      * the window is moved to another screen by user.
1014      *
1015      * Returns true if the graphics config has been changed, false otherwise.
1016      */
1017     private boolean setGraphicsConfig(GraphicsConfiguration gc) {
1018         synchronized (getStateLock()) {
1019             if (graphicsConfig == gc) {
1020                 return false;
1021             }
1022             // If window's graphics config is changed from the app code, the
1023             // config correspond to the same device as before; when the window
1024             // is moved by user, graphicsDevice is updated in notifyReshape().
1025             // In either case, there's nothing to do with screenOn here
1026             graphicsConfig = gc;
1027         }
1028         // SurfaceData is replaced later in updateGraphicsData()
1029         return true;
1030     }
1031 
1032     /**
1033      * Returns true if the GraphicsDevice has been changed, false otherwise.
1034      */
1035     public boolean updateGraphicsDevice() {
1036         GraphicsDevice newGraphicsDevice = platformWindow.getGraphicsDevice();
1037         synchronized (getStateLock()) {
1038             if (graphicsDevice == newGraphicsDevice) {
1039                 return false;
1040             }
1041             graphicsDevice = newGraphicsDevice;
1042         }
1043 
1044         final GraphicsConfiguration newGC = newGraphicsDevice.getDefaultConfiguration();
1045 
1046         if (!setGraphicsConfig(newGC)) return false;
1047 
1048         SunToolkit.executeOnEventHandlerThread(getTarget(), new Runnable() {
1049             public void run() {
1050                 AWTAccessor.getComponentAccessor().setGraphicsConfiguration(getTarget(), newGC);
1051             }
1052         });
1053         return true;
1054     }
1055 
1056     @Override
1057     public final void displayChanged() {
1058         if (updateGraphicsDevice()) {
1059             updateMinimumSize();
1060         }
1061         // Replace surface unconditionally, because internal state of the
1062         // GraphicsDevice could be changed.
1063         replaceSurfaceData();
1064         repaintPeer();
1065     }
1066 
1067     @Override
1068     public final void paletteChanged() {
1069         // components do not need to react to this event.
1070     }
1071 
1072     /*
1073      * May be called by delegate to provide SD to Java2D code.
1074      */
1075     public SurfaceData getSurfaceData() {
1076         synchronized (surfaceDataLock) {
1077             return surfaceData;
1078         }
1079     }
1080 
1081     private void replaceSurfaceData() {
1082         replaceSurfaceData(true);
1083     }
1084 
1085     private void replaceSurfaceData(final boolean blit) {
1086         synchronized (surfaceDataLock) {
1087             final SurfaceData oldData = getSurfaceData();
1088             surfaceData = platformWindow.replaceSurfaceData();
1089             final Rectangle size = getSize();
1090             if (getSurfaceData() != null && oldData != getSurfaceData()) {
1091                 clearBackground(size.width, size.height);
1092             }
1093 
1094             if (blit) {
1095                 blitSurfaceData(oldData, getSurfaceData());
1096             }
1097 
1098             if (oldData != null && oldData != getSurfaceData()) {
1099                 // TODO: drop oldData for D3D/WGL pipelines
1100                 // This can only happen when this peer is being created
1101                 oldData.flush();
1102             }
1103         }
1104         flushOnscreenGraphics();
1105     }
1106 
1107     private void blitSurfaceData(final SurfaceData src, final SurfaceData dst) {
1108         //TODO blit. proof-of-concept
1109         if (src != dst && src != null && dst != null
1110             && !(dst instanceof NullSurfaceData)
1111             && !(src instanceof NullSurfaceData)
1112             && src.getSurfaceType().equals(dst.getSurfaceType())
1113             && src.getDefaultScale() == dst.getDefaultScale()) {
1114             final Rectangle size = src.getBounds();
1115             final Blit blit = Blit.locate(src.getSurfaceType(),
1116                                           CompositeType.Src,
1117                                           dst.getSurfaceType());
1118             if (blit != null) {
1119                 blit.Blit(src, dst, AlphaComposite.Src, null, 0, 0, 0, 0,
1120                           size.width, size.height);
1121             }
1122         }
1123     }
1124 
1125     /**
1126      * Request the window insets from the delegate and compares it with the
1127      * current one. This method is mostly called by the delegate, e.g. when the
1128      * window state is changed and insets should be recalculated.
1129      * <p/>
1130      * This method may be called on the toolkit thread.
1131      */
1132     public final boolean updateInsets(final Insets newInsets) {
1133         synchronized (getStateLock()) {
1134             if (insets.equals(newInsets)) {
1135                 return false;
1136             }
1137             insets = newInsets;
1138         }
1139         return true;
1140     }
1141 
1142     public static LWWindowPeer getWindowUnderCursor() {
1143         return lastCommonMouseEventPeer != null ? lastCommonMouseEventPeer.getWindowPeerOrSelf() : null;
1144     }
1145 
1146     public static LWComponentPeer<?, ?> getPeerUnderCursor() {
1147         return lastCommonMouseEventPeer;
1148     }
1149 
1150     /*
1151      * Requests platform to set native focus on a frame/dialog.
1152      * In case of a simple window, triggers appropriate java focus change.
1153      */
1154     public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
1155         if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1156             focusLog.fine("requesting native focus to " + this);
1157         }
1158 
1159         if (!focusAllowedFor()) {
1160             focusLog.fine("focus is not allowed");
1161             return false;
1162         }
1163 
1164         if (platformWindow.rejectFocusRequest(cause)) {
1165             return false;
1166         }
1167 
1168         AppContext targetAppContext = AWTAccessor.getComponentAccessor().getAppContext(getTarget());
1169         KeyboardFocusManager kfm = AWTAccessor.getKeyboardFocusManagerAccessor()
1170                 .getCurrentKeyboardFocusManager(targetAppContext);
1171         Window currentActive = kfm.getActiveWindow();
1172 
1173 
1174         Window opposite = LWKeyboardFocusManagerPeer.getInstance().
1175             getCurrentFocusedWindow();
1176 
1177         // Make the owner active window.
1178         if (isSimpleWindow()) {
1179             LWWindowPeer owner = getOwnerFrameDialog(this);
1180 
1181             // If owner is not natively active, request native
1182             // activation on it w/o sending events up to java.
1183             if (owner != null && !owner.platformWindow.isActive()) {
1184                 if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1185                     focusLog.fine("requesting native focus to the owner " + owner);
1186                 }
1187                 LWWindowPeer currentActivePeer = currentActive == null ? null :
1188                 (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(
1189                         currentActive);
1190 
1191                 // Ensure the opposite is natively active and suppress sending events.
1192                 if (currentActivePeer != null && currentActivePeer.platformWindow.isActive()) {
1193                     if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1194                         focusLog.fine("the opposite is " + currentActivePeer);
1195                     }
1196                     currentActivePeer.skipNextFocusChange = true;
1197                 }
1198                 owner.skipNextFocusChange = true;
1199 
1200                 owner.platformWindow.requestWindowFocus();
1201             }
1202 
1203             // DKFM will synthesize all the focus/activation events correctly.
1204             changeFocusedWindow(true, opposite);
1205             return true;
1206 
1207         // In case the toplevel is active but not focused, change focus directly,
1208         // as requesting native focus on it will not have effect.
1209         } else if (getTarget() == currentActive && !getTarget().hasFocus()) {
1210 
1211             changeFocusedWindow(true, opposite);
1212             return true;
1213         }
1214 
1215         return platformWindow.requestWindowFocus();
1216     }
1217 
1218     protected boolean focusAllowedFor() {
1219         Window window = getTarget();
1220         // TODO: check if modal blocked
1221         return window.isVisible() && window.isEnabled() && isFocusableWindow();
1222     }
1223 
1224     private boolean isFocusableWindow() {
1225         boolean focusable  = targetFocusable;
1226         if (isSimpleWindow()) {
1227             LWWindowPeer ownerPeer = getOwnerFrameDialog(this);
1228             if (ownerPeer == null) {
1229                 return false;
1230             }
1231             return focusable && ownerPeer.targetFocusable;
1232         }
1233         return focusable;
1234     }
1235 
1236     public boolean isSimpleWindow() {
1237         Window window = getTarget();
1238         return !(window instanceof Dialog || window instanceof Frame);
1239     }
1240 
1241     @Override
1242     public void emulateActivation(boolean activate) {
1243         changeFocusedWindow(activate, null);
1244     }
1245 
1246     @SuppressWarnings("deprecation")
1247     private boolean isOneOfOwnersOf(LWWindowPeer peer) {
1248         Window owner = (peer != null ? peer.getTarget().getOwner() : null);
1249         while (owner != null) {
1250             final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
1251             if (acc.getPeer(owner) == this) {
1252                 return true;
1253             }
1254             owner = owner.getOwner();
1255         }
1256         return false;
1257     }
1258 
1259     /*
1260      * Changes focused window on java level.
1261      */
1262     protected void changeFocusedWindow(boolean becomesFocused, Window opposite) {
1263         if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1264             focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
1265         }
1266         if (skipNextFocusChange) {
1267             focusLog.fine("skipping focus change");
1268             skipNextFocusChange = false;
1269             return;
1270         }
1271         if (!isFocusableWindow() && becomesFocused) {
1272             focusLog.fine("the window is not focusable");
1273             return;
1274         }
1275         if (becomesFocused) {
1276             synchronized (getPeerTreeLock()) {
1277                 if (blocker != null) {
1278                     if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
1279                         focusLog.finest("the window is blocked by " + blocker);
1280                     }
1281                     return;
1282                 }
1283             }
1284         }
1285 
1286         // Note, the method is not called:
1287         // - when the opposite (gaining focus) window is an owned/owner window.
1288         // - for a simple window in any case.
1289         if (!becomesFocused &&
1290             (isGrabbing() || this.isOneOfOwnersOf(grabbingWindow)))
1291         {
1292             if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1293                 focusLog.fine("ungrabbing on " + grabbingWindow);
1294             }
1295             // ungrab a simple window if its owner looses activation.
1296             grabbingWindow.ungrab();
1297         }
1298 
1299         KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
1300         kfmPeer.setCurrentFocusedWindow(becomesFocused ? getTarget() : null);
1301 
1302         int eventID = becomesFocused ? WindowEvent.WINDOW_GAINED_FOCUS : WindowEvent.WINDOW_LOST_FOCUS;
1303         WindowEvent windowEvent = new TimedWindowEvent(getTarget(), eventID, opposite, System.currentTimeMillis());
1304 
1305         // TODO: wrap in SequencedEvent
1306         postEvent(windowEvent);
1307     }
1308 
1309     /*
1310      * Retrieves the owner of the peer.
1311      * Note: this method returns the owner which can be activated, (i.e. the instance
1312      * of Frame or Dialog may be returned).
1313      */
1314     static LWWindowPeer getOwnerFrameDialog(LWWindowPeer peer) {
1315         Window owner = (peer != null ? peer.getTarget().getOwner() : null);
1316         while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
1317             owner = owner.getOwner();
1318         }
1319         return owner == null ? null : AWTAccessor.getComponentAccessor()
1320                                                  .getPeer(owner);
1321     }
1322 
1323     /**
1324      * Returns the foremost modal blocker of this window, or null.
1325      */
1326     public LWWindowPeer getBlocker() {
1327         synchronized (getPeerTreeLock()) {
1328             LWWindowPeer blocker = this.blocker;
1329             if (blocker == null) {
1330                 return null;
1331             }
1332             while (blocker.blocker != null) {
1333                 blocker = blocker.blocker;
1334             }
1335             return blocker;
1336         }
1337     }
1338 
1339     @Override
1340     public void enterFullScreenMode() {
1341         platformWindow.enterFullScreenMode();
1342         updateSecurityWarningVisibility();
1343     }
1344 
1345     @Override
1346     public void exitFullScreenMode() {
1347         platformWindow.exitFullScreenMode();
1348         updateSecurityWarningVisibility();
1349     }
1350 
1351     public long getLayerPtr() {
1352         return getPlatformWindow().getLayerPtr();
1353     }
1354 
1355     void grab() {
1356         if (grabbingWindow != null && !isGrabbing()) {
1357             grabbingWindow.ungrab();
1358         }
1359         grabbingWindow = this;
1360     }
1361 
1362     final void ungrab(boolean doPost) {
1363         if (isGrabbing()) {
1364             grabbingWindow = null;
1365             if (doPost) {
1366                 postEvent(new UngrabEvent(getTarget()));
1367             }
1368         }
1369     }
1370 
1371     void ungrab() {
1372         ungrab(true);
1373     }
1374 
1375     private boolean isGrabbing() {
1376         return this == grabbingWindow;
1377     }
1378 
1379     public PeerType getPeerType() {
1380         return peerType;
1381     }
1382 
1383     public void updateSecurityWarningVisibility() {
1384         if (warningWindow == null) {
1385             return;
1386         }
1387 
1388         if (!isVisible()) {
1389             return; // The warning window should already be hidden.
1390         }
1391 
1392         boolean show = false;
1393 
1394         if (!platformWindow.isFullScreenMode()) {
1395             if (isVisible()) {
1396                 if (LWKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow() ==
1397                         getTarget()) {
1398                     show = true;
1399                 }
1400 
1401                 if (platformWindow.isUnderMouse() || warningWindow.isUnderMouse()) {
1402                     show = true;
1403                 }
1404             }
1405         }
1406 
1407         warningWindow.setVisible(show, true);
1408     }
1409 
1410     @Override
1411     public String toString() {
1412         return super.toString() + " [target is " + getTarget() + "]";
1413     }
1414 }