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