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     private volatile boolean textured;
 116 
 117     /**
 118      * Current modal blocker or null.
 119      *
 120      * Synchronization: peerTreeLock.
 121      */
 122     private LWWindowPeer blocker;
 123 
 124     public LWWindowPeer(Window target, PlatformComponent platformComponent,
 125                         PlatformWindow platformWindow)
 126     {
 127         super(target, platformComponent);
 128         this.platformWindow = platformWindow;
 129 
 130         Window owner = target.getOwner();
 131         LWWindowPeer ownerPeer = (owner != null) ? (LWWindowPeer)owner.getPeer() : null;
 132         PlatformWindow ownerDelegate = (ownerPeer != null) ? ownerPeer.getPlatformWindow() : null;
 133 
 134         // The delegate.initialize() needs a non-null GC on X11.
 135         GraphicsConfiguration gc = getTarget().getGraphicsConfiguration();
 136         synchronized (getStateLock()) {
 137             // graphicsConfig should be updated according to the real window
 138             // bounds when the window is shown, see 4868278
 139             this.graphicsConfig = gc;
 140         }
 141 
 142         if (!target.isFontSet()) {
 143             target.setFont(DEFAULT_FONT);
 144         }
 145 
 146         if (!target.isBackgroundSet()) {
 147             target.setBackground(SystemColor.window);
 148         } else {
 149             // first we check if user provided alpha for background. This is
 150             // similar to what Apple's Java do.
 151             // Since JDK7 we should rely on setOpacity() only.
 152             // this.opacity = c.getAlpha();
 153         }
 154 
 155         if (!target.isForegroundSet()) {
 156             target.setForeground(SystemColor.windowText);
 157             // we should not call setForeground because it will call a repaint
 158             // which the peer may not be ready to do yet.
 159         }
 160 
 161         platformWindow.initialize(target, this, ownerDelegate);
 162     }
 163 
 164     @Override
 165     void initializeImpl() {
 166         super.initializeImpl();
 167         if (getTarget() instanceof Frame) {
 168             setTitle(((Frame) getTarget()).getTitle());
 169             setState(((Frame) getTarget()).getExtendedState());
 170         } else if (getTarget() instanceof Dialog) {
 171             setTitle(((Dialog) getTarget()).getTitle());
 172         }
 173 
 174         setAlwaysOnTop(getTarget().isAlwaysOnTop());
 175         updateMinimumSize();
 176 
 177         final Shape shape = getTarget().getShape();
 178         if (shape != null) {
 179             applyShape(Region.getInstance(shape, null));
 180         }
 181 
 182         final float opacity = getTarget().getOpacity();
 183         if (opacity < 1.0f) {
 184             setOpacity(opacity);
 185         }
 186 
 187         setOpaque(getTarget().isOpaque());
 188 
 189         updateInsets(platformWindow.getInsets());
 190         if (getSurfaceData() == null) {
 191             replaceSurfaceData(false);
 192         }
 193     }
 194 
 195     // Just a helper method
 196     public PlatformWindow getPlatformWindow() {
 197         return platformWindow;
 198     }
 199 
 200     @Override
 201     protected LWWindowPeer getWindowPeerOrSelf() {
 202         return this;
 203     }
 204 
 205     @Override
 206     protected void initializeContainerPeer() {
 207         // No-op as LWWindowPeer doesn't have any containerPeer
 208     }
 209 
 210     // ---- PEER METHODS ---- //
 211 
 212     @Override
 213     protected void disposeImpl() {
 214         SurfaceData oldData = getSurfaceData();
 215         synchronized (surfaceDataLock){
 216             surfaceData = null;
 217         }
 218         if (oldData != null) {
 219             oldData.invalidate();
 220         }
 221         if (isGrabbing()) {
 222             ungrab();
 223         }
 224         destroyBuffers();
 225         platformWindow.dispose();
 226         super.disposeImpl();
 227     }
 228 
 229     @Override
 230     protected void setVisibleImpl(final boolean visible) {
 231         super.setVisibleImpl(visible);
 232         // TODO: update graphicsConfig, see 4868278
 233         platformWindow.setVisible(visible);
 234         if (isSimpleWindow()) {
 235             LWKeyboardFocusManagerPeer manager = LWKeyboardFocusManagerPeer.
 236                 getInstance(getAppContext());
 237 
 238             if (visible) {
 239                 if (!getTarget().isAutoRequestFocus()) {
 240                     return;
 241                 } else {
 242                     requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
 243                 }
 244             // Focus the owner in case this window is focused.
 245             } else if (manager.getCurrentFocusedWindow() == getTarget()) {
 246                 // Transfer focus to the owner.
 247                 LWWindowPeer owner = getOwnerFrameDialog(LWWindowPeer.this);
 248                 if (owner != null) {
 249                     owner.requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
 250                 }
 251             }
 252         }
 253     }
 254 
 255     @Override
 256     public GraphicsConfiguration getGraphicsConfiguration() {
 257         return graphicsConfig;
 258     }
 259 
 260     @Override
 261     public boolean updateGraphicsData(GraphicsConfiguration gc) {
 262         setGraphicsConfig(gc);
 263         return false;
 264     }
 265 
 266     protected final Graphics getOnscreenGraphics(Color fg, Color bg, Font f) {
 267         if (getSurfaceData() == null) {
 268             return null;
 269         }
 270         if (fg == null) {
 271             fg = SystemColor.windowText;
 272         }
 273         if (bg == null) {
 274             bg = SystemColor.window;
 275         }
 276         if (f == null) {
 277             f = DEFAULT_FONT;
 278         }
 279         return platformWindow.transformGraphics(new SunGraphics2D(getSurfaceData(), fg, bg, f));
 280     }
 281 
 282     @Override
 283     public void createBuffers(int numBuffers, BufferCapabilities caps)
 284         throws AWTException
 285     {
 286         try {
 287             // Assume this method is never called with numBuffers <= 1, as 0 is
 288             // unsupported, and 1 corresponds to a SingleBufferStrategy which
 289             // doesn't depend on the peer. Screen is considered as a separate
 290             // "buffer", that's why numBuffers - 1
 291             assert numBuffers > 1;
 292 
 293             replaceSurfaceData(numBuffers - 1, caps, false);
 294         } catch (InvalidPipeException z) {
 295             throw new AWTException(z.toString());
 296         }
 297     }
 298 
 299     @Override
 300     public final Image getBackBuffer() {
 301         synchronized (getStateLock()) {
 302             return backBuffer;
 303         }
 304     }
 305 
 306     @Override
 307     public void flip(int x1, int y1, int x2, int y2,
 308                      BufferCapabilities.FlipContents flipAction)
 309     {
 310         platformWindow.flip(x1, y1, x2, y2, flipAction);
 311     }
 312 
 313     @Override
 314     public final void destroyBuffers() {
 315         final Image oldBB = getBackBuffer();
 316         synchronized (getStateLock()) {
 317             backBuffer = null;
 318         }
 319         if (oldBB != null) {
 320             oldBB.flush();
 321         }
 322     }
 323 
 324     @Override
 325     public void setBounds(int x, int y, int w, int h, int op) {
 326         if ((op & SET_CLIENT_SIZE) != 0) {
 327             // SET_CLIENT_SIZE is only applicable to window peers, so handle it here
 328             // instead of pulling 'insets' field up to LWComponentPeer
 329             // no need to add insets since Window's notion of width and height includes insets.
 330             op &= ~SET_CLIENT_SIZE;
 331             op |= SET_SIZE;
 332         }
 333 
 334         if (w < MINIMUM_WIDTH) {
 335             w = MINIMUM_WIDTH;
 336         }
 337         if (h < MINIMUM_HEIGHT) {
 338             h = MINIMUM_HEIGHT;
 339         }
 340 
 341         // Don't post ComponentMoved/Resized and Paint events
 342         // until we've got a notification from the delegate
 343         setBounds(x, y, w, h, op, false, false);
 344         // Get updated bounds, so we don't have to handle 'op' here manually
 345         Rectangle r = getBounds();
 346         platformWindow.setBounds(r.x, r.y, r.width, r.height);
 347     }
 348 
 349     @Override
 350     public Point getLocationOnScreen() {
 351         return platformWindow.getLocationOnScreen();
 352     }
 353 
 354     /**
 355      * Overridden from LWContainerPeer to return the correct insets.
 356      * Insets are queried from the delegate and are kept up to date by
 357      * requiering when needed (i.e. when the window geometry is changed).
 358      */
 359     @Override
 360     public Insets getInsets() {
 361         synchronized (getStateLock()) {
 362             return insets;
 363         }
 364     }
 365 
 366     @Override
 367     public FontMetrics getFontMetrics(Font f) {
 368         // TODO: check for "use platform metrics" settings
 369         return platformWindow.getFontMetrics(f);
 370     }
 371 
 372     @Override
 373     public void toFront() {
 374         platformWindow.toFront();
 375     }
 376 
 377     @Override
 378     public void toBack() {
 379         platformWindow.toBack();
 380     }
 381 
 382     @Override
 383     public void setZOrder(ComponentPeer above) {
 384         throw new RuntimeException("not implemented");
 385     }
 386 
 387     @Override
 388     public void setAlwaysOnTop(boolean value) {
 389         platformWindow.setAlwaysOnTop(value);
 390     }
 391 
 392     @Override
 393     public void updateFocusableWindowState() {
 394         platformWindow.updateFocusableWindowState();
 395     }
 396 
 397     @Override
 398     public void setModalBlocked(Dialog blocker, boolean blocked) {
 399         synchronized (getPeerTreeLock()) {
 400             this.blocker = blocked ? (LWWindowPeer)blocker.getPeer() : null;
 401         }
 402 
 403         platformWindow.setModalBlocked(blocked);
 404     }
 405 
 406     @Override
 407     public void updateMinimumSize() {
 408         Dimension d = null;
 409         if (getTarget().isMinimumSizeSet()) {
 410             d = getTarget().getMinimumSize();
 411         }
 412         if (d == null) {
 413             d = new Dimension(MINIMUM_WIDTH, MINIMUM_HEIGHT);
 414         }
 415         platformWindow.setMinimumSize(d.width, d.height);
 416     }
 417 
 418     @Override
 419     public void updateIconImages() {
 420         getPlatformWindow().updateIconImages();
 421     }
 422 
 423     @Override
 424     public void setOpacity(float opacity) {
 425         getPlatformWindow().setOpacity(opacity);
 426         repaintPeer();
 427     }
 428 
 429     @Override
 430     public final void setOpaque(final boolean isOpaque) {
 431         if (this.isOpaque != isOpaque) {
 432             this.isOpaque = isOpaque;
 433             updateOpaque();
 434         }
 435     }
 436 
 437     private void updateOpaque() {
 438         getPlatformWindow().setOpaque(!isTranslucent());
 439         replaceSurfaceData(false);
 440         repaintPeer();
 441     }
 442 
 443     @Override
 444     public void updateWindow() {
 445     }
 446 
 447     public final boolean isTextured() {
 448         return textured;
 449     }
 450 
 451     public final void setTextured(final boolean isTextured) {
 452         textured = isTextured;
 453     }
 454 
 455     public final boolean isTranslucent() {
 456         synchronized (getStateLock()) {
 457             /*
 458              * Textured window is a special case of translucent window.
 459              * The difference is only in nswindow background. So when we set
 460              * texture property our peer became fully translucent. It doesn't
 461              * fill background, create non opaque backbuffers and layer etc.
 462              */
 463             return !isOpaque || isShaped() || isTextured();
 464         }
 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 Graphics g = getOnscreenGraphics(getForeground(), getBackground(),
 622                                                getFont());
 623         if (g != null) {
 624             try {
 625                 if (g instanceof Graphics2D) {
 626                     ((Graphics2D) g).setComposite(AlphaComposite.Src);
 627                 }
 628                 if (isTranslucent()) {
 629                     g.setColor(nonOpaqueBackground);
 630                     g.fillRect(0, 0, w, h);
 631                 }
 632                 if (!isTextured()) {
 633                     if (g instanceof SunGraphics2D) {
 634                         SG2DConstraint((SunGraphics2D) g, getRegion());
 635                     }
 636                     g.setColor(getBackground());
 637                     g.fillRect(0, 0, w, h);
 638                 }
 639             } finally {
 640                 g.dispose();
 641             }
 642         }
 643     }
 644 
 645     public void notifyUpdateCursor() {
 646         getLWToolkit().getCursorManager().updateCursorLater(this);
 647     }
 648 
 649     public void notifyActivation(boolean activation) {
 650         changeFocusedWindow(activation);
 651     }
 652 
 653     // MouseDown in non-client area
 654     public void notifyNCMouseDown() {
 655         // Ungrab except for a click on a Dialog with the grabbing owner
 656         if (grabbingWindow != null &&
 657             grabbingWindow != getOwnerFrameDialog(this))
 658         {
 659             grabbingWindow.ungrab();
 660         }
 661     }
 662 
 663     // ---- EVENTS ---- //
 664 
 665     /*
 666      * Called by the delegate to dispatch the event to Java. Event
 667      * coordinates are relative to non-client window are, i.e. the top-left
 668      * point of the client area is (insets.top, insets.left).
 669      */
 670     public void dispatchMouseEvent(int id, long when, int button,
 671                                    int x, int y, int screenX, int screenY,
 672                                    int modifiers, int clickCount, boolean popupTrigger,
 673                                    byte[] bdata)
 674     {
 675         // TODO: fill "bdata" member of AWTEvent
 676         Rectangle r = getBounds();
 677         // findPeerAt() expects parent coordinates
 678         LWComponentPeer targetPeer = findPeerAt(r.x + x, r.y + y);
 679         LWWindowPeer lastWindowPeer =
 680             (lastMouseEventPeer != null) ? lastMouseEventPeer.getWindowPeerOrSelf() : null;
 681         LWWindowPeer curWindowPeer =
 682             (targetPeer != null) ? targetPeer.getWindowPeerOrSelf() : null;
 683 
 684         if (id == MouseEvent.MOUSE_EXITED) {
 685             // Sometimes we may get MOUSE_EXITED after lastMouseEventPeer is switched
 686             // to a peer from another window. So we must first check if this peer is
 687             // the same as lastWindowPeer
 688             if (lastWindowPeer == this) {
 689                 if (isEnabled()) {
 690                     Point lp = lastMouseEventPeer.windowToLocal(x, y,
 691                                                                 lastWindowPeer);
 692                     postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
 693                                              MouseEvent.MOUSE_EXITED, when,
 694                                              modifiers, lp.x, lp.y, screenX,
 695                                              screenY, clickCount, popupTrigger,
 696                                              button));
 697                 }
 698                 lastMouseEventPeer = null;
 699             }
 700         } else {
 701             if (targetPeer != lastMouseEventPeer) {
 702 
 703                 if (id != MouseEvent.MOUSE_DRAGGED || lastMouseEventPeer == null) {
 704                     // lastMouseEventPeer may be null if mouse was out of Java windows
 705                     if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
 706                         // Sometimes, MOUSE_EXITED is not sent by delegate (or is sent a bit
 707                         // later), in which case lastWindowPeer is another window
 708                         if (lastWindowPeer != this) {
 709                             Point oldp = lastMouseEventPeer.windowToLocal(x, y, lastWindowPeer);
 710                             // Additionally translate from this to lastWindowPeer coordinates
 711                             Rectangle lr = lastWindowPeer.getBounds();
 712                             oldp.x += r.x - lr.x;
 713                             oldp.y += r.y - lr.y;
 714                             postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
 715                                                      MouseEvent.MOUSE_EXITED,
 716                                                      when, modifiers,
 717                                                      oldp.x, oldp.y, screenX, screenY,
 718                                                      clickCount, popupTrigger, button));
 719                         } else {
 720                             Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
 721                             postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
 722                                                      MouseEvent.MOUSE_EXITED,
 723                                                      when, modifiers,
 724                                                      oldp.x, oldp.y, screenX, screenY,
 725                                                      clickCount, popupTrigger, button));
 726                         }
 727                     }
 728                     if (targetPeer != null && targetPeer.isEnabled() && id != MouseEvent.MOUSE_ENTERED) {
 729                         Point newp = targetPeer.windowToLocal(x, y, curWindowPeer);
 730                         postEvent(new MouseEvent(targetPeer.getTarget(),
 731                                                  MouseEvent.MOUSE_ENTERED,
 732                                                  when, modifiers,
 733                                                  newp.x, newp.y, screenX, screenY,
 734                                                  clickCount, popupTrigger, button));
 735                     }
 736                 }
 737                 lastMouseEventPeer = targetPeer;
 738             }
 739             // TODO: fill "bdata" member of AWTEvent
 740 
 741             int eventButtonMask = (button > 0)? MouseEvent.getMaskForButton(button) : 0;
 742             int otherButtonsPressed = modifiers & ~eventButtonMask;
 743 
 744             // For pressed/dragged/released events OS X treats other
 745             // mouse buttons as if they were BUTTON2, so we do the same
 746             int targetIdx = (button > 3) ? MouseEvent.BUTTON2 - 1 : button - 1;
 747 
 748             // MOUSE_ENTERED/EXITED are generated for the components strictly under
 749             // mouse even when dragging. That's why we first update lastMouseEventPeer
 750             // based on initial targetPeer value and only then recalculate targetPeer
 751             // for MOUSE_DRAGGED/RELEASED events
 752             if (id == MouseEvent.MOUSE_PRESSED) {
 753 
 754                 // Ungrab only if this window is not an owned window of the grabbing one.
 755                 if (!isGrabbing() && grabbingWindow != null &&
 756                     grabbingWindow != getOwnerFrameDialog(this))
 757                 {
 758                     grabbingWindow.ungrab();
 759                 }
 760                 if (otherButtonsPressed == 0) {
 761                     mouseClickButtons = eventButtonMask;
 762                 } else {
 763                     mouseClickButtons |= eventButtonMask;
 764                 }
 765 
 766                 mouseDownTarget[targetIdx] = targetPeer;
 767             } else if (id == MouseEvent.MOUSE_DRAGGED) {
 768                 // Cocoa dragged event has the information about which mouse
 769                 // button is being dragged. Use it to determine the peer that
 770                 // should receive the dragged event.
 771                 targetPeer = mouseDownTarget[targetIdx];
 772                 mouseClickButtons &= ~modifiers;
 773             } else if (id == MouseEvent.MOUSE_RELEASED) {
 774                 // TODO: currently, mouse released event goes to the same component
 775                 // that received corresponding mouse pressed event. For most cases,
 776                 // it's OK, however, we need to make sure that our behavior is consistent
 777                 // with 1.6 for cases where component in question have been
 778                 // hidden/removed in between of mouse pressed/released events.
 779                 targetPeer = mouseDownTarget[targetIdx];
 780 
 781                 if ((modifiers & eventButtonMask) == 0) {
 782                     mouseDownTarget[targetIdx] = null;
 783                 }
 784 
 785                 // mouseClickButtons is updated below, after MOUSE_CLICK is sent
 786             }
 787 
 788             // check if we receive mouseEvent from outside the window's bounds
 789             // it can be either mouseDragged or mouseReleased
 790             if (curWindowPeer == null) {
 791                 //TODO This can happen if this window is invisible. this is correct behavior in this case?
 792                 curWindowPeer = this;
 793             }
 794             if (targetPeer == null) {
 795                 //TODO This can happen if this window is invisible. this is correct behavior in this case?
 796                 targetPeer = this;
 797             }
 798 
 799 
 800             Point lp = targetPeer.windowToLocal(x, y, curWindowPeer);
 801             if (targetPeer.isEnabled()) {
 802                 MouseEvent event = new MouseEvent(targetPeer.getTarget(), id,
 803                                                   when, modifiers, lp.x, lp.y,
 804                                                   screenX, screenY, clickCount,
 805                                                   popupTrigger, button);
 806                 postEvent(event);
 807             }
 808 
 809             if (id == MouseEvent.MOUSE_RELEASED) {
 810                 if ((mouseClickButtons & eventButtonMask) != 0
 811                     && targetPeer.isEnabled()) {
 812                     postEvent(new MouseEvent(targetPeer.getTarget(),
 813                                              MouseEvent.MOUSE_CLICKED,
 814                                              when, modifiers,
 815                                              lp.x, lp.y, screenX, screenY,
 816                                              clickCount, popupTrigger, button));
 817                 }
 818                 mouseClickButtons &= ~eventButtonMask;
 819             }
 820         }
 821         notifyUpdateCursor();
 822     }
 823 
 824     public void dispatchMouseWheelEvent(long when, int x, int y, int modifiers,
 825                                         int scrollType, int scrollAmount,
 826                                         int wheelRotation, double preciseWheelRotation,
 827                                         byte[] bdata)
 828     {
 829         // TODO: could we just use the last mouse event target here?
 830         Rectangle r = getBounds();
 831         // findPeerAt() expects parent coordinates
 832         final LWComponentPeer targetPeer = findPeerAt(r.x + x, r.y + y);
 833         if (targetPeer == null || !targetPeer.isEnabled()) {
 834             return;
 835         }
 836 
 837         Point lp = targetPeer.windowToLocal(x, y, this);
 838         // TODO: fill "bdata" member of AWTEvent
 839         // TODO: screenX/screenY
 840         postEvent(new MouseWheelEvent(targetPeer.getTarget(),
 841                                       MouseEvent.MOUSE_WHEEL,
 842                                       when, modifiers,
 843                                       lp.x, lp.y,
 844                                       0, 0, /* screenX, Y */
 845                                       0 /* clickCount */, false /* popupTrigger */,
 846                                       scrollType, scrollAmount,
 847                                       wheelRotation, preciseWheelRotation));
 848     }
 849 
 850     /*
 851      * Called by the delegate when a key is pressed.
 852      */
 853     public void dispatchKeyEvent(int id, long when, int modifiers,
 854                                  int keyCode, char keyChar, int keyLocation)
 855     {
 856         LWComponentPeer focusOwner =
 857             LWKeyboardFocusManagerPeer.getInstance(getAppContext()).
 858                 getFocusOwner();
 859 
 860         // Null focus owner may receive key event when
 861         // application hides the focused window upon ESC press
 862         // (AWT transfers/clears the focus owner) and pending ESC release
 863         // may come to already hidden window. This check eliminates NPE.
 864         if (focusOwner != null) {
 865             KeyEvent event =
 866                 new KeyEvent(focusOwner.getTarget(), id, when, modifiers,
 867                              keyCode, keyChar, keyLocation);
 868             focusOwner.postEvent(event);
 869         }
 870     }
 871 
 872 
 873     // ---- UTILITY METHODS ---- //
 874 
 875     private void postWindowStateChangedEvent(int newWindowState) {
 876         if (getTarget() instanceof Frame) {
 877             AWTAccessor.getFrameAccessor().setExtendedState(
 878                     (Frame)getTarget(), newWindowState);
 879         }
 880         WindowEvent stateChangedEvent = new WindowEvent(getTarget(),
 881                 WindowEvent.WINDOW_STATE_CHANGED,
 882                 windowState, newWindowState);
 883         postEvent(stateChangedEvent);
 884         windowState = newWindowState;
 885     }
 886 
 887     private static int getGraphicsConfigScreen(GraphicsConfiguration gc) {
 888         // TODO: this method can be implemented in a more
 889         // efficient way by forwarding to the delegate
 890         GraphicsDevice gd = gc.getDevice();
 891         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
 892         GraphicsDevice[] gds = ge.getScreenDevices();
 893         for (int i = 0; i < gds.length; i++) {
 894             if (gds[i] == gd) {
 895                 return i;
 896             }
 897         }
 898         // Should never happen if gc is a screen device config
 899         return 0;
 900     }
 901 
 902     /*
 903      * This method is called when window's graphics config is changed from
 904      * the app code (e.g. when the window is made non-opaque) or when
 905      * the window is moved to another screen by user.
 906      *
 907      * Returns true if the graphics config has been changed, false otherwise.
 908      */
 909     private boolean setGraphicsConfig(GraphicsConfiguration gc) {
 910         synchronized (getStateLock()) {
 911             if (graphicsConfig == gc) {
 912                 return false;
 913             }
 914             // If window's graphics config is changed from the app code, the
 915             // config correspond to the same device as before; when the window
 916             // is moved by user, graphicsDevice is updated in checkIfOnNewScreen().
 917             // In either case, there's nothing to do with screenOn here
 918             graphicsConfig = gc;
 919         }
 920         // SurfaceData is replaced later in updateGraphicsData()
 921         return true;
 922     }
 923 
 924     private void checkIfOnNewScreen() {
 925         GraphicsDevice newGraphicsDevice = platformWindow.getGraphicsDevice();
 926         synchronized (getStateLock()) {
 927             if (graphicsDevice == newGraphicsDevice) {
 928                 return;
 929             }
 930             graphicsDevice = newGraphicsDevice;
 931         }
 932 
 933         // TODO: DisplayChangedListener stuff
 934         final GraphicsConfiguration newGC = newGraphicsDevice.getDefaultConfiguration();
 935 
 936         if (!setGraphicsConfig(newGC)) return;
 937 
 938         SunToolkit.executeOnEventHandlerThread(getTarget(), new Runnable() {
 939             public void run() {
 940                 AWTAccessor.getComponentAccessor().setGraphicsConfiguration(getTarget(), newGC);
 941             }
 942         });
 943     }
 944 
 945     /*
 946      * May be called by delegate to provide SD to Java2D code.
 947      */
 948     public SurfaceData getSurfaceData() {
 949         synchronized (surfaceDataLock) {
 950             return surfaceData;
 951         }
 952     }
 953 
 954     private void replaceSurfaceData() {
 955         replaceSurfaceData(true);
 956     }
 957 
 958     private void replaceSurfaceData(boolean blit) {
 959         replaceSurfaceData(backBufferCount, backBufferCaps, blit);
 960     }
 961 
 962     private void replaceSurfaceData(int newBackBufferCount,
 963                                     BufferCapabilities newBackBufferCaps,
 964                                     boolean blit) {
 965         synchronized (surfaceDataLock) {
 966             final SurfaceData oldData = getSurfaceData();
 967             surfaceData = platformWindow.replaceSurfaceData();
 968             // TODO: volatile image
 969     //        VolatileImage oldBB = backBuffer;
 970             BufferedImage oldBB = backBuffer;
 971             backBufferCount = newBackBufferCount;
 972             backBufferCaps = newBackBufferCaps;
 973             final Rectangle size = getSize();
 974             if (getSurfaceData() != null && oldData != getSurfaceData()) {
 975                 clearBackground(size.width, size.height);
 976             }
 977 
 978             if (blit) {
 979                 blitSurfaceData(oldData, getSurfaceData());
 980             }
 981 
 982             if (oldData != null && oldData != getSurfaceData()) {
 983                 // TODO: drop oldData for D3D/WGL pipelines
 984                 // This can only happen when this peer is being created
 985                 oldData.flush();
 986             }
 987 
 988             // TODO: volatile image
 989     //        backBuffer = (VolatileImage)delegate.createBackBuffer();
 990             backBuffer = (BufferedImage) platformWindow.createBackBuffer();
 991             if (backBuffer != null) {
 992                 Graphics g = backBuffer.getGraphics();
 993                 try {
 994                     Rectangle r = getBounds();
 995                     if (g instanceof Graphics2D) {
 996                         ((Graphics2D) g).setComposite(AlphaComposite.Src);
 997                     }
 998                     g.setColor(nonOpaqueBackground);
 999                     g.fillRect(0, 0, r.width, r.height);
1000                     if (g instanceof SunGraphics2D) {
1001                         SG2DConstraint((SunGraphics2D) g, getRegion());
1002                     }
1003                     if (!isTextured()) {
1004                         g.setColor(getBackground());
1005                         g.fillRect(0, 0, r.width, r.height);
1006                     }
1007                     if (oldBB != null) {
1008                         // Draw the old back buffer to the new one
1009                         g.drawImage(oldBB, 0, 0, null);
1010                         oldBB.flush();
1011                     }
1012                 } finally {
1013                     g.dispose();
1014                 }
1015             }
1016         }
1017     }
1018 
1019     private void blitSurfaceData(final SurfaceData src, final SurfaceData dst) {
1020         //TODO blit. proof-of-concept
1021         if (src != dst && src != null && dst != null
1022             && !(dst instanceof NullSurfaceData)
1023             && !(src instanceof NullSurfaceData)
1024             && src.getSurfaceType().equals(dst.getSurfaceType())) {
1025             final Rectangle size = getSize();
1026             final Blit blit = Blit.locate(src.getSurfaceType(),
1027                                           CompositeType.Src,
1028                                           dst.getSurfaceType());
1029             if (blit != null) {
1030                 blit.Blit(src, dst, AlphaComposite.Src,
1031                           getRegion(), 0, 0, 0, 0, size.width, size.height);
1032             }
1033         }
1034     }
1035 
1036     public int getBackBufferCount() {
1037         return backBufferCount;
1038     }
1039 
1040     public BufferCapabilities getBackBufferCaps() {
1041         return backBufferCaps;
1042     }
1043 
1044     /*
1045      * Request the window insets from the delegate and compares it
1046      * with the current one. This method is mostly called by the
1047      * delegate, e.g. when the window state is changed and insets
1048      * should be recalculated.
1049      *
1050      * This method may be called on the toolkit thread.
1051      */
1052     public boolean updateInsets(Insets newInsets) {
1053         boolean changed = false;
1054         synchronized (getStateLock()) {
1055             changed = (insets.equals(newInsets));
1056             insets = newInsets;
1057         }
1058 
1059         if (changed) {
1060             replaceSurfaceData();
1061             repaintPeer();
1062         }
1063 
1064         return changed;
1065     }
1066 
1067     public static LWWindowPeer getWindowUnderCursor() {
1068         return lastMouseEventPeer != null ? lastMouseEventPeer.getWindowPeerOrSelf() : null;
1069     }
1070 
1071     public static LWComponentPeer<?, ?> getPeerUnderCursor() {
1072         return lastMouseEventPeer;
1073     }
1074 
1075     /*
1076      * Requests platform to set native focus on a frame/dialog.
1077      * In case of a simple window, triggers appropriate java focus change.
1078      */
1079     public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
1080         if (focusLog.isLoggable(PlatformLogger.FINE)) {
1081             focusLog.fine("requesting native focus to " + this);
1082         }
1083 
1084         if (!focusAllowedFor()) {
1085             focusLog.fine("focus is not allowed");
1086             return false;
1087         }
1088 
1089         if (platformWindow.rejectFocusRequest(cause)) {
1090             return false;
1091         }
1092 
1093         Window currentActive = KeyboardFocusManager.
1094             getCurrentKeyboardFocusManager().getActiveWindow();
1095 
1096         // Make the owner active window.
1097         if (isSimpleWindow()) {
1098             LWWindowPeer owner = getOwnerFrameDialog(this);
1099 
1100             // If owner is not natively active, request native
1101             // activation on it w/o sending events up to java.
1102             if (owner != null && !owner.platformWindow.isActive()) {
1103                 if (focusLog.isLoggable(PlatformLogger.FINE)) {
1104                     focusLog.fine("requesting native focus to the owner " + owner);
1105                 }
1106                 LWWindowPeer currentActivePeer = (currentActive != null ?
1107                     (LWWindowPeer)currentActive.getPeer() : null);
1108 
1109                 // Ensure the opposite is natively active and suppress sending events.
1110                 if (currentActivePeer != null && currentActivePeer.platformWindow.isActive()) {
1111                     if (focusLog.isLoggable(PlatformLogger.FINE)) {
1112                         focusLog.fine("the opposite is " + currentActivePeer);
1113                     }
1114                     currentActivePeer.skipNextFocusChange = true;
1115                 }
1116                 owner.skipNextFocusChange = true;
1117 
1118                 owner.platformWindow.requestWindowFocus();
1119             }
1120 
1121             // DKFM will synthesize all the focus/activation events correctly.
1122             changeFocusedWindow(true);
1123             return true;
1124 
1125         // In case the toplevel is active but not focused, change focus directly,
1126         // as requesting native focus on it will not have effect.
1127         } else if (getTarget() == currentActive && !getTarget().hasFocus()) {
1128 
1129             changeFocusedWindow(true);
1130             return true;
1131         }
1132         return platformWindow.requestWindowFocus();
1133     }
1134 
1135     private boolean focusAllowedFor() {
1136         Window window = getTarget();
1137         // TODO: check if modal blocked
1138         return window.isVisible() && window.isEnabled() && isFocusableWindow();
1139     }
1140 
1141     private boolean isFocusableWindow() {
1142         boolean focusable = getTarget().isFocusableWindow();
1143         if (isSimpleWindow()) {
1144             LWWindowPeer ownerPeer = getOwnerFrameDialog(this);
1145             if (ownerPeer == null) {
1146                 return false;
1147             }
1148             return focusable && ownerPeer.getTarget().isFocusableWindow();
1149         }
1150         return focusable;
1151     }
1152 
1153     public boolean isSimpleWindow() {
1154         Window window = getTarget();
1155         return !(window instanceof Dialog || window instanceof Frame);
1156     }
1157 
1158     /*
1159      * Changes focused window on java level.
1160      */
1161     private void changeFocusedWindow(boolean becomesFocused) {
1162         if (focusLog.isLoggable(PlatformLogger.FINE)) {
1163             focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
1164         }
1165         if (skipNextFocusChange) {
1166             focusLog.fine("skipping focus change");
1167             skipNextFocusChange = false;
1168             return;
1169         }
1170         if (!isFocusableWindow() && becomesFocused) {
1171             focusLog.fine("the window is not focusable");
1172             return;
1173         }
1174         if (becomesFocused) {
1175             synchronized (getPeerTreeLock()) {
1176                 if (blocker != null) {
1177                     if (focusLog.isLoggable(PlatformLogger.FINEST)) {
1178                         focusLog.finest("the window is blocked by " + blocker);
1179                     }
1180                     return;
1181                 }
1182             }
1183         }
1184 
1185         LWKeyboardFocusManagerPeer manager = LWKeyboardFocusManagerPeer.
1186             getInstance(getAppContext());
1187 
1188         Window oppositeWindow = becomesFocused ? manager.getCurrentFocusedWindow() : null;
1189 
1190         // Note, the method is not called:
1191         // - when the opposite (gaining focus) window is an owned/owner window.
1192         // - for a simple window in any case.
1193         if (!becomesFocused &&
1194             (isGrabbing() || getOwnerFrameDialog(grabbingWindow) == this))
1195         {
1196             focusLog.fine("ungrabbing on " + grabbingWindow);
1197             // ungrab a simple window if its owner looses activation.
1198             grabbingWindow.ungrab();
1199         }
1200 
1201         manager.setFocusedWindow(becomesFocused ? LWWindowPeer.this : null);
1202 
1203         int eventID = becomesFocused ? WindowEvent.WINDOW_GAINED_FOCUS : WindowEvent.WINDOW_LOST_FOCUS;
1204         WindowEvent windowEvent = new WindowEvent(getTarget(), eventID, oppositeWindow);
1205 
1206         // TODO: wrap in SequencedEvent
1207         postEvent(windowEvent);
1208     }
1209 
1210     static LWWindowPeer getOwnerFrameDialog(LWWindowPeer peer) {
1211         Window owner = (peer != null ? peer.getTarget().getOwner() : null);
1212         while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
1213             owner = owner.getOwner();
1214         }
1215         return owner != null ? (LWWindowPeer)owner.getPeer() : null;
1216     }
1217 
1218     /**
1219      * Returns the foremost modal blocker of this window, or null.
1220      */
1221     public LWWindowPeer getBlocker() {
1222         synchronized (getPeerTreeLock()) {
1223             LWWindowPeer blocker = this.blocker;
1224             if (blocker == null) {
1225                 return null;
1226             }
1227             while (blocker.blocker != null) {
1228                 blocker = blocker.blocker;
1229             }
1230             return blocker;
1231         }
1232     }
1233 
1234     public void enterFullScreenMode() {
1235         platformWindow.enterFullScreenMode();
1236     }
1237 
1238     public void exitFullScreenMode() {
1239         platformWindow.exitFullScreenMode();
1240     }
1241 
1242     public long getLayerPtr() {
1243         return getPlatformWindow().getLayerPtr();
1244     }
1245 
1246     void grab() {
1247         if (grabbingWindow != null && !isGrabbing()) {
1248             grabbingWindow.ungrab();
1249         }
1250         grabbingWindow = this;
1251     }
1252 
1253     void ungrab() {
1254         if (isGrabbing()) {
1255             grabbingWindow = null;
1256             postEvent(new UngrabEvent(getTarget()));
1257         }
1258     }
1259 
1260     private boolean isGrabbing() {
1261         return this == grabbingWindow;
1262     }
1263 
1264     @Override
1265     public String toString() {
1266         return super.toString() + " [target is " + getTarget() + "]";
1267     }
1268 }