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     private final 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 or window insets are changed. There's no notifyReshape() in
 559      * LWComponentPeer as the only components which could be resized by user are
 560      * top-level windows.
 561      */
 562     public final void notifyReshape(int x, int y, int w, int h) {
 563         final boolean moved;
 564         final boolean resized;
 565         final boolean invalid = updateInsets(platformWindow.getInsets());
 566         synchronized (getStateLock()) {
 567             moved = (x != sysX) || (y != sysY);
 568             resized = (w != sysW) || (h != sysH);
 569             sysX = x;
 570             sysY = y;
 571             sysW = w;
 572             sysH = h;
 573         }
 574 
 575         // Check if anything changed
 576         if (!moved && !resized && !invalid) {
 577             return;
 578         }
 579         // First, update peer's bounds
 580         setBounds(x, y, w, h, SET_BOUNDS, false, false);
 581 
 582         // Second, update the graphics config and surface data
 583         checkIfOnNewScreen();
 584         if (resized) {
 585             replaceSurfaceData();
 586             flushOnscreenGraphics();
 587         }
 588 
 589         // Third, COMPONENT_MOVED/COMPONENT_RESIZED/PAINT events
 590         if (moved || invalid) {
 591             handleMove(x, y, true);
 592         }
 593         if (resized || invalid) {
 594             handleResize(w, h, true);
 595             repaintPeer();
 596         }
 597     }
 598 
 599     private void clearBackground(final int w, final int h) {
 600         final Graphics g = getOnscreenGraphics(getForeground(), getBackground(),
 601                                                getFont());
 602         if (g != null) {
 603             try {
 604                 if (g instanceof Graphics2D) {
 605                     ((Graphics2D) g).setComposite(AlphaComposite.Src);
 606                 }
 607                 if (isTranslucent()) {
 608                     g.setColor(nonOpaqueBackground);
 609                     g.fillRect(0, 0, w, h);
 610                 }
 611                 if (!isTextured()) {
 612                     if (g instanceof SunGraphics2D) {
 613                         SG2DConstraint((SunGraphics2D) g, getRegion());
 614                     }
 615                     g.setColor(getBackground());
 616                     g.fillRect(0, 0, w, h);
 617                 }
 618             } finally {
 619                 g.dispose();
 620             }
 621         }
 622     }
 623 
 624     public void notifyUpdateCursor() {
 625         getLWToolkit().getCursorManager().updateCursorLater(this);
 626     }
 627 
 628     public void notifyActivation(boolean activation, LWWindowPeer opposite) {
 629         Window oppositeWindow = (opposite == null)? null : opposite.getTarget();
 630         changeFocusedWindow(activation, oppositeWindow);
 631     }
 632 
 633     // MouseDown in non-client area
 634     public void notifyNCMouseDown() {
 635         // Ungrab except for a click on a Dialog with the grabbing owner
 636         if (grabbingWindow != null &&
 637             grabbingWindow != getOwnerFrameDialog(this))
 638         {
 639             grabbingWindow.ungrab();
 640         }
 641     }
 642 
 643     // ---- EVENTS ---- //
 644 
 645     /*
 646      * Called by the delegate to dispatch the event to Java. Event
 647      * coordinates are relative to non-client window are, i.e. the top-left
 648      * point of the client area is (insets.top, insets.left).
 649      */
 650     public void dispatchMouseEvent(int id, long when, int button,
 651                                    int x, int y, int screenX, int screenY,
 652                                    int modifiers, int clickCount, boolean popupTrigger,
 653                                    byte[] bdata)
 654     {
 655         // TODO: fill "bdata" member of AWTEvent
 656         Rectangle r = getBounds();
 657         // findPeerAt() expects parent coordinates
 658         LWComponentPeer targetPeer = findPeerAt(r.x + x, r.y + y);
 659 
 660         if (id == MouseEvent.MOUSE_EXITED) {
 661             isMouseOver = false;
 662             if (lastMouseEventPeer != null) {
 663                 if (lastMouseEventPeer.isEnabled()) {
 664                     Point lp = lastMouseEventPeer.windowToLocal(x, y,
 665                             this);
 666                     postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
 667                             MouseEvent.MOUSE_EXITED, when,
 668                             modifiers, lp.x, lp.y, screenX,
 669                             screenY, clickCount, popupTrigger,
 670                             button));
 671                 }
 672 
 673                 // Sometimes we may get MOUSE_EXITED after lastCommonMouseEventPeer is switched
 674                 // to a peer from another window. So we must first check if this peer is
 675                 // the same as lastWindowPeer
 676                 if (lastCommonMouseEventPeer != null && lastCommonMouseEventPeer.getWindowPeerOrSelf() == this) {
 677                     lastCommonMouseEventPeer = null;
 678                 }
 679                 lastMouseEventPeer = null;
 680             }
 681         } else if(id == MouseEvent.MOUSE_ENTERED) {
 682             isMouseOver = true;
 683             if (targetPeer != null) {
 684                 if (targetPeer.isEnabled()) {
 685                     Point lp = targetPeer.windowToLocal(x, y, this);
 686                         postEvent(new MouseEvent(targetPeer.getTarget(),
 687                             MouseEvent.MOUSE_ENTERED, when,
 688                             modifiers, lp.x, lp.y, screenX,
 689                             screenY, clickCount, popupTrigger,
 690                             button));
 691                 }
 692                 lastCommonMouseEventPeer = targetPeer;
 693                 lastMouseEventPeer = targetPeer;
 694             }
 695         } else {
 696             PlatformWindow topmostPlatforWindow =
 697                     platformWindow.getTopmostPlatformWindowUnderMouse();
 698 
 699             LWWindowPeer topmostWindowPeer =
 700                     topmostPlatforWindow != null ? topmostPlatforWindow.getPeer() : null;
 701 
 702             // topmostWindowPeer == null condition is added for the backward
 703             // compatibility with applets. It can be removed when the
 704             // getTopmostPlatformWindowUnderMouse() method will be properly
 705             // implemented in CPlatformEmbeddedFrame class
 706             if (topmostWindowPeer == this || topmostWindowPeer == null) {
 707                 generateMouseEnterExitEventsForComponents(when, button, x, y,
 708                         screenX, screenY, modifiers, clickCount, popupTrigger,
 709                         targetPeer);
 710             } else {
 711                 LWComponentPeer topmostTargetPeer =
 712                         topmostWindowPeer != null ? topmostWindowPeer.findPeerAt(r.x + x, r.y + y) : null;
 713                 topmostWindowPeer.generateMouseEnterExitEventsForComponents(when, button, x, y,
 714                         screenX, screenY, modifiers, clickCount, popupTrigger,
 715                         topmostTargetPeer);
 716             }
 717 
 718             // TODO: fill "bdata" member of AWTEvent
 719 
 720             int eventButtonMask = (button > 0)? MouseEvent.getMaskForButton(button) : 0;
 721             int otherButtonsPressed = modifiers & ~eventButtonMask;
 722 
 723             // For pressed/dragged/released events OS X treats other
 724             // mouse buttons as if they were BUTTON2, so we do the same
 725             int targetIdx = (button > 3) ? MouseEvent.BUTTON2 - 1 : button - 1;
 726 
 727             // MOUSE_ENTERED/EXITED are generated for the components strictly under
 728             // mouse even when dragging. That's why we first update lastMouseEventPeer
 729             // based on initial targetPeer value and only then recalculate targetPeer
 730             // for MOUSE_DRAGGED/RELEASED events
 731             if (id == MouseEvent.MOUSE_PRESSED) {
 732 
 733                 // Ungrab only if this window is not an owned window of the grabbing one.
 734                 if (!isGrabbing() && grabbingWindow != null &&
 735                     grabbingWindow != getOwnerFrameDialog(this))
 736                 {
 737                     grabbingWindow.ungrab();
 738                 }
 739                 if (otherButtonsPressed == 0) {
 740                     mouseClickButtons = eventButtonMask;
 741                 } else {
 742                     mouseClickButtons |= eventButtonMask;
 743                 }
 744 
 745                 // The window should be focused on mouse click. If it gets activated by the native platform,
 746                 // this request will be no op. It will take effect when:
 747                 // 1. A simple not focused window is clicked.
 748                 // 2. An active but not focused owner frame/dialog is clicked.
 749                 // The mouse event then will trigger a focus request "in window" to the component, so the window
 750                 // should gain focus before.
 751                 requestWindowFocus(CausedFocusEvent.Cause.MOUSE_EVENT);
 752 
 753                 mouseDownTarget[targetIdx] = targetPeer;
 754             } else if (id == MouseEvent.MOUSE_DRAGGED) {
 755                 // Cocoa dragged event has the information about which mouse
 756                 // button is being dragged. Use it to determine the peer that
 757                 // should receive the dragged event.
 758                 targetPeer = mouseDownTarget[targetIdx];
 759                 mouseClickButtons &= ~modifiers;
 760             } else if (id == MouseEvent.MOUSE_RELEASED) {
 761                 // TODO: currently, mouse released event goes to the same component
 762                 // that received corresponding mouse pressed event. For most cases,
 763                 // it's OK, however, we need to make sure that our behavior is consistent
 764                 // with 1.6 for cases where component in question have been
 765                 // hidden/removed in between of mouse pressed/released events.
 766                 targetPeer = mouseDownTarget[targetIdx];
 767 
 768                 if ((modifiers & eventButtonMask) == 0) {
 769                     mouseDownTarget[targetIdx] = null;
 770                 }
 771 
 772                 // mouseClickButtons is updated below, after MOUSE_CLICK is sent
 773             }
 774 
 775             if (targetPeer == null) {
 776                 //TODO This can happen if this window is invisible. this is correct behavior in this case?
 777                 targetPeer = this;
 778             }
 779 
 780 
 781             Point lp = targetPeer.windowToLocal(x, y, this);
 782             if (targetPeer.isEnabled()) {
 783                 MouseEvent event = new MouseEvent(targetPeer.getTarget(), id,
 784                                                   when, modifiers, lp.x, lp.y,
 785                                                   screenX, screenY, clickCount,
 786                                                   popupTrigger, button);
 787                 postEvent(event);
 788             }
 789 
 790             if (id == MouseEvent.MOUSE_RELEASED) {
 791                 if ((mouseClickButtons & eventButtonMask) != 0
 792                     && targetPeer.isEnabled()) {
 793                     postEvent(new MouseEvent(targetPeer.getTarget(),
 794                                              MouseEvent.MOUSE_CLICKED,
 795                                              when, modifiers,
 796                                              lp.x, lp.y, screenX, screenY,
 797                                              clickCount, popupTrigger, button));
 798                 }
 799                 mouseClickButtons &= ~eventButtonMask;
 800             }
 801         }
 802         notifyUpdateCursor();
 803     }
 804 
 805     private void generateMouseEnterExitEventsForComponents(long when,
 806             int button, int x, int y, int screenX, int screenY,
 807             int modifiers, int clickCount, boolean popupTrigger,
 808             LWComponentPeer targetPeer) {
 809 
 810         if (!isMouseOver || targetPeer == lastMouseEventPeer) {
 811             return;
 812         }
 813 
 814         // Generate Mouse Exit for components
 815         if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
 816             Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
 817             postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
 818                     MouseEvent.MOUSE_EXITED,
 819                     when, modifiers,
 820                     oldp.x, oldp.y, screenX, screenY,
 821                     clickCount, popupTrigger, button));
 822         }
 823         lastCommonMouseEventPeer = targetPeer;
 824         lastMouseEventPeer = targetPeer;
 825 
 826         // Generate Mouse Enter for components
 827         if (targetPeer != null && targetPeer.isEnabled()) {
 828             Point newp = targetPeer.windowToLocal(x, y, this);
 829             postEvent(new MouseEvent(targetPeer.getTarget(),
 830                     MouseEvent.MOUSE_ENTERED,
 831                     when, modifiers,
 832                     newp.x, newp.y, screenX, screenY,
 833                     clickCount, popupTrigger, button));
 834         }
 835     }
 836 
 837     public void dispatchMouseWheelEvent(long when, int x, int y, int modifiers,
 838                                         int scrollType, int scrollAmount,
 839                                         int wheelRotation, double preciseWheelRotation,
 840                                         byte[] bdata)
 841     {
 842         // TODO: could we just use the last mouse event target here?
 843         Rectangle r = getBounds();
 844         // findPeerAt() expects parent coordinates
 845         final LWComponentPeer targetPeer = findPeerAt(r.x + x, r.y + y);
 846         if (targetPeer == null || !targetPeer.isEnabled()) {
 847             return;
 848         }
 849 
 850         Point lp = targetPeer.windowToLocal(x, y, this);
 851         // TODO: fill "bdata" member of AWTEvent
 852         // TODO: screenX/screenY
 853         postEvent(new MouseWheelEvent(targetPeer.getTarget(),
 854                                       MouseEvent.MOUSE_WHEEL,
 855                                       when, modifiers,
 856                                       lp.x, lp.y,
 857                                       0, 0, /* screenX, Y */
 858                                       0 /* clickCount */, false /* popupTrigger */,
 859                                       scrollType, scrollAmount,
 860                                       wheelRotation, preciseWheelRotation));
 861     }
 862 
 863     /*
 864      * Called by the delegate when a key is pressed.
 865      */
 866     public void dispatchKeyEvent(int id, long when, int modifiers,
 867                                  int keyCode, char keyChar, int keyLocation)
 868     {
 869         LWKeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
 870         Component focusOwner = kfmPeer.getCurrentFocusOwner();
 871 
 872         if (focusOwner == null) {
 873             focusOwner = kfmPeer.getCurrentFocusedWindow();
 874             if (focusOwner == null) {
 875                 focusOwner = this.getTarget();
 876             }
 877         }
 878         postEvent(new KeyEvent(focusOwner, id, when, modifiers, keyCode, keyChar, keyLocation));
 879     }
 880 
 881 
 882     // ---- UTILITY METHODS ---- //
 883 
 884     private void postWindowStateChangedEvent(int newWindowState) {
 885         if (getTarget() instanceof Frame) {
 886             AWTAccessor.getFrameAccessor().setExtendedState(
 887                     (Frame)getTarget(), newWindowState);
 888         }
 889         WindowEvent stateChangedEvent = new WindowEvent(getTarget(),
 890                 WindowEvent.WINDOW_STATE_CHANGED,
 891                 windowState, newWindowState);
 892         postEvent(stateChangedEvent);
 893         windowState = newWindowState;
 894     }
 895 
 896     private static int getGraphicsConfigScreen(GraphicsConfiguration gc) {
 897         // TODO: this method can be implemented in a more
 898         // efficient way by forwarding to the delegate
 899         GraphicsDevice gd = gc.getDevice();
 900         GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
 901         GraphicsDevice[] gds = ge.getScreenDevices();
 902         for (int i = 0; i < gds.length; i++) {
 903             if (gds[i] == gd) {
 904                 return i;
 905             }
 906         }
 907         // Should never happen if gc is a screen device config
 908         return 0;
 909     }
 910 
 911     /*
 912      * This method is called when window's graphics config is changed from
 913      * the app code (e.g. when the window is made non-opaque) or when
 914      * the window is moved to another screen by user.
 915      *
 916      * Returns true if the graphics config has been changed, false otherwise.
 917      */
 918     private boolean setGraphicsConfig(GraphicsConfiguration gc) {
 919         synchronized (getStateLock()) {
 920             if (graphicsConfig == gc) {
 921                 return false;
 922             }
 923             // If window's graphics config is changed from the app code, the
 924             // config correspond to the same device as before; when the window
 925             // is moved by user, graphicsDevice is updated in checkIfOnNewScreen().
 926             // In either case, there's nothing to do with screenOn here
 927             graphicsConfig = gc;
 928         }
 929         // SurfaceData is replaced later in updateGraphicsData()
 930         return true;
 931     }
 932 
 933     private void checkIfOnNewScreen() {
 934         GraphicsDevice newGraphicsDevice = platformWindow.getGraphicsDevice();
 935         synchronized (getStateLock()) {
 936             if (graphicsDevice == newGraphicsDevice) {
 937                 return;
 938             }
 939             graphicsDevice = newGraphicsDevice;
 940         }
 941 
 942         // TODO: DisplayChangedListener stuff
 943         final GraphicsConfiguration newGC = newGraphicsDevice.getDefaultConfiguration();
 944 
 945         if (!setGraphicsConfig(newGC)) return;
 946 
 947         SunToolkit.executeOnEventHandlerThread(getTarget(), new Runnable() {
 948             public void run() {
 949                 AWTAccessor.getComponentAccessor().setGraphicsConfiguration(getTarget(), newGC);
 950             }
 951         });
 952     }
 953 
 954     /*
 955      * May be called by delegate to provide SD to Java2D code.
 956      */
 957     public SurfaceData getSurfaceData() {
 958         synchronized (surfaceDataLock) {
 959             return surfaceData;
 960         }
 961     }
 962 
 963     private void replaceSurfaceData() {
 964         replaceSurfaceData(true);
 965     }
 966 
 967     private void replaceSurfaceData(final boolean blit) {
 968         synchronized (surfaceDataLock) {
 969             final SurfaceData oldData = getSurfaceData();
 970             surfaceData = platformWindow.replaceSurfaceData();
 971             final Rectangle size = getSize();
 972             if (getSurfaceData() != null && oldData != getSurfaceData()) {
 973                 clearBackground(size.width, size.height);
 974             }
 975 
 976             if (blit) {
 977                 blitSurfaceData(oldData, getSurfaceData());
 978             }
 979 
 980             if (oldData != null && oldData != getSurfaceData()) {
 981                 // TODO: drop oldData for D3D/WGL pipelines
 982                 // This can only happen when this peer is being created
 983                 oldData.flush();
 984             }
 985         }
 986     }
 987 
 988     private void blitSurfaceData(final SurfaceData src, final SurfaceData dst) {
 989         //TODO blit. proof-of-concept
 990         if (src != dst && src != null && dst != null
 991             && !(dst instanceof NullSurfaceData)
 992             && !(src instanceof NullSurfaceData)
 993             && src.getSurfaceType().equals(dst.getSurfaceType())) {
 994             final Rectangle size = getSize();
 995             final Blit blit = Blit.locate(src.getSurfaceType(),
 996                                           CompositeType.Src,
 997                                           dst.getSurfaceType());
 998             if (blit != null) {
 999                 blit.Blit(src, dst, AlphaComposite.Src,
1000                           getRegion(), 0, 0, 0, 0, size.width, size.height);
1001             }
1002         }
1003     }
1004 
1005     /**
1006      * Request the window insets from the delegate and compares it with the
1007      * current one. This method is mostly called by the delegate, e.g. when the
1008      * window state is changed and insets should be recalculated.
1009      * <p/>
1010      * This method may be called on the toolkit thread.
1011      */
1012     public final boolean updateInsets(final Insets newInsets) {
1013         synchronized (getStateLock()) {
1014             if (insets.equals(newInsets)) {
1015                 return false;
1016             }
1017             insets = newInsets;
1018         }
1019         return true;
1020     }
1021 
1022     public static LWWindowPeer getWindowUnderCursor() {
1023         return lastCommonMouseEventPeer != null ? lastCommonMouseEventPeer.getWindowPeerOrSelf() : null;
1024     }
1025 
1026     public static LWComponentPeer<?, ?> getPeerUnderCursor() {
1027         return lastCommonMouseEventPeer;
1028     }
1029 
1030     /*
1031      * Requests platform to set native focus on a frame/dialog.
1032      * In case of a simple window, triggers appropriate java focus change.
1033      */
1034     public boolean requestWindowFocus(CausedFocusEvent.Cause cause) {
1035         if (focusLog.isLoggable(PlatformLogger.FINE)) {
1036             focusLog.fine("requesting native focus to " + this);
1037         }
1038 
1039         if (!focusAllowedFor()) {
1040             focusLog.fine("focus is not allowed");
1041             return false;
1042         }
1043 
1044         if (platformWindow.rejectFocusRequest(cause)) {
1045             return false;
1046         }
1047 
1048         Window currentActive = KeyboardFocusManager.
1049             getCurrentKeyboardFocusManager().getActiveWindow();
1050 
1051         Window opposite = LWKeyboardFocusManagerPeer.getInstance().
1052             getCurrentFocusedWindow();
1053 
1054         // Make the owner active window.
1055         if (isSimpleWindow()) {
1056             LWWindowPeer owner = getOwnerFrameDialog(this);
1057 
1058             // If owner is not natively active, request native
1059             // activation on it w/o sending events up to java.
1060             if (owner != null && !owner.platformWindow.isActive()) {
1061                 if (focusLog.isLoggable(PlatformLogger.FINE)) {
1062                     focusLog.fine("requesting native focus to the owner " + owner);
1063                 }
1064                 LWWindowPeer currentActivePeer = (currentActive != null ?
1065                     (LWWindowPeer)currentActive.getPeer() : null);
1066 
1067                 // Ensure the opposite is natively active and suppress sending events.
1068                 if (currentActivePeer != null && currentActivePeer.platformWindow.isActive()) {
1069                     if (focusLog.isLoggable(PlatformLogger.FINE)) {
1070                         focusLog.fine("the opposite is " + currentActivePeer);
1071                     }
1072                     currentActivePeer.skipNextFocusChange = true;
1073                 }
1074                 owner.skipNextFocusChange = true;
1075 
1076                 owner.platformWindow.requestWindowFocus();
1077             }
1078 
1079             // DKFM will synthesize all the focus/activation events correctly.
1080             changeFocusedWindow(true, opposite);
1081             return true;
1082 
1083         // In case the toplevel is active but not focused, change focus directly,
1084         // as requesting native focus on it will not have effect.
1085         } else if (getTarget() == currentActive && !getTarget().hasFocus()) {
1086 
1087             changeFocusedWindow(true, opposite);
1088             return true;
1089         }
1090 
1091         return platformWindow.requestWindowFocus();
1092     }
1093 
1094     protected boolean focusAllowedFor() {
1095         Window window = getTarget();
1096         // TODO: check if modal blocked
1097         return window.isVisible() && window.isEnabled() && isFocusableWindow();
1098     }
1099 
1100     private boolean isFocusableWindow() {
1101         boolean focusable = getTarget().isFocusableWindow();
1102         if (isSimpleWindow()) {
1103             LWWindowPeer ownerPeer = getOwnerFrameDialog(this);
1104             if (ownerPeer == null) {
1105                 return false;
1106             }
1107             return focusable && ownerPeer.getTarget().isFocusableWindow();
1108         }
1109         return focusable;
1110     }
1111 
1112     public boolean isSimpleWindow() {
1113         Window window = getTarget();
1114         return !(window instanceof Dialog || window instanceof Frame);
1115     }
1116    
1117     @Override
1118     public void emulateActivation(boolean activate) {
1119         changeFocusedWindow(activate, null);
1120     }
1121 
1122     /*
1123      * Changes focused window on java level.
1124      */
1125     protected void changeFocusedWindow(boolean becomesFocused, Window opposite) {
1126         if (focusLog.isLoggable(PlatformLogger.FINE)) {
1127             focusLog.fine((becomesFocused?"gaining":"loosing") + " focus window: " + this);
1128         }
1129         if (skipNextFocusChange) {
1130             focusLog.fine("skipping focus change");
1131             skipNextFocusChange = false;
1132             return;
1133         }
1134         if (!isFocusableWindow() && becomesFocused) {
1135             focusLog.fine("the window is not focusable");
1136             return;
1137         }
1138         if (becomesFocused) {
1139             synchronized (getPeerTreeLock()) {
1140                 if (blocker != null) {
1141                     if (focusLog.isLoggable(PlatformLogger.FINEST)) {
1142                         focusLog.finest("the window is blocked by " + blocker);
1143                     }
1144                     return;
1145                 }
1146             }
1147         }
1148 
1149         // Note, the method is not called:
1150         // - when the opposite (gaining focus) window is an owned/owner window.
1151         // - for a simple window in any case.
1152         if (!becomesFocused &&
1153             (isGrabbing() || getOwnerFrameDialog(grabbingWindow) == this))
1154         {
1155             focusLog.fine("ungrabbing on " + grabbingWindow);
1156             // ungrab a simple window if its owner looses activation.
1157             grabbingWindow.ungrab();
1158         }
1159 
1160         KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
1161         kfmPeer.setCurrentFocusedWindow(becomesFocused ? getTarget() : null);
1162 
1163         int eventID = becomesFocused ? WindowEvent.WINDOW_GAINED_FOCUS : WindowEvent.WINDOW_LOST_FOCUS;
1164         WindowEvent windowEvent = new TimedWindowEvent(getTarget(), eventID, opposite, System.currentTimeMillis());
1165 
1166         // TODO: wrap in SequencedEvent
1167         postEvent(windowEvent);
1168     }
1169 
1170     static LWWindowPeer getOwnerFrameDialog(LWWindowPeer peer) {
1171         Window owner = (peer != null ? peer.getTarget().getOwner() : null);
1172         while (owner != null && !(owner instanceof Frame || owner instanceof Dialog)) {
1173             owner = owner.getOwner();
1174         }
1175         return owner != null ? (LWWindowPeer)owner.getPeer() : null;
1176     }
1177 
1178     /**
1179      * Returns the foremost modal blocker of this window, or null.
1180      */
1181     public LWWindowPeer getBlocker() {
1182         synchronized (getPeerTreeLock()) {
1183             LWWindowPeer blocker = this.blocker;
1184             if (blocker == null) {
1185                 return null;
1186             }
1187             while (blocker.blocker != null) {
1188                 blocker = blocker.blocker;
1189             }
1190             return blocker;
1191         }
1192     }
1193 
1194     public void enterFullScreenMode() {
1195         platformWindow.enterFullScreenMode();
1196     }
1197 
1198     public void exitFullScreenMode() {
1199         platformWindow.exitFullScreenMode();
1200     }
1201 
1202     public long getLayerPtr() {
1203         return getPlatformWindow().getLayerPtr();
1204     }
1205     
1206     @Override
1207     public void grabFocus() {
1208         grab();
1209     }
1210 
1211     @Override
1212     public void ungrabFocus(boolean postEvent) {
1213         ungrab(postEvent);
1214     }
1215     
1216     void grab() {
1217         if (grabbingWindow != null && !isGrabbing()) {
1218             grabbingWindow.ungrab();
1219         }
1220         grabbingWindow = this;
1221     } 
1222 
1223     final void ungrab(boolean doPost) {
1224         if (isGrabbing()) {
1225             grabbingWindow = null;
1226             if (doPost) {
1227                 postEvent(new UngrabEvent(getTarget()));
1228             }
1229         }
1230     }
1231 
1232     void ungrab() {
1233         ungrab(true);
1234     }
1235 
1236     private boolean isGrabbing() {
1237         return this == grabbingWindow;
1238     }
1239 
1240     public PeerType getPeerType() {
1241         return peerType;
1242     }
1243 
1244     @Override
1245     public String toString() {
1246         return super.toString() + " [target is " + getTarget() + "]";
1247     }
1248 }