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