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