1 /*
   2  * Copyright (c) 2004, 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 sun.swing;
  26 
  27 import java.awt.*;
  28 import java.awt.geom.AffineTransform;
  29 import java.awt.image.*;
  30 import java.util.*;
  31 
  32 /**
  33  * A base class used for icons or images that are expensive to paint.
  34  * A subclass will do the following:
  35  * <ol>
  36  * <li>Invoke <code>paint</code> when you want to paint the image,
  37  *     if you are implementing <code>Icon</code> you'll invoke this from
  38  *     <code>paintIcon</code>.
  39  *     The args argument is useful when additional state is needed.
  40  * <li>Override <code>paintToImage</code> to render the image.  The code that
  41  *     lives here is equivalent to what previously would go in
  42  *     <code>paintIcon</code>, for an <code>Icon</code>.
  43  * </ol>
  44  * The two ways to use this class are:
  45  * <ol>
  46  * <li>Invoke <code>paint</code> to draw the cached reprensentation at
  47  *     the specified location.
  48  * <li>Invoke <code>getImage</code> to get the cached reprensentation and
  49  *     draw the image yourself.  This is primarly useful when you are not
  50  *     using <code>VolatileImage</code>.
  51  * </ol>
  52  *
  53  *
  54  */
  55 public abstract class CachedPainter {
  56     // CacheMap maps from class to ImageCache.
  57     private static final Map<Object,ImageCache> cacheMap = new HashMap<>();
  58 
  59     private static ImageCache getCache(Object key) {
  60         synchronized(CachedPainter.class) {
  61             ImageCache cache = cacheMap.get(key);
  62             if (cache == null) {
  63                 cache = new ImageCache(1);
  64                 cacheMap.put(key, cache);
  65             }
  66             return cache;
  67         }
  68     }
  69 
  70     /**
  71      * Creates an instance of <code>CachedPainter</code> that will cache up
  72      * to <code>cacheCount</code> images of this class.
  73      *
  74      * @param cacheCount Max number of images to cache
  75      */
  76     public CachedPainter(int cacheCount) {
  77         getCache(getClass()).setMaxCount(cacheCount);
  78     }
  79 
  80     /**
  81      * Renders the cached image to the passed in <code>Graphic</code>.
  82      * If there is no cached image <code>paintToImage</code> will be invoked.
  83      * <code>paintImage</code> is invoked to paint the cached image.
  84      *
  85      * @param c Component rendering to, this may be null.
  86      * @param g Graphics to paint to
  87      * @param x X-coordinate to render to
  88      * @param y Y-coordinate to render to
  89      * @param w Width to render in
  90      * @param h Height to render in
  91      * @param args Variable arguments that will be passed to paintToImage
  92      */
  93     public void paint(Component c, Graphics g, int x,
  94                          int y, int w, int h, Object... args) {
  95         if (w <= 0 || h <= 0) {
  96             return;
  97         }
  98         synchronized (CachedPainter.class) {
  99             paint0(c, g, x, y, w, h, args);
 100         }
 101     }
 102 
 103     private Image getImage(Object key, Component c, int w, int h, Object... args) {
 104         GraphicsConfiguration config = getGraphicsConfiguration(c);
 105         ImageCache cache = getCache(key);
 106         Image image = cache.getImage(key, config, w, h, args);
 107         int attempts = 0;
 108         do {
 109             boolean draw = false;
 110             if (image instanceof VolatileImage) {
 111                 // See if we need to recreate the image
 112                 switch (((VolatileImage)image).validate(config)) {
 113                 case VolatileImage.IMAGE_INCOMPATIBLE:
 114                     ((VolatileImage)image).flush();
 115                     image = null;
 116                     break;
 117                 case VolatileImage.IMAGE_RESTORED:
 118                     draw = true;
 119                     break;
 120                 }
 121             }
 122             if (image == null) {
 123                 // Recreate the image
 124                 image = createImage(c, w, h, config, args);
 125                 cache.setImage(key, config, w, h, args, image);
 126                 draw = true;
 127             }
 128             if (draw) {
 129                 // Render to the Image
 130                 Graphics g2 = image.getGraphics();
 131                 paintToImage(c, image, g2, w, h, args);
 132                 g2.dispose();
 133             }
 134 
 135             // If we did this 3 times and the contents are still lost
 136             // assume we're painting to a VolatileImage that is bogus and
 137             // give up.  Presumably we'll be called again to paint.
 138         } while ((image instanceof VolatileImage) &&
 139                  ((VolatileImage)image).contentsLost() && ++attempts < 3);
 140 
 141         return image;
 142     }
 143 
 144     private void paint0(Component c, Graphics g, int x,
 145                         int y, int w, int h, Object... args) {
 146         Object key = getClass();
 147         GraphicsConfiguration config = getGraphicsConfiguration(c);
 148         ImageCache cache = getCache(key);
 149         Image image = cache.getImage(key, config, w, h, args);
 150 
 151         if (image == null) {
 152             double sx = 1;
 153             double sy = 1;
 154             if (g instanceof Graphics2D) {
 155                 AffineTransform tx = ((Graphics2D) g).getTransform();
 156                 sx = tx.getScaleX();
 157                 sy = tx.getScaleY();
 158             }
 159             image = new PainterMultiResolutionCachedImage(sx, sy, w, h);
 160             cache.setImage(key, config, w, h, args, image);
 161         }
 162 
 163         if (image instanceof PainterMultiResolutionCachedImage) {
 164             ((PainterMultiResolutionCachedImage) image).setParams(c, args);
 165         }
 166 
 167         // Render to the passed in Graphics
 168         paintImage(c, g, x, y, w, h, image, args);
 169     }
 170 
 171     /**
 172      * Paints the representation to cache to the supplied Graphics.
 173      *
 174      * @param c Component painting to, may be null.
 175      * @param image Image to paint to
 176      * @param g Graphics to paint to, obtained from the passed in Image.
 177      * @param w Width to paint to
 178      * @param h Height to paint to
 179      * @param args Arguments supplied to <code>paint</code>
 180      */
 181     protected abstract void paintToImage(Component c, Image image, Graphics g,
 182                                          int w, int h, Object[] args);
 183 
 184 
 185     /**
 186      * Paints the image to the specified location.
 187      *
 188      * @param c Component painting to
 189      * @param g Graphics to paint to
 190      * @param x X coordinate to paint to
 191      * @param y Y coordinate to paint to
 192      * @param w Width to paint to
 193      * @param h Height to paint to
 194      * @param image Image to paint
 195      * @param args Arguments supplied to <code>paint</code>
 196      */
 197     protected void paintImage(Component c, Graphics g,
 198                               int x, int y, int w, int h, Image image,
 199                               Object[] args) {
 200         g.drawImage(image, x, y, null);
 201     }
 202 
 203     /**
 204      * Creates the image to cache.  This returns an opaque image, subclasses
 205      * that require translucency or transparency will need to override this
 206      * method.
 207      *
 208      * @param c Component painting to
 209      * @param w Width of image to create
 210      * @param h Height to image to create
 211      * @param config GraphicsConfiguration that will be
 212      *        rendered to, this may be null.
 213      * @param args Arguments passed to paint
 214      */
 215     protected Image createImage(Component c, int w, int h,
 216                                 GraphicsConfiguration config, Object[] args) {
 217         if (config == null) {
 218             return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
 219         }
 220         return config.createCompatibleVolatileImage(w, h);
 221     }
 222 
 223     /**
 224      * Clear the image cache
 225      */
 226     protected void flush() {
 227         synchronized(CachedPainter.class) {
 228             getCache(getClass()).flush();
 229         }
 230     }
 231 
 232     private GraphicsConfiguration getGraphicsConfiguration(Component c) {
 233         if (c == null) {
 234             return null;
 235         }
 236         return c.getGraphicsConfiguration();
 237     }
 238 
 239     class PainterMultiResolutionCachedImage extends AbstractMultiResolutionImage {
 240 
 241         private final double scaleX;
 242         private final double scaleY;
 243         private final int baseWidth;
 244         private final int baseHeight;
 245         private Component c;
 246         private Object[] args;
 247 
 248         public PainterMultiResolutionCachedImage(double scaleX, double scaleY,
 249                                                  int baseWidth, int baseHeight) {
 250             this.scaleX = scaleX;
 251             this.scaleY = scaleY;
 252             this.baseWidth = baseWidth;
 253             this.baseHeight = baseHeight;
 254         }
 255 
 256         public void setParams(Component c, Object[] args) {
 257             this.c = c;
 258             this.args = args;
 259         }
 260 
 261         @Override
 262         public int getWidth(ImageObserver observer) {
 263             return baseWidth;
 264         }
 265 
 266         @Override
 267         public int getHeight(ImageObserver observer) {
 268             return baseHeight;
 269         }
 270 
 271         @Override
 272         public Image getResolutionVariant(double destWidth, double destHeight) {
 273             int w = (int) Math.ceil(destWidth);
 274             int h = (int) Math.ceil(destHeight);
 275             return getImage(this, c, w, h, args);
 276         }
 277 
 278         @Override
 279         protected Image getBaseImage() {
 280             return getResolutionVariant(baseWidth, baseHeight);
 281         }
 282 
 283         @Override
 284         public java.util.List<Image> getResolutionVariants() {
 285 
 286             if (scaleX == 1 && scaleY == 1) {
 287                 return Arrays.asList(getResolutionVariant(baseWidth, baseHeight));
 288             }
 289 
 290             return Arrays.asList(
 291                     getResolutionVariant(baseWidth, baseHeight),
 292                     getResolutionVariant(scaleX * baseWidth, scaleY * baseHeight)
 293             );
 294         }
 295     }
 296 }