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