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