1 /*
   2  * Copyright (c) 2011, 2012, 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, final int h, final JRSUIState state) {
  85         lock.readLock().lock();
  86         try {
  87             final PixelCountSoftReference ref = map.get(hash(config, w, h, state));
  88             // check reference has not been lost and the key truly matches, in case of false positive hash match
  89             if (ref != null && ref.equals(config, w, h, state)) return ref.get();
  90             return null;
  91         } finally {
  92             lock.readLock().unlock();
  93         }
  94     }
  95 
  96     /**
  97      * Sets the cached image for the specified constraints.
  98      *
  99      * @param image  The image to store in cache
 100      * @param config The graphics configuration, needed if cached image is a Volatile Image. Used as part of cache key
 101      * @param w      The image width, used as part of cache key
 102      * @param h      The image height, used as part of cache key
 103      * @return true if the image could be cached, false otherwise.
 104      */
 105     public boolean setImage(final Image image, final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
 106         if (state.is(JRSUIConstants.Animating.YES)) {
 107             return false;
 108         }
 109 
 110         final int hash = hash(config, w, h, state);
 111 
 112         lock.writeLock().lock();
 113         try {
 114             PixelCountSoftReference ref = map.get(hash);
 115             // check if currently in map
 116             if (ref != null && ref.get() == image) return true;
 117 
 118             // clear out old
 119             if (ref != null) {
 120                 currentPixelCount -= ref.pixelCount;
 121                 map.remove(hash);
 122             }
 123 
 124             // add new image to pixel count
 125             final int newPixelCount = image.getWidth(null) * image.getHeight(null);
 126             currentPixelCount += newPixelCount;
 127             // clean out lost references if not enough space
 128             if (currentPixelCount > maxPixelCount) {
 129                 while ((ref = (PixelCountSoftReference)referenceQueue.poll()) != null) {
 130                     //reference lost
 131                     map.remove(ref.hash);
 132                     currentPixelCount -= ref.pixelCount;
 133                 }
 134             }
 135 
 136             // remove old items till there is enough free space
 137             if (currentPixelCount > maxPixelCount) {
 138                 final Iterator<Map.Entry<Integer, PixelCountSoftReference>> mapIter = map.entrySet().iterator();
 139                 while ((currentPixelCount > maxPixelCount) && mapIter.hasNext()) {
 140                     final Map.Entry<Integer, PixelCountSoftReference> entry = mapIter.next();
 141                     mapIter.remove();
 142                     final Image img = entry.getValue().get();
 143                     if (img != null) img.flush();
 144                     currentPixelCount -= entry.getValue().pixelCount;
 145                 }
 146             }
 147             // finally put new in map
 148             map.put(hash, new PixelCountSoftReference(image, referenceQueue, newPixelCount, hash, config, w, h, state));
 149             return true;
 150         } finally {
 151             lock.writeLock().unlock();
 152         }
 153     }
 154 
 155     private int hash(final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
 156         int hash = (config != null ? config.hashCode() : 0);
 157         hash = 31 * hash + w;
 158         hash = 31 * hash + h;
 159         hash = 31 * hash + state.hashCode();
 160         return hash;
 161     }
 162 
 163     /** Extended SoftReference that stores the pixel count even after the image is lost */
 164     private static class PixelCountSoftReference extends SoftReference<Image> {
 165         private final int pixelCount;
 166         private final int hash;
 167 
 168         // key parts
 169         private final GraphicsConfiguration config;
 170         private final int w;
 171         private final int h;
 172         private final JRSUIState state;
 173 
 174         PixelCountSoftReference(final Image referent, final ReferenceQueue<? super Image> q, final int pixelCount, final int hash, final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
 175             super(referent, q);
 176             this.pixelCount = pixelCount;
 177             this.hash = hash;
 178             this.config = config;
 179             this.w = w;
 180             this.h = h;
 181             this.state = state;
 182         }
 183 
 184         public boolean equals(final GraphicsConfiguration config, final int w, final int h, final JRSUIState state) {
 185             return config == this.config && w == this.w && h == this.h && state.equals(this.state);
 186         }
 187     }
 188 
 189 //    /** Gets the rendered image for this painter at the requested size, either from cache or create a new one */
 190 //    private VolatileImage getImage(GraphicsConfiguration config, JComponent c, int w, int h, Object[] extendedCacheKeys) {
 191 //        VolatileImage buffer = (VolatileImage)getImage(config, w, h, this, extendedCacheKeys);
 192 //
 193 //        int renderCounter = 0; // to avoid any potential, though unlikely, infinite loop
 194 //        do {
 195 //            //validate the buffer so we can check for surface loss
 196 //            int bufferStatus = VolatileImage.IMAGE_INCOMPATIBLE;
 197 //            if (buffer != null) {
 198 //                bufferStatus = buffer.validate(config);
 199 //            }
 200 //
 201 //            //If the buffer status is incompatible or restored, then we need to re-render to the volatile image
 202 //            if (bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE || bufferStatus == VolatileImage.IMAGE_RESTORED) {
 203 //                // if the buffer isn't the right size, or has lost its contents, then recreate
 204 //                if (buffer != null) {
 205 //                    if (buffer.getWidth() != w || buffer.getHeight() != h || bufferStatus == VolatileImage.IMAGE_INCOMPATIBLE) {
 206 //                        // clear any resources related to the old back buffer
 207 //                        buffer.flush();
 208 //                        buffer = null;
 209 //                    }
 210 //                }
 211 //
 212 //                if (buffer == null) {
 213 //                    // recreate the buffer
 214 //                    buffer = config.createCompatibleVolatileImage(w, h, Transparency.TRANSLUCENT);
 215 //                    // put in cache for future
 216 //                    setImage(buffer, config, w, h, this, extendedCacheKeys);
 217 //                }
 218 //
 219 //                //create the graphics context with which to paint to the buffer
 220 //                Graphics2D bg = buffer.createGraphics();
 221 //
 222 //                //clear the background before configuring the graphics
 223 //                bg.setComposite(AlphaComposite.Clear);
 224 //                bg.fillRect(0, 0, w, h);
 225 //                bg.setComposite(AlphaComposite.SrcOver);
 226 //                bg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
 227 //
 228 //                // paint the painter into buffer
 229 //                paint0(bg, c, w, h, extendedCacheKeys);
 230 //                //close buffer graphics
 231 //                bg.dispose();
 232 //            }
 233 //        } while (buffer.contentsLost() && renderCounter++ < 3);
 234 //
 235 //        // check if we failed
 236 //        if (renderCounter >= 3) return null;
 237 //
 238 //        return buffer;
 239 //    }
 240 }