LWWindowPeer.java 49.2 KB
Newer Older
1
/*
2
 * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package sun.lwawt;

import java.awt.*;
import java.awt.event.*;
import java.awt.peer.*;
import java.util.List;

import javax.swing.*;

import sun.awt.*;
import sun.java2d.*;
import sun.java2d.loops.Blit;
import sun.java2d.loops.CompositeType;
S
serb 已提交
39
import sun.java2d.pipe.Region;
40 41 42 43
import sun.util.logging.PlatformLogger;

public class LWWindowPeer
    extends LWContainerPeer<Window, JComponent>
C
Merge  
chegar 已提交
44
    implements FramePeer, DialogPeer, FullScreenCapable, DisplayChangedListener, PlatformEventNotifier
45
{
46
    public enum PeerType {
47 48 49
        SIMPLEWINDOW,
        FRAME,
        DIALOG,
50
        EMBEDDED_FRAME,
51 52
        VIEW_EMBEDDED_FRAME,
        LW_FRAME
53 54
    }

55
    private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.lwawt.focus.LWWindowPeer");
56

57
    private final PlatformWindow platformWindow;
58 59 60 61 62 63

    private static final int MINIMUM_WIDTH = 1;
    private static final int MINIMUM_HEIGHT = 1;

    private Insets insets = new Insets(0, 0, 0, 0);

64
    private GraphicsDevice graphicsDevice;
65 66 67 68 69 70 71
    private GraphicsConfiguration graphicsConfig;

    private SurfaceData surfaceData;
    private final Object surfaceDataLock = new Object();

    private volatile int windowState = Frame.NORMAL;

72 73 74 75
    // check that the mouse is over the window
    private volatile boolean isMouseOver = false;

    // A peer where the last mouse event came to. Used by cursor manager to
76
    // find the component under cursor
77
    private static volatile LWComponentPeer<?, ?> lastCommonMouseEventPeer;
78 79 80

    // A peer where the last mouse event came to. Used to generate
    // MOUSE_ENTERED/EXITED notifications
81
    private volatile LWComponentPeer<?, ?> lastMouseEventPeer;
82 83 84

    // Peers where all dragged/released events should come to,
    // depending on what mouse button is being dragged according to Cocoa
85
    private static final LWComponentPeer<?, ?>[] mouseDownTarget = new LWComponentPeer<?, ?>[3];
86 87 88 89 90 91 92 93 94 95 96 97 98 99

    // A bitmask that indicates what mouse buttons produce MOUSE_CLICKED events
    // on MOUSE_RELEASE. Click events are only generated if there were no drag
    // events between MOUSE_PRESSED and MOUSE_RELEASED for particular button
    private static int mouseClickButtons = 0;

    private volatile boolean isOpaque = true;

    private static final Font DEFAULT_FONT = new Font("Lucida Grande", Font.PLAIN, 13);

    private static LWWindowPeer grabbingWindow;

    private volatile boolean skipNextFocusChange;

S
serb 已提交
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 113 114 115 116 117
    /**
     * Current modal blocker or null.
     *
     * Synchronization: peerTreeLock.
     */
    private LWWindowPeer blocker;

    public LWWindowPeer(Window target, PlatformComponent platformComponent,
118
                        PlatformWindow platformWindow, PeerType peerType)
