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 27 package sun.lwawt; 28 29 import java.awt.*; 30 31 import java.awt.dnd.DropTarget; 32 import java.awt.dnd.peer.DropTargetPeer; 33 import java.awt.event.*; 34 35 import java.awt.image.ColorModel; 36 import java.awt.image.ImageObserver; 37 import java.awt.image.ImageProducer; 38 import java.awt.image.VolatileImage; 39 40 import java.awt.peer.ComponentPeer; 41 import java.awt.peer.ContainerPeer; 42 43 import java.awt.peer.KeyboardFocusManagerPeer; 44 import java.util.concurrent.atomic.AtomicBoolean; 45 import java.lang.reflect.Field; 46 import java.security.AccessController; 47 import java.security.PrivilegedAction; 48 49 import sun.awt.*; 50 51 import sun.awt.event.IgnorePaintEvent; 52 53 import sun.awt.image.SunVolatileImage; 54 import sun.awt.image.ToolkitImage; 55 56 import sun.java2d.SunGraphics2D; 57 import sun.java2d.opengl.OGLRenderQueue; 58 import sun.java2d.pipe.Region; 59 60 import sun.util.logging.PlatformLogger; 61 62 import javax.swing.JComponent; 63 import javax.swing.SwingUtilities; 64 import javax.swing.RepaintManager; 65 66 import sun.lwawt.macosx.CDropTarget; 67 68 import com.sun.java.swing.SwingUtilities3; 69 70 public abstract class LWComponentPeer<T extends Component, D extends JComponent> 71 implements ComponentPeer, DropTargetPeer 72 { 73 private static final PlatformLogger focusLog = PlatformLogger.getLogger("sun.lwawt.focus.LWComponentPeer"); 74 75 // State lock is to be used for modifications to this 76 // peer's fields (e.g. bounds, background, font, etc.) 77 // It should be the last lock in the lock chain 78 private final Object stateLock = 79 new StringBuilder("LWComponentPeer.stateLock"); 80 81 // The lock to operate with the peers hierarchy. AWT tree 82 // lock is not used as there are many peers related ops 83 // to be done on the toolkit thread, and we don't want to 84 // depend on a public lock on this thread 85 private static final Object peerTreeLock = 86 new StringBuilder("LWComponentPeer.peerTreeLock"); 87 88 private final T target; 89 90 /** 91 * Container peer. It may not be the peer of the target's direct parent, for 92 * example, in the case of hw/lw mixing. However, let's skip this scenario 93 * for the time being. We also assume the container peer is not null, which 94 * might also be false if addNotify() is called for a component outside of 95 * the hierarchy. The exception is LWWindowPeers: their containers are 96 * always null 97 */ 98 private final LWContainerPeer containerPeer; 99 100 /** 101 * Handy reference to the top-level window peer. Window peer is borrowed 102 * from the containerPeer in constructor, and should also be updated when 103 * the component is reparented to another container 104 */ 105 private final LWWindowPeer windowPeer; 106 107 private final AtomicBoolean disposed = new AtomicBoolean(false); 108 109 // Bounds are relative to parent peer 110 private final Rectangle bounds = new Rectangle(); 111 private Region region; 112 113 // Component state. Should be accessed under the state lock 114 private boolean visible = false; 115 private boolean enabled = true; 116 117 private Color background; 118 private Color foreground; 119 private Font font; 120 121 /** 122 * Paint area to coalesce all the paint events and store the target dirty 123 * area. 124 */ 125 private final RepaintArea targetPaintArea; 126 127 // private volatile boolean paintPending; 128 private volatile boolean isLayouting; 129 130 private final D delegate; 131 private Container delegateContainer; 132 private Component delegateDropTarget; 133 private final Object dropTargetLock = new Object(); 134 135 private int fNumDropTargets = 0; 136 private CDropTarget fDropTarget = null; 137 138 private final PlatformComponent platformComponent; 139 140 /** 141 * Character with reasonable value between the minimum width and maximum. 142 */ 143 static final char WIDE_CHAR = '0'; 144 145 /** 146 * The back buffer provide user with a BufferStrategy. 147 */ 148 private Image backBuffer; 149 150 private final class DelegateContainer extends Container { 151 { 152 enableEvents(0xFFFFFFFF); 153 } 154 155 DelegateContainer() { 156 super(); 157 } 158 159 @Override 160 public boolean isLightweight() { 161 return false; 162 } 163 164 @Override 165 public Point getLocation() { 166 return getLocationOnScreen(); 167 } 168 169 @Override 170 public Point getLocationOnScreen() { 171 return LWComponentPeer.this.getLocationOnScreen(); 172 } 173 174 @Override 175 public int getX() { 176 return getLocation().x; 177 } 178 179 @Override 180 public int getY() { 181 return getLocation().y; 182 } 183 } 184 185 public LWComponentPeer(T target, PlatformComponent platformComponent) { 186 targetPaintArea = new LWRepaintArea(); 187 this.target = target; 188 this.platformComponent = platformComponent; 189 190 // Container peer is always null for LWWindowPeers, so 191 // windowPeer is always null for them as well. On the other 192 // hand, LWWindowPeer shouldn't use windowPeer at all 193 final Container container = SunToolkit.getNativeContainer(target); 194 containerPeer = (LWContainerPeer) LWToolkit.targetToPeer(container); 195 windowPeer = containerPeer != null ? containerPeer.getWindowPeerOrSelf() 196 : null; 197 // don't bother about z-order here as updateZOrder() 198 // will be called from addNotify() later anyway 199 if (containerPeer != null) { 200 containerPeer.addChildPeer(this); 201 } 202 203 // the delegate must be created after the target is set 204 AWTEventListener toolkitListener = null; 205 synchronized (Toolkit.getDefaultToolkit()) { 206 try { 207 toolkitListener = getToolkitAWTEventListener(); 208 setToolkitAWTEventListener(null); 209 210 synchronized (getDelegateLock()) { 211 delegate = createDelegate(); 212 if (delegate != null) { 213 delegate.setVisible(false); 214 delegateContainer = new DelegateContainer(); 215 delegateContainer.add(delegate); 216 delegateContainer.addNotify(); 217 delegate.addNotify(); 218 resetColorsAndFont(delegate); 219 delegate.setOpaque(true); 220 } else { 221 return; 222 } 223 } 224 225 } finally { 226 setToolkitAWTEventListener(toolkitListener); 227 } 228 229 // todo swing: later on we will probably have one global RM 230 SwingUtilities3.setDelegateRepaintManager(delegate, new RepaintManager() { 231 @Override 232 public void addDirtyRegion(final JComponent c, final int x, final int y, final int w, final int h) { 233 repaintPeer(SwingUtilities.convertRectangle( 234 c, new Rectangle(x, y, w, h), getDelegate())); 235 } 236 }); 237 } 238 } 239 240 /** 241 * This method must be called under Toolkit.getDefaultToolkit() lock 242 * and followed by setToolkitAWTEventListener() 243 */ 244 protected final AWTEventListener getToolkitAWTEventListener() { 245 return AccessController.doPrivileged(new PrivilegedAction<AWTEventListener>() { 246 public AWTEventListener run() { 247 Toolkit toolkit = Toolkit.getDefaultToolkit(); 248 try { 249 Field field = Toolkit.class.getDeclaredField("eventListener"); 250 field.setAccessible(true); 251 return (AWTEventListener) field.get(toolkit); 252 } catch (Exception e) { 253 throw new InternalError(e.toString()); 254 } 255 } 256 }); 257 } 258 259 protected final void setToolkitAWTEventListener(final AWTEventListener listener) { 260 AccessController.doPrivileged(new PrivilegedAction<Void>() { 261 public Void run() { 262 Toolkit toolkit = Toolkit.getDefaultToolkit(); 263 try { 264 Field field = Toolkit.class.getDeclaredField("eventListener"); 265 field.setAccessible(true); 266 field.set(toolkit, listener); 267 } catch (Exception e) { 268 throw new InternalError(e.toString()); 269 } 270 return null; 271 } 272 }); 273 } 274 275 /** 276 * This method is called under getDelegateLock(). 277 * Overridden in subclasses. 278 */ 279 protected D createDelegate() { 280 return null; 281 } 282 283 protected final D getDelegate() { 284 return delegate; 285 } 286 287 protected Component getDelegateFocusOwner() { 288 return getDelegate(); 289 } 290 291 /** 292 * Initializes this peer. The call to initialize() is not placed to 293 * LWComponentPeer ctor to let the subclass ctor to finish completely first. 294 * Instead, it's the LWToolkit object who is responsible for initialization. 295 * Note that we call setVisible() at the end of initialization. 296 */ 297 public final void initialize() { 298 platformComponent.initialize(getPlatformWindow()); 299 initializeImpl(); 300 setVisible(target.isVisible()); 301 } 302 303 /** 304 * Fetching general properties from the target. Should be overridden in 305 * subclasses to initialize specific peers properties. 306 */ 307 void initializeImpl() { 308 setBackground(target.getBackground()); 309 setForeground(target.getForeground()); 310 setFont(target.getFont()); 311 setBounds(target.getBounds()); 312 setEnabled(target.isEnabled()); 313 } 314 315 private static void resetColorsAndFont(final Container c) { 316 c.setBackground(null); 317 c.setForeground(null); 318 c.setFont(null); 319 for (int i = 0; i < c.getComponentCount(); i++) { 320 resetColorsAndFont((Container) c.getComponent(i)); 321 } 322 } 323 324 final Object getStateLock() { 325 return stateLock; 326 } 327 328 /** 329 * Synchronize all operations with the Swing delegates under AWT tree lock, 330 * using a new separate lock to synchronize access to delegates may lead 331 * deadlocks. Think of it as a 'virtual EDT'. 332 * 333 * @return DelegateLock 334 */ 335 final Object getDelegateLock() { 336 return getTarget().getTreeLock(); 337 } 338 339 protected static final Object getPeerTreeLock() { 340 return peerTreeLock; 341 } 342 343 public final T getTarget() { 344 return target; 345 } 346 347 // Just a helper method 348 // Returns the window peer or null if this is a window peer 349 protected final LWWindowPeer getWindowPeer() { 350 return windowPeer; 351 } 352 353 // Returns the window peer or 'this' if this is a window peer 354 protected LWWindowPeer getWindowPeerOrSelf() { 355 return getWindowPeer(); 356 } 357 358 // Just a helper method 359 protected final LWContainerPeer getContainerPeer() { 360 return containerPeer; 361 } 362 363 public PlatformWindow getPlatformWindow() { 364 LWWindowPeer windowPeer = getWindowPeer(); 365 return windowPeer.getPlatformWindow(); 366 } 367 368 protected AppContext getAppContext() { 369 return SunToolkit.targetToAppContext(getTarget()); 370 } 371 372 // ---- PEER METHODS ---- // 373 374 @Override 375 public Toolkit getToolkit() { 376 return LWToolkit.getLWToolkit(); 377 } 378 379 // Just a helper method 380 public LWToolkit getLWToolkit() { 381 return LWToolkit.getLWToolkit(); 382 } 383 384 @Override 385 public final void dispose() { 386 if (disposed.compareAndSet(false, true)) { 387 disposeImpl(); 388 } 389 } 390 391 protected void disposeImpl() { 392 destroyBuffers(); 393 LWContainerPeer cp = getContainerPeer(); 394 if (cp != null) { 395 cp.removeChildPeer(this); 396 } 397 platformComponent.dispose(); 398 LWToolkit.targetDisposedPeer(getTarget(), this); 399 } 400 401 public final boolean isDisposed() { 402 return disposed.get(); 403 } 404 405 /* 406 * GraphicsConfiguration is borrowed from the parent peer. The 407 * return value must not be null. 408 * 409 * Overridden in LWWindowPeer. 410 */ 411 @Override 412 public GraphicsConfiguration getGraphicsConfiguration() { 413 // Don't check windowPeer for null as it can only happen 414 // for windows, but this method is overridden in 415 // LWWindowPeer and doesn't call super() 416 return getWindowPeer().getGraphicsConfiguration(); 417 } 418 419 420 // Just a helper method 421 public final LWGraphicsConfig getLWGC() { 422 return (LWGraphicsConfig) getGraphicsConfiguration(); 423 } 424 425 /* 426 * Overridden in LWWindowPeer to replace its surface 427 * data and back buffer. 428 */ 429 @Override 430 public boolean updateGraphicsData(GraphicsConfiguration gc) { 431 // TODO: not implemented 432 // throw new RuntimeException("Has not been implemented yet."); 433 return false; 434 } 435 436 @Override 437 public Graphics getGraphics() { 438 final Graphics g = getOnscreenGraphics(); 439 if (g != null) { 440 synchronized (getPeerTreeLock()){ 441 applyConstrain(g); 442 } 443 } 444 return g; 445 } 446 447 /* 448 * Peer Graphics is borrowed from the parent peer, while 449 * foreground and background colors and font are specific to 450 * this peer. 451 */ 452 public final Graphics getOnscreenGraphics() { 453 final LWWindowPeer wp = getWindowPeerOrSelf(); 454 return wp.getOnscreenGraphics(getForeground(), getBackground(), 455 getFont()); 456 457 } 458 459 private void applyConstrain(final Graphics g) { 460 final SunGraphics2D sg2d = (SunGraphics2D) g; 461 final Rectangle size = localToWindow(getSize()); 462 sg2d.constrain(size.x, size.y, size.width, size.height, getVisibleRegion()); 463 } 464 465 public Region getVisibleRegion() { 466 return computeVisibleRect(this, getRegion()); 467 } 468 469 static final Region computeVisibleRect(LWComponentPeer c, Region region) { 470 final LWContainerPeer p = c.getContainerPeer(); 471 if (p != null) { 472 final Rectangle r = c.getBounds(); 473 region = region.getTranslatedRegion(r.x, r.y); 474 region = region.getIntersection(p.getRegion()); 475 region = region.getIntersection(p.getContentSize()); 476 region = p.cutChildren(region, c); 477 region = computeVisibleRect(p, region); 478 region = region.getTranslatedRegion(-r.x, -r.y); 479 } 480 return region; 481 } 482 483 @Override 484 public ColorModel getColorModel() { 485 // Is it a correct implementation? 486 return getGraphicsConfiguration().getColorModel(); 487 } 488 489 public boolean isTranslucent() { 490 // Translucent windows of the top level are supported only 491 return false; 492 } 493 494 @Override 495 public final void createBuffers(int numBuffers, BufferCapabilities caps) 496 throws AWTException { 497 getLWGC().assertOperationSupported(numBuffers, caps); 498 final Image buffer = getLWGC().createBackBuffer(this); 499 synchronized (getStateLock()) { 500 backBuffer = buffer; 501 } 502 } 503 504 @Override 505 public final Image getBackBuffer() { 506 synchronized (getStateLock()) { 507 if (backBuffer != null) { 508 return backBuffer; 509 } 510 } 511 throw new IllegalStateException("Buffers have not been created"); 512 } 513 514 @Override 515 public final void flip(int x1, int y1, int x2, int y2, 516 BufferCapabilities.FlipContents flipAction) { 517 getLWGC().flip(this, getBackBuffer(), x1, y1, x2, y2, flipAction); 518 } 519 520 @Override 521 public final void destroyBuffers() { 522 final Image oldBB; 523 synchronized (getStateLock()) { 524 oldBB = backBuffer; 525 backBuffer = null; 526 } 527 getLWGC().destroyBackBuffer(oldBB); 528 } 529 530 // Helper method 531 public void setBounds(Rectangle r) { 532 setBounds(r.x, r.y, r.width, r.height, SET_BOUNDS); 533 } 534 535 /** 536 * This method could be called on the toolkit thread. 537 */ 538 @Override 539 public void setBounds(int x, int y, int w, int h, int op) { 540 setBounds(x, y, w, h, op, true, false); 541 } 542 543 protected void setBounds(int x, int y, int w, int h, int op, boolean notify, 544 final boolean updateTarget) { 545 Rectangle oldBounds; 546 synchronized (getStateLock()) { 547 oldBounds = new Rectangle(bounds); 548 if ((op & (SET_LOCATION | SET_BOUNDS)) != 0) { 549 bounds.x = x; 550 bounds.y = y; 551 } 552 if ((op & (SET_SIZE | SET_BOUNDS)) != 0) { 553 bounds.width = w; 554 bounds.height = h; 555 } 556 } 557 boolean moved = (oldBounds.x != x) || (oldBounds.y != y); 558 boolean resized = (oldBounds.width != w) || (oldBounds.height != h); 559 if (!moved && !resized) { 560 return; 561 } 562 final D delegate = getDelegate(); 563 if (delegate != null) { 564 synchronized (getDelegateLock()) { 565 delegateContainer.setBounds(0, 0, w, h); 566 delegate.setBounds(delegateContainer.getBounds()); 567 // TODO: the following means that the delegateContainer NEVER gets validated. That's WRONG! 568 delegate.validate(); 569 } 570 } 571 572 final Point locationInWindow = localToWindow(0, 0); 573 platformComponent.setBounds(locationInWindow.x, locationInWindow.y, w, 574 h); 575 if (notify) { 576 repaintOldNewBounds(oldBounds); 577 if (resized) { 578 handleResize(w, h, updateTarget); 579 } 580 if (moved) { 581 handleMove(x, y, updateTarget); 582 } 583 } 584 } 585 586 public final Rectangle getBounds() { 587 synchronized (getStateLock()) { 588 // Return a copy to prevent subsequent modifications 589 return bounds.getBounds(); 590 } 591 } 592 593 public final Rectangle getSize() { 594 synchronized (getStateLock()) { 595 // Return a copy to prevent subsequent modifications 596 return new Rectangle(bounds.width, bounds.height); 597 } 598 } 599 600 @Override 601 public Point getLocationOnScreen() { 602 Point windowLocation = getWindowPeer().getLocationOnScreen(); 603 Point locationInWindow = localToWindow(0, 0); 604 return new Point(windowLocation.x + locationInWindow.x, 605 windowLocation.y + locationInWindow.y); 606 } 607 608 /** 609 * Returns the cursor of the peer, which is cursor of the target by default, 610 * but peer can override this behavior. 611 * 612 * @param p Point relative to the peer. 613 * @return Cursor of the peer or null if default cursor should be used. 614 */ 615 protected Cursor getCursor(final Point p) { 616 return getTarget().getCursor(); 617 } 618 619 @Override 620 public void setBackground(final Color c) { 621 final Color oldBg = getBackground(); 622 if (oldBg == c || (oldBg != null && oldBg.equals(c))) { 623 return; 624 } 625 synchronized (getStateLock()) { 626 background = c; 627 } 628 final D delegate = getDelegate(); 629 if (delegate != null) { 630 synchronized (getDelegateLock()) { 631 // delegate will repaint the target 632 delegate.setBackground(c); 633 } 634 } else { 635 repaintPeer(); 636 } 637 } 638 639 public final Color getBackground() { 640 synchronized (getStateLock()) { 641 return background; 642 } 643 } 644 645 @Override 646 public void setForeground(final Color c) { 647 final Color oldFg = getForeground(); 648 if (oldFg == c || (oldFg != null && oldFg.equals(c))) { 649 return; 650 } 651 synchronized (getStateLock()) { 652 foreground = c; 653 } 654 final D delegate = getDelegate(); 655 if (delegate != null) { 656 synchronized (getDelegateLock()) { 657 // delegate will repaint the target 658 delegate.setForeground(c); 659 } 660 } else { 661 repaintPeer(); 662 } 663 } 664 665 protected final Color getForeground() { 666 synchronized (getStateLock()) { 667 return foreground; 668 } 669 } 670 671 @Override 672 public void setFont(final Font f) { 673 final Font oldF = getFont(); 674 if (oldF == f || (oldF != null && oldF.equals(f))) { 675 return; 676 } 677 synchronized (getStateLock()) { 678 font = f; 679 } 680 final D delegate = getDelegate(); 681 if (delegate != null) { 682 synchronized (getDelegateLock()) { 683 // delegate will repaint the target 684 delegate.setFont(f); 685 } 686 } else { 687 repaintPeer(); 688 } 689 } 690 691 protected final Font getFont() { 692 synchronized (getStateLock()) { 693 return font; 694 } 695 } 696 697 @Override 698 public FontMetrics getFontMetrics(final Font f) { 699 // Borrow the metrics from the top-level window 700 // return getWindowPeer().getFontMetrics(f); 701 // Obtain the metrics from the offscreen window where this peer is 702 // mostly drawn to. 703 // TODO: check for "use platform metrics" settings 704 final Graphics g = getOnscreenGraphics(); 705 if (g != null) { 706 try { 707 return g.getFontMetrics(f); 708 } finally { 709 g.dispose(); 710 } 711 } 712 synchronized (getDelegateLock()) { 713 return delegateContainer.getFontMetrics(f); 714 } 715 } 716 717 @Override 718 public void setEnabled(final boolean e) { 719 boolean status = e; 720 final LWComponentPeer cp = getContainerPeer(); 721 if (cp != null) { 722 status &= cp.isEnabled(); 723 } 724 synchronized (getStateLock()) { 725 if (enabled == status) { 726 return; 727 } 728 enabled = status; 729 } 730 731 final D delegate = getDelegate(); 732 733 if (delegate != null) { 734 synchronized (getDelegateLock()) { 735 delegate.setEnabled(status); 736 } 737 } else { 738 repaintPeer(); 739 } 740 } 741 742 // Helper method 743 public final boolean isEnabled() { 744 synchronized (getStateLock()) { 745 return enabled; 746 } 747 } 748 749 @Override 750 public void setVisible(final boolean v) { 751 synchronized (getStateLock()) { 752 if (visible == v) { 753 return; 754 } 755 visible = v; 756 } 757 setVisibleImpl(v); 758 } 759 760 protected void setVisibleImpl(final boolean v) { 761 final D delegate = getDelegate(); 762 763 if (delegate != null) { 764 synchronized (getDelegateLock()) { 765 delegate.setVisible(v); 766 } 767 } 768 if (visible) { 769 repaintPeer(); 770 } else { 771 repaintParent(getBounds()); 772 } 773 } 774 775 // Helper method 776 public final boolean isVisible() { 777 synchronized (getStateLock()) { 778 return visible; 779 } 780 } 781 782 @Override 783 public void paint(final Graphics g) { 784 getTarget().paint(g); 785 } 786 787 @Override 788 public void print(final Graphics g) { 789 getTarget().print(g); 790 } 791 792 @Override 793 public void reparent(ContainerPeer newContainer) { 794 // TODO: not implemented 795 throw new UnsupportedOperationException("ComponentPeer.reparent()"); 796 } 797 798 @Override 799 public boolean isReparentSupported() { 800 // TODO: not implemented 801 return false; 802 } 803 804 @Override 805 public void setZOrder(ComponentPeer above) { 806 LWContainerPeer cp = getContainerPeer(); 807 // Don't check containerPeer for null as it can only happen 808 // for windows, but this method is overridden in 809 // LWWindowPeer and doesn't call super() 810 cp.setChildPeerZOrder(this, (LWComponentPeer) above); 811 } 812 813 @Override 814 public void coalescePaintEvent(PaintEvent e) { 815 if (!(e instanceof IgnorePaintEvent)) { 816 Rectangle r = e.getUpdateRect(); 817 if ((r != null) && !r.isEmpty()) { 818 targetPaintArea.add(r, e.getID()); 819 } 820 } 821 } 822 823 /* 824 * Should be overridden in subclasses which use complex Swing components. 825 */ 826 @Override 827 public void layout() { 828 // TODO: not implemented 829 } 830 831 @Override 832 public boolean isObscured() { 833 // TODO: not implemented 834 return false; 835 } 836 837 @Override 838 public boolean canDetermineObscurity() { 839 // TODO: not implemented 840 return false; 841 } 842 843 /** 844 * Determines the preferred size of the component. By default forwards the 845 * request to the Swing helper component. Should be overridden in subclasses 846 * if required. 847 */ 848 @Override 849 public Dimension getPreferredSize() { 850 final Dimension size; 851 synchronized (getDelegateLock()) { 852 size = getDelegate().getPreferredSize(); 853 } 854 return validateSize(size); 855 } 856 857 /** 858 * Determines the minimum size of the component. By default forwards the 859 * request to the Swing helper component. Should be overridden in subclasses 860 * if required. 861 */ 862 @Override 863 public Dimension getMinimumSize() { 864 final Dimension size; 865 synchronized (getDelegateLock()) { 866 size = getDelegate().getMinimumSize(); 867 } 868 return validateSize(size); 869 } 870 871 /** 872 * In some situations delegates can return empty minimum/preferred size. 873 * (For example: empty JLabel, etc), but awt components never should be 874 * empty. In the XPeers or WPeers we use some magic constants, but here we 875 * try to use something more useful, 876 */ 877 private Dimension validateSize(final Dimension size) { 878 if (size.width == 0 || size.height == 0) { 879 final FontMetrics fm = getFontMetrics(getFont()); 880 size.width = fm.charWidth(WIDE_CHAR); 881 size.height = fm.getHeight(); 882 } 883 return size; 884 } 885 886 @Override 887 public void updateCursorImmediately() { 888 getLWToolkit().getCursorManager().updateCursor(); 889 } 890 891 @Override 892 public boolean isFocusable() { 893 // Overridden in focusable subclasses like buttons 894 return false; 895 } 896 897 @Override 898 public boolean requestFocus(Component lightweightChild, boolean temporary, 899 boolean focusedWindowChangeAllowed, long time, 900 CausedFocusEvent.Cause cause) 901 { 902 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 903 focusLog.finest("lightweightChild=" + lightweightChild + ", temporary=" + temporary + 904 ", focusedWindowChangeAllowed=" + focusedWindowChangeAllowed + 905 ", time= " + time + ", cause=" + cause); 906 } 907 if (LWKeyboardFocusManagerPeer.processSynchronousLightweightTransfer( 908 getTarget(), lightweightChild, temporary, 909 focusedWindowChangeAllowed, time)) { 910 return true; 911 } 912 913 int result = LWKeyboardFocusManagerPeer.shouldNativelyFocusHeavyweight( 914 getTarget(), lightweightChild, temporary, 915 focusedWindowChangeAllowed, time, cause); 916 switch (result) { 917 case LWKeyboardFocusManagerPeer.SNFH_FAILURE: 918 return false; 919 case LWKeyboardFocusManagerPeer.SNFH_SUCCESS_PROCEED: 920 Window parentWindow = SunToolkit.getContainingWindow(getTarget()); 921 if (parentWindow == null) { 922 focusLog.fine("request rejected, parentWindow is null"); 923 LWKeyboardFocusManagerPeer.removeLastFocusRequest(getTarget()); 924 return false; 925 } 926 LWWindowPeer parentPeer = (LWWindowPeer) parentWindow.getPeer(); 927 if (parentPeer == null) { 928 focusLog.fine("request rejected, parentPeer is null"); 929 LWKeyboardFocusManagerPeer.removeLastFocusRequest(getTarget()); 930 return false; 931 } 932 933 // A fix for 7145768. Ensure the parent window is currently natively focused. 934 // The more evident place to perform this check is in KFM.shouldNativelyFocusHeavyweight, 935 // however that is the shared code and this particular problem's reproducibility has 936 // platform specifics. So, it was decided to narrow down the fix to lwawt (OSX) in 937 // current release. TODO: consider fixing it in the shared code. 938 if (!focusedWindowChangeAllowed) { 939 LWWindowPeer decoratedPeer = parentPeer.isSimpleWindow() ? 940 LWWindowPeer.getOwnerFrameDialog(parentPeer) : parentPeer; 941 942 if (decoratedPeer == null || !decoratedPeer.getPlatformWindow().isActive()) { 943 if (focusLog.isLoggable(PlatformLogger.Level.FINE)) { 944 focusLog.fine("request rejected, focusedWindowChangeAllowed==false, " + 945 "decoratedPeer is inactive: " + decoratedPeer); 946 } 947 LWKeyboardFocusManagerPeer.removeLastFocusRequest(getTarget()); 948 return false; 949 } 950 } 951 952 boolean res = parentPeer.requestWindowFocus(cause); 953 // If parent window can be made focused and has been made focused (synchronously) 954 // then we can proceed with children, otherwise we retreat 955 if (!res || !parentWindow.isFocused()) { 956 if (focusLog.isLoggable(PlatformLogger.Level.FINE)) { 957 focusLog.fine("request rejected, res= " + res + ", parentWindow.isFocused()=" + 958 parentWindow.isFocused()); 959 } 960 LWKeyboardFocusManagerPeer.removeLastFocusRequest(getTarget()); 961 return false; 962 } 963 964 KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance(); 965 Component focusOwner = kfmPeer.getCurrentFocusOwner(); 966 return LWKeyboardFocusManagerPeer.deliverFocus(lightweightChild, 967 getTarget(), temporary, 968 focusedWindowChangeAllowed, 969 time, cause, focusOwner); 970 971 case LWKeyboardFocusManagerPeer.SNFH_SUCCESS_HANDLED: 972 return true; 973 } 974 975 return false; 976 } 977 978 @Override 979 public final Image createImage(final ImageProducer producer) { 980 return new ToolkitImage(producer); 981 } 982 983 @Override 984 public final Image createImage(final int width, final int height) { 985 return getLWGC().createAcceleratedImage(getTarget(), width, height); 986 } 987 988 @Override 989 public final VolatileImage createVolatileImage(final int w, final int h) { 990 return new SunVolatileImage(getTarget(), w, h); 991 } 992 993 @Override 994 public boolean prepareImage(Image img, int w, int h, ImageObserver o) { 995 // TODO: is it a right/complete implementation? 996 return getToolkit().prepareImage(img, w, h, o); 997 } 998 999 @Override 1000 public int checkImage(Image img, int w, int h, ImageObserver o) { 1001 // TODO: is it a right/complete implementation? 1002 return getToolkit().checkImage(img, w, h, o); 1003 } 1004 1005 @Override 1006 public boolean handlesWheelScrolling() { 1007 // TODO: not implemented 1008 return false; 1009 } 1010 1011 @Override 1012 public final void applyShape(final Region shape) { 1013 synchronized (getStateLock()) { 1014 if (region == shape || (region != null && region.equals(shape))) { 1015 return; 1016 } 1017 } 1018 applyShapeImpl(shape); 1019 } 1020 1021 void applyShapeImpl(final Region shape) { 1022 synchronized (getStateLock()) { 1023 if (shape != null) { 1024 region = Region.WHOLE_REGION.getIntersection(shape); 1025 } else { 1026 region = null; 1027 } 1028 } 1029 repaintParent(getBounds()); 1030 } 1031 1032 protected final Region getRegion() { 1033 synchronized (getStateLock()) { 1034 return isShaped() ? region : Region.getInstance(getSize()); 1035 } 1036 } 1037 1038 public boolean isShaped() { 1039 synchronized (getStateLock()) { 1040 return region != null; 1041 } 1042 } 1043 1044 // DropTargetPeer Method 1045 @Override 1046 public void addDropTarget(DropTarget dt) { 1047 LWWindowPeer winPeer = getWindowPeerOrSelf(); 1048 if (winPeer != null && winPeer != this) { 1049 // We need to register the DropTarget in the 1050 // peer of the window ancestor of the component 1051 winPeer.addDropTarget(dt); 1052 } else { 1053 synchronized (dropTargetLock) { 1054 // 10-14-02 VL: Windows WComponentPeer would add (or remove) the drop target only 1055 // if it's the first (or last) one for the component. Otherwise this call is a no-op. 1056 if (++fNumDropTargets == 1) { 1057 // Having a non-null drop target would be an error but let's check just in case: 1058 if (fDropTarget != null) 1059 System.err.println("CComponent.addDropTarget(): current drop target is non-null."); 1060 1061 // Create a new drop target: 1062 fDropTarget = CDropTarget.createDropTarget(dt, target, this); 1063 } 1064 } 1065 } 1066 } 1067 1068 // DropTargetPeer Method 1069 @Override 1070 public void removeDropTarget(DropTarget dt) { 1071 LWWindowPeer winPeer = getWindowPeerOrSelf(); 1072 if (winPeer != null && winPeer != this) { 1073 // We need to unregister the DropTarget in the 1074 // peer of the window ancestor of the component 1075 winPeer.removeDropTarget(dt); 1076 } else { 1077 synchronized (dropTargetLock){ 1078 // 10-14-02 VL: Windows WComponentPeer would add (or remove) the drop target only 1079 // if it's the first (or last) one for the component. Otherwise this call is a no-op. 1080 if (--fNumDropTargets == 0) { 1081 // Having a null drop target would be an error but let's check just in case: 1082 if (fDropTarget != null) { 1083 // Dispose of the drop target: 1084 fDropTarget.dispose(); 1085 fDropTarget = null; 1086 } else 1087 System.err.println("CComponent.removeDropTarget(): current drop target is null."); 1088 } 1089 } 1090 } 1091 } 1092 1093 // ---- PEER NOTIFICATIONS ---- // 1094 1095 /** 1096 * Called when this peer's location has been changed either as a result 1097 * of target.setLocation() or as a result of user actions (window is 1098 * dragged with mouse). 1099 * 1100 * This method could be called on the toolkit thread. 1101 */ 1102 protected final void handleMove(final int x, final int y, 1103 final boolean updateTarget) { 1104 if (updateTarget) { 1105 AWTAccessor.getComponentAccessor().setLocation(getTarget(), x, y); 1106 } 1107 postEvent(new ComponentEvent(getTarget(), 1108 ComponentEvent.COMPONENT_MOVED)); 1109 } 1110 1111 /** 1112 * Called when this peer's size has been changed either as a result of 1113 * target.setSize() or as a result of user actions (window is resized). 1114 * 1115 * This method could be called on the toolkit thread. 1116 */ 1117 protected final void handleResize(final int w, final int h, 1118 final boolean updateTarget) { 1119 Image oldBB = null; 1120 synchronized (getStateLock()) { 1121 if (backBuffer != null) { 1122 oldBB = backBuffer; 1123 backBuffer = getLWGC().createBackBuffer(this); 1124 } 1125 } 1126 getLWGC().destroyBackBuffer(oldBB); 1127 1128 if (updateTarget) { 1129 AWTAccessor.getComponentAccessor().setSize(getTarget(), w, h); 1130 } 1131 postEvent(new ComponentEvent(getTarget(), 1132 ComponentEvent.COMPONENT_RESIZED)); 1133 } 1134 1135 protected final void repaintOldNewBounds(final Rectangle oldB) { 1136 repaintParent(oldB); 1137 repaintPeer(getSize()); 1138 } 1139 1140 protected final void repaintParent(final Rectangle oldB) { 1141 final LWContainerPeer cp = getContainerPeer(); 1142 if (cp != null) { 1143 // Repaint unobscured part of the parent 1144 cp.repaintPeer(cp.getContentSize().intersection(oldB)); 1145 } 1146 } 1147 1148 // ---- EVENTS ---- // 1149 1150 /** 1151 * Post an event to the proper Java EDT. 1152 */ 1153 public void postEvent(AWTEvent event) { 1154 SunToolkit.postEvent(getAppContext(), event); 1155 } 1156 1157 protected void postPaintEvent(int x, int y, int w, int h) { 1158 // TODO: call getIgnoreRepaint() directly with the right ACC 1159 if (AWTAccessor.getComponentAccessor().getIgnoreRepaint(target)) { 1160 return; 1161 } 1162 PaintEvent event = PaintEventDispatcher.getPaintEventDispatcher(). 1163 createPaintEvent(getTarget(), x, y, w, h); 1164 if (event != null) { 1165 postEvent(event); 1166 } 1167 } 1168 1169 /* 1170 * Gives a chance for the peer to handle the event after it's been 1171 * processed by the target. 1172 */ 1173 @Override 1174 public void handleEvent(AWTEvent e) { 1175 if ((e instanceof InputEvent) && ((InputEvent) e).isConsumed()) { 1176 return; 1177 } 1178 switch (e.getID()) { 1179 case FocusEvent.FOCUS_GAINED: 1180 case FocusEvent.FOCUS_LOST: 1181 handleJavaFocusEvent((FocusEvent) e); 1182 break; 1183 case PaintEvent.PAINT: 1184 // Got a native paint event 1185 // paintPending = false; 1186 // fall through to the next statement 1187 case PaintEvent.UPDATE: 1188 handleJavaPaintEvent(); 1189 break; 1190 case MouseEvent.MOUSE_PRESSED: 1191 handleJavaMouseEvent((MouseEvent)e); 1192 } 1193 1194 sendEventToDelegate(e); 1195 } 1196 1197 protected void sendEventToDelegate(final AWTEvent e) { 1198 if (getDelegate() == null || !isShowing() || !isEnabled()) { 1199 return; 1200 } 1201 synchronized (getDelegateLock()) { 1202 AWTEvent delegateEvent = createDelegateEvent(e); 1203 if (delegateEvent != null) { 1204 AWTAccessor.getComponentAccessor() 1205 .processEvent((Component) delegateEvent.getSource(), 1206 delegateEvent); 1207 if (delegateEvent instanceof KeyEvent) { 1208 KeyEvent ke = (KeyEvent) delegateEvent; 1209 SwingUtilities.processKeyBindings(ke); 1210 } 1211 } 1212 } 1213 } 1214 1215 /** 1216 * Changes the target of the AWTEvent from awt component to appropriate 1217 * swing delegate. 1218 */ 1219 private AWTEvent createDelegateEvent(final AWTEvent e) { 1220 // TODO modifiers should be changed to getModifiers()|getModifiersEx()? 1221 AWTEvent delegateEvent = null; 1222 if (e instanceof MouseWheelEvent) { 1223 MouseWheelEvent me = (MouseWheelEvent) e; 1224 delegateEvent = new MouseWheelEvent( 1225 delegate, me.getID(), me.getWhen(), 1226 me.getModifiers(), 1227 me.getX(), me.getY(), 1228 me.getClickCount(), 1229 me.isPopupTrigger(), 1230 me.getScrollType(), 1231 me.getScrollAmount(), 1232 me.getWheelRotation()); 1233 } else if (e instanceof MouseEvent) { 1234 MouseEvent me = (MouseEvent) e; 1235 1236 Component eventTarget = SwingUtilities.getDeepestComponentAt(delegate, me.getX(), me.getY()); 1237 1238 if (me.getID() == MouseEvent.MOUSE_DRAGGED) { 1239 if (delegateDropTarget == null) { 1240 delegateDropTarget = eventTarget; 1241 } else { 1242 eventTarget = delegateDropTarget; 1243 } 1244 } 1245 if (me.getID() == MouseEvent.MOUSE_RELEASED && delegateDropTarget != null) { 1246 eventTarget = delegateDropTarget; 1247 delegateDropTarget = null; 1248 } 1249 if (eventTarget == null) { 1250 eventTarget = delegate; 1251 } 1252 delegateEvent = SwingUtilities.convertMouseEvent(getTarget(), me, eventTarget); 1253 } else if (e instanceof KeyEvent) { 1254 KeyEvent ke = (KeyEvent) e; 1255 delegateEvent = new KeyEvent(getDelegateFocusOwner(), ke.getID(), ke.getWhen(), 1256 ke.getModifiers(), ke.getKeyCode(), ke.getKeyChar(), ke.getKeyLocation()); 1257 AWTAccessor.getKeyEventAccessor().setExtendedKeyCode((KeyEvent) delegateEvent, 1258 ke.getExtendedKeyCode()); 1259 } else if (e instanceof FocusEvent) { 1260 FocusEvent fe = (FocusEvent) e; 1261 delegateEvent = new FocusEvent(getDelegateFocusOwner(), fe.getID(), fe.isTemporary()); 1262 } 1263 return delegateEvent; 1264 } 1265 1266 protected void handleJavaMouseEvent(MouseEvent e) { 1267 Component target = getTarget(); 1268 assert (e.getSource() == target); 1269 1270 if (!target.isFocusOwner() && LWKeyboardFocusManagerPeer.shouldFocusOnClick(target)) { 1271 LWKeyboardFocusManagerPeer.requestFocusFor(target, CausedFocusEvent.Cause.MOUSE_EVENT); 1272 } 1273 } 1274 1275 /** 1276 * Handler for FocusEvents. 1277 */ 1278 protected void handleJavaFocusEvent(FocusEvent e) { 1279 // Note that the peer receives all the FocusEvents from 1280 // its lightweight children as well 1281 KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance(); 1282 kfmPeer.setCurrentFocusOwner(e.getID() == FocusEvent.FOCUS_GAINED ? getTarget() : null); 1283 } 1284 1285 /** 1286 * All peers should clear background before paint. 1287 * 1288 * @return false on components that DO NOT require a clearRect() before 1289 * painting. 1290 */ 1291 protected final boolean shouldClearRectBeforePaint() { 1292 // TODO: sun.awt.noerasebackground 1293 return true; 1294 } 1295 1296 /** 1297 * Handler for PAINT and UPDATE PaintEvents. 1298 */ 1299 private void handleJavaPaintEvent() { 1300 // Skip all painting while layouting and all UPDATEs 1301 // while waiting for native paint 1302 // if (!isLayouting && !paintPending) { 1303 if (!isLayouting()) { 1304 targetPaintArea.paint(getTarget(), shouldClearRectBeforePaint()); 1305 } 1306 } 1307 1308 // ---- UTILITY METHODS ---- // 1309 1310 /** 1311 * Finds a top-most visible component for the given point. The location is 1312 * specified relative to the peer's parent. 1313 */ 1314 public LWComponentPeer findPeerAt(final int x, final int y) { 1315 final Rectangle r = getBounds(); 1316 final Region sh = getRegion(); 1317 final boolean found = isVisible() && sh.contains(x - r.x, y - r.y); 1318 return found ? this : null; 1319 } 1320 1321 /* 1322 * Translated the given point in Window coordinates to the point in 1323 * coordinates local to this component. The given window peer must be 1324 * the window where this component is in. 1325 */ 1326 public Point windowToLocal(int x, int y, LWWindowPeer wp) { 1327 return windowToLocal(new Point(x, y), wp); 1328 } 1329 1330 public Point windowToLocal(Point p, LWWindowPeer wp) { 1331 LWComponentPeer cp = this; 1332 while (cp != wp) { 1333 Rectangle cpb = cp.getBounds(); 1334 p.x -= cpb.x; 1335 p.y -= cpb.y; 1336 cp = cp.getContainerPeer(); 1337 } 1338 // Return a copy to prevent subsequent modifications 1339 return new Point(p); 1340 } 1341 1342 public Rectangle windowToLocal(Rectangle r, LWWindowPeer wp) { 1343 Point p = windowToLocal(r.getLocation(), wp); 1344 return new Rectangle(p, r.getSize()); 1345 } 1346 1347 public Point localToWindow(int x, int y) { 1348 return localToWindow(new Point(x, y)); 1349 } 1350 1351 public Point localToWindow(Point p) { 1352 LWComponentPeer cp = getContainerPeer(); 1353 Rectangle r = getBounds(); 1354 while (cp != null) { 1355 p.x += r.x; 1356 p.y += r.y; 1357 r = cp.getBounds(); 1358 cp = cp.getContainerPeer(); 1359 } 1360 // Return a copy to prevent subsequent modifications 1361 return new Point(p); 1362 } 1363 1364 public Rectangle localToWindow(Rectangle r) { 1365 Point p = localToWindow(r.getLocation()); 1366 return new Rectangle(p, r.getSize()); 1367 } 1368 1369 public final void repaintPeer() { 1370 repaintPeer(getSize()); 1371 } 1372 1373 public void repaintPeer(final Rectangle r) { 1374 final Rectangle toPaint = getSize().intersection(r); 1375 if (!isShowing() || toPaint.isEmpty()) { 1376 return; 1377 } 1378 1379 postPaintEvent(toPaint.x, toPaint.y, toPaint.width, toPaint.height); 1380 } 1381 1382 /** 1383 * Determines whether this peer is showing on screen. This means that the 1384 * peer must be visible, and it must be in a container that is visible and 1385 * showing. 1386 * 1387 * @see #isVisible() 1388 */ 1389 protected final boolean isShowing() { 1390 synchronized (getPeerTreeLock()) { 1391 if (isVisible()) { 1392 final LWContainerPeer container = getContainerPeer(); 1393 return (container == null) || container.isShowing(); 1394 } 1395 } 1396 return false; 1397 } 1398 1399 /** 1400 * Paints the peer. Overridden in subclasses to delegate the actual painting 1401 * to Swing components. 1402 */ 1403 protected final void paintPeer(final Graphics g) { 1404 final D delegate = getDelegate(); 1405 if (delegate != null) { 1406 if (!SwingUtilities.isEventDispatchThread()) { 1407 throw new InternalError("Painting must be done on EDT"); 1408 } 1409 synchronized (getDelegateLock()) { 1410 // JComponent.print() is guaranteed to not affect the double buffer 1411 getDelegate().print(g); 1412 } 1413 } 1414 } 1415 1416 protected static final void flushOnscreenGraphics(){ 1417 final OGLRenderQueue rq = OGLRenderQueue.getInstance(); 1418 rq.lock(); 1419 try { 1420 rq.flushNow(); 1421 } finally { 1422 rq.unlock(); 1423 } 1424 } 1425 1426 /** 1427 * Used by ContainerPeer to skip all the paint events during layout. 1428 * 1429 * @param isLayouting layouting state. 1430 */ 1431 protected final void setLayouting(final boolean isLayouting) { 1432 this.isLayouting = isLayouting; 1433 } 1434 1435 /** 1436 * Returns layouting state. Used by ComponentPeer to skip all the paint 1437 * events during layout. 1438 * 1439 * @return true during layout, false otherwise. 1440 */ 1441 private final boolean isLayouting() { 1442 return isLayouting; 1443 } 1444 }