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