119 120 121
    {
        super(target, platformComponent);
        this.platformWindow = platformWindow;
122
        this.peerType = peerType;
123 124

        Window owner = target.getOwner();
125 126
        LWWindowPeer ownerPeer = owner == null ? null :
             (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(owner);
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        PlatformWindow ownerDelegate = (ownerPeer != null) ? ownerPeer.getPlatformWindow() : null;

        // The delegate.initialize() needs a non-null GC on X11.
        GraphicsConfiguration gc = getTarget().getGraphicsConfiguration();
        synchronized (getStateLock()) {
            // graphicsConfig should be updated according to the real window
            // bounds when the window is shown, see 4868278
            this.graphicsConfig = gc;
        }

        if (!target.isFontSet()) {
            target.setFont(DEFAULT_FONT);
        }

        if (!target.isBackgroundSet()) {
            target.setBackground(SystemColor.window);
        } else {
            // first we check if user provided alpha for background. This is
            // similar to what Apple's Java do.
            // Since JDK7 we should rely on setOpacity() only.
            // this.opacity = c.getAlpha();
        }

        if (!target.isForegroundSet()) {
            target.setForeground(SystemColor.windowText);
            // we should not call setForeground because it will call a repaint
            // which the peer may not be ready to do yet.
        }

        platformWindow.initialize(target, this, ownerDelegate);
157 158 159

        // Init warning window(for applets)
        SecurityWarningWindow warn = null;
160
        if (target.getWarningString() != null) {
161 162
            // accessSystemTray permission allows to display TrayIcon, TrayIcon tooltip
            // and TrayIcon balloon windows without a warning window.
163
            if (!AWTAccessor.getWindowAccessor().isTrayIconWindow(target)) {
164 165 166 167 168 169
                LWToolkit toolkit = (LWToolkit)Toolkit.getDefaultToolkit();
                warn = toolkit.createSecurityWarning(target, this);
            }
        }

        warningWindow = warn;
170 171 172
    }

    @Override
173 174
    void initializeImpl() {
        super.initializeImpl();
175 176


177
        if (getTarget() instanceof Frame) {
178 179
            setTitle(((Frame) getTarget()).getTitle());
            setState(((Frame) getTarget()).getExtendedState());
180
        } else if (getTarget() instanceof Dialog) {
181
            setTitle(((Dialog) getTarget()).getTitle());
182 183
        }

M
malenkov 已提交
184
        updateAlwaysOnTopState();
185 186
        updateMinimumSize();

S
serb 已提交
187 188 189 190 191
        final Shape shape = getTarget().getShape();
        if (shape != null) {
            applyShape(Region.getInstance(shape, null));
        }

192 193 194 195
        final float opacity = getTarget().getOpacity();
        if (opacity < 1.0f) {
            setOpacity(opacity);
        }
196

197
        setOpaque(getTarget().isOpaque());
198 199

        updateInsets(platformWindow.getInsets());
200
        if (getSurfaceData() == null) {
S
serb 已提交
201
            replaceSurfaceData(false);
202
        }
203
        activateDisplayListener();
204 205 206
    }

    // Just a helper method
207
    @Override
208 209 210 211 212 213 214 215 216 217 218 219 220
    public PlatformWindow getPlatformWindow() {
        return platformWindow;
    }

    @Override
    protected LWWindowPeer getWindowPeerOrSelf() {
        return this;
    }

    // ---- PEER METHODS ---- //

    @Override
    protected void disposeImpl() {
221
        deactivateDisplayListener();
222 223 224 225 226 227 228 229 230 231
        SurfaceData oldData = getSurfaceData();
        synchronized (surfaceDataLock){
            surfaceData = null;
        }
        if (oldData != null) {
            oldData.invalidate();
        }
        if (isGrabbing()) {
            ungrab();
        }
232 233 234 235
        if (warningWindow != null) {
            warningWindow.dispose();
        }

236 237 238 239 240
        platformWindow.dispose();
        super.disposeImpl();
    }

    @Override
241
    protected void setVisibleImpl(final boolean visible) {
242 243 244
        if (!visible && warningWindow != null) {
            warningWindow.setVisible(false, false);
        }
245
        updateFocusableWindowState();
246
        super.setVisibleImpl(visible);
247
        // TODO: update graphicsConfig, see 4868278
248 249
        platformWindow.setVisible(visible);
        if (isSimpleWindow()) {
250
            KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
251 252 253 254 255 256 257
            if (visible) {
                if (!getTarget().isAutoRequestFocus()) {
                    return;
                } else {
                    requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
                }
            // Focus the owner in case this window is focused.
258
            } else if (kfmPeer.getCurrentFocusedWindow() == getTarget()) {
259 260 261 262
                // Transfer focus to the owner.
                LWWindowPeer owner = getOwnerFrameDialog(LWWindowPeer.this);
                if (owner != null) {
                    owner.requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
263 264
                }
            }
265
        }
266 267 268
    }

    @Override
269 270 271 272
    public final GraphicsConfiguration getGraphicsConfiguration() {
        synchronized (getStateLock()) {
            return graphicsConfig;
        }
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    }

    @Override
    public boolean updateGraphicsData(GraphicsConfiguration gc) {
        setGraphicsConfig(gc);
        return false;
    }

    protected final Graphics getOnscreenGraphics(Color fg, Color bg, Font f) {
        if (getSurfaceData() == null) {
            return null;
        }
        if (fg == null) {
            fg = SystemColor.windowText;
        }
        if (bg == null) {
            bg = SystemColor.window;
        }
        if (f == null) {
            f = DEFAULT_FONT;
        }
        return platformWindow.transformGraphics(new SunGraphics2D(getSurfaceData(), fg, bg, f));
    }

    @Override
    public void setBounds(int x, int y, int w, int h, int op) {
299 300 301 302 303

        if((op & NO_EMBEDDED_CHECK) == 0 && getPeerType() == PeerType.VIEW_EMBEDDED_FRAME) {
            return;
        }

304 305 306 307 308 309 310 311
        if ((op & SET_CLIENT_SIZE) != 0) {
            // SET_CLIENT_SIZE is only applicable to window peers, so handle it here
            // instead of pulling 'insets' field up to LWComponentPeer
            // no need to add insets since Window's notion of width and height includes insets.
            op &= ~SET_CLIENT_SIZE;
            op |= SET_SIZE;
        }

312 313 314
        // Don't post ComponentMoved/Resized and Paint events
        // until we've got a notification from the delegate
        Rectangle cb = constrainBounds(x, y, w, h);
315 316 317 318 319 320 321 322 323 324 325 326

        Rectangle newBounds = new Rectangle(getBounds());
        if ((op & (SET_LOCATION | SET_BOUNDS)) != 0) {
            newBounds.x = cb.x;
            newBounds.y = cb.y;
        }
        if ((op & (SET_SIZE | SET_BOUNDS)) != 0) {
            newBounds.width = cb.width;
            newBounds.height = cb.height;
        }
        // Native system could constraint bounds, so the peer wold be updated in the callback
        platformWindow.setBounds(newBounds.x, newBounds.y, newBounds.width, newBounds.height);
327 328 329 330 331 332 333 334
    }

    public Rectangle constrainBounds(Rectangle bounds) {
        return constrainBounds(bounds.x, bounds.y, bounds.width, bounds.height);
    }

    public Rectangle constrainBounds(int x, int y, int w, int h) {

335 336 337
        if (w < MINIMUM_WIDTH) {
            w = MINIMUM_WIDTH;
        }
338

339 340 341 342
        if (h < MINIMUM_HEIGHT) {
            h = MINIMUM_HEIGHT;
        }

343 344
        final int maxW = getLWGC().getMaxTextureWidth();
        final int maxH = getLWGC().getMaxTextureHeight();
345

346 347 348 349 350
        if (w > maxW) {
            w = maxW;
        }
        if (h > maxH) {
            h = maxH;
351 352
        }

353
        return new Rectangle(x, y, w, h);
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    }

    @Override
    public Point getLocationOnScreen() {
        return platformWindow.getLocationOnScreen();
    }

    /**
     * Overridden from LWContainerPeer to return the correct insets.
     * Insets are queried from the delegate and are kept up to date by
     * requiering when needed (i.e. when the window geometry is changed).
     */
    @Override
    public Insets getInsets() {
        synchronized (getStateLock()) {
            return insets;
        }
    }

    @Override
    public FontMetrics getFontMetrics(Font f) {
        // TODO: check for "use platform metrics" settings
        return platformWindow.getFontMetrics(f);
    }

    @Override
    public void toFront() {
        platformWindow.toFront();
    }

    @Override
    public void toBack() {
        platformWindow.toBack();
    }

    @Override
    public void setZOrder(ComponentPeer above) {
        throw new RuntimeException("not implemented");
    }

    @Override
M
malenkov 已提交
395 396
    public void updateAlwaysOnTopState() {
        platformWindow.setAlwaysOnTop(getTarget().isAlwaysOnTop());
397 398 399 400
    }

    @Override
    public void updateFocusableWindowState() {
401
        targetFocusable = getTarget().isFocusableWindow();
402 403 404 405 406 407
        platformWindow.updateFocusableWindowState();
    }

    @Override
    public void setModalBlocked(Dialog blocker, boolean blocked) {
        synchronized (getPeerTreeLock()) {
408 409 410 411 412 413
            ComponentPeer peer =  AWTAccessor.getComponentAccessor().getPeer(blocker);
            if (blocked && (peer instanceof LWWindowPeer)) {
                this.blocker = (LWWindowPeer) peer;
            } else {
                this.blocker = null;
            }
414
        }
415 416

        platformWindow.setModalBlocked(blocked);
417 418 419 420
    }

    @Override
    public void updateMinimumSize() {
421
        final Dimension min;
422
        if (getTarget().isMinimumSizeSet()) {
423 424 425 426 427
            min = getTarget().getMinimumSize();
            min.width = Math.max(min.width, MINIMUM_WIDTH);
            min.height = Math.max(min.height, MINIMUM_HEIGHT);
        } else {
            min = new Dimension(MINIMUM_WIDTH, MINIMUM_HEIGHT);
428
        }
429 430 431 432

        final Dimension max;
        if (getTarget().isMaximumSizeSet()) {
            max = getTarget().getMaximumSize();
433 434
            max.width = Math.min(max.width, getLWGC().getMaxTextureWidth());
            max.height = Math.min(max.height, getLWGC().getMaxTextureHeight());
435
        } else {
436 437
            max = new Dimension(getLWGC().getMaxTextureWidth(),
                                getLWGC().getMaxTextureHeight());
438
        }
439 440

        platformWindow.setSizeConstraints(min.width, min.height, max.width, max.height);
441 442 443 444 445 446 447
    }

    @Override
    public void updateIconImages() {
        getPlatformWindow().updateIconImages();
    }

448 449 450 451 452 453
    @Override
    public void setBackground(final Color c) {
        super.setBackground(c);
        updateOpaque();
    }

454 455 456 457 458 459 460 461 462 463
    @Override
    public void setOpacity(float opacity) {
        getPlatformWindow().setOpacity(opacity);
        repaintPeer();
    }

    @Override
    public final void setOpaque(final boolean isOpaque) {
        if (this.isOpaque != isOpaque) {
            this.isOpaque = isOpaque;
S
serb 已提交
464
            updateOpaque();
465 466 467
        }
    }

S
serb 已提交
468 469 470 471
    private void updateOpaque() {
        getPlatformWindow().setOpaque(!isTranslucent());
        replaceSurfaceData(false);
        repaintPeer();
472 473 474 475
    }

    @Override
    public void updateWindow() {
S
serb 已提交
476 477
    }

478 479 480 481 482 483 484 485
    public final boolean isTextured() {
        return textured;
    }

    public final void setTextured(final boolean isTextured) {
        textured = isTextured;
    }

486
    @Override
S
serb 已提交
487 488
    public final boolean isTranslucent() {
        synchronized (getStateLock()) {
489 490 491 492 493 494 495
            /*
             * Textured window is a special case of translucent window.
             * The difference is only in nswindow background. So when we set
             * texture property our peer became fully translucent. It doesn't
             * fill background, create non opaque backbuffers and layer etc.
             */
            return !isOpaque || isShaped() || isTextured();
S
serb 已提交
496 497 498 499 500 501 502
        }
    }

    @Override
    final void applyShapeImpl(final Region shape) {
        super.applyShapeImpl(shape);
        updateOpaque();
503 504 505 506
    }

    @Override
    public void repositionSecurityWarning() {
507 508 509 510 511 512 513 514 515
        if (warningWindow != null) {
            AWTAccessor.ComponentAccessor compAccessor = AWTAccessor.getComponentAccessor();
            Window target = getTarget();
            int x = compAccessor.getX(target);
            int y = compAccessor.getY(target);
            int width = compAccessor.getWidth(target);
            int height = compAccessor.getHeight(target);
            warningWindow.reposition(x, y, width, height);
        }
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
    }

    // ---- FRAME PEER METHODS ---- //

    @Override // FramePeer and DialogPeer
    public void setTitle(String title) {
        platformWindow.setTitle(title == null ? "" : title);
    }

    @Override
    public void setMenuBar(MenuBar mb) {
         platformWindow.setMenuBar(mb);
    }

    @Override // FramePeer and DialogPeer
    public void setResizable(boolean resizable) {
        platformWindow.setResizable(resizable);
    }

    @Override
    public void setState(int state) {
        platformWindow.setWindowState(state);
    }

    @Override
    public int getState() {
        return windowState;
    }

    @Override
    public void setMaximizedBounds(Rectangle bounds) {
        // TODO: not implemented
    }

    @Override
    public void setBoundsPrivate(int x, int y, int width, int height) {
        setBounds(x, y, width, height, SET_BOUNDS | NO_EMBEDDED_CHECK);
    }

    @Override
    public Rectangle getBoundsPrivate() {
        throw new RuntimeException("not implemented");
    }

    // ---- DIALOG PEER METHODS ---- //

    @Override
    public void blockWindows(List<Window> windows) {
        //TODO: LWX will probably need some collectJavaToplevels to speed this up
        for (Window w : windows) {
566 567
            WindowPeer wp =
                    (WindowPeer) AWTAccessor.getComponentAccessor().getPeer(w);
568 569 570 571 572 573 574 575
            if (wp != null) {
                wp.setModalBlocked((Dialog)getTarget(), true);
            }
        }
    }

    // ---- PEER NOTIFICATIONS ---- //

576
    @Override
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
    public void notifyIconify(boolean iconify) {
        //The toplevel target is Frame and states are applicable to it.
        //Otherwise, the target is Window and it don't have state property.
        //Hopefully, no such events are posted in the queue so consider the
        //target as Frame in all cases.

        // REMIND: should we send it anyway if the state not changed since last
        // time?
        WindowEvent iconifyEvent = new WindowEvent(getTarget(),
                iconify ? WindowEvent.WINDOW_ICONIFIED
                        : WindowEvent.WINDOW_DEICONIFIED);
        postEvent(iconifyEvent);

        int newWindowState = iconify ? Frame.ICONIFIED : Frame.NORMAL;
        postWindowStateChangedEvent(newWindowState);

        // REMIND: RepaintManager doesn't repaint iconified windows and
        // hence ignores any repaint request during deiconification.
        // So, we need to repaint window explicitly when it becomes normal.
        if (!iconify) {
            repaintPeer();
        }
    }

601
    @Override
602 603 604 605 606 607
    public void notifyZoom(boolean isZoomed) {
        int newWindowState = isZoomed ? Frame.MAXIMIZED_BOTH : Frame.NORMAL;
        postWindowStateChangedEvent(newWindowState);
    }

    /**
608 609
     * Called by the {@code PlatformWindow} when any part of the window should
     * be repainted.
610
     */
611 612
    @Override
    public void notifyExpose(final Rectangle r) {
613
        repaintPeer(r);
614 615 616
    }

    /**
617
     * Called by the {@code PlatformWindow} when this window is moved/resized by
618 619 620
     * user or window insets are changed. There's no notifyReshape() in
     * LWComponentPeer as the only components which could be resized by user are
     * top-level windows.
621
     */
622 623
    @Override
    public void notifyReshape(int x, int y, int w, int h) {
624
        Rectangle oldBounds = getBounds();
625
        final boolean invalid = updateInsets(platformWindow.getInsets());
626 627
        final boolean moved = (x != oldBounds.x) || (y != oldBounds.y);
        final boolean resized = (w != oldBounds.width) || (h != oldBounds.height);
628 629

        // Check if anything changed
630
        if (!moved && !resized && !invalid) {
631 632 633 634 635 636
            return;
        }
        // First, update peer's bounds
        setBounds(x, y, w, h, SET_BOUNDS, false, false);

        // Second, update the graphics config and surface data
637 638
        final boolean isNewDevice = updateGraphicsDevice();
        if (resized || isNewDevice) {
639
            replaceSurfaceData();
640
            updateMinimumSize();
641 642
        }

643
        // Third, COMPONENT_MOVED/COMPONENT_RESIZED/PAINT events
644
        if (moved || invalid) {
645 646
            handleMove(x, y, true);
        }
647
        if (resized || invalid || isNewDevice) {
648 649
            handleResize(w, h, true);
            repaintPeer();
650
        }
651 652

        repositionSecurityWarning();
653 654 655 656 657 658 659
    }

    private void clearBackground(final int w, final int h) {
        final Graphics g = getOnscreenGraphics(getForeground(), getBackground(),
                                               getFont());
        if (g != null) {
            try {
S
serb 已提交
660 661 662 663 664 665 666
                if (g instanceof Graphics2D) {
                    ((Graphics2D) g).setComposite(AlphaComposite.Src);
                }
                if (isTranslucent()) {
                    g.setColor(nonOpaqueBackground);
                    g.fillRect(0, 0, w, h);
                }
667 668
                if (!isTextured()) {
                    if (g instanceof SunGraphics2D) {
669
                        ((SunGraphics2D) g).constrain(0, 0, w, h, getRegion());
670 671 672
                    }
                    g.setColor(getBackground());
                    g.fillRect(0, 0, w, h);
S
serb 已提交
673
                }
674 675 676 677 678 679
            } finally {
                g.dispose();
            }
        }
    }

680
    @Override
681 682 683 684
    public void notifyUpdateCursor() {
        getLWToolkit().getCursorManager().updateCursorLater(this);
    }

685
    @Override
686 687 688
    public void notifyActivation(boolean activation, LWWindowPeer opposite) {
        Window oppositeWindow = (opposite == null)? null : opposite.getTarget();
        changeFocusedWindow(activation, oppositeWindow);
689 690 691
    }

    // MouseDown in non-client area
692
    @Override
693 694 695
    public void notifyNCMouseDown() {
        // Ungrab except for a click on a Dialog with the grabbing owner
        if (grabbingWindow != null &&
696
            !grabbingWindow.isOneOfOwnersOf(this))
697 698 699 700 701 702 703 704 705 706 707 708
        {
            grabbingWindow.ungrab();
        }
    }

    // ---- EVENTS ---- //

    /*
     * Called by the delegate to dispatch the event to Java. Event
     * coordinates are relative to non-client window are, i.e. the top-left
     * point of the client area is (insets.top, insets.left).
     */
709 710 711 712 713
    @Override
    public void notifyMouseEvent(int id, long when, int button,
                                 int x, int y, int screenX, int screenY,
                                 int modifiers, int clickCount, boolean popupTrigger,
                                 byte[] bdata)
714 715 716 717
    {
        // TODO: fill "bdata" member of AWTEvent
        Rectangle r = getBounds();
        // findPeerAt() expects parent coordinates
718
        LWComponentPeer<?, ?> targetPeer = findPeerAt(r.x + x, r.y + y);
719 720

        if (id == MouseEvent.MOUSE_EXITED) {
721 722 723
            isMouseOver = false;
            if (lastMouseEventPeer != null) {
                if (lastMouseEventPeer.isEnabled()) {
724
                    Point lp = lastMouseEventPeer.windowToLocal(x, y,
725
                            this);
726 727 728
                    Component target = lastMouseEventPeer.getTarget();
                    postMouseExitedEvent(target, when, modifiers, lp,
                            screenX, screenY, clickCount, popupTrigger, button);
729 730 731 732 733 734 735
                }

                // Sometimes we may get MOUSE_EXITED after lastCommonMouseEventPeer is switched
                // to a peer from another window. So we must first check if this peer is
                // the same as lastWindowPeer
                if (lastCommonMouseEventPeer != null && lastCommonMouseEventPeer.getWindowPeerOrSelf() == this) {
                    lastCommonMouseEventPeer = null;
736 737 738
                }
                lastMouseEventPeer = null;
            }
739 740 741 742 743
        } else if(id == MouseEvent.MOUSE_ENTERED) {
            isMouseOver = true;
            if (targetPeer != null) {
                if (targetPeer.isEnabled()) {
                    Point lp = targetPeer.windowToLocal(x, y, this);
744 745 746
                    Component target = targetPeer.getTarget();
                    postMouseEnteredEvent(target, when, modifiers, lp,
                            screenX, screenY, clickCount, popupTrigger, button);
747
                }
748
                lastCommonMouseEventPeer = targetPeer;
749 750
                lastMouseEventPeer = targetPeer;
            }
751
        } else {
752 753
            PlatformWindow topmostPlatforWindow =
                    platformWindow.getTopmostPlatformWindowUnderMouse();
754 755

            LWWindowPeer topmostWindowPeer =
756
                    topmostPlatforWindow != null ? topmostPlatforWindow.getPeer() : null;
757 758 759 760 761 762 763 764 765 766

            // topmostWindowPeer == null condition is added for the backward
            // compatibility with applets. It can be removed when the
            // getTopmostPlatformWindowUnderMouse() method will be properly
            // implemented in CPlatformEmbeddedFrame class
            if (topmostWindowPeer == this || topmostWindowPeer == null) {
                generateMouseEnterExitEventsForComponents(when, button, x, y,
                        screenX, screenY, modifiers, clickCount, popupTrigger,
                        targetPeer);
            } else {
767 768
                LWComponentPeer<?, ?> topmostTargetPeer =
                        topmostWindowPeer != null ? topmostWindowPeer.findPeerAt(r.x + x, r.y + y) : null;
769 770 771 772 773
                topmostWindowPeer.generateMouseEnterExitEventsForComponents(when, button, x, y,
                        screenX, screenY, modifiers, clickCount, popupTrigger,
                        topmostTargetPeer);
            }

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
            // TODO: fill "bdata" member of AWTEvent

            int eventButtonMask = (button > 0)? MouseEvent.getMaskForButton(button) : 0;
            int otherButtonsPressed = modifiers & ~eventButtonMask;

            // For pressed/dragged/released events OS X treats other
            // mouse buttons as if they were BUTTON2, so we do the same
            int targetIdx = (button > 3) ? MouseEvent.BUTTON2 - 1 : button - 1;

            // MOUSE_ENTERED/EXITED are generated for the components strictly under
            // mouse even when dragging. That's why we first update lastMouseEventPeer
            // based on initial targetPeer value and only then recalculate targetPeer
            // for MOUSE_DRAGGED/RELEASED events
            if (id == MouseEvent.MOUSE_PRESSED) {

                // Ungrab only if this window is not an owned window of the grabbing one.
                if (!isGrabbing() && grabbingWindow != null &&
791
                    !grabbingWindow.isOneOfOwnersOf(this))
792 793 794 795 796 797 798 799 800
                {
                    grabbingWindow.ungrab();
                }
                if (otherButtonsPressed == 0) {
                    mouseClickButtons = eventButtonMask;
                } else {
                    mouseClickButtons |= eventButtonMask;
                }

801 802 803 804 805 806 807 808
                // The window should be focused on mouse click. If it gets activated by the native platform,
                // this request will be no op. It will take effect when:
                // 1. A simple not focused window is clicked.
                // 2. An active but not focused owner frame/dialog is clicked.
                // The mouse event then will trigger a focus request "in window" to the component, so the window
                // should gain focus before.
                requestWindowFocus(CausedFocusEvent.Cause.MOUSE_EVENT);

809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
                mouseDownTarget[targetIdx] = targetPeer;
            } else if (id == MouseEvent.MOUSE_DRAGGED) {
                // Cocoa dragged event has the information about which mouse
                // button is being dragged. Use it to determine the peer that
                // should receive the dragged event.
                targetPeer = mouseDownTarget[targetIdx];
                mouseClickButtons &= ~modifiers;
            } else if (id == MouseEvent.MOUSE_RELEASED) {
                // TODO: currently, mouse released event goes to the same component
                // that received corresponding mouse pressed event. For most cases,
                // it's OK, however, we need to make sure that our behavior is consistent
                // with 1.6 for cases where component in question have been
                // hidden/removed in between of mouse pressed/released events.
                targetPeer = mouseDownTarget[targetIdx];

                if ((modifiers & eventButtonMask) == 0) {
                    mouseDownTarget[targetIdx] = null;
                }

                // mouseClickButtons is updated below, after MOUSE_CLICK is sent
            }

            if (targetPeer == null) {
                //TODO This can happen if this window is invisible. this is correct behavior in this case?
                targetPeer = this;
            }


837
            Point lp = targetPeer.windowToLocal(x, y, this);
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
            if (targetPeer.isEnabled()) {
                MouseEvent event = new MouseEvent(targetPeer.getTarget(), id,
                                                  when, modifiers, lp.x, lp.y,
                                                  screenX, screenY, clickCount,
                                                  popupTrigger, button);
                postEvent(event);
            }

            if (id == MouseEvent.MOUSE_RELEASED) {
                if ((mouseClickButtons & eventButtonMask) != 0
                    && targetPeer.isEnabled()) {
                    postEvent(new MouseEvent(targetPeer.getTarget(),
                                             MouseEvent.MOUSE_CLICKED,
                                             when, modifiers,
                                             lp.x, lp.y, screenX, screenY,
                                             clickCount, popupTrigger, button));
                }
                mouseClickButtons &= ~eventButtonMask;
            }
        }
858
        notifyUpdateCursor();
859 860
    }

861 862 863
    private void generateMouseEnterExitEventsForComponents(long when,
            int button, int x, int y, int screenX, int screenY,
            int modifiers, int clickCount, boolean popupTrigger,
864
            final LWComponentPeer<?, ?> targetPeer) {
865 866 867 868 869 870 871 872

        if (!isMouseOver || targetPeer == lastMouseEventPeer) {
            return;
        }

        // Generate Mouse Exit for components
        if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
            Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
873 874 875
            Component target = lastMouseEventPeer.getTarget();
            postMouseExitedEvent(target, when, modifiers, oldp, screenX, screenY,
                    clickCount, popupTrigger, button);
876 877 878 879 880 881 882
        }
        lastCommonMouseEventPeer = targetPeer;
        lastMouseEventPeer = targetPeer;

        // Generate Mouse Enter for components
        if (targetPeer != null && targetPeer.isEnabled()) {
            Point newp = targetPeer.windowToLocal(x, y, this);
883 884
            Component target = targetPeer.getTarget();
            postMouseEnteredEvent(target, when, modifiers, newp, screenX, screenY, clickCount, popupTrigger, button);
885 886 887
        }
    }

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
    private void postMouseEnteredEvent(Component target, long when, int modifiers,
                                       Point loc, int xAbs, int yAbs,
                                       int clickCount, boolean popupTrigger, int button) {

        updateSecurityWarningVisibility();

        postEvent(new MouseEvent(target,
                MouseEvent.MOUSE_ENTERED,
                when, modifiers,
                loc.x, loc.y, xAbs, yAbs,
                clickCount, popupTrigger, button));
    }

    private void postMouseExitedEvent(Component target, long when, int modifiers,
                                      Point loc, int xAbs, int yAbs,
                                      int clickCount, boolean popupTrigger, int button) {

        updateSecurityWarningVisibility();

        postEvent(new MouseEvent(target,
                MouseEvent.MOUSE_EXITED,
                when, modifiers,
                loc.x, loc.y, xAbs, yAbs,
                clickCount, popupTrigger, button));
    }

    @Override
    public void notifyMouseWheelEvent(long when, int x, int y, int modifiers,
                                      int scrollType, int scrollAmount,
                                      int wheelRotation, double preciseWheelRotation,
                                      byte[] bdata)
