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