1 /* 2 * Copyright (c) 1997, 2009, 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 package javax.swing; 26 27 28 import java.awt.*; 29 import java.awt.event.*; 30 import java.awt.peer.ComponentPeer; 31 import java.awt.peer.ContainerPeer; 32 import java.awt.image.VolatileImage; 33 import java.security.AccessController; 34 import java.util.*; 35 import java.applet.*; 36 37 import sun.awt.AWTAccessor; 38 import sun.awt.AppContext; 39 import sun.awt.DisplayChangedListener; 40 import sun.awt.SunToolkit; 41 import sun.java2d.SunGraphicsEnvironment; 42 import sun.security.action.GetPropertyAction; 43 44 import com.sun.java.swing.SwingUtilities3; 45 46 /** 47 * This class manages repaint requests, allowing the number 48 * of repaints to be minimized, for example by collapsing multiple 49 * requests into a single repaint for members of a component tree. 50 * <p> 51 * As of 1.6 <code>RepaintManager</code> handles repaint requests 52 * for Swing's top level components (<code>JApplet</code>, 53 * <code>JWindow</code>, <code>JFrame</code> and <code>JDialog</code>). 54 * Any calls to <code>repaint</code> on one of these will call into the 55 * appropriate <code>addDirtyRegion</code> method. 56 * 57 * @author Arnaud Weber 58 */ 59 public class RepaintManager 60 { 61 /** 62 * Whether or not the RepaintManager should handle paint requests 63 * for top levels. 64 */ 65 static final boolean HANDLE_TOP_LEVEL_PAINT; 66 67 private static final short BUFFER_STRATEGY_NOT_SPECIFIED = 0; 68 private static final short BUFFER_STRATEGY_SPECIFIED_ON = 1; 69 private static final short BUFFER_STRATEGY_SPECIFIED_OFF = 2; 70 71 private static final short BUFFER_STRATEGY_TYPE; 72 73 /** 74 * Maps from GraphicsConfiguration to VolatileImage. 75 */ 76 private Map<GraphicsConfiguration,VolatileImage> volatileMap = new 77 HashMap<GraphicsConfiguration,VolatileImage>(1); 78 79 // 80 // As of 1.6 Swing handles scheduling of paint events from native code. 81 // That is, SwingPaintEventDispatcher is invoked on the toolkit thread, 82 // which in turn invokes nativeAddDirtyRegion. Because this is invoked 83 // from the native thread we can not invoke any public methods and so 84 // we introduce these added maps. So, any time nativeAddDirtyRegion is 85 // invoked the region is added to hwDirtyComponents and a work request 86 // is scheduled. When the work request is processed all entries in 87 // this map are pushed to the real map (dirtyComponents) and then 88 // painted with the rest of the components. 89 // 90 private Map<Container,Rectangle> hwDirtyComponents; 91 92 private Map<Component,Rectangle> dirtyComponents; 93 private Map<Component,Rectangle> tmpDirtyComponents; 94 private java.util.List<Component> invalidComponents; 95 96 // List of Runnables that need to be processed before painting from AWT. 97 private java.util.List<Runnable> runnableList; 98 99 boolean doubleBufferingEnabled = true; 100 101 private Dimension doubleBufferMaxSize; 102 103 // Support for both the standard and volatile offscreen buffers exists to 104 // provide backwards compatibility for the [rare] programs which may be 105 // calling getOffScreenBuffer() and not expecting to get a VolatileImage. 106 // Swing internally is migrating to use *only* the volatile image buffer. 107 108 // Support for standard offscreen buffer 109 // 110 DoubleBufferInfo standardDoubleBuffer; 111 112 /** 113 * Object responsible for hanlding core paint functionality. 114 */ 115 private PaintManager paintManager; 116 117 private static final Object repaintManagerKey = RepaintManager.class; 118 119 // Whether or not a VolatileImage should be used for double-buffered painting 120 static boolean volatileImageBufferEnabled = true; 121 /** 122 * Value of the system property awt.nativeDoubleBuffering. 123 */ 124 private static boolean nativeDoubleBuffering; 125 126 // The maximum number of times Swing will attempt to use the VolatileImage 127 // buffer during a paint operation. 128 private static final int VOLATILE_LOOP_MAX = 2; 129 130 /** 131 * Number of <code>beginPaint</code> that have been invoked. 132 */ 133 private int paintDepth = 0; 134 135 /** 136 * Type of buffer strategy to use. Will be one of the BUFFER_STRATEGY_ 137 * constants. 138 */ 139 private short bufferStrategyType; 140 141 // 142 // BufferStrategyPaintManager has the unique characteristic that it 143 // must deal with the buffer being lost while painting to it. For 144 // example, if we paint a component and show it and the buffer has 145 // become lost we must repaint the whole window. To deal with that 146 // the PaintManager calls into repaintRoot, and if we're still in 147 // the process of painting the repaintRoot field is set to the JRootPane 148 // and after the current JComponent.paintImmediately call finishes 149 // paintImmediately will be invoked on the repaintRoot. In this 150 // way we don't try to show garbage to the screen. 151 // 152 /** 153 * True if we're in the process of painting the dirty regions. This is 154 * set to true in <code>paintDirtyRegions</code>. 155 */ 156 private boolean painting; 157 /** 158 * If the PaintManager calls into repaintRoot during painting this field 159 * will be set to the root. 160 */ 161 private JComponent repaintRoot; 162 163 /** 164 * The Thread that has initiated painting. If null it 165 * indicates painting is not currently in progress. 166 */ 167 private Thread paintThread; 168 169 /** 170 * Runnable used to process all repaint/revalidate requests. 171 */ 172 private final ProcessingRunnable processingRunnable; 173 174 175 static { 176 volatileImageBufferEnabled = "true".equals(AccessController. 177 doPrivileged(new GetPropertyAction( 178 "swing.volatileImageBufferEnabled", "true"))); 179 boolean headless = GraphicsEnvironment.isHeadless(); 180 if (volatileImageBufferEnabled && headless) { 181 volatileImageBufferEnabled = false; 182 } 183 nativeDoubleBuffering = "true".equals(AccessController.doPrivileged( 184 new GetPropertyAction("awt.nativeDoubleBuffering"))); 185 String bs = AccessController.doPrivileged( 186 new GetPropertyAction("swing.bufferPerWindow")); 187 if (headless) { 188 BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_SPECIFIED_OFF; 189 } 190 else if (bs == null) { 191 BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_NOT_SPECIFIED; 192 } 193 else if ("true".equals(bs)) { 194 BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_SPECIFIED_ON; 195 } 196 else { 197 BUFFER_STRATEGY_TYPE = BUFFER_STRATEGY_SPECIFIED_OFF; 198 } 199 HANDLE_TOP_LEVEL_PAINT = "true".equals(AccessController.doPrivileged( 200 new GetPropertyAction("swing.handleTopLevelPaint", "true"))); 201 GraphicsEnvironment ge = GraphicsEnvironment. 202 getLocalGraphicsEnvironment(); 203 if (ge instanceof SunGraphicsEnvironment) { 204 ((SunGraphicsEnvironment)ge).addDisplayChangedListener( 205 new DisplayChangedHandler()); 206 } 207 } 208 209 /** 210 * Return the RepaintManager for the calling thread given a Component. 211 * 212 * @param c a Component -- unused in the default implementation, but could 213 * be used by an overridden version to return a different RepaintManager 214 * depending on the Component 215 * @return the RepaintManager object 216 */ 217 public static RepaintManager currentManager(Component c) { 218 // Note: DisplayChangedRunnable passes in null as the component, so if 219 // component is ever used to determine the current 220 // RepaintManager, DisplayChangedRunnable will need to be modified 221 // accordingly. 222 return currentManager(AppContext.getAppContext()); 223 } 224 225 /** 226 * Returns the RepaintManager for the specified AppContext. If 227 * a RepaintManager has not been created for the specified 228 * AppContext this will return null. 229 */ 230 static RepaintManager currentManager(AppContext appContext) { 231 RepaintManager rm = (RepaintManager)appContext.get(repaintManagerKey); 232 if (rm == null) { 233 rm = new RepaintManager(BUFFER_STRATEGY_TYPE); 234 appContext.put(repaintManagerKey, rm); 235 } 236 return rm; 237 } 238 239 /** 240 * Return the RepaintManager for the calling thread given a JComponent. 241 * <p> 242 * Note: This method exists for backward binary compatibility with earlier 243 * versions of the Swing library. It simply returns the result returned by 244 * {@link #currentManager(Component)}. 245 * 246 * @param c a JComponent -- unused 247 * @return the RepaintManager object 248 */ 249 public static RepaintManager currentManager(JComponent c) { 250 return currentManager((Component)c); 251 } 252 253 254 /** 255 * Set the RepaintManager that should be used for the calling 256 * thread. <b>aRepaintManager</b> will become the current RepaintManager 257 * for the calling thread's thread group. 258 * @param aRepaintManager the RepaintManager object to use 259 */ 260 public static void setCurrentManager(RepaintManager aRepaintManager) { 261 if (aRepaintManager != null) { 262 SwingUtilities.appContextPut(repaintManagerKey, aRepaintManager); 263 } else { 264 SwingUtilities.appContextRemove(repaintManagerKey); 265 } 266 } 267 268 /** 269 * Create a new RepaintManager instance. You rarely call this constructor. 270 * directly. To get the default RepaintManager, use 271 * RepaintManager.currentManager(JComponent) (normally "this"). 272 */ 273 public RepaintManager() { 274 // Because we can't know what a subclass is doing with the 275 // volatile image we immediately punt in subclasses. If this 276 // poses a problem we'll need a more sophisticated detection algorithm, 277 // or API. 278 this(BUFFER_STRATEGY_SPECIFIED_OFF); 279 } 280 281 private RepaintManager(short bufferStrategyType) { 282 // If native doublebuffering is being used, do NOT use 283 // Swing doublebuffering. 284 doubleBufferingEnabled = !nativeDoubleBuffering; 285 synchronized(this) { 286 dirtyComponents = new IdentityHashMap<Component,Rectangle>(); 287 tmpDirtyComponents = new IdentityHashMap<Component,Rectangle>(); 288 this.bufferStrategyType = bufferStrategyType; 289 hwDirtyComponents = new IdentityHashMap<Container,Rectangle>(); 290 } 291 processingRunnable = new ProcessingRunnable(); 292 } 293 294 private void displayChanged() { 295 clearImages(); 296 } 297 298 /** 299 * Mark the component as in need of layout and queue a runnable 300 * for the event dispatching thread that will validate the components 301 * first isValidateRoot() ancestor. 302 * 303 * @see JComponent#isValidateRoot 304 * @see #removeInvalidComponent 305 */ 306 public synchronized void addInvalidComponent(JComponent invalidComponent) 307 { 308 RepaintManager delegate = getDelegate(invalidComponent); 309 if (delegate != null) { 310 delegate.addInvalidComponent(invalidComponent); 311 return; 312 } 313 Component validateRoot = 314 SwingUtilities.getValidateRoot(invalidComponent, true); 315 316 if (validateRoot == null) { 317 return; 318 } 319 320 /* Lazily create the invalidateComponents vector and add the 321 * validateRoot if it's not there already. If this validateRoot 322 * is already in the vector, we're done. 323 */ 324 if (invalidComponents == null) { 325 invalidComponents = new ArrayList<Component>(); 326 } 327 else { 328 int n = invalidComponents.size(); 329 for(int i = 0; i < n; i++) { 330 if(validateRoot == invalidComponents.get(i)) { 331 return; 332 } 333 } 334 } 335 invalidComponents.add(validateRoot); 336 337 // Queue a Runnable to invoke paintDirtyRegions and 338 // validateInvalidComponents. 339 scheduleProcessingRunnable(); 340 } 341 342 343 /** 344 * Remove a component from the list of invalid components. 345 * 346 * @see #addInvalidComponent 347 */ 348 public synchronized void removeInvalidComponent(JComponent component) { 349 RepaintManager delegate = getDelegate(component); 350 if (delegate != null) { 351 delegate.removeInvalidComponent(component); 352 return; 353 } 354 if(invalidComponents != null) { 355 int index = invalidComponents.indexOf(component); 356 if(index != -1) { 357 invalidComponents.remove(index); 358 } 359 } 360 } 361 362 363 /** 364 * Add a component in the list of components that should be refreshed. 365 * If <i>c</i> already has a dirty region, the rectangle <i>(x,y,w,h)</i> 366 * will be unioned with the region that should be redrawn. 367 * 368 * @see JComponent#repaint 369 */ 370 private void addDirtyRegion0(Container c, int x, int y, int w, int h) { 371 /* Special cases we don't have to bother with. 372 */ 373 if ((w <= 0) || (h <= 0) || (c == null)) { 374 return; 375 } 376 377 if ((c.getWidth() <= 0) || (c.getHeight() <= 0)) { 378 return; 379 } 380 381 if (extendDirtyRegion(c, x, y, w, h)) { 382 // Component was already marked as dirty, region has been 383 // extended, no need to continue. 384 return; 385 } 386 387 /* Make sure that c and all it ancestors (up to an Applet or 388 * Window) are visible. This loop has the same effect as 389 * checking c.isShowing() (and note that it's still possible 390 * that c is completely obscured by an opaque ancestor in 391 * the specified rectangle). 392 */ 393 Component root = null; 394 395 // Note: We can't synchronize around this, Frame.getExtendedState 396 // is synchronized so that if we were to synchronize around this 397 // it could lead to the possibility of getting locks out 398 // of order and deadlocking. 399 for (Container p = c; p != null; p = p.getParent()) { 400 if (!p.isVisible() || (p.getPeer() == null)) { 401 return; 402 } 403 if ((p instanceof Window) || (p instanceof Applet)) { 404 // Iconified frames are still visible! 405 if (p instanceof Frame && 406 (((Frame)p).getExtendedState() & Frame.ICONIFIED) == 407 Frame.ICONIFIED) { 408 return; 409 } 410 root = p; 411 break; 412 } 413 } 414 415 if (root == null) return; 416 417 synchronized(this) { 418 if (extendDirtyRegion(c, x, y, w, h)) { 419 // In between last check and this check another thread 420 // queued up runnable, can bail here. 421 return; 422 } 423 dirtyComponents.put(c, new Rectangle(x, y, w, h)); 424 } 425 426 // Queue a Runnable to invoke paintDirtyRegions and 427 // validateInvalidComponents. 428 scheduleProcessingRunnable(); 429 } 430 431 /** 432 * Add a component in the list of components that should be refreshed. 433 * If <i>c</i> already has a dirty region, the rectangle <i>(x,y,w,h)</i> 434 * will be unioned with the region that should be redrawn. 435 * 436 * @param c Component to repaint, null results in nothing happening. 437 * @param x X coordinate of the region to repaint 438 * @param y Y coordinate of the region to repaint 439 * @param w Width of the region to repaint 440 * @param h Height of the region to repaint 441 * @see JComponent#isPaintingOrigin() 442 * @see JComponent#repaint 443 */ 444 public void addDirtyRegion(JComponent c, int x, int y, int w, int h) 445 { 446 RepaintManager delegate = getDelegate(c); 447 if (delegate != null) { 448 delegate.addDirtyRegion(c, x, y, w, h); 449 return; 450 } 451 Container p = c; 452 while ((p = p.getParent()) instanceof JComponent) { 453 JComponent jp = (JComponent) p; 454 if (jp.isPaintingOrigin()) { 455 Rectangle rectangle = SwingUtilities.convertRectangle( 456 c, new Rectangle(x, y, w, h), jp); 457 jp.repaint(0, rectangle.x, rectangle.y, rectangle.width, rectangle.height); 458 return; 459 } 460 } 461 addDirtyRegion0(c, x, y, w, h); 462 } 463 464 /** 465 * Adds <code>window</code> to the list of <code>Component</code>s that 466 * need to be repainted. 467 * 468 * @param window Window to repaint, null results in nothing happening. 469 * @param x X coordinate of the region to repaint 470 * @param y Y coordinate of the region to repaint 471 * @param w Width of the region to repaint 472 * @param h Height of the region to repaint 473 * @see JFrame#repaint 474 * @see JWindow#repaint 475 * @see JDialog#repaint 476 * @since 1.6 477 */ 478 public void addDirtyRegion(Window window, int x, int y, int w, int h) { 479 addDirtyRegion0(window, x, y, w, h); 480 } 481 482 /** 483 * Adds <code>applet</code> to the list of <code>Component</code>s that 484 * need to be repainted. 485 * 486 * @param applet Applet to repaint, null results in nothing happening. 487 * @param x X coordinate of the region to repaint 488 * @param y Y coordinate of the region to repaint 489 * @param w Width of the region to repaint 490 * @param h Height of the region to repaint 491 * @see JApplet#repaint 492 * @since 1.6 493 */ 494 public void addDirtyRegion(Applet applet, int x, int y, int w, int h) { 495 addDirtyRegion0(applet, x, y, w, h); 496 } 497 498 void scheduleHeavyWeightPaints() { 499 Map<Container,Rectangle> hws; 500 501 synchronized(this) { 502 if (hwDirtyComponents.size() == 0) { 503 return; 504 } 505 hws = hwDirtyComponents; 506 hwDirtyComponents = new IdentityHashMap<Container,Rectangle>(); 507 } 508 for (Container hw : hws.keySet()) { 509 Rectangle dirty = hws.get(hw); 510 if (hw instanceof Window) { 511 addDirtyRegion((Window)hw, dirty.x, dirty.y, 512 dirty.width, dirty.height); 513 } 514 else if (hw instanceof Applet) { 515 addDirtyRegion((Applet)hw, dirty.x, dirty.y, 516 dirty.width, dirty.height); 517 } 518 else { // SwingHeavyWeight 519 addDirtyRegion0(hw, dirty.x, dirty.y, 520 dirty.width, dirty.height); 521 } 522 } 523 } 524 525 // 526 // This is called from the toolkit thread when a native expose is 527 // received. 528 // 529 void nativeAddDirtyRegion(AppContext appContext, Container c, 530 int x, int y, int w, int h) { 531 if (w > 0 && h > 0) { 532 synchronized(this) { 533 Rectangle dirty = hwDirtyComponents.get(c); 534 if (dirty == null) { 535 hwDirtyComponents.put(c, new Rectangle(x, y, w, h)); 536 } 537 else { 538 hwDirtyComponents.put(c, SwingUtilities.computeUnion( 539 x, y, w, h, dirty)); 540 } 541 } 542 scheduleProcessingRunnable(appContext); 543 } 544 } 545 546 // 547 // This is called from the toolkit thread when awt needs to run a 548 // Runnable before we paint. 549 // 550 void nativeQueueSurfaceDataRunnable(AppContext appContext, Component c, 551 Runnable r) { 552 synchronized(this) { 553 if (runnableList == null) { 554 runnableList = new LinkedList<Runnable>(); 555 } 556 runnableList.add(r); 557 } 558 scheduleProcessingRunnable(appContext); 559 } 560 561 /** 562 * Extends the dirty region for the specified component to include 563 * the new region. 564 * 565 * @return false if <code>c</code> is not yet marked dirty. 566 */ 567 private synchronized boolean extendDirtyRegion( 568 Component c, int x, int y, int w, int h) { 569 Rectangle r = dirtyComponents.get(c); 570 if (r != null) { 571 // A non-null r implies c is already marked as dirty, 572 // and that the parent is valid. Therefore we can 573 // just union the rect and bail. 574 SwingUtilities.computeUnion(x, y, w, h, r); 575 return true; 576 } 577 return false; 578 } 579 580 /** Return the current dirty region for a component. 581 * Return an empty rectangle if the component is not 582 * dirty. 583 */ 584 public Rectangle getDirtyRegion(JComponent aComponent) { 585 RepaintManager delegate = getDelegate(aComponent); 586 if (delegate != null) { 587 return delegate.getDirtyRegion(aComponent); 588 } 589 Rectangle r; 590 synchronized(this) { 591 r = dirtyComponents.get(aComponent); 592 } 593 if(r == null) 594 return new Rectangle(0,0,0,0); 595 else 596 return new Rectangle(r); 597 } 598 599 /** 600 * Mark a component completely dirty. <b>aComponent</b> will be 601 * completely painted during the next paintDirtyRegions() call. 602 */ 603 public void markCompletelyDirty(JComponent aComponent) { 604 RepaintManager delegate = getDelegate(aComponent); 605 if (delegate != null) { 606 delegate.markCompletelyDirty(aComponent); 607 return; 608 } 609 addDirtyRegion(aComponent,0,0,Integer.MAX_VALUE,Integer.MAX_VALUE); 610 } 611 612 /** 613 * Mark a component completely clean. <b>aComponent</b> will not 614 * get painted during the next paintDirtyRegions() call. 615 */ 616 public void markCompletelyClean(JComponent aComponent) { 617 RepaintManager delegate = getDelegate(aComponent); 618 if (delegate != null) { 619 delegate.markCompletelyClean(aComponent); 620 return; 621 } 622 synchronized(this) { 623 dirtyComponents.remove(aComponent); 624 } 625 } 626 627 /** 628 * Convenience method that returns true if <b>aComponent</b> will be completely 629 * painted during the next paintDirtyRegions(). If computing dirty regions is 630 * expensive for your component, use this method and avoid computing dirty region 631 * if it return true. 632 */ 633 public boolean isCompletelyDirty(JComponent aComponent) { 634 RepaintManager delegate = getDelegate(aComponent); 635 if (delegate != null) { 636 return delegate.isCompletelyDirty(aComponent); 637 } 638 Rectangle r; 639 640 r = getDirtyRegion(aComponent); 641 if(r.width == Integer.MAX_VALUE && 642 r.height == Integer.MAX_VALUE) 643 return true; 644 else 645 return false; 646 } 647 648 649 /** 650 * Validate all of the components that have been marked invalid. 651 * @see #addInvalidComponent 652 */ 653 public void validateInvalidComponents() { 654 java.util.List<Component> ic; 655 synchronized(this) { 656 if(invalidComponents == null) { 657 return; 658 } 659 ic = invalidComponents; 660 invalidComponents = null; 661 } 662 int n = ic.size(); 663 for(int i = 0; i < n; i++) { 664 ic.get(i).validate(); 665 } 666 } 667 668 669 /** 670 * This is invoked to process paint requests. It's needed 671 * for backward compatability in so far as RepaintManager would previously 672 * not see paint requests for top levels, so, we have to make sure 673 * a subclass correctly paints any dirty top levels. 674 */ 675 private void prePaintDirtyRegions() { 676 Map<Component,Rectangle> dirtyComponents; 677 java.util.List<Runnable> runnableList; 678 synchronized(this) { 679 dirtyComponents = this.dirtyComponents; 680 runnableList = this.runnableList; 681 this.runnableList = null; 682 } 683 if (runnableList != null) { 684 for (Runnable runnable : runnableList) { 685 runnable.run(); 686 } 687 } 688 paintDirtyRegions(); 689 if (dirtyComponents.size() > 0) { 690 // This'll only happen if a subclass isn't correctly dealing 691 // with toplevels. 692 paintDirtyRegions(dirtyComponents); 693 } 694 } 695 696 private void updateWindows(Map<Component,Rectangle> dirtyComponents) { 697 Toolkit toolkit = Toolkit.getDefaultToolkit(); 698 if (!(toolkit instanceof SunToolkit && 699 ((SunToolkit)toolkit).needUpdateWindow())) 700 { 701 return; 702 } 703 704 Set<Window> windows = new HashSet<Window>(); 705 Set<Component> dirtyComps = dirtyComponents.keySet(); 706 for (Iterator<Component> it = dirtyComps.iterator(); it.hasNext();) { 707 Component dirty = it.next(); 708 Window window = dirty instanceof Window ? 709 (Window)dirty : 710 SwingUtilities.getWindowAncestor(dirty); 711 if (window != null && 712 !window.isOpaque()) 713 { 714 windows.add(window); 715 } 716 } 717 718 for (Window window : windows) { 719 AWTAccessor.getWindowAccessor().updateWindow(window); 720 } 721 } 722 723 boolean isPainting() { 724 return painting; 725 } 726 727 /** 728 * Paint all of the components that have been marked dirty. 729 * 730 * @see #addDirtyRegion 731 */ 732 public void paintDirtyRegions() { 733 synchronized(this) { // swap for thread safety 734 Map<Component,Rectangle> tmp = tmpDirtyComponents; 735 tmpDirtyComponents = dirtyComponents; 736 dirtyComponents = tmp; 737 dirtyComponents.clear(); 738 } 739 paintDirtyRegions(tmpDirtyComponents); 740 } 741 742 private void paintDirtyRegions(Map<Component,Rectangle> 743 tmpDirtyComponents){ 744 int i, count; 745 java.util.List<Component> roots; 746 Component dirtyComponent; 747 748 count = tmpDirtyComponents.size(); 749 if (count == 0) { 750 return; 751 } 752 753 Rectangle rect; 754 int localBoundsX = 0; 755 int localBoundsY = 0; 756 int localBoundsH; 757 int localBoundsW; 758 Enumeration keys; 759 760 roots = new ArrayList<Component>(count); 761 762 for (Component dirty : tmpDirtyComponents.keySet()) { 763 collectDirtyComponents(tmpDirtyComponents, dirty, roots); 764 } 765 766 count = roots.size(); 767 painting = true; 768 try { 769 for(i=0 ; i < count ; i++) { 770 dirtyComponent = roots.get(i); 771 rect = tmpDirtyComponents.get(dirtyComponent); 772 localBoundsH = dirtyComponent.getHeight(); 773 localBoundsW = dirtyComponent.getWidth(); 774 775 SwingUtilities.computeIntersection(localBoundsX, 776 localBoundsY, 777 localBoundsW, 778 localBoundsH, 779 rect); 780 if (dirtyComponent instanceof JComponent) { 781 ((JComponent)dirtyComponent).paintImmediately( 782 rect.x,rect.y,rect.width, rect.height); 783 } 784 else if (dirtyComponent.isShowing()) { 785 Graphics g = JComponent.safelyGetGraphics( 786 dirtyComponent, dirtyComponent); 787 // If the Graphics goes away, it means someone disposed of 788 // the window, don't do anything. 789 if (g != null) { 790 g.setClip(rect.x, rect.y, rect.width, rect.height); 791 try { 792 dirtyComponent.paint(g); 793 } finally { 794 g.dispose(); 795 } 796 } 797 } 798 // If the repaintRoot has been set, service it now and 799 // remove any components that are children of repaintRoot. 800 if (repaintRoot != null) { 801 adjustRoots(repaintRoot, roots, i + 1); 802 count = roots.size(); 803 paintManager.isRepaintingRoot = true; 804 repaintRoot.paintImmediately(0, 0, repaintRoot.getWidth(), 805 repaintRoot.getHeight()); 806 paintManager.isRepaintingRoot = false; 807 // Only service repaintRoot once. 808 repaintRoot = null; 809 } 810 } 811 } finally { 812 painting = false; 813 } 814 815 updateWindows(tmpDirtyComponents); 816 817 tmpDirtyComponents.clear(); 818 } 819 820 821 /** 822 * Removes any components from roots that are children of 823 * root. 824 */ 825 private void adjustRoots(JComponent root, 826 java.util.List<Component> roots, int index) { 827 for (int i = roots.size() - 1; i >= index; i--) { 828 Component c = roots.get(i); 829 for(;;) { 830 if (c == root || c == null || !(c instanceof JComponent)) { 831 break; 832 } 833 c = c.getParent(); 834 } 835 if (c == root) { 836 roots.remove(i); 837 } 838 } 839 } 840 841 Rectangle tmp = new Rectangle(); 842 843 void collectDirtyComponents(Map<Component,Rectangle> dirtyComponents, 844 Component dirtyComponent, 845 java.util.List<Component> roots) { 846 int dx, dy, rootDx, rootDy; 847 Component component, rootDirtyComponent,parent; 848 Rectangle cBounds; 849 850 // Find the highest parent which is dirty. When we get out of this 851 // rootDx and rootDy will contain the translation from the 852 // rootDirtyComponent's coordinate system to the coordinates of the 853 // original dirty component. The tmp Rect is also used to compute the 854 // visible portion of the dirtyRect. 855 856 component = rootDirtyComponent = dirtyComponent; 857 858 int x = dirtyComponent.getX(); 859 int y = dirtyComponent.getY(); 860 int w = dirtyComponent.getWidth(); 861 int h = dirtyComponent.getHeight(); 862 863 dx = rootDx = 0; 864 dy = rootDy = 0; 865 tmp.setBounds(dirtyComponents.get(dirtyComponent)); 866 867 // System.out.println("Collect dirty component for bound " + tmp + 868 // "component bounds is " + cBounds);; 869 SwingUtilities.computeIntersection(0,0,w,h,tmp); 870 871 if (tmp.isEmpty()) { 872 // System.out.println("Empty 1"); 873 return; 874 } 875 876 for(;;) { 877 if(!(component instanceof JComponent)) 878 break; 879 880 parent = component.getParent(); 881 if(parent == null) 882 break; 883 884 component = parent; 885 886 dx += x; 887 dy += y; 888 tmp.setLocation(tmp.x + x, tmp.y + y); 889 890 x = component.getX(); 891 y = component.getY(); 892 w = component.getWidth(); 893 h = component.getHeight(); 894 tmp = SwingUtilities.computeIntersection(0,0,w,h,tmp); 895 896 if (tmp.isEmpty()) { 897 // System.out.println("Empty 2"); 898 return; 899 } 900 901 if (dirtyComponents.get(component) != null) { 902 rootDirtyComponent = component; 903 rootDx = dx; 904 rootDy = dy; 905 } 906 } 907 908 if (dirtyComponent != rootDirtyComponent) { 909 Rectangle r; 910 tmp.setLocation(tmp.x + rootDx - dx, 911 tmp.y + rootDy - dy); 912 r = dirtyComponents.get(rootDirtyComponent); 913 SwingUtilities.computeUnion(tmp.x,tmp.y,tmp.width,tmp.height,r); 914 } 915 916 // If we haven't seen this root before, then we need to add it to the 917 // list of root dirty Views. 918 919 if (!roots.contains(rootDirtyComponent)) 920 roots.add(rootDirtyComponent); 921 } 922 923 924 /** 925 * Returns a string that displays and identifies this 926 * object's properties. 927 * 928 * @return a String representation of this object 929 */ 930 public synchronized String toString() { 931 StringBuffer sb = new StringBuffer(); 932 if(dirtyComponents != null) 933 sb.append("" + dirtyComponents); 934 return sb.toString(); 935 } 936 937 938 /** 939 * Return the offscreen buffer that should be used as a double buffer with 940 * the component <code>c</code>. 941 * By default there is a double buffer per RepaintManager. 942 * The buffer might be smaller than <code>(proposedWidth,proposedHeight)</code> 943 * This happens when the maximum double buffer size as been set for the receiving 944 * repaint manager. 945 */ 946 public Image getOffscreenBuffer(Component c,int proposedWidth,int proposedHeight) { 947 RepaintManager delegate = getDelegate(c); 948 if (delegate != null) { 949 return delegate.getOffscreenBuffer(c, proposedWidth, proposedHeight); 950 } 951 return _getOffscreenBuffer(c, proposedWidth, proposedHeight); 952 } 953 954 /** 955 * Return a volatile offscreen buffer that should be used as a 956 * double buffer with the specified component <code>c</code>. 957 * The image returned will be an instance of VolatileImage, or null 958 * if a VolatileImage object could not be instantiated. 959 * This buffer might be smaller than <code>(proposedWidth,proposedHeight)</code>. 960 * This happens when the maximum double buffer size has been set for this 961 * repaint manager. 962 * 963 * @see java.awt.image.VolatileImage 964 * @since 1.4 965 */ 966 public Image getVolatileOffscreenBuffer(Component c, 967 int proposedWidth,int proposedHeight) { 968 RepaintManager delegate = getDelegate(c); 969 if (delegate != null) { 970 return delegate.getVolatileOffscreenBuffer(c, proposedWidth, 971 proposedHeight); 972 } 973 974 // If the window is non-opaque, it's double-buffered at peer's level 975 Window w = (c instanceof Window) ? (Window)c : SwingUtilities.getWindowAncestor(c); 976 if (!w.isOpaque()) { 977 Toolkit tk = Toolkit.getDefaultToolkit(); 978 if ((tk instanceof SunToolkit) && (((SunToolkit)tk).needUpdateWindow())) { 979 return null; 980 } 981 } 982 983 GraphicsConfiguration config = c.getGraphicsConfiguration(); 984 if (config == null) { 985 config = GraphicsEnvironment.getLocalGraphicsEnvironment(). 986 getDefaultScreenDevice().getDefaultConfiguration(); 987 } 988 Dimension maxSize = getDoubleBufferMaximumSize(); 989 int width = proposedWidth < 1 ? 1 : 990 (proposedWidth > maxSize.width? maxSize.width : proposedWidth); 991 int height = proposedHeight < 1 ? 1 : 992 (proposedHeight > maxSize.height? maxSize.height : proposedHeight); 993 VolatileImage image = volatileMap.get(config); 994 if (image == null || image.getWidth() < width || 995 image.getHeight() < height) { 996 if (image != null) { 997 image.flush(); 998 } 999 image = config.createCompatibleVolatileImage(width, height); 1000 volatileMap.put(config, image); 1001 } 1002 return image; 1003 } 1004 1005 private Image _getOffscreenBuffer(Component c, int proposedWidth, int proposedHeight) { 1006 Dimension maxSize = getDoubleBufferMaximumSize(); 1007 DoubleBufferInfo doubleBuffer; 1008 int width, height; 1009 1010 // If the window is non-opaque, it's double-buffered at peer's level 1011 Window w = (c instanceof Window) ? (Window)c : SwingUtilities.getWindowAncestor(c); 1012 if (!w.isOpaque()) { 1013 Toolkit tk = Toolkit.getDefaultToolkit(); 1014 if ((tk instanceof SunToolkit) && (((SunToolkit)tk).needUpdateWindow())) { 1015 return null; 1016 } 1017 } 1018 1019 if (standardDoubleBuffer == null) { 1020 standardDoubleBuffer = new DoubleBufferInfo(); 1021 } 1022 doubleBuffer = standardDoubleBuffer; 1023 1024 width = proposedWidth < 1? 1 : 1025 (proposedWidth > maxSize.width? maxSize.width : proposedWidth); 1026 height = proposedHeight < 1? 1 : 1027 (proposedHeight > maxSize.height? maxSize.height : proposedHeight); 1028 1029 if (doubleBuffer.needsReset || (doubleBuffer.image != null && 1030 (doubleBuffer.size.width < width || 1031 doubleBuffer.size.height < height))) { 1032 doubleBuffer.needsReset = false; 1033 if (doubleBuffer.image != null) { 1034 doubleBuffer.image.flush(); 1035 doubleBuffer.image = null; 1036 } 1037 width = Math.max(doubleBuffer.size.width, width); 1038 height = Math.max(doubleBuffer.size.height, height); 1039 } 1040 1041 Image result = doubleBuffer.image; 1042 1043 if (doubleBuffer.image == null) { 1044 result = c.createImage(width , height); 1045 doubleBuffer.size = new Dimension(width, height); 1046 if (c instanceof JComponent) { 1047 ((JComponent)c).setCreatedDoubleBuffer(true); 1048 doubleBuffer.image = result; 1049 } 1050 // JComponent will inform us when it is no longer valid 1051 // (via removeNotify) we have no such hook to other components, 1052 // therefore we don't keep a ref to the Component 1053 // (indirectly through the Image) by stashing the image. 1054 } 1055 return result; 1056 } 1057 1058 1059 /** Set the maximum double buffer size. **/ 1060 public void setDoubleBufferMaximumSize(Dimension d) { 1061 doubleBufferMaxSize = d; 1062 if (doubleBufferMaxSize == null) { 1063 clearImages(); 1064 } else { 1065 clearImages(d.width, d.height); 1066 } 1067 } 1068 1069 private void clearImages() { 1070 clearImages(0, 0); 1071 } 1072 1073 private void clearImages(int width, int height) { 1074 if (standardDoubleBuffer != null && standardDoubleBuffer.image != null) { 1075 if (standardDoubleBuffer.image.getWidth(null) > width || 1076 standardDoubleBuffer.image.getHeight(null) > height) { 1077 standardDoubleBuffer.image.flush(); 1078 standardDoubleBuffer.image = null; 1079 } 1080 } 1081 // Clear out the VolatileImages 1082 Iterator gcs = volatileMap.keySet().iterator(); 1083 while (gcs.hasNext()) { 1084 GraphicsConfiguration gc = (GraphicsConfiguration)gcs.next(); 1085 VolatileImage image = volatileMap.get(gc); 1086 if (image.getWidth() > width || image.getHeight() > height) { 1087 image.flush(); 1088 gcs.remove(); 1089 } 1090 } 1091 } 1092 1093 /** 1094 * Returns the maximum double buffer size. 1095 * 1096 * @return a Dimension object representing the maximum size 1097 */ 1098 public Dimension getDoubleBufferMaximumSize() { 1099 if (doubleBufferMaxSize == null) { 1100 try { 1101 Rectangle virtualBounds = new Rectangle(); 1102 GraphicsEnvironment ge = GraphicsEnvironment. 1103 getLocalGraphicsEnvironment(); 1104 for (GraphicsDevice gd : ge.getScreenDevices()) { 1105 GraphicsConfiguration gc = gd.getDefaultConfiguration(); 1106 virtualBounds = virtualBounds.union(gc.getBounds()); 1107 } 1108 doubleBufferMaxSize = new Dimension(virtualBounds.width, 1109 virtualBounds.height); 1110 } catch (HeadlessException e) { 1111 doubleBufferMaxSize = new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); 1112 } 1113 } 1114 return doubleBufferMaxSize; 1115 } 1116 1117 /** 1118 * Enables or disables double buffering in this RepaintManager. 1119 * CAUTION: The default value for this property is set for optimal 1120 * paint performance on the given platform and it is not recommended 1121 * that programs modify this property directly. 1122 * 1123 * @param aFlag true to activate double buffering 1124 * @see #isDoubleBufferingEnabled 1125 */ 1126 public void setDoubleBufferingEnabled(boolean aFlag) { 1127 doubleBufferingEnabled = aFlag; 1128 PaintManager paintManager = getPaintManager(); 1129 if (!aFlag && paintManager.getClass() != PaintManager.class) { 1130 setPaintManager(new PaintManager()); 1131 } 1132 } 1133 1134 /** 1135 * Returns true if this RepaintManager is double buffered. 1136 * The default value for this property may vary from platform 1137 * to platform. On platforms where native double buffering 1138 * is supported in the AWT, the default value will be <code>false</code> 1139 * to avoid unnecessary buffering in Swing. 1140 * On platforms where native double buffering is not supported, 1141 * the default value will be <code>true</code>. 1142 * 1143 * @return true if this object is double buffered 1144 */ 1145 public boolean isDoubleBufferingEnabled() { 1146 return doubleBufferingEnabled; 1147 } 1148 1149 /** 1150 * This resets the double buffer. Actually, it marks the double buffer 1151 * as invalid, the double buffer will then be recreated on the next 1152 * invocation of getOffscreenBuffer. 1153 */ 1154 void resetDoubleBuffer() { 1155 if (standardDoubleBuffer != null) { 1156 standardDoubleBuffer.needsReset = true; 1157 } 1158 } 1159 1160 /** 1161 * This resets the volatile double buffer. 1162 */ 1163 void resetVolatileDoubleBuffer(GraphicsConfiguration gc) { 1164 Image image = volatileMap.remove(gc); 1165 if (image != null) { 1166 image.flush(); 1167 } 1168 } 1169 1170 /** 1171 * Returns true if we should use the <code>Image</code> returned 1172 * from <code>getVolatileOffscreenBuffer</code> to do double buffering. 1173 */ 1174 boolean useVolatileDoubleBuffer() { 1175 return volatileImageBufferEnabled; 1176 } 1177 1178 /** 1179 * Returns true if the current thread is the thread painting. This 1180 * will return false if no threads are painting. 1181 */ 1182 private synchronized boolean isPaintingThread() { 1183 return (Thread.currentThread() == paintThread); 1184 } 1185 // 1186 // Paint methods. You very, VERY rarely need to invoke these. 1187 // They are invoked directly from JComponent's painting code and 1188 // when painting happens outside the normal flow: DefaultDesktopManager 1189 // and JViewport. If you end up needing these methods in other places be 1190 // careful that you don't get stuck in a paint loop. 1191 // 1192 1193 /** 1194 * Paints a region of a component 1195 * 1196 * @param paintingComponent Component to paint 1197 * @param bufferComponent Component to obtain buffer for 1198 * @param g Graphics to paint to 1199 * @param x X-coordinate 1200 * @param y Y-coordinate 1201 * @param w Width 1202 * @param h Height 1203 */ 1204 void paint(JComponent paintingComponent, 1205 JComponent bufferComponent, Graphics g, 1206 int x, int y, int w, int h) { 1207 PaintManager paintManager = getPaintManager(); 1208 if (!isPaintingThread()) { 1209 // We're painting to two threads at once. PaintManager deals 1210 // with this a bit better than BufferStrategyPaintManager, use 1211 // it to avoid possible exceptions/corruption. 1212 if (paintManager.getClass() != PaintManager.class) { 1213 paintManager = new PaintManager(); 1214 paintManager.repaintManager = this; 1215 } 1216 } 1217 if (!paintManager.paint(paintingComponent, bufferComponent, g, 1218 x, y, w, h)) { 1219 g.setClip(x, y, w, h); 1220 paintingComponent.paintToOffscreen(g, x, y, w, h, x + w, y + h); 1221 } 1222 } 1223 1224 /** 1225 * Does a copy area on the specified region. 1226 * 1227 * @param clip Whether or not the copyArea needs to be clipped to the 1228 * Component's bounds. 1229 */ 1230 void copyArea(JComponent c, Graphics g, int x, int y, int w, int h, 1231 int deltaX, int deltaY, boolean clip) { 1232 getPaintManager().copyArea(c, g, x, y, w, h, deltaX, deltaY, clip); 1233 } 1234 1235 /** 1236 * Invoked prior to any paint/copyArea method calls. This will 1237 * be followed by an invocation of <code>endPaint</code>. 1238 * <b>WARNING</b>: Callers of this method need to wrap the call 1239 * in a <code>try/finally</code>, otherwise if an exception is thrown 1240 * during the course of painting the RepaintManager may 1241 * be left in a state in which the screen is not updated, eg: 1242 * <pre> 1243 * repaintManager.beginPaint(); 1244 * try { 1245 * repaintManager.paint(...); 1246 * } finally { 1247 * repaintManager.endPaint(); 1248 * } 1249 * </pre> 1250 */ 1251 void beginPaint() { 1252 boolean multiThreadedPaint = false; 1253 int paintDepth; 1254 Thread currentThread = Thread.currentThread(); 1255 synchronized(this) { 1256 paintDepth = this.paintDepth; 1257 if (paintThread == null || currentThread == paintThread) { 1258 paintThread = currentThread; 1259 this.paintDepth++; 1260 } else { 1261 multiThreadedPaint = true; 1262 } 1263 } 1264 if (!multiThreadedPaint && paintDepth == 0) { 1265 getPaintManager().beginPaint(); 1266 } 1267 } 1268 1269 /** 1270 * Invoked after <code>beginPaint</code> has been invoked. 1271 */ 1272 void endPaint() { 1273 if (isPaintingThread()) { 1274 PaintManager paintManager = null; 1275 synchronized(this) { 1276 if (--paintDepth == 0) { 1277 paintManager = getPaintManager(); 1278 } 1279 } 1280 if (paintManager != null) { 1281 paintManager.endPaint(); 1282 synchronized(this) { 1283 paintThread = null; 1284 } 1285 } 1286 } 1287 } 1288 1289 /** 1290 * If possible this will show a previously rendered portion of 1291 * a Component. If successful, this will return true, otherwise false. 1292 * <p> 1293 * WARNING: This method is invoked from the native toolkit thread, be 1294 * very careful as to what methods this invokes! 1295 */ 1296 boolean show(Container c, int x, int y, int w, int h) { 1297 return getPaintManager().show(c, x, y, w, h); 1298 } 1299 1300 /** 1301 * Invoked when the doubleBuffered or useTrueDoubleBuffering 1302 * properties of a JRootPane change. This may come in on any thread. 1303 */ 1304 void doubleBufferingChanged(JRootPane rootPane) { 1305 getPaintManager().doubleBufferingChanged(rootPane); 1306 } 1307 1308 /** 1309 * Sets the <code>PaintManager</code> that is used to handle all 1310 * double buffered painting. 1311 * 1312 * @param paintManager The PaintManager to use. Passing in null indicates 1313 * the fallback PaintManager should be used. 1314 */ 1315 void setPaintManager(PaintManager paintManager) { 1316 if (paintManager == null) { 1317 paintManager = new PaintManager(); 1318 } 1319 PaintManager oldPaintManager; 1320 synchronized(this) { 1321 oldPaintManager = this.paintManager; 1322 this.paintManager = paintManager; 1323 paintManager.repaintManager = this; 1324 } 1325 if (oldPaintManager != null) { 1326 oldPaintManager.dispose(); 1327 } 1328 } 1329 1330 private synchronized PaintManager getPaintManager() { 1331 if (paintManager == null) { 1332 PaintManager paintManager = null; 1333 if (doubleBufferingEnabled && !nativeDoubleBuffering) { 1334 switch (bufferStrategyType) { 1335 case BUFFER_STRATEGY_NOT_SPECIFIED: 1336 Toolkit tk = Toolkit.getDefaultToolkit(); 1337 if (tk instanceof SunToolkit) { 1338 SunToolkit stk = (SunToolkit) tk; 1339 if (stk.useBufferPerWindow()) { 1340 paintManager = new BufferStrategyPaintManager(); 1341 } 1342 } 1343 break; 1344 case BUFFER_STRATEGY_SPECIFIED_ON: 1345 paintManager = new BufferStrategyPaintManager(); 1346 break; 1347 default: 1348 break; 1349 } 1350 } 1351 // null case handled in setPaintManager 1352 setPaintManager(paintManager); 1353 } 1354 return paintManager; 1355 } 1356 1357 private void scheduleProcessingRunnable() { 1358 scheduleProcessingRunnable(AppContext.getAppContext()); 1359 } 1360 1361 private void scheduleProcessingRunnable(AppContext context) { 1362 if (processingRunnable.markPending()) { 1363 Toolkit tk = Toolkit.getDefaultToolkit(); 1364 if (tk instanceof SunToolkit) { 1365 SunToolkit.getSystemEventQueueImplPP(context). 1366 postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), 1367 processingRunnable)); 1368 } else { 1369 Toolkit.getDefaultToolkit().getSystemEventQueue(). 1370 postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(), 1371 processingRunnable)); 1372 } 1373 } 1374 } 1375 1376 1377 /** 1378 * PaintManager is used to handle all double buffered painting for 1379 * Swing. Subclasses should call back into the JComponent method 1380 * <code>paintToOffscreen</code> to handle the actual painting. 1381 */ 1382 static class PaintManager { 1383 /** 1384 * RepaintManager the PaintManager has been installed on. 1385 */ 1386 protected RepaintManager repaintManager; 1387 boolean isRepaintingRoot; 1388 1389 /** 1390 * Paints a region of a component 1391 * 1392 * @param paintingComponent Component to paint 1393 * @param bufferComponent Component to obtain buffer for 1394 * @param g Graphics to paint to 1395 * @param x X-coordinate 1396 * @param y Y-coordinate 1397 * @param w Width 1398 * @param h Height 1399 * @return true if painting was successful. 1400 */ 1401 public boolean paint(JComponent paintingComponent, 1402 JComponent bufferComponent, Graphics g, 1403 int x, int y, int w, int h) { 1404 // First attempt to use VolatileImage buffer for performance. 1405 // If this fails (which should rarely occur), fallback to a 1406 // standard Image buffer. 1407 boolean paintCompleted = false; 1408 Image offscreen; 1409 if (repaintManager.useVolatileDoubleBuffer() && 1410 (offscreen = getValidImage(repaintManager. 1411 getVolatileOffscreenBuffer(bufferComponent, w, h))) != null) { 1412 VolatileImage vImage = (java.awt.image.VolatileImage)offscreen; 1413 GraphicsConfiguration gc = bufferComponent. 1414 getGraphicsConfiguration(); 1415 for (int i = 0; !paintCompleted && 1416 i < RepaintManager.VOLATILE_LOOP_MAX; i++) { 1417 if (vImage.validate(gc) == 1418 VolatileImage.IMAGE_INCOMPATIBLE) { 1419 repaintManager.resetVolatileDoubleBuffer(gc); 1420 offscreen = repaintManager.getVolatileOffscreenBuffer( 1421 bufferComponent,w, h); 1422 vImage = (java.awt.image.VolatileImage)offscreen; 1423 } 1424 paintDoubleBuffered(paintingComponent, vImage, g, x, y, 1425 w, h); 1426 paintCompleted = !vImage.contentsLost(); 1427 } 1428 } 1429 // VolatileImage painting loop failed, fallback to regular 1430 // offscreen buffer 1431 if (!paintCompleted && (offscreen = getValidImage( 1432 repaintManager.getOffscreenBuffer( 1433 bufferComponent, w, h))) != null) { 1434 paintDoubleBuffered(paintingComponent, offscreen, g, x, y, w, 1435 h); 1436 paintCompleted = true; 1437 } 1438 return paintCompleted; 1439 } 1440 1441 /** 1442 * Does a copy area on the specified region. 1443 */ 1444 public void copyArea(JComponent c, Graphics g, int x, int y, int w, 1445 int h, int deltaX, int deltaY, boolean clip) { 1446 g.copyArea(x, y, w, h, deltaX, deltaY); 1447 } 1448 1449 /** 1450 * Invoked prior to any calls to paint or copyArea. 1451 */ 1452 public void beginPaint() { 1453 } 1454 1455 /** 1456 * Invoked to indicate painting has been completed. 1457 */ 1458 public void endPaint() { 1459 } 1460 1461 /** 1462 * Shows a region of a previously rendered component. This 1463 * will return true if successful, false otherwise. The default 1464 * implementation returns false. 1465 */ 1466 public boolean show(Container c, int x, int y, int w, int h) { 1467 return false; 1468 } 1469 1470 /** 1471 * Invoked when the doubleBuffered or useTrueDoubleBuffering 1472 * properties of a JRootPane change. This may come in on any thread. 1473 */ 1474 public void doubleBufferingChanged(JRootPane rootPane) { 1475 } 1476 1477 /** 1478 * Paints a portion of a component to an offscreen buffer. 1479 */ 1480 protected void paintDoubleBuffered(JComponent c, Image image, 1481 Graphics g, int clipX, int clipY, 1482 int clipW, int clipH) { 1483 Graphics osg = image.getGraphics(); 1484 int bw = Math.min(clipW, image.getWidth(null)); 1485 int bh = Math.min(clipH, image.getHeight(null)); 1486 int x,y,maxx,maxy; 1487 1488 try { 1489 for(x = clipX, maxx = clipX+clipW; x < maxx ; x += bw ) { 1490 for(y=clipY, maxy = clipY + clipH; y < maxy ; y += bh) { 1491 osg.translate(-x, -y); 1492 osg.setClip(x,y,bw,bh); 1493 c.paintToOffscreen(osg, x, y, bw, bh, maxx, maxy); 1494 g.setClip(x, y, bw, bh); 1495 g.drawImage(image, x, y, c); 1496 osg.translate(x, y); 1497 } 1498 } 1499 } finally { 1500 osg.dispose(); 1501 } 1502 } 1503 1504 /** 1505 * If <code>image</code> is non-null with a positive size it 1506 * is returned, otherwise null is returned. 1507 */ 1508 private Image getValidImage(Image image) { 1509 if (image != null && image.getWidth(null) > 0 && 1510 image.getHeight(null) > 0) { 1511 return image; 1512 } 1513 return null; 1514 } 1515 1516 /** 1517 * Schedules a repaint for the specified component. This differs 1518 * from <code>root.repaint</code> in that if the RepaintManager is 1519 * currently processing paint requests it'll process this request 1520 * with the current set of requests. 1521 */ 1522 protected void repaintRoot(JComponent root) { 1523 assert (repaintManager.repaintRoot == null); 1524 if (repaintManager.painting) { 1525 repaintManager.repaintRoot = root; 1526 } 1527 else { 1528 root.repaint(); 1529 } 1530 } 1531 1532 /** 1533 * Returns true if the component being painted is the root component 1534 * that was previously passed to <code>repaintRoot</code>. 1535 */ 1536 protected boolean isRepaintingRoot() { 1537 return isRepaintingRoot; 1538 } 1539 1540 /** 1541 * Cleans up any state. After invoked the PaintManager will no 1542 * longer be used anymore. 1543 */ 1544 protected void dispose() { 1545 } 1546 } 1547 1548 1549 private class DoubleBufferInfo { 1550 public Image image; 1551 public Dimension size; 1552 public boolean needsReset = false; 1553 } 1554 1555 1556 /** 1557 * Listener installed to detect display changes. When display changes, 1558 * schedules a callback to notify all RepaintManagers of the display 1559 * changes. Only one DisplayChangedHandler is ever installed. The 1560 * singleton instance will schedule notification for all AppContexts. 1561 */ 1562 private static final class DisplayChangedHandler implements 1563 DisplayChangedListener { 1564 public void displayChanged() { 1565 scheduleDisplayChanges(); 1566 } 1567 1568 public void paletteChanged() { 1569 } 1570 1571 private void scheduleDisplayChanges() { 1572 // To avoid threading problems, we notify each RepaintManager 1573 // on the thread it was created on. 1574 for (Object c : AppContext.getAppContexts()) { 1575 AppContext context = (AppContext) c; 1576 synchronized(context) { 1577 if (!context.isDisposed()) { 1578 EventQueue eventQueue = (EventQueue)context.get( 1579 AppContext.EVENT_QUEUE_KEY); 1580 if (eventQueue != null) { 1581 eventQueue.postEvent(new InvocationEvent( 1582 Toolkit.getDefaultToolkit(), 1583 new DisplayChangedRunnable())); 1584 } 1585 } 1586 } 1587 } 1588 } 1589 } 1590 1591 1592 private static final class DisplayChangedRunnable implements Runnable { 1593 public void run() { 1594 RepaintManager.currentManager((JComponent)null).displayChanged(); 1595 } 1596 } 1597 1598 1599 /** 1600 * Runnable used to process all repaint/revalidate requests. 1601 */ 1602 private final class ProcessingRunnable implements Runnable { 1603 // If true, we're wainting on the EventQueue. 1604 private boolean pending; 1605 1606 /** 1607 * Marks this processing runnable as pending. If this was not 1608 * already marked as pending, true is returned. 1609 */ 1610 public synchronized boolean markPending() { 1611 if (!pending) { 1612 pending = true; 1613 return true; 1614 } 1615 return false; 1616 } 1617 1618 public void run() { 1619 synchronized (this) { 1620 pending = false; 1621 } 1622 // First pass, flush any heavy paint events into real paint 1623 // events. If there are pending heavy weight requests this will 1624 // result in q'ing this request up one more time. As 1625 // long as no other requests come in between now and the time 1626 // the second one is processed nothing will happen. This is not 1627 // ideal, but the logic needed to suppress the second request is 1628 // more headache than it's worth. 1629 scheduleHeavyWeightPaints(); 1630 // Do the actual validation and painting. 1631 validateInvalidComponents(); 1632 prePaintDirtyRegions(); 1633 } 1634 } 1635 private RepaintManager getDelegate(Component c) { 1636 RepaintManager delegate = SwingUtilities3.getDelegateRepaintManager(c); 1637 if (this == delegate) { 1638 delegate = null; 1639 } 1640 return delegate; 1641 } 1642 }