919 920 921 922
    {
        // TODO: could we just use the last mouse event target here?
        Rectangle r = getBounds();
        // findPeerAt() expects parent coordinates
923
        final LWComponentPeer<?, ?> targetPeer = findPeerAt(r.x + x, r.y + y);
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
        if (targetPeer == null || !targetPeer.isEnabled()) {
            return;
        }

        Point lp = targetPeer.windowToLocal(x, y, this);
        // TODO: fill "bdata" member of AWTEvent
        // TODO: screenX/screenY
        postEvent(new MouseWheelEvent(targetPeer.getTarget(),
                                      MouseEvent.MOUSE_WHEEL,
                                      when, modifiers,
                                      lp.x, lp.y,
                                      0, 0, /* screenX, Y */
                                      0 /* clickCount */, false /* popupTrigger */,
                                      scrollType, scrollAmount,
                                      wheelRotation, preciseWheelRotation));
    }

    /*
     * Called by the delegate when a key is pressed.
     */
944 945 946
    @Override
    public void notifyKeyEvent(int id, long when, int modifiers,
                               int keyCode, char keyChar, int keyLocation)
947
    {
948
        LWKeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
949
        Component focusOwner = kfmPeer.getCurrentFocusOwner();
950

951 952 953 954 955
        if (focusOwner == null) {
            focusOwner = kfmPeer.getCurrentFocusedWindow();
            if (focusOwner == null) {
                focusOwner = this.getTarget();
            }
956
        }
957 958 959 960

        KeyEvent keyEvent = new KeyEvent(focusOwner, id, when, modifiers,
            keyCode, keyChar, keyLocation);
        AWTAccessor.getKeyEventAccessor().setExtendedKeyCode(keyEvent,
961 962
                (keyChar == KeyEvent.CHAR_UNDEFINED) ? keyCode
                : ExtendedKeyCodes.getExtendedKeyCodeForChar(keyChar));
963
        postEvent(keyEvent);
964 965 966 967
    }

    // ---- UTILITY METHODS ---- //

