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     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 topmostPlatforWindow =
 791                     platformWindow.getTopmostPlatformWindowUnderMouse();
 792 
 793             LWWindowPeer topmostWindowPeer =
 794                     topmostPlatforWindow != null ? topmostPlatforWindow.getPeer() : null;
 795 
 796             // topmostWindowPeer == null condition is added for the backward
 797             // compatibility with applets. It can be removed when the
 798             // getTopmostPlatformWindowUnderMouse() method will be properly
 799             // implemented in CPlatformEmbeddedFrame class
 800             if (topmostWindowPeer == this || topmostWindowPeer == null) {
 801                 generateMouseEnterExitEventsForComponents(when, button, x, y,
 802                         screenX, screenY, modifiers, clickCount, popupTrigger,
 803                         targetPeer);
 804             } else {
 805                 LWComponentPeer<?, ?> topmostTargetPeer =
 806                         topmostWindowPeer != null ? topmostWindowPeer.findPeerAt(r.x + x, r.y + y) : null;
 807                 topmostWindowPeer.generateMouseEnterExitEventsForComponents(when, button, x, y,
 808                         screenX, screenY, modifiers, clickCount, popupTrigger,
 809                         topmostTargetPeer);
 810             }
 811 
 812             // TODO: fill "bdata" member of AWTEvent
 813 
 814             int eventButtonMask = (button > 0)? MouseEvent.getMaskForButton(button) : 0;
 815             int otherButtonsPressed = modifiers & ~eventButtonMask;
 816 
 817             // For pressed/dragged/released events OS X treats other
 818             // mouse buttons as if they were BUTTON2, so we do the same
 819             int targetIdx = (button > 3) ? MouseEvent.BUTTON2 - 1 : button - 1;
 820 
 821             // MOUSE_ENTERED/EXITED are generated for the components strictly under
 822             // mouse even when dragging. That's why we first update lastMouseEventPeer
 823             // based on initial targetPeer value and only then recalculate targetPeer
 824             // for MOUSE_DRAGGED/RELEASED events
 825             if (id == MouseEvent.MOUSE_PRESSED) {
 826 
 827                 // Ungrab only if this window is not an owned window of the grabbing one.
 828                 if (!isGrabbing() && grabbingWindow != null &&
 829                     !grabbingWindow.isOneOfOwnersOf(this))
 830                 {
 831                     grabbingWindow.ungrab();
 832                 }
 833                 if (otherButtonsPressed == 0) {
 834                     mouseClickButtons = eventButtonMask;
 835                 } else {
 836                     mouseClickButtons |= eventButtonMask;
 837                 }
 838 
 839                 // The window should be focused on mouse click. If it gets activated by the native platform,
 840                 // this request will be no op. It will take effect when:
 841                 // 1. A simple not focused window is clicked.
 842                 // 2. An active but not focused owner frame/dialog is clicked.
 843                 // The mouse event then will trigger a focus request "in window" to the component, so the window
 844                 // should gain focus before.
 845                 requestWindowFocus(CausedFocusEvent.Cause.MOUSE_EVENT);
 846 
 847                 mouseDownTarget[targetIdx] = targetPeer;
 848             } else if (id == MouseEvent.MOUSE_DRAGGED) {
 849                 // Cocoa dragged event has the information about which mouse
 850                 // button is being dragged. Use it to determine the peer that
 851                 // should receive the dragged event.
 852                 targetPeer = mouseDownTarget[targetIdx];
 853                 mouseClickButtons &= ~modifiers;
 854             } else if (id == MouseEvent.MOUSE_RELEASED) {
 855                 // TODO: currently, mouse released event goes to the same component
 856                 // that received corresponding mouse pressed event. For most cases,
 857                 // it's OK, however, we need to make sure that our behavior is consistent
 858                 // with 1.6 for cases where component in question have been
 859                 // hidden/removed in between of mouse pressed/released events.
 860                 targetPeer = mouseDownTarget[targetIdx];
 861 
 862                 if ((modifiers & eventButtonMask) == 0) {
 863                     mouseDownTarget[targetIdx] = null;
 864                 }
 865 
 866                 // mouseClickButtons is updated below, after MOUSE_CLICK is sent
 867             }
 868 
 869             if (targetPeer == null) {
 870                 //TODO This can happen if this window is invisible. this is correct behavior in this case?
 871                 targetPeer = this;
 872             }
 873 
 874 
 875             Point lp = targetPeer.windowToLocal(x, y, this);
 876             if (targetPeer.isEnabled()) {
 877                 MouseEvent event = new MouseEvent(targetPeer.getTarget(), id,
 878                                                   when, modifiers, lp.x, lp.y,
 879                                                   screenX, screenY, clickCount,
 880                                                   popupTrigger, button);
 881                 postEvent(event);
 882             }
 883 
 884             if (id == MouseEvent.MOUSE_RELEASED) {
 885                 if ((mouseClickButtons & eventButtonMask) != 0
 886                     && targetPeer.isEnabled()) {
 887                     postEvent(new MouseEvent(targetPeer.getTarget(),
 888                                              MouseEvent.MOUSE_CLICKED,
 889                                              when, modifiers,
 890                                              lp.x, lp.y, screenX, screenY,
 891                                              clickCount, popupTrigger, button));
 892                 }
 893                 mouseClickButtons &= ~eventButtonMask;
 894             }
 895         }
 896         notifyUpdateCursor();
 897     }
 898 
 899     private void generateMouseEnterExitEventsForComponents(long when,
 900             int button, int x, int y, int screenX, int screenY,
 901             int modifiers, int clickCount, boolean popupTrigger,
 902             final LWComponentPeer<?, ?> targetPeer) {
 903 
 904         if (!isMouseOver || targetPeer == lastMouseEventPeer) {
 905             return;
 906         }
 907 
 908         // Generate Mouse Exit for components
 909         if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
 910             Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
 911             Component target = lastMouseEventPeer.getTarget();
 912             postMouseExitedEvent(target, when, modifiers, oldp, screenX, screenY,
 913                     clickCount, popupTrigger, button);
 914         }
 915         lastCommonMouseEventPeer = targetPeer;
 916         lastMouseEventPeer = targetPeer;
 917 
 918         // Generate Mouse Enter for components
 919         if (targetPeer != null && targetPeer.isEnabled()) {
 920             Point newp = targetPeer.windowToLocal(x, y, this);
 921             Component target = targetPeer.getTarget();
 922             postMouseEnteredEvent(target, when, modifiers, newp, screenX, screenY, clickCount, popupTrigger, button);
 923         }
 924     }
 925 
 926     private void postMouseEnteredEvent(Component target, long when, int modifiers,
 927                                        Point loc, int xAbs, int yAbs,
 928                                        int clickCount, boolean popupTrigger, int button) {
 929 
 930         updateSecurityWarningVisibility();
 931 
 932         postEvent(new MouseEvent(target,
 933                 MouseEvent.MOUSE_ENTERED,
 934                 when, modifiers,
 935                 loc.x, loc.y, xAbs, yAbs,
 936                 clickCount, popupTrigger, button));
 937     }
 938 
 939     private void postMouseExitedEvent(Component target, long when, int modifiers,
 940                                       Point loc, int xAbs, int yAbs,
 941                                       int clickCount, boolean popupTrigger, int button) {
 942 
 943         updateSecurityWarningVisibility();
 944 
 945         postEvent(new MouseEvent(target,
 946                 MouseEvent.MOUSE_EXITED,
 947                 when, modifiers,
 948                 loc.x, loc.y, xAbs, yAbs,
 949                 clickCount, popupTrigger, button));
 950     }
 951 
 952     @Override
 953     public void notifyMouseWheelEvent(long when, int x, int y, int modifiers,
 954                                       int scrollType, int scrollAmount,
 955                                       int wheelRotation, double preciseWheelRotation,
 956                                       byte[] bdata)
 957     {
 958         // TODO: could we just use the last mouse event target here?
 959         Rectangle r = getBounds();
 960         // findPeerAt() expects parent coordinates
 961         final LWComponentPeer<?, ?> targetPeer = findPeerAt(r.x + x, r.y + y);
 962         if (targetPeer == null || !targetPeer.isEnabled()) {
 963             return;
 964         }
 965 
 966         Point lp = targetPeer.windowToLocal(x, y, this);
 967         // TODO: fill "bdata" member of AWTEvent
 968         // TODO: screenX/screenY
 969         postEvent(new MouseWheelEvent(targetPeer.getTarget(),
 970                                       MouseEvent.MOUSE_WHEEL,
 971                                       when, modifiers,
 972                                       lp.x, lp.y,
 973                                       0, 0, /* screenX, Y */
 974                                       0 /* clickCount */, false /* popupTrigger */,
 975                                       scrollType, scrollAmount,
 976                                       wheelRotation, preciseWheelRotation));
 977     }
 978 
 979     /*
 980      * Called by the delegate when a key is pressed.
 981      */
 982     @Override
 983     public void notifyKeyEvent(int id, long when, int modifiers,
 984                                int keyCode, char keyChar, int keyLocation)
 985     {
 986         LWKeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
 987         Component focusOwner = kfmPeer.getCurrentFocusOwner();
 988 
 989         if (focusOwner == null) {
 990             focusOwner = kfmPeer.getCurrentFocusedWindow();
 991             if (focusOwner == null) {
 992                 focusOwner = this.getTarget();
 993             }
 994         }
 995 
 996         KeyEvent keyEvent = new KeyEvent(focusOwner, id, when, modifiers,
 997             keyCode, keyChar, keyLocation);
 998         AWTAccessor.getKeyEventAccessor().setExtendedKeyCode(keyEvent,
 999                 (keyChar == KeyEvent.CHAR_UNDEFINED) ? keyCode
1000                 : ExtendedKeyCodes.getExtendedKeyCodeForChar(keyChar));
1001         postEvent(keyEvent);
1002     }
1003 
1004     // ---- UTILITY METHODS ---- //
1005 
1006     private void activateDisplayListener() {
1007         final GraphicsEnvironment ge =
1008                 GraphicsEnvironment.getLocalGraphicsEnvironment();
1009         ((SunGraphicsEnvironment) ge).addDisplayChangedListener(this);
1010     }
1011 
1012     private void deactivateDisplayListener() {
1013         final GraphicsEnvironment ge =
1014                 GraphicsEnvironment.getLocalGraphicsEnvironment();
1015         ((SunGraphicsEnvironment) ge).removeDisplayChangedListener(this);
1016     }
1017 
1018     private void postWindowStateChangedEvent(int newWindowState) {
1019         if (getTarget() instanceof Frame) {
1020             AWTAccessor.getFrameAccessor().setExtendedState(
1021                     (Frame)getTarget(), newWindowState);
1022         }
1023 
1024         WindowEvent stateChangedEvent = new WindowEvent(getTarget(),
1025                 WindowEvent.WINDOW_STATE_CHANGED,
1026                 windowState, newWindowState);
1027         postEvent(stateChangedEvent);
1028         windowState = newWindowState;
1029 
1030         updateSecurityWarningVisibility();
1031     }
1032 
1033     private static int getGraphicsConfigScreen(GraphicsConfiguration gc) {
1034         // TODO: this method can be implemented in a more
1035         // efficient way by forwarding to the delegate
1036         GraphicsDevice gd = gc.getDevice();
1037         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
1038         GraphicsDevice[] gds = ge.getScreenDevices();
1039         for (int i = 0; i < gds.length; i++) {
1040             if (gds[i] == gd) {
1041                 return i;
1042             }
1043         }
1044         // Should never happen if gc is a screen device config
1045         return 0;
1046     }
1047 
1048     /*
1049      * This method is called when window's graphics config is changed from
1050      * the app code (e.g. when the window is made non-opaque) or when
1051      * the window is moved to another screen by user.
1052      *
1053      * Returns true if the graphics config has been changed, false otherwise.
1054      */
1055     private boolean setGraphicsConfig(GraphicsConfiguration gc) {
1056         synchronized (getStateLock()) {
1057             if (graphicsConfig == gc) {
1058                 return false;
1059             }
1060             // If window's graphics config is changed from the app code, the
1061             // config correspond to the same device as before; when the window
1062             // is moved by user, graphicsDevice is updated in notifyReshape().
1063             // In either case, there's nothing to do with screenOn here
1064             graphicsConfig = gc;
1065         }
1066         // SurfaceData is replaced later in updateGraphicsData()
1067         return true;
1068     }
1069 
1070     /**
1071      * Returns true if the GraphicsDevice has been changed, false otherwise.
1072      */
1073     public boolean updateGraphicsDevice() {
1074         GraphicsDevice newGraphicsDevice = platformWindow.getGraphicsDevice();
1075         synchronized (getStateLock()) {
1076             if (graphicsDevice == newGraphicsDevice) {
1077                 return false;
1078             }
1079             graphicsDevice = newGraphicsDevice;
1080         }
1081 
1082         final GraphicsConfiguration newGC = newGraphicsDevice.getDefaultConfiguration();
1083 
1084         if (!setGraphicsConfig(newGC)) return false;
1085 
1086         SunToolkit.executeOnEventHandlerThread(getTarget(), new Runnable() {
1087             public void run() {
1088                 AWTAccessor.getComponentAccessor().setGraphicsConfiguration(getTarget(), newGC);
1089             }
1090         });
1091         return true;
1092     }
1093 
1094     @Override
1095     public final void displayChanged() {
1096         if (updateGraphicsDevice()) {
1097             updateMinimumSize();
1098             if (!isMaximizedBoundsSet()) {
1099                 setPlatformMaximizedBounds(getDefaultMaximizedBounds());
1100             }
1101         }
1102         // Replace surface unconditionally, because internal state of the
1103         // GraphicsDevice could be changed.
1104         replaceSurfaceData();
1105         repaintPeer();
1106     }
1107 
1108     @Override
1109     public final void paletteChanged() {
1110         // components do not need to react to this event.
1111     }
1112 
1113     /*
1114      * May be called by delegate to provide SD to Java2D code.
1115      */
1116     public SurfaceData getSurfaceData() {
1117         synchronized (surfaceDataLock) {
1118             return surfaceData;
1119         }
1120     }
1121 
1122     private void replaceSurfaceData() {
1123         replaceSurfaceData(true);
1124     }
1125 
1126     private void replaceSurfaceData(final boolean blit) {
1127         synchronized (surfaceDataLock) {
1128             final SurfaceData oldData = getSurfaceData();
1129             surfaceData = platformWindow.replaceSurfaceData();
1130             final Rectangle size = getSize();
1131             if (getSurfaceData() != null && oldData != getSurfaceData()) {
1132                 clearBackground(size.width, size.height);
1133             }
1134 
1135             if (blit) {
1136                 blitSurfaceData(oldData, getSurfaceData());
1137             }
1138 
1139             if (oldData != null && oldData != getSurfaceData()) {
1140                 // TODO: drop oldData for D3D/WGL pipelines
1141                 // This can only happen when this peer is being created
1142                 oldData.flush();
1143             }
1144         }
1145         flushOnscreenGraphics();
1146     }
1147 
1148     private void blitSurfaceData(final SurfaceData src, final SurfaceData dst) {
1149         //TODO blit. proof-of-concept
1150         if (src != dst && src != null && dst != null
1151             && !(dst instanceof NullSurfaceData)
1152             && !(src instanceof NullSurfaceData)
1153             && src.getSurfaceType().equals(dst.getSurfaceType())
1154             && src.getDefaultScale() == dst.getDefaultScale()) {
1155             final Rectangle size = src.getBounds();
1156             final Blit blit = Blit.locate(src.getSurfaceType(),
1157                                           CompositeType.Src,
1158                                           dst.getSurfaceType());
1159             if (blit != null) {
1160                 blit.Blit(src, dst, AlphaComposite.Src, null, 0, 0, 0, 0,
1161                           size.width, size.height);
1162             }
1163         }
1164     }
1165 
1166     /**
1167      * Request the window insets from the delegate and compares it with the
1168      * current one. This method is mostly called by the delegate, e.g. when the
1169      * window state is changed and insets should be recalculated.
1170      * <p/>
1171      * This method may be called on the toolkit thread.
1172      */
1173     public final boolean updateInsets(final Insets newInsets) {
1174         synchronized (getStateLock()) {
1175             if (insets.equals(newInsets)) {
1176                 return false;
1177             }
1178             insets = newInsets;
1179         }
1180         return true;
1181     }
1182 
1183     public static LWWindowPeer getWindowUnderCursor() {
1184         return lastCommonMouseEventPeer != null ? lastCommonMouseEventPeer.getWindowPeerOrSelf() : null;
1185     }
1186 
1187     public static LWComponentPeer<?, ?> getPeerUnderCursor() {
1188         return lastCommonMouseEventPeer;
1189     }
1190 
1191     /*
1192      * Requests platform to set native focus on a frame/dialog.
1193      * In case of a simple window, triggers appropriate java focus change.
1194      */
1195     public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
1196         if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1197             focusLog.fine("requesting native focus to " + this);
1198         }
1199 
1200         if (!focusAllowedFor()) {
1201             focusLog.fine("focus is not allowed");
1202             return false;
1203         }
1204 
1205         if (platformWindow.rejectFocusRequest(cause)) {
1206             return false;
1207         }
1208 
1209         AppContext targetAppContext = AWTAccessor.getComponentAccessor().getAppContext(getTarget());
1210         KeyboardFocusManager kfm = AWTAccessor.getKeyboardFocusManagerAccessor()
1211                 .getCurrentKeyboardFocusManager(targetAppContext);
1212         Window currentActive = kfm.getActiveWindow();
1213 
1214 
1215         Window opposite = LWKeyboardFocusManagerPeer.getInstance().
1216             getCurrentFocusedWindow();
1217 
1218         // Make the owner active window.
1219         if (isSimpleWindow()) {
1220             LWWindowPeer owner = getOwnerFrameDialog(this);
1221 
1222             // If owner is not natively active, request native
1223             // activation on it w/o sending events up to java.
1224             if (owner != null && !owner.platformWindow.isActive()) {
1225                 if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1226                     focusLog.fine("requesting native focus to the owner " + owner);
1227                 }
1228                 LWWindowPeer currentActivePeer = currentActive == null ? null :
1229                 (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(
1230                         currentActive);
1231 
1232                 // Ensure the opposite is natively active and suppress sending events.
1233                 if (currentActivePeer != null && currentActivePeer.platformWindow.isActive()) {
1234                     if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1235                         focusLog.fine("the opposite is " + currentActivePeer);
1236                     }
1237                     currentActivePeer.skipNextFocusChange = true;
1238                 }
1239                 owner.skipNextFocusChange = true;
1240 
1241                 owner.platformWindow.requestWindowFocus();
1242             }
1243 
1244             // DKFM will synthesize all the focus/activation events correctly.
1245             changeFocusedWindow(true, opposite);
1246             return true;
1247 
1248         // In case the toplevel is active but not focused, change focus directly,
1249         // as requesting native focus on it will not have effect.
1250         } else if (getTarget() == currentActive && !getTarget().hasFocus()) {
1251 
1252             changeFocusedWindow(true, opposite);
1253             return true;
1254         }
1255 
1256         return platformWindow.requestWindowFocus();
1257     }
1258 
1259     protected boolean focusAllowedFor() {
1260         Window window = getTarget();
1261         // TODO: check if modal blocked
1262         return window.isVisible() && window.isEnabled() && isFocusableWindow();
1263     }
1264 
1265     private boolean isFocusableWindow() {
1266         boolean focusable  = targetFocusable;
1267         if (isSimpleWindow()) {
1268             LWWindowPeer ownerPeer = getOwnerFrameDialog(this);
1269             if (ownerPeer == null) {
1270                 return false;
1271             }
1272             return focusable && ownerPeer.targetFocusable;
1273         }
1274         return focusable;
1275     }
1276 
1277     public boolean isSimpleWindow() {
1278         Window window = getTarget();
1279         return !(window instanceof Dialog || window instanceof Frame);
1280     }
1281 
1282     @Override
1283     public void emulateActivation(boolean activate) {
1284         changeFocusedWindow(activate, null);
1285     }
1286 
1287     @SuppressWarnings("deprecation")
1288     private boolean isOneOfOwnersOf(LWWindowPeer peer) {
1289         Window owner = (peer != null ? peer.getTarget().getOwner() : null);
1290         while (owner != null) {
1291             final ComponentAccessor acc = AWTAccessor.getComponentAccessor();
1292             if (acc.getPeer(owner) == this) {
1293                 return true;
1294             }
1295             owner = owner.getOwner();
1296         }
1297         return false;
1298     }
1299 
1300     /*
1301      * Changes focused window on java level.
1302      */
1303     protected void changeFocusedWindow(boolean becomesFocused, Window opposite) {
1304         if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1305             focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
1306         }
1307         if (skipNextFocusChange) {
1308             focusLog.fine("skipping focus change");
1309             skipNextFocusChange = false;
1310             return;
1311         }
1312         if (!isFocusableWindow() && becomesFocused) {
1313             focusLog.fine("the window is not focusable");
1314             return;
1315         }
1316         if (becomesFocused) {
1317             synchronized (getPeerTreeLock()) {
1318                 if (blocker != null) {
1319                     if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
1320                         focusLog.finest("the window is blocked by " + blocker);
1321                     }
1322                     return;
1323                 }
1324             }
1325         }
1326 
1327         // Note, the method is not called:
1328         // - when the opposite (gaining focus) window is an owned/owner window.
1329         // - for a simple window in any case.
1330         if (!becomesFocused &&
1331             (isGrabbing() || this.isOneOfOwnersOf(grabbingWindow)))
1332         {
1333             if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1334                 focusLog.fine("ungrabbing on " + grabbingWindow);
1335             }
1336             // ungrab a simple window if its owner looses activation.
1337             grabbingWindow.ungrab();
1338         }
1339 
1340         KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
1341 
1342         if (!becomesFocused && kfmPeer.getCurrentFocusedWindow() != getTarget()) {
1343             // late window focus lost event - ingoring
1344             return;
1345         }
1346 
1347         kfmPeer.setCurrentFocusedWindow(becomesFocused ? getTarget() : null);
1348 
1349         int eventID = becomesFocused ? WindowEvent.WINDOW_GAINED_FOCUS : WindowEvent.WINDOW_LOST_FOCUS;
1350         WindowEvent windowEvent = new TimedWindowEvent(getTarget(), eventID, opposite, System.currentTimeMillis());
1351 
1352         // TODO: wrap in SequencedEvent
1353         postEvent(windowEvent);
1354     }
1355 
1356     /*
1357      * Retrieves the owner of the peer.
1358      * Note: this method returns the owner which can be activated, (i.e. the instance
1359      * of Frame or Dialog may be returned).
1360      */
1361     static LWWindowPeer getOwnerFrameDialog(LWWindowPeer peer) {
1362         Window owner = (peer != null ? peer.getTarget().getOwner() : null);
1363         while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
1364             owner = owner.getOwner();
1365         }
1366         return owner == null ? null : AWTAccessor.getComponentAccessor()
1367                                                  .getPeer(owner);
1368     }
1369 
1370     /**
1371      * Returns the foremost modal blocker of this window, or null.
1372      */
1373     public LWWindowPeer getBlocker() {
1374         synchronized (getPeerTreeLock()) {
1375             LWWindowPeer blocker = this.blocker;
1376             if (blocker == null) {
1377                 return null;
1378             }
1379             while (blocker.blocker != null) {
1380                 blocker = blocker.blocker;
1381             }
1382             return blocker;
1383         }
1384     }
1385 
1386     @Override
1387     public void enterFullScreenMode() {
1388         platformWindow.enterFullScreenMode();
1389         updateSecurityWarningVisibility();
1390     }
1391 
1392     @Override
1393     public void exitFullScreenMode() {
1394         platformWindow.exitFullScreenMode();
1395         updateSecurityWarningVisibility();
1396     }
1397 
1398     public long getLayerPtr() {
1399         return getPlatformWindow().getLayerPtr();
1400     }
1401 
1402     void grab() {
1403         if (grabbingWindow != null && !isGrabbing()) {
1404             grabbingWindow.ungrab();
1405         }
1406         grabbingWindow = this;
1407     }
1408 
1409     final void ungrab(boolean doPost) {
1410         if (isGrabbing()) {
1411             grabbingWindow = null;
1412             if (doPost) {
1413                 postEvent(new UngrabEvent(getTarget()));
1414             }
1415         }
1416     }
1417 
1418     void ungrab() {
1419         ungrab(true);
1420     }
1421 
1422     private boolean isGrabbing() {
1423         return this == grabbingWindow;
1424     }
1425 
1426     public PeerType getPeerType() {
1427         return peerType;
1428     }
1429 
1430     public void updateSecurityWarningVisibility() {
1431         if (warningWindow == null) {
1432             return;
1433         }
1434 
1435         if (!isVisible()) {
1436             return; // The warning window should already be hidden.
1437         }
1438 
1439         boolean show = false;
1440 
1441         if (!platformWindow.isFullScreenMode()) {
1442             if (isVisible()) {
1443                 if (LWKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow() ==
1444                         getTarget()) {
1445                     show = true;
1446                 }
1447 
1448                 if (platformWindow.isUnderMouse() || warningWindow.isUnderMouse()) {
1449                     show = true;
1450                 }
1451             }
1452         }
1453 
1454         warningWindow.setVisible(show, true);
1455     }
1456 
1457     @Override
1458     public String toString() {
1459         return super.toString() + " [target is " + getTarget() + "]";
1460     }
1461 }