1 /*
   2  * Copyright (c) 2011, 2013, 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.peer.*;
  31 import java.util.List;
  32 
  33 import javax.swing.*;
  34 
  35 import sun.awt.*;
  36 import sun.java2d.*;
  37 import sun.java2d.loops.Blit;
  38 import sun.java2d.loops.CompositeType;
  39 import sun.java2d.pipe.Region;
  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         EMBEDDED_FRAME,
  51         VIEW_EMBEDDED_FRAME
  52     }
  53 
  54     private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.lwawt.focus.LWWindowPeer");
  55 
  56     private final PlatformWindow platformWindow;
  57 
  58     // Window bounds reported by the native system (as opposed to
  59     // regular bounds inherited from LWComponentPeer which are
  60     // requested by user and may haven't been applied yet because
  61     // of asynchronous requests to the windowing system)
  62     private int sysX;
  63     private int sysY;
  64     private int sysW;
  65     private int sysH;
  66 
  67     private static final int MINIMUM_WIDTH = 1;
  68     private static final int MINIMUM_HEIGHT = 1;
  69 
  70     private Insets insets = new Insets(0, 0, 0, 0);
  71 
  72     private GraphicsDevice graphicsDevice;
  73     private GraphicsConfiguration graphicsConfig;
  74 
  75     private SurfaceData surfaceData;
  76     private final Object surfaceDataLock = new Object();
  77 
  78     private volatile int windowState = Frame.NORMAL;
  79 
  80     // check that the mouse is over the window
  81     private volatile boolean isMouseOver = false;
  82 
  83     // A peer where the last mouse event came to. Used by cursor manager to
  84     // find the component under cursor
  85     private static volatile LWComponentPeer lastCommonMouseEventPeer = null;
  86 
  87     // A peer where the last mouse event came to. Used to generate
  88     // MOUSE_ENTERED/EXITED notifications
  89     private volatile LWComponentPeer lastMouseEventPeer;
  90 
  91     // Peers where all dragged/released events should come to,
  92     // depending on what mouse button is being dragged according to Cocoa
  93     private static LWComponentPeer mouseDownTarget[] = new LWComponentPeer[3];
  94 
  95     // A bitmask that indicates what mouse buttons produce MOUSE_CLICKED events
  96     // on MOUSE_RELEASE. Click events are only generated if there were no drag
  97     // events between MOUSE_PRESSED and MOUSE_RELEASED for particular button
  98     private static int mouseClickButtons = 0;
  99 
 100     private volatile boolean isOpaque = true;
 101 
 102     private static final Font DEFAULT_FONT = new Font("Lucida Grande", Font.PLAIN, 13);
 103 
 104     private static LWWindowPeer grabbingWindow;
 105 
 106     private volatile boolean skipNextFocusChange;
 107 
 108     private static final Color nonOpaqueBackground = new Color(0, 0, 0, 0);
 109 
 110     private volatile boolean textured;
 111 
 112     private final PeerType peerType;
 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, PeerType peerType)
 123     {
 124         super(target, platformComponent);
 125         this.platformWindow = platformWindow;
 126         this.peerType = peerType;
 127 
 128         Window owner = target.getOwner();
 129         LWWindowPeer ownerPeer = (owner != null) ? (LWWindowPeer)owner.getPeer() : null;
 130         PlatformWindow ownerDelegate = (ownerPeer != null) ? ownerPeer.getPlatformWindow() : null;
 131 
 132         // The delegate.initialize() needs a non-null GC on X11.
 133         GraphicsConfiguration gc = getTarget().getGraphicsConfiguration();
 134         synchronized (getStateLock()) {
 135             // graphicsConfig should be updated according to the real window
 136             // bounds when the window is shown, see 4868278
 137             this.graphicsConfig = gc;
 138         }
 139 
 140         if (!target.isFontSet()) {
 141             target.setFont(DEFAULT_FONT);
 142         }
 143 
 144         if (!target.isBackgroundSet()) {
 145             target.setBackground(SystemColor.window);
 146         } else {
 147             // first we check if user provided alpha for background. This is
 148             // similar to what Apple's Java do.
 149             // Since JDK7 we should rely on setOpacity() only.
 150             // this.opacity = c.getAlpha();
 151         }
 152 
 153         if (!target.isForegroundSet()) {
 154             target.setForeground(SystemColor.windowText);
 155             // we should not call setForeground because it will call a repaint
 156             // which the peer may not be ready to do yet.
 157         }
 158 
 159         platformWindow.initialize(target, this, ownerDelegate);
 160     }
 161 
 162     @Override
 163     void initializeImpl() {
 164         super.initializeImpl();
 165         if (getTarget() instanceof Frame) {
 166             setTitle(((Frame) getTarget()).getTitle());
 167             setState(((Frame) getTarget()).getExtendedState());
 168         } else if (getTarget() instanceof Dialog) {
 169             setTitle(((Dialog) getTarget()).getTitle());
 170         }
 171 
 172         setAlwaysOnTop(getTarget().isAlwaysOnTop());
 173         updateMinimumSize();
 174 
 175         final Shape shape = getTarget().getShape();
 176         if (shape != null) {
 177             applyShape(Region.getInstance(shape, null));
 178         }
 179 
 180         final float opacity = getTarget().getOpacity();
 181         if (opacity < 1.0f) {
 182             setOpacity(opacity);
 183         }
 184 
 185         setOpaque(getTarget().isOpaque());
 186 
 187         updateInsets(platformWindow.getInsets());
 188         if (getSurfaceData() == null) {
 189             replaceSurfaceData(false);
 190         }
 191     }
 192 
 193     // Just a helper method
 194     public PlatformWindow getPlatformWindow() {
 195         return platformWindow;
 196     }
 197 
 198     @Override
 199     protected LWWindowPeer getWindowPeerOrSelf() {
 200         return this;
 201     }
 202 
 203     @Override
 204     protected void initializeContainerPeer() {
 205         // No-op as LWWindowPeer doesn't have any containerPeer
 206     }
 207 
 208     // ---- PEER METHODS ---- //
 209 
 210     @Override
 211     protected void disposeImpl() {
 212         SurfaceData oldData = getSurfaceData();
 213         synchronized (surfaceDataLock){
 214             surfaceData = null;
 215         }
 216         if (oldData != null) {
 217             oldData.invalidate();
 218         }
 219         if (isGrabbing()) {
 220             ungrab();
 221         }
 222         platformWindow.dispose();
 223         super.disposeImpl();
 224     }
 225 
 226     @Override
 227     protected void setVisibleImpl(final boolean visible) {
 228         super.setVisibleImpl(visible);
 229         // TODO: update graphicsConfig, see 4868278
 230         platformWindow.setVisible(visible);
 231         if (isSimpleWindow()) {
 232             KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
 233 
 234             if (visible) {
 235                 if (!getTarget().isAutoRequestFocus()) {
 236                     return;
 237                 } else {
 238                     requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
 239                 }
 240             // Focus the owner in case this window is focused.
 241             } else if (kfmPeer.getCurrentFocusedWindow() == getTarget()) {
 242                 // Transfer focus to the owner.
 243                 LWWindowPeer owner = getOwnerFrameDialog(LWWindowPeer.this);
 244                 if (owner != null) {
 245                     owner.requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
 246                 }
 247             }
 248         }
 249     }
 250 
 251     @Override
 252     public final GraphicsConfiguration getGraphicsConfiguration() {
 253         synchronized (getStateLock()) {
 254             return graphicsConfig;
 255         }
 256     }
 257 
 258     @Override
 259     public boolean updateGraphicsData(GraphicsConfiguration gc) {
 260         setGraphicsConfig(gc);
 261         return false;
 262     }
 263 
 264     protected final Graphics getOnscreenGraphics(Color fg, Color bg, Font f) {
 265         if (getSurfaceData() == null) {
 266             return null;
 267         }
 268         if (fg == null) {
 269             fg = SystemColor.windowText;
 270         }
 271         if (bg == null) {
 272             bg = SystemColor.window;
 273         }
 274         if (f == null) {
 275             f = DEFAULT_FONT;
 276         }
 277         return platformWindow.transformGraphics(new SunGraphics2D(getSurfaceData(), fg, bg, f));
 278     }
 279 
 280     @Override
 281     public void setBounds(int x, int y, int w, int h, int op) {
 282 
 283         if((op & NO_EMBEDDED_CHECK) == 0 && getPeerType() == PeerType.VIEW_EMBEDDED_FRAME) {
 284             return;
 285         }
 286 
 287         if ((op & SET_CLIENT_SIZE) != 0) {
 288             // SET_CLIENT_SIZE is only applicable to window peers, so handle it here
 289             // instead of pulling 'insets' field up to LWComponentPeer
 290             // no need to add insets since Window's notion of width and height includes insets.
 291             op &= ~SET_CLIENT_SIZE;
 292             op |= SET_SIZE;
 293         }
 294 
 295         if (w < MINIMUM_WIDTH) {
 296             w = MINIMUM_WIDTH;
 297         }
 298         if (h < MINIMUM_HEIGHT) {
 299             h = MINIMUM_HEIGHT;
 300         }
 301 
 302         final int maxW = getLWGC().getMaxTextureWidth();
 303         final int maxH = getLWGC().getMaxTextureHeight();
 304 
 305         if (w > maxW) {
 306             w = maxW;
 307         }
 308         if (h > maxH) {
 309             h = maxH;
 310         }
 311 
 312         // Don't post ComponentMoved/Resized and Paint events
 313         // until we've got a notification from the delegate
 314         setBounds(x, y, w, h, op, false, false);
 315         // Get updated bounds, so we don't have to handle 'op' here manually
 316         Rectangle r = getBounds();
 317         platformWindow.setBounds(r.x, r.y, r.width, r.height);
 318     }
 319 
 320     @Override
 321     public Point getLocationOnScreen() {
 322         return platformWindow.getLocationOnScreen();
 323     }
 324 
 325     /**
 326      * Overridden from LWContainerPeer to return the correct insets.
 327      * Insets are queried from the delegate and are kept up to date by
 328      * requiering when needed (i.e. when the window geometry is changed).
 329      */
 330     @Override
 331     public Insets getInsets() {
 332         synchronized (getStateLock()) {
 333             return insets;
 334         }
 335     }
 336 
 337     @Override
 338     public FontMetrics getFontMetrics(Font f) {
 339         // TODO: check for "use platform metrics" settings
 340         return platformWindow.getFontMetrics(f);
 341     }
 342 
 343     @Override
 344     public void toFront() {
 345         platformWindow.toFront();
 346     }
 347 
 348     @Override
 349     public void toBack() {
 350         platformWindow.toBack();
 351     }
 352 
 353     @Override
 354     public void setZOrder(ComponentPeer above) {
 355         throw new RuntimeException("not implemented");
 356     }
 357 
 358     @Override
 359     public void setAlwaysOnTop(boolean value) {
 360         platformWindow.setAlwaysOnTop(value);
 361     }
 362 
 363     @Override
 364     public void updateFocusableWindowState() {
 365         platformWindow.updateFocusableWindowState();
 366     }
 367 
 368     @Override
 369     public void setModalBlocked(Dialog blocker, boolean blocked) {
 370         synchronized (getPeerTreeLock()) {
 371             this.blocker = blocked ? (LWWindowPeer)blocker.getPeer() : null;
 372         }
 373 
 374         platformWindow.setModalBlocked(blocked);
 375     }
 376 
 377     @Override
 378     public void updateMinimumSize() {
 379         final Dimension min;
 380         if (getTarget().isMinimumSizeSet()) {
 381             min = getTarget().getMinimumSize();
 382             min.width = Math.max(min.width, MINIMUM_WIDTH);
 383             min.height = Math.max(min.height, MINIMUM_HEIGHT);
 384         } else {
 385             min = new Dimension(MINIMUM_WIDTH, MINIMUM_HEIGHT);
 386         }
 387 
 388         final Dimension max;
 389         if (getTarget().isMaximumSizeSet()) {
 390             max = getTarget().getMaximumSize();
 391             max.width = Math.min(max.width, getLWGC().getMaxTextureWidth());
 392             max.height = Math.min(max.height, getLWGC().getMaxTextureHeight());
 393         } else {
 394             max = new Dimension(getLWGC().getMaxTextureWidth(),
 395                                 getLWGC().getMaxTextureHeight());
 396         }
 397 
 398         platformWindow.setSizeConstraints(min.width, min.height, max.width, max.height);
 399     }
 400 
 401     @Override
 402     public void updateIconImages() {
 403         getPlatformWindow().updateIconImages();
 404     }
 405 
 406     @Override
 407     public void setOpacity(float opacity) {
 408         getPlatformWindow().setOpacity(opacity);
 409         repaintPeer();
 410     }
 411 
 412     @Override
 413     public final void setOpaque(final boolean isOpaque) {
 414         if (this.isOpaque != isOpaque) {
 415             this.isOpaque = isOpaque;
 416             updateOpaque();
 417         }
 418     }
 419 
 420     private void updateOpaque() {
 421         getPlatformWindow().setOpaque(!isTranslucent());
 422         replaceSurfaceData(false);
 423         repaintPeer();
 424     }
 425 
 426     @Override
 427     public void updateWindow() {
 428     }
 429 
 430     public final boolean isTextured() {
 431         return textured;
 432     }
 433 
 434     public final void setTextured(final boolean isTextured) {
 435         textured = isTextured;
 436     }
 437 
 438     public final boolean isTranslucent() {
 439         synchronized (getStateLock()) {
 440             /*
 441              * Textured window is a special case of translucent window.
 442              * The difference is only in nswindow background. So when we set
 443              * texture property our peer became fully translucent. It doesn't
 444              * fill background, create non opaque backbuffers and layer etc.
 445              */
 446             return !isOpaque || isShaped() || isTextured();
 447         }
 448     }
 449 
 450     @Override
 451     final void applyShapeImpl(final Region shape) {
 452         super.applyShapeImpl(shape);
 453         updateOpaque();
 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 {@code PlatformWindow} when any part of the window should
 549      * be repainted.
 550      */
 551     public final void notifyExpose(final Rectangle r) {
 552         repaintPeer(r);
 553     }
 554 
 555     /**
 556      * Called by the {@code PlatformWindow} when this window is moved/resized by
 557      * user or window insets are changed. There's no notifyReshape() in
 558      * LWComponentPeer as the only components which could be resized by user are
 559      * top-level windows.
 560      */
 561     public final void notifyReshape(int x, int y, int w, int h) {
 562         final boolean moved;
 563         final boolean resized;
 564         final boolean invalid = updateInsets(platformWindow.getInsets());
 565         synchronized (getStateLock()) {
 566             moved = (x != sysX) || (y != sysY);
 567             resized = (w != sysW) || (h != sysH);
 568             sysX = x;
 569             sysY = y;
 570             sysW = w;
 571             sysH = h;
 572         }
 573 
 574         // Check if anything changed
 575         if (!moved && !resized && !invalid) {
 576             return;
 577         }
 578         // First, update peer's bounds
 579         setBounds(x, y, w, h, SET_BOUNDS, false, false);
 580 
 581         // Second, update the graphics config and surface data
 582         checkIfOnNewScreen();
 583         if (resized) {
 584             replaceSurfaceData();
 585             flushOnscreenGraphics();
 586         }
 587 
 588         // Third, COMPONENT_MOVED/COMPONENT_RESIZED/PAINT events
 589         if (moved || invalid) {
 590             handleMove(x, y, true);
 591         }
 592         if (resized || invalid) {
 593             handleResize(w, h, true);
 594             repaintPeer();
 595         }
 596     }
 597 
 598     private void clearBackground(final int w, final int h) {
 599         final Graphics g = getOnscreenGraphics(getForeground(), getBackground(),
 600                                                getFont());
 601         if (g != null) {
 602             try {
 603                 if (g instanceof Graphics2D) {
 604                     ((Graphics2D) g).setComposite(AlphaComposite.Src);
 605                 }
 606                 if (isTranslucent()) {
 607                     g.setColor(nonOpaqueBackground);
 608                     g.fillRect(0, 0, w, h);
 609                 }
 610                 if (!isTextured()) {
 611                     if (g instanceof SunGraphics2D) {
 612                         SG2DConstraint((SunGraphics2D) g, getRegion());
 613                     }
 614                     g.setColor(getBackground());
 615                     g.fillRect(0, 0, w, h);
 616                 }
 617             } finally {
 618                 g.dispose();
 619             }
 620         }
 621     }
 622 
 623     public void notifyUpdateCursor() {
 624         getLWToolkit().getCursorManager().updateCursorLater(this);
 625     }
 626 
 627     public void notifyActivation(boolean activation, LWWindowPeer opposite) {
 628         Window oppositeWindow = (opposite == null)? null : opposite.getTarget();
 629         changeFocusedWindow(activation, oppositeWindow);
 630     }
 631 
 632     // MouseDown in non-client area
 633     public void notifyNCMouseDown() {
 634         // Ungrab except for a click on a Dialog with the grabbing owner
 635         if (grabbingWindow != null &&
 636             grabbingWindow != getOwnerFrameDialog(this))
 637         {
 638             grabbingWindow.ungrab();
 639         }
 640     }
 641 
 642     // ---- EVENTS ---- //
 643 
 644     /*
 645      * Called by the delegate to dispatch the event to Java. Event
 646      * coordinates are relative to non-client window are, i.e. the top-left
 647      * point of the client area is (insets.top, insets.left).
 648      */
 649     public void dispatchMouseEvent(int id, long when, int button,
 650                                    int x, int y, int screenX, int screenY,
 651                                    int modifiers, int clickCount, boolean popupTrigger,
 652                                    byte[] bdata)
 653     {
 654         // TODO: fill "bdata" member of AWTEvent
 655         Rectangle r = getBounds();
 656         // findPeerAt() expects parent coordinates
 657         LWComponentPeer targetPeer = findPeerAt(r.x + x, r.y + y);
 658 
 659         if (id == MouseEvent.MOUSE_EXITED) {
 660             isMouseOver = false;
 661             if (lastMouseEventPeer != null) {
 662                 if (lastMouseEventPeer.isEnabled()) {
 663                     Point lp = lastMouseEventPeer.windowToLocal(x, y,
 664                             this);
 665                     postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
 666                             MouseEvent.MOUSE_EXITED, when,
 667                             modifiers, lp.x, lp.y, screenX,
 668                             screenY, clickCount, popupTrigger,
 669                             button));
 670                 }
 671 
 672                 // Sometimes we may get MOUSE_EXITED after lastCommonMouseEventPeer is switched
 673                 // to a peer from another window. So we must first check if this peer is
 674                 // the same as lastWindowPeer
 675                 if (lastCommonMouseEventPeer != null && lastCommonMouseEventPeer.getWindowPeerOrSelf() == this) {
 676                     lastCommonMouseEventPeer = null;
 677                 }
 678                 lastMouseEventPeer = null;
 679             }
 680         } else if(id == MouseEvent.MOUSE_ENTERED) {
 681             isMouseOver = true;
 682             if (targetPeer != null) {
 683                 if (targetPeer.isEnabled()) {
 684                     Point lp = targetPeer.windowToLocal(x, y, this);
 685                         postEvent(new MouseEvent(targetPeer.getTarget(),
 686                             MouseEvent.MOUSE_ENTERED, when,
 687                             modifiers, lp.x, lp.y, screenX,
 688                             screenY, clickCount, popupTrigger,
 689                             button));
 690                 }
 691                 lastCommonMouseEventPeer = targetPeer;
 692                 lastMouseEventPeer = targetPeer;
 693             }
 694         } else {
 695             PlatformWindow topmostPlatforWindow =
 696                     platformWindow.getTopmostPlatformWindowUnderMouse();
 697 
 698             LWWindowPeer topmostWindowPeer =
 699                     topmostPlatforWindow != null ? topmostPlatforWindow.getPeer() : null;
 700 
 701             // topmostWindowPeer == null condition is added for the backward
 702             // compatibility with applets. It can be removed when the
 703             // getTopmostPlatformWindowUnderMouse() method will be properly
 704             // implemented in CPlatformEmbeddedFrame class
 705             if (topmostWindowPeer == this || topmostWindowPeer == null) {
 706                 generateMouseEnterExitEventsForComponents(when, button, x, y,
 707                         screenX, screenY, modifiers, clickCount, popupTrigger,
 708                         targetPeer);
 709             } else {
 710                 LWComponentPeer topmostTargetPeer =
 711                         topmostWindowPeer != null ? topmostWindowPeer.findPeerAt(r.x + x, r.y + y) : null;
 712                 topmostWindowPeer.generateMouseEnterExitEventsForComponents(when, button, x, y,
 713                         screenX, screenY, modifiers, clickCount, popupTrigger,
 714                         topmostTargetPeer);
 715             }
 716 
 717             // TODO: fill "bdata" member of AWTEvent
 718 
 719             int eventButtonMask = (button > 0)? MouseEvent.getMaskForButton(button) : 0;
 720             int otherButtonsPressed = modifiers & ~eventButtonMask;
 721 
 722             // For pressed/dragged/released events OS X treats other
 723             // mouse buttons as if they were BUTTON2, so we do the same
 724             int targetIdx = (button > 3) ? MouseEvent.BUTTON2 - 1 : button - 1;
 725 
 726             // MOUSE_ENTERED/EXITED are generated for the components strictly under
 727             // mouse even when dragging. That's why we first update lastMouseEventPeer
 728             // based on initial targetPeer value and only then recalculate targetPeer
 729             // for MOUSE_DRAGGED/RELEASED events
 730             if (id == MouseEvent.MOUSE_PRESSED) {
 731 
 732                 // Ungrab only if this window is not an owned window of the grabbing one.
 733                 if (!isGrabbing() && grabbingWindow != null &&
 734                     grabbingWindow != getOwnerFrameDialog(this))
 735                 {
 736                     grabbingWindow.ungrab();
 737                 }
 738                 if (otherButtonsPressed == 0) {
 739                     mouseClickButtons = eventButtonMask;
 740                 } else {
 741                     mouseClickButtons |= eventButtonMask;
 742                 }
 743 
 744                 // The window should be focused on mouse click. If it gets activated by the native platform,
 745                 // this request will be no op. It will take effect when:
 746                 // 1. A simple not focused window is clicked.
 747                 // 2. An active but not focused owner frame/dialog is clicked.
 748                 // The mouse event then will trigger a focus request "in window" to the component, so the window
 749                 // should gain focus before.
 750                 requestWindowFocus(CausedFocusEvent.Cause.MOUSE_EVENT);
 751 
 752                 mouseDownTarget[targetIdx] = targetPeer;
 753             } else if (id == MouseEvent.MOUSE_DRAGGED) {
 754                 // Cocoa dragged event has the information about which mouse
 755                 // button is being dragged. Use it to determine the peer that
 756                 // should receive the dragged event.
 757                 targetPeer = mouseDownTarget[targetIdx];
 758                 mouseClickButtons &= ~modifiers;
 759             } else if (id == MouseEvent.MOUSE_RELEASED) {
 760                 // TODO: currently, mouse released event goes to the same component
 761                 // that received corresponding mouse pressed event. For most cases,
 762                 // it's OK, however, we need to make sure that our behavior is consistent
 763                 // with 1.6 for cases where component in question have been
 764                 // hidden/removed in between of mouse pressed/released events.
 765                 targetPeer = mouseDownTarget[targetIdx];
 766 
 767                 if ((modifiers & eventButtonMask) == 0) {
 768                     mouseDownTarget[targetIdx] = null;
 769                 }
 770 
 771                 // mouseClickButtons is updated below, after MOUSE_CLICK is sent
 772             }
 773 
 774             if (targetPeer == null) {
 775                 //TODO This can happen if this window is invisible. this is correct behavior in this case?
 776                 targetPeer = this;
 777             }
 778 
 779 
 780             Point lp = targetPeer.windowToLocal(x, y, this);
 781             if (targetPeer.isEnabled()) {
 782                 MouseEvent event = new MouseEvent(targetPeer.getTarget(), id,
 783                                                   when, modifiers, lp.x, lp.y,
 784                                                   screenX, screenY, clickCount,
 785                                                   popupTrigger, button);
 786                 postEvent(event);
 787             }
 788 
 789             if (id == MouseEvent.MOUSE_RELEASED) {
 790                 if ((mouseClickButtons & eventButtonMask) != 0
 791                     && targetPeer.isEnabled()) {
 792                     postEvent(new MouseEvent(targetPeer.getTarget(),
 793                                              MouseEvent.MOUSE_CLICKED,
 794                                              when, modifiers,
 795                                              lp.x, lp.y, screenX, screenY,
 796                                              clickCount, popupTrigger, button));
 797                 }
 798                 mouseClickButtons &= ~eventButtonMask;
 799             }
 800         }
 801         notifyUpdateCursor();
 802     }
 803 
 804     private void generateMouseEnterExitEventsForComponents(long when,
 805             int button, int x, int y, int screenX, int screenY,
 806             int modifiers, int clickCount, boolean popupTrigger,
 807             LWComponentPeer targetPeer) {
 808 
 809         if (!isMouseOver || targetPeer == lastMouseEventPeer) {
 810             return;
 811         }
 812 
 813         // Generate Mouse Exit for components
 814         if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
 815             Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
 816             postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
 817                     MouseEvent.MOUSE_EXITED,
 818                     when, modifiers,
 819                     oldp.x, oldp.y, screenX, screenY,
 820                     clickCount, popupTrigger, button));
 821         }
 822         lastCommonMouseEventPeer = targetPeer;
 823         lastMouseEventPeer = targetPeer;
 824 
 825         // Generate Mouse Enter for components
 826         if (targetPeer != null && targetPeer.isEnabled()) {
 827             Point newp = targetPeer.windowToLocal(x, y, this);
 828             postEvent(new MouseEvent(targetPeer.getTarget(),
 829                     MouseEvent.MOUSE_ENTERED,
 830                     when, modifiers,
 831                     newp.x, newp.y, screenX, screenY,
 832                     clickCount, popupTrigger, button));
 833         }
 834     }
 835 
 836     public void dispatchMouseWheelEvent(long when, int x, int y, int modifiers,
 837                                         int scrollType, int scrollAmount,
 838                                         int wheelRotation, double preciseWheelRotation,
 839                                         byte[] bdata)
 840     {
 841         // TODO: could we just use the last mouse event target here?
 842         Rectangle r = getBounds();
 843         // findPeerAt() expects parent coordinates
 844         final LWComponentPeer targetPeer = findPeerAt(r.x + x, r.y + y);
 845         if (targetPeer == null || !targetPeer.isEnabled()) {
 846             return;
 847         }
 848 
 849         Point lp = targetPeer.windowToLocal(x, y, this);
 850         // TODO: fill "bdata" member of AWTEvent
 851         // TODO: screenX/screenY
 852         postEvent(new MouseWheelEvent(targetPeer.getTarget(),
 853                                       MouseEvent.MOUSE_WHEEL,
 854                                       when, modifiers,
 855                                       lp.x, lp.y,
 856                                       0, 0, /* screenX, Y */
 857                                       0 /* clickCount */, false /* popupTrigger */,
 858                                       scrollType, scrollAmount,
 859                                       wheelRotation, preciseWheelRotation));
 860     }
 861 
 862     /*
 863      * Called by the delegate when a key is pressed.
 864      */
 865     public void dispatchKeyEvent(int id, long when, int modifiers,
 866                                  int keyCode, char keyChar, int keyLocation)
 867     {
 868         LWKeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
 869         Component focusOwner = kfmPeer.getCurrentFocusOwner();
 870 
 871         if (focusOwner == null) {
 872             focusOwner = kfmPeer.getCurrentFocusedWindow();
 873             if (focusOwner == null) {
 874                 focusOwner = this.getTarget();
 875             }
 876         }
 877         postEvent(new KeyEvent(focusOwner, id, when, modifiers, keyCode, keyChar, keyLocation));
 878     }
 879 
 880 
 881     // ---- UTILITY METHODS ---- //
 882 
 883     private void postWindowStateChangedEvent(int newWindowState) {
 884         if (getTarget() instanceof Frame) {
 885             AWTAccessor.getFrameAccessor().setExtendedState(
 886                     (Frame)getTarget(), newWindowState);
 887         }
 888         WindowEvent stateChangedEvent = new WindowEvent(getTarget(),
 889                 WindowEvent.WINDOW_STATE_CHANGED,
 890                 windowState, newWindowState);
 891         postEvent(stateChangedEvent);
 892         windowState = newWindowState;
 893     }
 894 
 895     private static int getGraphicsConfigScreen(GraphicsConfiguration gc) {
 896         // TODO: this method can be implemented in a more
 897         // efficient way by forwarding to the delegate
 898         GraphicsDevice gd = gc.getDevice();
 899         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
 900         GraphicsDevice[] gds = ge.getScreenDevices();
 901         for (int i = 0; i < gds.length; i++) {
 902             if (gds[i] == gd) {
 903                 return i;
 904             }
 905         }
 906         // Should never happen if gc is a screen device config
 907         return 0;
 908     }
 909 
 910     /*
 911      * This method is called when window's graphics config is changed from
 912      * the app code (e.g. when the window is made non-opaque) or when
 913      * the window is moved to another screen by user.
 914      *
 915      * Returns true if the graphics config has been changed, false otherwise.
 916      */
 917     private boolean setGraphicsConfig(GraphicsConfiguration gc) {
 918         synchronized (getStateLock()) {
 919             if (graphicsConfig == gc) {
 920                 return false;
 921             }
 922             // If window's graphics config is changed from the app code, the
 923             // config correspond to the same device as before; when the window
 924             // is moved by user, graphicsDevice is updated in checkIfOnNewScreen().
 925             // In either case, there's nothing to do with screenOn here
 926             graphicsConfig = gc;
 927         }
 928         // SurfaceData is replaced later in updateGraphicsData()
 929         return true;
 930     }
 931 
 932     private void checkIfOnNewScreen() {
 933         GraphicsDevice newGraphicsDevice = platformWindow.getGraphicsDevice();
 934         synchronized (getStateLock()) {
 935             if (graphicsDevice == newGraphicsDevice) {
 936                 return;
 937             }
 938             graphicsDevice = newGraphicsDevice;
 939         }
 940 
 941         // TODO: DisplayChangedListener stuff
 942         final GraphicsConfiguration newGC = newGraphicsDevice.getDefaultConfiguration();
 943 
 944         if (!setGraphicsConfig(newGC)) return;
 945 
 946         SunToolkit.executeOnEventHandlerThread(getTarget(), new Runnable() {
 947             public void run() {
 948                 AWTAccessor.getComponentAccessor().setGraphicsConfiguration(getTarget(), newGC);
 949             }
 950         });
 951     }
 952 
 953     /*
 954      * May be called by delegate to provide SD to Java2D code.
 955      */
 956     public SurfaceData getSurfaceData() {
 957         synchronized (surfaceDataLock) {
 958             return surfaceData;
 959         }
 960     }
 961 
 962     private void replaceSurfaceData() {
 963         replaceSurfaceData(true);
 964     }
 965 
 966     private void replaceSurfaceData(final boolean blit) {
 967         synchronized (surfaceDataLock) {
 968             final SurfaceData oldData = getSurfaceData();
 969             surfaceData = platformWindow.replaceSurfaceData();
 970             final Rectangle size = getSize();
 971             if (getSurfaceData() != null && oldData != getSurfaceData()) {
 972                 clearBackground(size.width, size.height);
 973             }
 974 
 975             if (blit) {
 976                 blitSurfaceData(oldData, getSurfaceData());
 977             }
 978 
 979             if (oldData != null && oldData != getSurfaceData()) {
 980                 // TODO: drop oldData for D3D/WGL pipelines
 981                 // This can only happen when this peer is being created
 982                 oldData.flush();
 983             }
 984         }
 985     }
 986 
 987     private void blitSurfaceData(final SurfaceData src, final SurfaceData dst) {
 988         //TODO blit. proof-of-concept
 989         if (src != dst && src != null && dst != null
 990             && !(dst instanceof NullSurfaceData)
 991             && !(src instanceof NullSurfaceData)
 992             && src.getSurfaceType().equals(dst.getSurfaceType())) {
 993             final Rectangle size = getSize();
 994             final Blit blit = Blit.locate(src.getSurfaceType(),
 995                                           CompositeType.Src,
 996                                           dst.getSurfaceType());
 997             if (blit != null) {
 998                 blit.Blit(src, dst, AlphaComposite.Src,
 999                           getRegion(), 0, 0, 0, 0, size.width, size.height);
1000             }
1001         }
1002     }
1003 
1004     /**
1005      * Request the window insets from the delegate and compares it with the
1006      * current one. This method is mostly called by the delegate, e.g. when the
1007      * window state is changed and insets should be recalculated.
1008      * <p/>
1009      * This method may be called on the toolkit thread.
1010      */
1011     public final boolean updateInsets(final Insets newInsets) {
1012         synchronized (getStateLock()) {
1013             if (insets.equals(newInsets)) {
1014                 return false;
1015             }
1016             insets = newInsets;
1017         }
1018         return true;
1019     }
1020 
1021     public static LWWindowPeer getWindowUnderCursor() {
1022         return lastCommonMouseEventPeer != null ? lastCommonMouseEventPeer.getWindowPeerOrSelf() : null;
1023     }
1024 
1025     public static LWComponentPeer<?, ?> getPeerUnderCursor() {
1026         return lastCommonMouseEventPeer;
1027     }
1028 
1029     /*
1030      * Requests platform to set native focus on a frame/dialog.
1031      * In case of a simple window, triggers appropriate java focus change.
1032      */
1033     public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
1034         if (focusLog.isLoggable(PlatformLogger.FINE)) {
1035             focusLog.fine("requesting native focus to " + this);
1036         }
1037 
1038         if (!focusAllowedFor()) {
1039             focusLog.fine("focus is not allowed");
1040             return false;
1041         }
1042 
1043         if (platformWindow.rejectFocusRequest(cause)) {
1044             return false;
1045         }
1046 
1047         Window currentActive = KeyboardFocusManager.
1048             getCurrentKeyboardFocusManager().getActiveWindow();
1049 
1050         Window opposite = LWKeyboardFocusManagerPeer.getInstance().
1051             getCurrentFocusedWindow();
1052 
1053         // Make the owner active window.
1054         if (isSimpleWindow()) {
1055             LWWindowPeer owner = getOwnerFrameDialog(this);
1056 
1057             // If owner is not natively active, request native
1058             // activation on it w/o sending events up to java.
1059             if (owner != null && !owner.platformWindow.isActive()) {
1060                 if (focusLog.isLoggable(PlatformLogger.FINE)) {
1061                     focusLog.fine("requesting native focus to the owner " + owner);
1062                 }
1063                 LWWindowPeer currentActivePeer = (currentActive != null ?
1064                     (LWWindowPeer)currentActive.getPeer() : null);
1065 
1066                 // Ensure the opposite is natively active and suppress sending events.
1067                 if (currentActivePeer != null && currentActivePeer.platformWindow.isActive()) {
1068                     if (focusLog.isLoggable(PlatformLogger.FINE)) {
1069                         focusLog.fine("the opposite is " + currentActivePeer);
1070                     }
1071                     currentActivePeer.skipNextFocusChange = true;
1072                 }
1073                 owner.skipNextFocusChange = true;
1074 
1075                 owner.platformWindow.requestWindowFocus();
1076             }
1077 
1078             // DKFM will synthesize all the focus/activation events correctly.
1079             changeFocusedWindow(true, opposite);
1080             return true;
1081 
1082         // In case the toplevel is active but not focused, change focus directly,
1083         // as requesting native focus on it will not have effect.
1084         } else if (getTarget() == currentActive && !getTarget().hasFocus()) {
1085 
1086             changeFocusedWindow(true, opposite);
1087             return true;
1088         }
1089 
1090         return platformWindow.requestWindowFocus();
1091     }
1092 
1093     private boolean focusAllowedFor() {
1094         Window window = getTarget();
1095         // TODO: check if modal blocked
1096         return window.isVisible() && window.isEnabled() && isFocusableWindow();
1097     }
1098 
1099     private boolean isFocusableWindow() {
1100         boolean focusable = getTarget().isFocusableWindow();
1101         if (isSimpleWindow()) {
1102             LWWindowPeer ownerPeer = getOwnerFrameDialog(this);
1103             if (ownerPeer == null) {
1104                 return false;
1105             }
1106             return focusable && ownerPeer.getTarget().isFocusableWindow();
1107         }
1108         return focusable;
1109     }
1110 
1111     public boolean isSimpleWindow() {
1112         Window window = getTarget();
1113         return !(window instanceof Dialog || window instanceof Frame);
1114     }
1115 
1116     /*
1117      * Changes focused window on java level.
1118      */
1119     private void changeFocusedWindow(boolean becomesFocused, Window opposite) {
1120         if (focusLog.isLoggable(PlatformLogger.FINE)) {
1121             focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
1122         }
1123         if (skipNextFocusChange) {
1124             focusLog.fine("skipping focus change");
1125             skipNextFocusChange = false;
1126             return;
1127         }
1128         if (!isFocusableWindow() && becomesFocused) {
1129             focusLog.fine("the window is not focusable");
1130             return;
1131         }
1132         if (becomesFocused) {
1133             synchronized (getPeerTreeLock()) {
1134                 if (blocker != null) {
1135                     if (focusLog.isLoggable(PlatformLogger.FINEST)) {
1136                         focusLog.finest("the window is blocked by " + blocker);
1137                     }
1138                     return;
1139                 }
1140             }
1141         }
1142 
1143         // Note, the method is not called:
1144         // - when the opposite (gaining focus) window is an owned/owner window.
1145         // - for a simple window in any case.
1146         if (!becomesFocused &&
1147             (isGrabbing() || getOwnerFrameDialog(grabbingWindow) == this))
1148         {
1149             focusLog.fine("ungrabbing on " + grabbingWindow);
1150             // ungrab a simple window if its owner looses activation.
1151             grabbingWindow.ungrab();
1152         }
1153 
1154         KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
1155         kfmPeer.setCurrentFocusedWindow(becomesFocused ? getTarget() : null);
1156 
1157         int eventID = becomesFocused ? WindowEvent.WINDOW_GAINED_FOCUS : WindowEvent.WINDOW_LOST_FOCUS;
1158         WindowEvent windowEvent = new TimedWindowEvent(getTarget(), eventID, opposite, System.currentTimeMillis());
1159 
1160         // TODO: wrap in SequencedEvent
1161         postEvent(windowEvent);
1162     }
1163 
1164     static LWWindowPeer getOwnerFrameDialog(LWWindowPeer peer) {
1165         Window owner = (peer != null ? peer.getTarget().getOwner() : null);
1166         while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
1167             owner = owner.getOwner();
1168         }
1169         return owner != null ? (LWWindowPeer)owner.getPeer() : null;
1170     }
1171 
1172     /**
1173      * Returns the foremost modal blocker of this window, or null.
1174      */
1175     public LWWindowPeer getBlocker() {
1176         synchronized (getPeerTreeLock()) {
1177             LWWindowPeer blocker = this.blocker;
1178             if (blocker == null) {
1179                 return null;
1180             }
1181             while (blocker.blocker != null) {
1182                 blocker = blocker.blocker;
1183             }
1184             return blocker;
1185         }
1186     }
1187 
1188     public void enterFullScreenMode() {
1189         platformWindow.enterFullScreenMode();
1190     }
1191 
1192     public void exitFullScreenMode() {
1193         platformWindow.exitFullScreenMode();
1194     }
1195 
1196     public long getLayerPtr() {
1197         return getPlatformWindow().getLayerPtr();
1198     }
1199 
1200     void grab() {
1201         if (grabbingWindow != null && !isGrabbing()) {
1202             grabbingWindow.ungrab();
1203         }
1204         grabbingWindow = this;
1205     }
1206 
1207     final void ungrab(boolean doPost) {
1208         if (isGrabbing()) {
1209             grabbingWindow = null;
1210             if (doPost) {
1211                 postEvent(new UngrabEvent(getTarget()));
1212             }
1213         }
1214     }
1215 
1216     void ungrab() {
1217         ungrab(true);
1218     }
1219 
1220     private boolean isGrabbing() {
1221         return this == grabbingWindow;
1222     }
1223 
1224     public PeerType getPeerType() {
1225         return peerType;
1226     }
1227 
1228     @Override
1229     public String toString() {
1230         return super.toString() + " [target is " + getTarget() + "]";
1231     }
1232 }