968 969 970 971 972 973 974 975 976 977 978 979
    private void activateDisplayListener() {
        final GraphicsEnvironment ge =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
        ((SunGraphicsEnvironment) ge).addDisplayChangedListener(this);
    }

    private void deactivateDisplayListener() {
        final GraphicsEnvironment ge =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
        ((SunGraphicsEnvironment) ge).removeDisplayChangedListener(this);
    }

980 981 982 983 984
    private void postWindowStateChangedEvent(int newWindowState) {
        if (getTarget() instanceof Frame) {
            AWTAccessor.getFrameAccessor().setExtendedState(
                    (Frame)getTarget(), newWindowState);
        }
985

986 987 988 989 990
        WindowEvent stateChangedEvent = new WindowEvent(getTarget(),
                WindowEvent.WINDOW_STATE_CHANGED,
                windowState, newWindowState);
        postEvent(stateChangedEvent);
        windowState = newWindowState;
991 992

        updateSecurityWarningVisibility();
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    }

    private static int getGraphicsConfigScreen(GraphicsConfiguration gc) {
        // TODO: this method can be implemented in a more
        // efficient way by forwarding to the delegate
        GraphicsDevice gd = gc.getDevice();
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] gds = ge.getScreenDevices();
        for (int i = 0; i < gds.length; i++) {
            if (gds[i] == gd) {
                return i;
            }
        }
        // Should never happen if gc is a screen device config
        return 0;
    }

    /*
     * This method is called when window's graphics config is changed from
     * the app code (e.g. when the window is made non-opaque) or when
     * the window is moved to another screen by user.
     *
     * Returns true if the graphics config has been changed, false otherwise.
     */
    private boolean setGraphicsConfig(GraphicsConfiguration gc) {
        synchronized (getStateLock()) {
            if (graphicsConfig == gc) {
                return false;
            }
            // If window's graphics config is changed from the app code, the
            // config correspond to the same device as before; when the window
1024
            // is moved by user, graphicsDevice is updated in notifyReshape().
1025 1026 1027 1028 1029 1030 1031
            // In either case, there's nothing to do with screenOn here
            graphicsConfig = gc;
        }
        // SurfaceData is replaced later in updateGraphicsData()
        return true;
    }

