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