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