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