rev 10520 : 8055723[client]: Replace concat String to append in StringBuilder parameters
Contributed-by: Otavio Santana <otaviojava@java.net>

   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         StringBuilder sb = new StringBuilder();
 994         if(dirtyComponents != null)
 995             sb.append("" + dirtyComponents);
 996         return sb.toString();
 997     }
 998 
 999 
1000     /**
1001      * Return the offscreen buffer that should be used as a double buffer with
1002      * the component <code>c</code>.
1003      * By default there is a double buffer per RepaintManager.
1004      * The buffer might be smaller than <code>(proposedWidth,proposedHeight)</code>
1005      * This happens when the maximum double buffer size as been set for the receiving
1006      * repaint manager.
1007      *
1008      * @param c the component
1009      * @param proposedWidth the width of the buffer
1010      * @param proposedHeight the height of the buffer
1011      *
1012      * @return the image
1013      */
1014     public Image getOffscreenBuffer(Component c,int proposedWidth,int proposedHeight) {
1015         RepaintManager delegate = getDelegate(c);
1016         if (delegate != null) {
1017             return delegate.getOffscreenBuffer(c, proposedWidth, proposedHeight);
1018         }
1019         return _getOffscreenBuffer(c, proposedWidth, proposedHeight);
1020     }
1021 
1022     /**
1023      * Return a volatile offscreen buffer that should be used as a
1024      * double buffer with the specified component <code>c</code>.
1025      * The image returned will be an instance of VolatileImage, or null
1026      * if a VolatileImage object could not be instantiated.
1027      * This buffer might be smaller than <code>(proposedWidth,proposedHeight)</code>.
1028      * This happens when the maximum double buffer size has been set for this
1029      * repaint manager.
1030      *
1031      * @param c the component
1032      * @param proposedWidth the width of the buffer
1033      * @param proposedHeight the height of the buffer
1034      *
1035      * @return the volatile image
1036      * @see java.awt.image.VolatileImage
1037      * @since 1.4
1038      */
1039     public Image getVolatileOffscreenBuffer(Component c,
1040                                             int proposedWidth,int proposedHeight) {
1041         RepaintManager delegate = getDelegate(c);
1042         if (delegate != null) {
1043             return delegate.getVolatileOffscreenBuffer(c, proposedWidth,
1044                                                         proposedHeight);
1045         }
1046 
1047         // If the window is non-opaque, it's double-buffered at peer's level
1048         Window w = (c instanceof Window) ? (Window)c : SwingUtilities.getWindowAncestor(c);
1049         if (!w.isOpaque()) {
1050             Toolkit tk = Toolkit.getDefaultToolkit();
1051             if ((tk instanceof SunToolkit) && (((SunToolkit)tk).needUpdateWindow())) {
1052                 return null;
1053             }
1054         }
1055 
1056         GraphicsConfiguration config = c.getGraphicsConfiguration();
1057         if (config == null) {
1058             config = GraphicsEnvironment.getLocalGraphicsEnvironment().
1059                             getDefaultScreenDevice().getDefaultConfiguration();
1060         }
1061         Dimension maxSize = getDoubleBufferMaximumSize();
1062         int width = proposedWidth < 1 ? 1 :
1063             (proposedWidth > maxSize.width? maxSize.width : proposedWidth);
1064         int height = proposedHeight < 1 ? 1 :
1065             (proposedHeight > maxSize.height? maxSize.height : proposedHeight);
1066         VolatileImage image = volatileMap.get(config);
1067         if (image == null || image.getWidth() < width ||
1068                              image.getHeight() < height) {
1069             if (image != null) {
1070                 image.flush();
1071             }
1072             image = config.createCompatibleVolatileImage(width, height,
1073                                                          volatileBufferType);
1074             volatileMap.put(config, image);
1075         }
1076         return image;
1077     }
1078 
1079     private Image _getOffscreenBuffer(Component c, int proposedWidth, int proposedHeight) {
1080         Dimension maxSize = getDoubleBufferMaximumSize();
1081         DoubleBufferInfo doubleBuffer;
1082         int width, height;
1083 
1084         // If the window is non-opaque, it's double-buffered at peer's level
1085         Window w = (c instanceof Window) ? (Window)c : SwingUtilities.getWindowAncestor(c);
1086         if (!w.isOpaque()) {
1087             Toolkit tk = Toolkit.getDefaultToolkit();
1088             if ((tk instanceof SunToolkit) && (((SunToolkit)tk).needUpdateWindow())) {
1089                 return null;
1090             }
1091         }
1092 
1093         if (standardDoubleBuffer == null) {
1094             standardDoubleBuffer = new DoubleBufferInfo();
1095         }
1096         doubleBuffer = standardDoubleBuffer;
1097 
1098         width = proposedWidth < 1? 1 :
1099                   (proposedWidth > maxSize.width? maxSize.width : proposedWidth);
1100         height = proposedHeight < 1? 1 :
1101                   (proposedHeight > maxSize.height? maxSize.height : proposedHeight);
1102 
1103         if (doubleBuffer.needsReset || (doubleBuffer.image != null &&
1104                                         (doubleBuffer.size.width < width ||
1105                                          doubleBuffer.size.height < height))) {
1106             doubleBuffer.needsReset = false;
1107             if (doubleBuffer.image != null) {
1108                 doubleBuffer.image.flush();
1109                 doubleBuffer.image = null;
1110             }
1111             width = Math.max(doubleBuffer.size.width, width);
1112             height = Math.max(doubleBuffer.size.height, height);
1113         }
1114 
1115         Image result = doubleBuffer.image;
1116 
1117         if (doubleBuffer.image == null) {
1118             result = c.createImage(width , height);
1119             doubleBuffer.size = new Dimension(width, height);
1120             if (c instanceof JComponent) {
1121                 ((JComponent)c).setCreatedDoubleBuffer(true);
1122                 doubleBuffer.image = result;
1123             }
1124             // JComponent will inform us when it is no longer valid
1125             // (via removeNotify) we have no such hook to other components,
1126             // therefore we don't keep a ref to the Component
1127             // (indirectly through the Image) by stashing the image.
1128         }
1129         return result;
1130     }
1131 
1132 
1133     /**
1134      * Set the maximum double buffer size.
1135      *
1136      * @param d the dimension
1137      */
1138     public void setDoubleBufferMaximumSize(Dimension d) {
1139         doubleBufferMaxSize = d;
1140         if (doubleBufferMaxSize == null) {
1141             clearImages();
1142         } else {
1143             clearImages(d.width, d.height);
1144         }
1145     }
1146 
1147     private void clearImages() {
1148         clearImages(0, 0);
1149     }
1150 
1151     private void clearImages(int width, int height) {
1152         if (standardDoubleBuffer != null && standardDoubleBuffer.image != null) {
1153             if (standardDoubleBuffer.image.getWidth(null) > width ||
1154                 standardDoubleBuffer.image.getHeight(null) > height) {
1155                 standardDoubleBuffer.image.flush();
1156                 standardDoubleBuffer.image = null;
1157             }
1158         }
1159         // Clear out the VolatileImages
1160         Iterator<GraphicsConfiguration> gcs = volatileMap.keySet().iterator();
1161         while (gcs.hasNext()) {
1162             GraphicsConfiguration gc = gcs.next();
1163             VolatileImage image = volatileMap.get(gc);
1164             if (image.getWidth() > width || image.getHeight() > height) {
1165                 image.flush();
1166                 gcs.remove();
1167             }
1168         }
1169     }
1170 
1171     /**
1172      * Returns the maximum double buffer size.
1173      *
1174      * @return a Dimension object representing the maximum size
1175      */
1176     public Dimension getDoubleBufferMaximumSize() {
1177         if (doubleBufferMaxSize == null) {
1178             try {
1179                 Rectangle virtualBounds = new Rectangle();
1180                 GraphicsEnvironment ge = GraphicsEnvironment.
1181                                                  getLocalGraphicsEnvironment();
1182                 for (GraphicsDevice gd : ge.getScreenDevices()) {
1183                     GraphicsConfiguration gc = gd.getDefaultConfiguration();
1184                     virtualBounds = virtualBounds.union(gc.getBounds());
1185                 }
1186                 doubleBufferMaxSize = new Dimension(virtualBounds.width,
1187                                                     virtualBounds.height);
1188             } catch (HeadlessException e) {
1189                 doubleBufferMaxSize = new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
1190             }
1191         }
1192         return doubleBufferMaxSize;
1193     }
1194 
1195     /**
1196      * Enables or disables double buffering in this RepaintManager.
1197      * CAUTION: The default value for this property is set for optimal
1198      * paint performance on the given platform and it is not recommended
1199      * that programs modify this property directly.
1200      *
1201      * @param aFlag  true to activate double buffering
1202      * @see #isDoubleBufferingEnabled
1203      */
1204     public void setDoubleBufferingEnabled(boolean aFlag) {
1205         doubleBufferingEnabled = aFlag;
1206         PaintManager paintManager = getPaintManager();
1207         if (!aFlag && paintManager.getClass() != PaintManager.class) {
1208             setPaintManager(new PaintManager());
1209         }
1210     }
1211 
1212     /**
1213      * Returns true if this RepaintManager is double buffered.
1214      * The default value for this property may vary from platform
1215      * to platform.  On platforms where native double buffering
1216      * is supported in the AWT, the default value will be <code>false</code>
1217      * to avoid unnecessary buffering in Swing.
1218      * On platforms where native double buffering is not supported,
1219      * the default value will be <code>true</code>.
1220      *
1221      * @return true if this object is double buffered
1222      */
1223     public boolean isDoubleBufferingEnabled() {
1224         return doubleBufferingEnabled;
1225     }
1226 
1227     /**
1228      * This resets the double buffer. Actually, it marks the double buffer
1229      * as invalid, the double buffer will then be recreated on the next
1230      * invocation of getOffscreenBuffer.
1231      */
1232     void resetDoubleBuffer() {
1233         if (standardDoubleBuffer != null) {
1234             standardDoubleBuffer.needsReset = true;
1235         }
1236     }
1237 
1238     /**
1239      * This resets the volatile double buffer.
1240      */
1241     void resetVolatileDoubleBuffer(GraphicsConfiguration gc) {
1242         Image image = volatileMap.remove(gc);
1243         if (image != null) {
1244             image.flush();
1245         }
1246     }
1247 
1248     /**
1249      * Returns true if we should use the <code>Image</code> returned
1250      * from <code>getVolatileOffscreenBuffer</code> to do double buffering.
1251      */
1252     boolean useVolatileDoubleBuffer() {
1253         return volatileImageBufferEnabled;
1254     }
1255 
1256     /**
1257      * Returns true if the current thread is the thread painting.  This
1258      * will return false if no threads are painting.
1259      */
1260     private synchronized boolean isPaintingThread() {
1261         return (Thread.currentThread() == paintThread);
1262     }
1263     //
1264     // Paint methods.  You very, VERY rarely need to invoke these.
1265     // They are invoked directly from JComponent's painting code and
1266     // when painting happens outside the normal flow: DefaultDesktopManager
1267     // and JViewport.  If you end up needing these methods in other places be
1268     // careful that you don't get stuck in a paint loop.
1269     //
1270 
1271     /**
1272      * Paints a region of a component
1273      *
1274      * @param paintingComponent Component to paint
1275      * @param bufferComponent Component to obtain buffer for
1276      * @param g Graphics to paint to
1277      * @param x X-coordinate
1278      * @param y Y-coordinate
1279      * @param w Width
1280      * @param h Height
1281      */
1282     void paint(JComponent paintingComponent,
1283                JComponent bufferComponent, Graphics g,
1284                int x, int y, int w, int h) {
1285         PaintManager paintManager = getPaintManager();
1286         if (!isPaintingThread()) {
1287             // We're painting to two threads at once.  PaintManager deals
1288             // with this a bit better than BufferStrategyPaintManager, use
1289             // it to avoid possible exceptions/corruption.
1290             if (paintManager.getClass() != PaintManager.class) {
1291                 paintManager = new PaintManager();
1292                 paintManager.repaintManager = this;
1293             }
1294         }
1295         if (!paintManager.paint(paintingComponent, bufferComponent, g,
1296                                 x, y, w, h)) {
1297             g.setClip(x, y, w, h);
1298             paintingComponent.paintToOffscreen(g, x, y, w, h, x + w, y + h);
1299         }
1300     }
1301 
1302     /**
1303      * Does a copy area on the specified region.
1304      *
1305      * @param clip Whether or not the copyArea needs to be clipped to the
1306      *             Component's bounds.
1307      */
1308     void copyArea(JComponent c, Graphics g, int x, int y, int w, int h,
1309                   int deltaX, int deltaY, boolean clip) {
1310         getPaintManager().copyArea(c, g, x, y, w, h, deltaX, deltaY, clip);
1311     }
1312 
1313     private java.util.List<RepaintListener> repaintListeners = new ArrayList<>(1);
1314 
1315     private void addRepaintListener(RepaintListener l) {
1316         repaintListeners.add(l);
1317     }
1318 
1319     private void removeRepaintListener(RepaintListener l) {
1320         repaintListeners.remove(l);
1321     }
1322 
1323     /**
1324      * Notify the attached repaint listeners that an area of the {@code c} component
1325      * has been immediately repainted, that is without scheduling a repaint runnable,
1326      * due to performing a "blit" (via calling the {@code copyArea} method).
1327      *
1328      * @param c the component
1329      * @param x the x coordinate of the area
1330      * @param y the y coordinate of the area
1331      * @param w the width of the area
1332      * @param h the height of the area
1333      */
1334     void notifyRepaintPerformed(JComponent c, int x, int y, int w, int h) {
1335         for (RepaintListener l : repaintListeners) {
1336             l.repaintPerformed(c, x, y, w, h);
1337         }
1338     }
1339 
1340     /**
1341      * Invoked prior to any paint/copyArea method calls.  This will
1342      * be followed by an invocation of <code>endPaint</code>.
1343      * <b>WARNING</b>: Callers of this method need to wrap the call
1344      * in a <code>try/finally</code>, otherwise if an exception is thrown
1345      * during the course of painting the RepaintManager may
1346      * be left in a state in which the screen is not updated, eg:
1347      * <pre>
1348      * repaintManager.beginPaint();
1349      * try {
1350      *   repaintManager.paint(...);
1351      * } finally {
1352      *   repaintManager.endPaint();
1353      * }
1354      * </pre>
1355      */
1356     void beginPaint() {
1357         boolean multiThreadedPaint = false;
1358         int paintDepth;
1359         Thread currentThread = Thread.currentThread();
1360         synchronized(this) {
1361             paintDepth = this.paintDepth;
1362             if (paintThread == null || currentThread == paintThread) {
1363                 paintThread = currentThread;
1364                 this.paintDepth++;
1365             } else {
1366                 multiThreadedPaint = true;
1367             }
1368         }
1369         if (!multiThreadedPaint && paintDepth == 0) {
1370             getPaintManager().beginPaint();
1371         }
1372     }
1373 
1374     /**
1375      * Invoked after <code>beginPaint</code> has been invoked.
1376      */
1377     void endPaint() {
1378         if (isPaintingThread()) {
1379             PaintManager paintManager = null;
1380             synchronized(this) {
1381                 if (--paintDepth == 0) {
1382                     paintManager = getPaintManager();
1383                 }
1384             }
1385             if (paintManager != null) {
1386                 paintManager.endPaint();
1387                 synchronized(this) {
1388                     paintThread = null;
1389                 }
1390             }
1391         }
1392     }
1393 
1394     /**
1395      * If possible this will show a previously rendered portion of
1396      * a Component.  If successful, this will return true, otherwise false.
1397      * <p>
1398      * WARNING: This method is invoked from the native toolkit thread, be
1399      * very careful as to what methods this invokes!
1400      */
1401     boolean show(Container c, int x, int y, int w, int h) {
1402         return getPaintManager().show(c, x, y, w, h);
1403     }
1404 
1405     /**
1406      * Invoked when the doubleBuffered or useTrueDoubleBuffering
1407      * properties of a JRootPane change.  This may come in on any thread.
1408      */
1409     void doubleBufferingChanged(JRootPane rootPane) {
1410         getPaintManager().doubleBufferingChanged(rootPane);
1411     }
1412 
1413     /**
1414      * Sets the <code>PaintManager</code> that is used to handle all
1415      * double buffered painting.
1416      *
1417      * @param paintManager The PaintManager to use.  Passing in null indicates
1418      *        the fallback PaintManager should be used.
1419      */
1420     void setPaintManager(PaintManager paintManager) {
1421         if (paintManager == null) {
1422             paintManager = new PaintManager();
1423         }
1424         PaintManager oldPaintManager;
1425         synchronized(this) {
1426             oldPaintManager = this.paintManager;
1427             this.paintManager = paintManager;
1428             paintManager.repaintManager = this;
1429         }
1430         if (oldPaintManager != null) {
1431             oldPaintManager.dispose();
1432         }
1433     }
1434 
1435     private synchronized PaintManager getPaintManager() {
1436         if (paintManager == null) {
1437             PaintManager paintManager = null;
1438             if (doubleBufferingEnabled && !nativeDoubleBuffering) {
1439                 switch (bufferStrategyType) {
1440                 case BUFFER_STRATEGY_NOT_SPECIFIED:
1441                     Toolkit tk = Toolkit.getDefaultToolkit();
1442                     if (tk instanceof SunToolkit) {
1443                         SunToolkit stk = (SunToolkit) tk;
1444                         if (stk.useBufferPerWindow()) {
1445                             paintManager = new BufferStrategyPaintManager();
1446                         }
1447                     }
1448                     break;
1449                 case BUFFER_STRATEGY_SPECIFIED_ON:
1450                     paintManager = new BufferStrategyPaintManager();
1451                     break;
1452                 default:
1453                     break;
1454                 }
1455             }
1456             // null case handled in setPaintManager
1457             setPaintManager(paintManager);
1458         }
1459         return paintManager;
1460     }
1461 
1462     private void scheduleProcessingRunnable(AppContext context) {
1463         if (processingRunnable.markPending()) {
1464             Toolkit tk = Toolkit.getDefaultToolkit();
1465             if (tk instanceof SunToolkit) {
1466                 SunToolkit.getSystemEventQueueImplPP(context).
1467                   postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(),
1468                                                 processingRunnable));
1469             } else {
1470                 Toolkit.getDefaultToolkit().getSystemEventQueue().
1471                       postEvent(new InvocationEvent(Toolkit.getDefaultToolkit(),
1472                                                     processingRunnable));
1473             }
1474         }
1475     }
1476 
1477 
1478     /**
1479      * PaintManager is used to handle all double buffered painting for
1480      * Swing.  Subclasses should call back into the JComponent method
1481      * <code>paintToOffscreen</code> to handle the actual painting.
1482      */
1483     static class PaintManager {
1484         /**
1485          * RepaintManager the PaintManager has been installed on.
1486          */
1487         protected RepaintManager repaintManager;
1488         boolean isRepaintingRoot;
1489 
1490         /**
1491          * Paints a region of a component
1492          *
1493          * @param paintingComponent Component to paint
1494          * @param bufferComponent Component to obtain buffer for
1495          * @param g Graphics to paint to
1496          * @param x X-coordinate
1497          * @param y Y-coordinate
1498          * @param w Width
1499          * @param h Height
1500          * @return true if painting was successful.
1501          */
1502         public boolean paint(JComponent paintingComponent,
1503                              JComponent bufferComponent, Graphics g,
1504                              int x, int y, int w, int h) {
1505             // First attempt to use VolatileImage buffer for performance.
1506             // If this fails (which should rarely occur), fallback to a
1507             // standard Image buffer.
1508             boolean paintCompleted = false;
1509             Image offscreen;
1510             if (repaintManager.useVolatileDoubleBuffer() &&
1511                 (offscreen = getValidImage(repaintManager.
1512                 getVolatileOffscreenBuffer(bufferComponent, w, h))) != null) {
1513                 VolatileImage vImage = (java.awt.image.VolatileImage)offscreen;
1514                 GraphicsConfiguration gc = bufferComponent.
1515                                             getGraphicsConfiguration();
1516                 for (int i = 0; !paintCompleted &&
1517                          i < RepaintManager.VOLATILE_LOOP_MAX; i++) {
1518                     if (vImage.validate(gc) ==
1519                                    VolatileImage.IMAGE_INCOMPATIBLE) {
1520                         repaintManager.resetVolatileDoubleBuffer(gc);
1521                         offscreen = repaintManager.getVolatileOffscreenBuffer(
1522                             bufferComponent,w, h);
1523                         vImage = (java.awt.image.VolatileImage)offscreen;
1524                     }
1525                     paintDoubleBuffered(paintingComponent, vImage, g, x, y,
1526                                         w, h);
1527                     paintCompleted = !vImage.contentsLost();
1528                 }
1529             }
1530             // VolatileImage painting loop failed, fallback to regular
1531             // offscreen buffer
1532             if (!paintCompleted && (offscreen = getValidImage(
1533                       repaintManager.getOffscreenBuffer(
1534                       bufferComponent, w, h))) != null) {
1535                 paintDoubleBuffered(paintingComponent, offscreen, g, x, y, w,
1536                                     h);
1537                 paintCompleted = true;
1538             }
1539             return paintCompleted;
1540         }
1541 
1542         /**
1543          * Does a copy area on the specified region.
1544          */
1545         public void copyArea(JComponent c, Graphics g, int x, int y, int w,
1546                              int h, int deltaX, int deltaY, boolean clip) {
1547             g.copyArea(x, y, w, h, deltaX, deltaY);
1548         }
1549 
1550         /**
1551          * Invoked prior to any calls to paint or copyArea.
1552          */
1553         public void beginPaint() {
1554         }
1555 
1556         /**
1557          * Invoked to indicate painting has been completed.
1558          */
1559         public void endPaint() {
1560         }
1561 
1562         /**
1563          * Shows a region of a previously rendered component.  This
1564          * will return true if successful, false otherwise.  The default
1565          * implementation returns false.
1566          */
1567         public boolean show(Container c, int x, int y, int w, int h) {
1568             return false;
1569         }
1570 
1571         /**
1572          * Invoked when the doubleBuffered or useTrueDoubleBuffering
1573          * properties of a JRootPane change.  This may come in on any thread.
1574          */
1575         public void doubleBufferingChanged(JRootPane rootPane) {
1576         }
1577 
1578         /**
1579          * Paints a portion of a component to an offscreen buffer.
1580          */
1581         protected void paintDoubleBuffered(JComponent c, Image image,
1582                             Graphics g, int clipX, int clipY,
1583                             int clipW, int clipH) {
1584             Graphics osg = image.getGraphics();
1585             int bw = Math.min(clipW, image.getWidth(null));
1586             int bh = Math.min(clipH, image.getHeight(null));
1587             int x,y,maxx,maxy;
1588 
1589             try {
1590                 for(x = clipX, maxx = clipX+clipW; x < maxx ;  x += bw ) {
1591                     for(y=clipY, maxy = clipY + clipH; y < maxy ; y += bh) {
1592                         osg.translate(-x, -y);
1593                         osg.setClip(x,y,bw,bh);
1594                         if (volatileBufferType != Transparency.OPAQUE
1595                                 && osg instanceof Graphics2D) {
1596                             final Graphics2D g2d = (Graphics2D) osg;
1597                             final Color oldBg = g2d.getBackground();
1598                             g2d.setBackground(c.getBackground());
1599                             g2d.clearRect(x, y, bw, bh);
1600                             g2d.setBackground(oldBg);
1601                         }
1602                         c.paintToOffscreen(osg, x, y, bw, bh, maxx, maxy);
1603                         g.setClip(x, y, bw, bh);
1604                         if (volatileBufferType != Transparency.OPAQUE
1605                                 && g instanceof Graphics2D) {
1606                             final Graphics2D g2d = (Graphics2D) g;
1607                             final Composite oldComposite = g2d.getComposite();
1608                             g2d.setComposite(AlphaComposite.Src);
1609                             g2d.drawImage(image, x, y, c);
1610                             g2d.setComposite(oldComposite);
1611                         } else {
1612                             g.drawImage(image, x, y, c);
1613                         }
1614                         osg.translate(x, y);
1615                     }
1616                 }
1617             } finally {
1618                 osg.dispose();
1619             }
1620         }
1621 
1622         /**
1623          * If <code>image</code> is non-null with a positive size it
1624          * is returned, otherwise null is returned.
1625          */
1626         private Image getValidImage(Image image) {
1627             if (image != null && image.getWidth(null) > 0 &&
1628                                  image.getHeight(null) > 0) {
1629                 return image;
1630             }
1631             return null;
1632         }
1633 
1634         /**
1635          * Schedules a repaint for the specified component.  This differs
1636          * from <code>root.repaint</code> in that if the RepaintManager is
1637          * currently processing paint requests it'll process this request
1638          * with the current set of requests.
1639          */
1640         protected void repaintRoot(JComponent root) {
1641             assert (repaintManager.repaintRoot == null);
1642             if (repaintManager.painting) {
1643                 repaintManager.repaintRoot = root;
1644             }
1645             else {
1646                 root.repaint();
1647             }
1648         }
1649 
1650         /**
1651          * Returns true if the component being painted is the root component
1652          * that was previously passed to <code>repaintRoot</code>.
1653          */
1654         protected boolean isRepaintingRoot() {
1655             return isRepaintingRoot;
1656         }
1657 
1658         /**
1659          * Cleans up any state.  After invoked the PaintManager will no
1660          * longer be used anymore.
1661          */
1662         protected void dispose() {
1663         }
1664     }
1665 
1666 
1667     private class DoubleBufferInfo {
1668         public Image image;
1669         public Dimension size;
1670         public boolean needsReset = false;
1671     }
1672 
1673 
1674     /**
1675      * Listener installed to detect display changes. When display changes,
1676      * schedules a callback to notify all RepaintManagers of the display
1677      * changes. Only one DisplayChangedHandler is ever installed. The
1678      * singleton instance will schedule notification for all AppContexts.
1679      */
1680     private static final class DisplayChangedHandler implements
1681                                              DisplayChangedListener {
1682         public void displayChanged() {
1683             scheduleDisplayChanges();
1684         }
1685 
1686         public void paletteChanged() {
1687         }
1688 
1689         private void scheduleDisplayChanges() {
1690             // To avoid threading problems, we notify each RepaintManager
1691             // on the thread it was created on.
1692             for (Object c : AppContext.getAppContexts()) {
1693                 AppContext context = (AppContext) c;
1694                 synchronized(context) {
1695                     if (!context.isDisposed()) {
1696                         EventQueue eventQueue = (EventQueue)context.get(
1697                             AppContext.EVENT_QUEUE_KEY);
1698                         if (eventQueue != null) {
1699                             eventQueue.postEvent(new InvocationEvent(
1700                                 Toolkit.getDefaultToolkit(),
1701                                 new DisplayChangedRunnable()));
1702                         }
1703                     }
1704                 }
1705             }
1706         }
1707     }
1708 
1709 
1710     private static final class DisplayChangedRunnable implements Runnable {
1711         public void run() {
1712             RepaintManager.currentManager((JComponent)null).displayChanged();
1713         }
1714     }
1715 
1716 
1717     /**
1718      * Runnable used to process all repaint/revalidate requests.
1719      */
1720     private final class ProcessingRunnable implements Runnable {
1721         // If true, we're wainting on the EventQueue.
1722         private boolean pending;
1723 
1724         /**
1725          * Marks this processing runnable as pending. If this was not
1726          * already marked as pending, true is returned.
1727          */
1728         public synchronized boolean markPending() {
1729             if (!pending) {
1730                 pending = true;
1731                 return true;
1732             }
1733             return false;
1734         }
1735 
1736         public void run() {
1737             synchronized (this) {
1738                 pending = false;
1739             }
1740             // First pass, flush any heavy paint events into real paint
1741             // events.  If there are pending heavy weight requests this will
1742             // result in q'ing this request up one more time.  As
1743             // long as no other requests come in between now and the time
1744             // the second one is processed nothing will happen.  This is not
1745             // ideal, but the logic needed to suppress the second request is
1746             // more headache than it's worth.
1747             scheduleHeavyWeightPaints();
1748             // Do the actual validation and painting.
1749             validateInvalidComponents();
1750             prePaintDirtyRegions();
1751         }
1752     }
1753     private RepaintManager getDelegate(Component c) {
1754         RepaintManager delegate = SwingUtilities3.getDelegateRepaintManager(c);
1755         if (this == delegate) {
1756             delegate = null;
1757         }
1758         return delegate;
1759     }
1760 }
--- EOF ---