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