1032 1033 1034 1035
    /**
     * Returns true if the GraphicsDevice has been changed, false otherwise.
     */
    public boolean updateGraphicsDevice() {
1036
        GraphicsDevice newGraphicsDevice = platformWindow.getGraphicsDevice();
1037
        synchronized (getStateLock()) {
1038
            if (graphicsDevice == newGraphicsDevice) {
1039
                return false;
1040
            }
1041
            graphicsDevice = newGraphicsDevice;
1042 1043
        }

1044 1045
        final GraphicsConfiguration newGC = newGraphicsDevice.getDefaultConfiguration();

1046
        if (!setGraphicsConfig(newGC)) return false;
1047 1048 1049 1050 1051 1052

        SunToolkit.executeOnEventHandlerThread(getTarget(), new Runnable() {
            public void run() {
                AWTAccessor.getComponentAccessor().setGraphicsConfiguration(getTarget(), newGC);
            }
        });
1053
        return true;
1054 1055
    }

1056 1057
    @Override
    public final void displayChanged() {
1058 1059 1060
        if (updateGraphicsDevice()) {
            updateMinimumSize();
        }
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        // Replace surface unconditionally, because internal state of the
        // GraphicsDevice could be changed.
        replaceSurfaceData();
        repaintPeer();
    }

    @Override
    public final void paletteChanged() {
        // components do not need to react to this event.
    }

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    /*
     * May be called by delegate to provide SD to Java2D code.
     */
    public SurfaceData getSurfaceData() {
        synchronized (surfaceDataLock) {
            return surfaceData;
        }
    }

    private void replaceSurfaceData() {
S
serb 已提交
1082 1083 1084
        replaceSurfaceData(true);
    }

