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