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