1085
    private void replaceSurfaceData(final boolean blit) {
1086 1087 1088 1089 1090 1091 1092
        synchronized (surfaceDataLock) {
            final SurfaceData oldData = getSurfaceData();
            surfaceData = platformWindow.replaceSurfaceData();
            final Rectangle size = getSize();
            if (getSurfaceData() != null && oldData != getSurfaceData()) {
                clearBackground(size.width, size.height);
            }
S
serb 已提交
1093 1094 1095 1096

            if (blit) {
                blitSurfaceData(oldData, getSurfaceData());
            }
1097 1098 1099 1100 1101 1102 1103

            if (oldData != null && oldData != getSurfaceData()) {
                // TODO: drop oldData for D3D/WGL pipelines
                // This can only happen when this peer is being created
                oldData.flush();
            }
        }
1104
        flushOnscreenGraphics();
1105 1106 1107 1108 1109 1110 1111
    }

    private void blitSurfaceData(final SurfaceData src, final SurfaceData dst) {
        //TODO blit. proof-of-concept
        if (src != dst && src != null && dst != null
            && !(dst instanceof NullSurfaceData)
            && !(src instanceof NullSurfaceData)
1112 1113 1114
            && src.getSurfaceType().equals(dst.getSurfaceType())
            && src.getDefaultScale() == dst.getDefaultScale()) {
            final Rectangle size = src.getBounds();
1115 1116 1117 1118
            final Blit blit = Blit.locate(src.getSurfaceType(),
                                          CompositeType.Src,
                                          dst.getSurfaceType());
            if (blit != null) {
1119 1120
                blit.Blit(src, dst, AlphaComposite.Src, null, 0, 0, 0, 0,
                          size.width, size.height);
1121 1122 1123 1124
            }
        }
    }

