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