1 /*
   2  * Copyright (c) 2011, 2013, 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 
  26 package com.apple.laf;
  27 
  28 import java.awt.*;
  29 import java.lang.ref.*;
  30 import java.util.*;
  31 import java.util.concurrent.locks.*;
  32 
  33 import apple.laf.JRSUIConstants;
  34 import apple.laf.JRSUIState;
  35 import com.apple.laf.AquaUtils.RecyclableSingleton;
  36 
  37 /**
  38  * ImageCache - A fixed pixel count sized cache of Images keyed by arbitrary set of arguments. All images are held with
  39  * SoftReferences so they will be dropped by the GC if heap memory gets tight. When our size hits max pixel count least
  40  * recently requested images are removed first.
  41  */
  42 final class ImageCache {
  43     // Ordered Map keyed by args hash, ordered by most recent accessed entry.
  44     private final LinkedHashMap<Integer, PixelCountSoftReference> map = new LinkedHashMap<>(16, 0.75f, true);
  45 
  46     // Maximum number of pixels to cache, this is used if maxCount
  47     private final int maxPixelCount;
  48     // The current number of pixels stored in the cache
  49     private int currentPixelCount = 0;
  50 
  51     // Lock for concurrent access to map
  52     private final ReadWriteLock lock = new ReentrantReadWriteLock();
  53     // Reference queue for tracking lost softreferences to images in the cache
  54     private final ReferenceQueue<Image> referenceQueue = new ReferenceQueue<>();
  55 
  56     // Singleton Instance
  57     private static final RecyclableSingleton<ImageCache> instance = new RecyclableSingleton<ImageCache>() {
  58         @Override
  59         protected ImageCache getInstance() {
  60             return new ImageCache();
  61         }
  62     };
  63     static ImageCache getInstance() {
  64         return instance.get();
  65     }
  66 
  67     ImageCache(final int maxPixelCount) {
  68         this.maxPixelCount = maxPixelCount;
  69     }
  70 
  71     ImageCache() {
  72         this((8 * 1024 * 1024) / 4); // 8Mb of pixels
  73     }
  74 
  75     public void flush() {
  76         lock.writeLock().lock();
  77         try {
  78             map.clear();
  79         } finally {
  80             lock.writeLock().unlock();
  81         }
  82     }
  83 
  84     public Image getImage(final GraphicsConfiguration config, final int w,
  85                           final int h, final int scale,
  86                           final JRSUIState state) {
  87         final int hash = hash(config, w, h, scale, state);
  88         final PixelCountSoftReference ref;
  89         lock.readLock().lock();
  90         try {
  91             ref = map.get(hash);
  92         } finally {
  93             lock.readLock().unlock();
  94         }
  95         // check reference has not been lost and the key truly matches,
  96         // in case of false positive hash match
  97         if (ref != null && ref.equals(config, w, h, scale, state)) {
  98             return ref.get();
  99         }
 100         return null;
 101     }
 102 
 103     /**
 104      * Sets the cached image for the specified constraints.
 105      *
 106      * @param image  The image to store in cache
 107      * @param config The graphics configuration, needed if cached image is a Volatile Image. Used as part of cache key
 108      * @param w      The image width, used as part of cache key
 109      * @param h      The image height, used as part of cache key
 110      * @param scale  The image scale factor, used as part of cache key
 111      * @return true if the image could be cached, false otherwise.
 112      */
 113     public boolean setImage(final Image image,
 114             final GraphicsConfiguration config, final int w, final int h,
 115             final int scale, final JRSUIState state) {
 116         if (state.is(JRSUIConstants.Animating.YES)) {
 117             return false;
 118         }
 119 
 120         final int hash = hash(config, w, h, scale, state);
 121 
 122         lock.writeLock().lock();
 123         try {
 124             PixelCountSoftReference ref = map.get(hash);
 125             // check if currently in map
 126             if (ref != null && ref.get() == image) return true;
 127 
 128             // clear out old
 129             if (ref != null) {
 130                 currentPixelCount -= ref.pixelCount;
 131                 map.remove(hash);
 132             }
 133 
 134             // add new image to pixel count
 135             final int newPixelCount = image.getWidth(null) * image.getHeight(null);
 136             currentPixelCount += newPixelCount;
 137             // clean out lost references if not enough space
 138             if (currentPixelCount > maxPixelCount) {
 139                 while ((ref = (PixelCountSoftReference)referenceQueue.poll()) != null) {
 140                     //reference lost
 141                     map.remove(ref.hash);
 142                     currentPixelCount -= ref.pixelCount;
 143                 }
 144             }
 145 
 146             // remove old items till there is enough free space
 147             if (currentPixelCount > maxPixelCount) {
 148                 final Iterator<Map.Entry<Integer, PixelCountSoftReference>> mapIter = map.entrySet().iterator();
 149                 while ((currentPixelCount > maxPixelCount) && mapIter.hasNext()) {
 150                     final Map.Entry<Integer, PixelCountSoftReference> entry = mapIter.next();
 151                     mapIter.remove();
 152                     final Image img = entry.getValue().get();
 153                     if (img != null) img.flush();
 154                     currentPixelCount -= entry.getValue().pixelCount;
 155                 }
 156             }
 157             // finally put new in map
 158             map.put(hash, new PixelCountSoftReference(image, referenceQueue, newPixelCount, hash, config, w, h, scale, state));
 159             return true;
 160         } finally {
 161             lock.writeLock().unlock();
 162         }
 163     }
 164 
 165     private static int hash(final GraphicsConfiguration config, final int w,
 166                             final int h, final int scale,
 167                             final JRSUIState state) {
 168         int hash = config != null ? config.hashCode() : 0;
 169         hash = 31 * hash + w;
 170         hash = 31 * hash + h;
 171         hash = 31 * hash + scale;
 172         hash = 31 * hash + state.hashCode();
 173         return hash;
 174     }
 175 
 176     /**
 177      * Extended SoftReference that stores the pixel count even after the image
 178      * is lost.
 179      */
 180     private static class PixelCountSoftReference extends SoftReference<Image> {
 181 
 182         // default access, because access to these fields shouldn't be emulated
 183         // by a synthetic accessor.
 184         final int pixelCount;
 185         final int hash;
 186 
 187         // key parts
 188         private final GraphicsConfiguration config;
 189         private final int w;
 190         private final int h;
 191         private final int scale;
 192         private final JRSUIState state;
 193 
 194         PixelCountSoftReference(final Image referent,
 195                 final ReferenceQueue<? super Image> q, final int pixelCount,
 196                 final int hash, final GraphicsConfiguration config, final int w,
 197                 final int h, final int scale, final JRSUIState state) {
 198             super(referent, q);
 199             this.pixelCount = pixelCount;
 200             this.hash = hash;
 201             this.config = config;
 202             this.w = w;
 203             this.h = h;
 204             this.scale = scale;
 205             this.state = state;
 206         }
 207 
 208         boolean equals(final GraphicsConfiguration config, final int w,
 209                        final int h, final int scale, final JRSUIState state) {
 210             return config == this.config && w == this.w && h == this.h
 211                     && scale == this.scale && state.equals(this.state);
 212         }
 213     }
 214 
 215 //    /** Gets the rendered image for this painter at the requested size, either from cache or create a new one */
 216 //    private VolatileImage getImage(GraphicsConfiguration config, JComponent c, int w, int h, Object[] extendedCacheKeys) {
 217 //        VolatileImage buffer = (VolatileImage)getImage(config, w, h, this, extendedCacheKeys);
 218 //
 219 //        int renderCounter = 0; // to avoid any potential, though unlikely, infinite loop
 220 //        do {
 221 //            //validate the buffer so we can check for surface loss
 222 //            int bufferStatus = VolatileImage.IMAGE_INCOMPATIBLE;
 223 //            if (buffer != null) {
 224 //                bufferStatus = buffer.validate(config);
 225 //            }
 226 //
 227 //            //If the buffer status is incompatible or restored, then we need to re-render to the volatile image
 228 //            if (bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE || bufferStatus == VolatileImage.IMAGE_RESTORED) {
 229 //                // if the buffer isn't the right size, or has lost its contents, then recreate
 230 //                if (buffer != null) {
 231 //                    if (buffer.getWidth() != w || buffer.getHeight() != h || bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE) {
 232 //                        // clear any resources related to the old back buffer
 233 //                        buffer.flush();
 234 //                        buffer = null;
 235 //                    }
 236 //                }
 237 //
 238 //                if (buffer == null) {
 239 //                    // recreate the buffer
 240 //                    buffer = config.createCompatibleVolatileImage(w, h, Transparency.TRANSLUCENT);
 241 //                    // put in cache for future
 242 //                    setImage(buffer, config, w, h, this, extendedCacheKeys);
 243 //                }
 244 //
 245 //                //create the graphics context with which to paint to the buffer
 246 //                Graphics2D bg = buffer.createGraphics();
 247 //
 248 //                //clear the background before configuring the graphics
 249 //                bg.setComposite(AlphaComposite.Clear);
 250 //                bg.fillRect(0, 0, w, h);
 251 //                bg.setComposite(AlphaComposite.SrcOver);
 252 //                bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
 253 //
 254 //                // paint the painter into buffer
 255 //                paint0(bg, c, w, h, extendedCacheKeys);
 256 //                //close buffer graphics
 257 //                bg.dispose();
 258 //            }
 259 //        } while (buffer.contentsLost() && renderCounter++ < 3);
 260 //
 261 //        // check if we failed
 262 //        if (renderCounter >= 3) return null;
 263 //
 264 //        return buffer;
 265 //    }
 266 }