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