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