1125 1126 1127 1128 1129
    /**
     * Request the window insets from the delegate and compares it with the
     * current one. This method is mostly called by the delegate, e.g. when the
     * window state is changed and insets should be recalculated.
     * <p/>
1130 1131
     * This method may be called on the toolkit thread.
     */
1132
    public final boolean updateInsets(final Insets newInsets) {
1133
        synchronized (getStateLock()) {
1134 1135 1136
            if (insets.equals(newInsets)) {
                return false;
            }
1137 1138
            insets = newInsets;
        }
1139
        return true;
1140 1141 1142
    }

    public static LWWindowPeer getWindowUnderCursor() {
1143
        return lastCommonMouseEventPeer != null ? lastCommonMouseEventPeer.getWindowPeerOrSelf() : null;
1144 1145
    }

1146
    public static LWComponentPeer<?, ?> getPeerUnderCursor() {
1147
        return lastCommonMouseEventPeer;
1148 1149
    }

1150 1151 1152 1153
    /*
     * Requests platform to set native focus on a frame/dialog.
     * In case of a simple window, triggers appropriate java focus change.
     */
1154
    public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
1155
        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1156 1157 1158 1159 1160 1161 1162 1163
            focusLog.fine("requesting native focus to " + this);
        }

        if (!focusAllowedFor()) {
            focusLog.fine("focus is not allowed");
            return false;
        }

1164
        if (platformWindow.rejectFocusRequest(cause)) {
1165 1166 1167
            return false;
        }

1168 1169 1170 1171 1172
        AppContext targetAppContext = AWTAccessor.getComponentAccessor().getAppContext(getTarget());
        KeyboardFocusManager kfm = AWTAccessor.getKeyboardFocusManagerAccessor()
                .getCurrentKeyboardFocusManager(targetAppContext);
        Window currentActive = kfm.getActiveWindow();

1173

1174 1175 1176
        Window opposite = LWKeyboardFocusManagerPeer.getInstance().
            getCurrentFocusedWindow();

1177 1178 1179 1180 1181 1182 1183
        // Make the owner active window.
        if (isSimpleWindow()) {
            LWWindowPeer owner = getOwnerFrameDialog(this);

            // If owner is not natively active, request native
            // activation on it w/o sending events up to java.
            if (owner != null && !owner.platformWindow.isActive()) {
1184
                if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1185 1186
                    focusLog.fine("requesting native focus to the owner " + owner);
                }
1187 1188 1189
                LWWindowPeer currentActivePeer = currentActive == null ? null :
                (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(
                        currentActive);
1190 1191 1192

                // Ensure the opposite is natively active and suppress sending events.
                if (currentActivePeer != null && currentActivePeer.platformWindow.isActive()) {
1193
                    if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
                        focusLog.fine("the opposite is " + currentActivePeer);
                    }
                    currentActivePeer.skipNextFocusChange = true;
                }
                owner.skipNextFocusChange = true;

                owner.platformWindow.requestWindowFocus();
            }

            // DKFM will synthesize all the focus/activation events correctly.
1204
            changeFocusedWindow(true, opposite);
1205 1206 1207 1208 1209 1210
            return true;

        // In case the toplevel is active but not focused, change focus directly,
        // as requesting native focus on it will not have effect.
        } else if (getTarget() == currentActive && !getTarget().hasFocus()) {

1211
            changeFocusedWindow(true, opposite);
1212 1213
            return true;
        }
1214

1215 1216 1217
        return platformWindow.requestWindowFocus();
    }

1218
    protected boolean focusAllowedFor() {
1219 1220
        Window window = getTarget();
        // TODO: check if modal blocked
1221 1222 1223 1224
        return window.isVisible() && window.isEnabled() && isFocusableWindow();
    }

    private boolean isFocusableWindow() {
1225
        boolean focusable  = targetFocusable;
1226 1227 1228 1229 1230
        if (isSimpleWindow()) {
            LWWindowPeer ownerPeer = getOwnerFrameDialog(this);
            if (ownerPeer == null) {
                return false;
            }
1231
            return focusable && ownerPeer.targetFocusable;
1232 1233
        }
        return focusable;
1234 1235 1236 1237 1238 1239 1240
    }

    public boolean isSimpleWindow() {
        Window window = getTarget();
        return !(window instanceof Dialog || window instanceof Frame);
    }

1241 1242 1243 1244 1245
    @Override
    public void emulateActivation(boolean activate) {
        changeFocusedWindow(activate, null);
    }

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    private boolean isOneOfOwnersOf(LWWindowPeer peer) {
        Window owner = (peer != null ? peer.getTarget().getOwner() : null);
        while (owner != null) {
            if ((LWWindowPeer)owner.getPeer() == this) {
                return true;
            }
            owner = owner.getOwner();
        }
        return false;
    }

1257
    /*
1258
     * Changes focused window on java level.
1259
     */
1260
    protected void changeFocusedWindow(boolean becomesFocused, Window opposite) {
1261
        if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1262 1263
            focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
        }
1264
        if (skipNextFocusChange) {
1265 1266 1267 1268
            focusLog.fine("skipping focus change");
            skipNextFocusChange = false;
            return;
        }
1269 1270
        if (!isFocusableWindow() && becomesFocused) {
            focusLog.fine("the window is not focusable");
1271 1272 1273 1274 1275
            return;
        }
        if (becomesFocused) {
            synchronized (getPeerTreeLock()) {
                if (blocker != null) {
1276
                    if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
                        focusLog.finest("the window is blocked by " + blocker);
                    }
                    return;
                }
            }
        }

        // Note, the method is not called:
        // - when the opposite (gaining focus) window is an owned/owner window.
        // - for a simple window in any case.
        if (!becomesFocused &&
1288
            (isGrabbing() || this.isOneOfOwnersOf(grabbingWindow)))
1289
        {
1290
            if (focusLog.isLoggable(PlatformLogger.Level.FINE)) {
1291 1292
                focusLog.fine("ungrabbing on " + grabbingWindow);
            }
1293 1294 1295 1296
            // ungrab a simple window if its owner looses activation.
            grabbingWindow.ungrab();
        }

1297
        KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
1298 1299 1300 1301 1302 1303

        if (!becomesFocused && kfmPeer.getCurrentFocusedWindow() != getTarget()) {
            // late window focus lost event - ingoring
            return;
        }

1304
        kfmPeer.setCurrentFocusedWindow(becomesFocused ? getTarget() : null);
1305 1306

        int eventID = becomesFocused ? WindowEvent.WINDOW_GAINED_FOCUS : WindowEvent.WINDOW_LOST_FOCUS;
1307
        WindowEvent windowEvent = new TimedWindowEvent(getTarget(), eventID, opposite, System.currentTimeMillis());
1308 1309 1310 1311 1312

        // TODO: wrap in SequencedEvent
        postEvent(windowEvent);
    }

1313 1314 1315 1316 1317
    /*
     * Retrieves the owner of the peer.
     * Note: this method returns the owner which can be activated, (i.e. the instance
     * of Frame or Dialog may be returned).
     */
1318
    static LWWindowPeer getOwnerFrameDialog(LWWindowPeer peer) {
1319 1320 1321 1322
        Window owner = (peer != null ? peer.getTarget().getOwner() : null);
        while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
            owner = owner.getOwner();
        }
1323 1324
        return owner == null ? null :
               (LWWindowPeer) AWTAccessor.getComponentAccessor().getPeer(owner);
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
    }

    /**
     * Returns the foremost modal blocker of this window, or null.
     */
    public LWWindowPeer getBlocker() {
        synchronized (getPeerTreeLock()) {
            LWWindowPeer blocker = this.blocker;
            if (blocker == null) {
                return null;
            }
            while (blocker.blocker != null) {
                blocker = blocker.blocker;
            }
            return blocker;
        }
    }

1343
    @Override
1344 1345
    public void enterFullScreenMode() {
        platformWindow.enterFullScreenMode();
1346
        updateSecurityWarningVisibility();
1347 1348
    }

1349
    @Override
1350 1351
    public void exitFullScreenMode() {
        platformWindow.exitFullScreenMode();
1352
        updateSecurityWarningVisibility();
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    }

    public long getLayerPtr() {
        return getPlatformWindow().getLayerPtr();
    }

    void grab() {
        if (grabbingWindow != null && !isGrabbing()) {
            grabbingWindow.ungrab();
        }
        grabbingWindow = this;
    }

1366
    final void ungrab(boolean doPost) {
1367 1368
        if (isGrabbing()) {
            grabbingWindow = null;
1369 1370 1371
            if (doPost) {
                postEvent(new UngrabEvent(getTarget()));
            }
1372 1373 1374
        }
    }

1375 1376 1377 1378
    void ungrab() {
        ungrab(true);
    }

1379 1380 1381 1382
    private boolean isGrabbing() {
        return this == grabbingWindow;
    }

1383 1384 1385 1386
    public PeerType getPeerType() {
        return peerType;
    }

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
    public void updateSecurityWarningVisibility() {
        if (warningWindow == null) {
            return;
        }

        if (!isVisible()) {
            return; // The warning window should already be hidden.
        }

        boolean show = false;

        if (!platformWindow.isFullScreenMode()) {
            if (isVisible()) {
                if (LWKeyboardFocusManagerPeer.getInstance().getCurrentFocusedWindow() ==
                        getTarget()) {
                    show = true;
                }

                if (platformWindow.isUnderMouse() || warningWindow.isUnderMouse()) {
                    show = true;
                }
            }
        }

        warningWindow.setVisible(show, true);
    }

1414 1415 1416 1417 1418
    @Override
    public String toString() {
        return super.toString() + " [target is " + getTarget() + "]";
    }
}