aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/tv/util/ImageLoader.java
blob: 8e901dd0592372e3a02125e5300004e2fb93657f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.tv.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.tv.TvInputInfo;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.annotation.WorkerThread;
import android.util.Log;

import com.android.tv.R;
import com.android.tv.util.BitmapUtils.ScaledBitmapInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;

/**
 * This class wraps up completing some arbitrary long running work when loading a bitmap. It
 * handles things like using a memory cache, running the work in a background thread.
 */
public final class ImageLoader {
    private static final String TAG = "ImageLoader";
    private static final boolean DEBUG = false;

    /**
     * Interface definition for a callback to be invoked when image loading is finished.
     */
    @UiThread
    public interface ImageLoaderCallback {
        /**
         * Called when bitmap is loaded.
         */
        void onBitmapLoaded(@Nullable Bitmap bitmap);
    }

    private static final Map<String, LoadBitmapTask> sPendingListMap = new HashMap<>();

    /**
     * Preload a bitmap image into the cache.
     *
     * <p>Not to make heavy CPU load, AsyncTask.SERIAL_EXECUTOR is used for the image loading.
     */
    @UiThread
    public static void prefetchBitmap(Context context, String uriString,
            int maxWidth, int maxHeight) {
        if (DEBUG) {
            Log.d(TAG, "prefetchBitmap() " + uriString);
        }
        doLoadBitmap(context, uriString, maxWidth, maxHeight, null, AsyncTask.SERIAL_EXECUTOR);
    }

    /**
     * Load a bitmap image with the cache using a ContentResolver.
     *
     * <p><b>Note</b> that the callback will be called synchronously if the bitmap already is in
     * the cache.
     *
     * @return {@code true} if the load is complete and the callback is executed.
     */
    @UiThread
    public static boolean loadBitmap(Context context, String uriString,
            ImageLoaderCallback callback) {
        return loadBitmap(context, uriString, Integer.MAX_VALUE, Integer.MAX_VALUE, callback);
    }

    /**
     * Load a bitmap image with the cache and resize it with given params.
     *
     * <p><b>Note</b> that the callback will be called synchronously if the bitmap already is in
     * the cache.
     *
     * @return {@code true} if the load is complete and the callback is executed.
     */
    @UiThread
    public static boolean loadBitmap(Context context, String uriString, int maxWidth, int maxHeight,
            ImageLoaderCallback callback) {
        if (DEBUG) {
            Log.d(TAG, "loadBitmap() " + uriString);
        }
        return doLoadBitmap(context, uriString, maxWidth, maxHeight, callback,
                AsyncTask.THREAD_POOL_EXECUTOR);
    }

    private static boolean doLoadBitmap(Context context, String uriString,
            int maxWidth, int maxHeight, ImageLoaderCallback callback, Executor executor) {
        // Check the cache before creating a Task.  The cache will be checked again in doLoadBitmap
        // but checking a cache is much cheaper than creating an new task.
        ImageCache imageCache = ImageCache.getInstance();
        ScaledBitmapInfo bitmapInfo = imageCache.get(uriString);
        if (bitmapInfo != null && !bitmapInfo.needToReload(maxWidth, maxHeight)) {
            if (callback != null) {
                callback.onBitmapLoaded(bitmapInfo.bitmap);
            }
            return true;
        }
        return doLoadBitmap(callback, executor,
                new LoadBitmapFromUriTask(context, imageCache, uriString, maxWidth, maxHeight));
    }

    /**
     * Load a bitmap image with the cache and resize it with given params.
     *
     * <p>The LoadBitmapTask will be executed on a non ui thread.
     *
     * @return {@code true} if the load is complete and the callback is executed.
     */
    @UiThread
    public static boolean loadBitmap(ImageLoaderCallback callback, LoadBitmapTask loadBitmapTask) {
        if (DEBUG) {
            Log.d(TAG, "loadBitmap() " + loadBitmapTask);
        }
        return doLoadBitmap(callback, AsyncTask.THREAD_POOL_EXECUTOR, loadBitmapTask);
    }

    /**
     * @return {@code true} if the load is complete and the callback is executed.
     */
    private static boolean doLoadBitmap(ImageLoaderCallback callback, Executor executor,
            LoadBitmapTask loadBitmapTask) {
        ScaledBitmapInfo bitmapInfo = loadBitmapTask.getFromCache();
        boolean needToReload = loadBitmapTask.isReloadNeeded();
        if (bitmapInfo != null && !needToReload) {
            if (callback != null) {
                callback.onBitmapLoaded(bitmapInfo.bitmap);
            }
            return true;
        }
        LoadBitmapTask existingTask = sPendingListMap.get(loadBitmapTask.getKey());
        if (existingTask != null && !loadBitmapTask.isReloadNeeded(existingTask) ) {
            // The image loading is already scheduled and is large enough.
            if (callback != null) {
                existingTask.mCallbacks.add(callback);
            }
        } else {
            if (callback != null) {
                loadBitmapTask.mCallbacks.add(callback);
            }
            sPendingListMap.put(loadBitmapTask.getKey(), loadBitmapTask);
            try {
                loadBitmapTask.executeOnExecutor(executor);
            } catch (RejectedExecutionException e) {
                Log.e(TAG, "Failed to create new image loader", e);
                sPendingListMap.remove(loadBitmapTask.getKey());
            }
        }
        return false;
    }

/**
 * Loads and caches a a possibly scaled down version of a bitmap.
 *
 * <p>Implement {@link #doGetBitmapInBackground()} to to the actual loading.
 */
    public static abstract class LoadBitmapTask extends AsyncTask<Void, Void, ScaledBitmapInfo> {
        protected final int mMaxWidth;
        protected final int mMaxHeight;
        private final List<ImageLoader.ImageLoaderCallback> mCallbacks = new ArrayList<>();
        private final ImageCache mImageCache;
        private final String mKey;

        /**
         * Returns true if a reload is needed compared to current results in the cache or false if
         * there is not match in the cache.
         */
        private boolean isReloadNeeded() {
            ScaledBitmapInfo bitmapInfo = getFromCache();
            boolean needToReload = bitmapInfo != null && bitmapInfo
                    .needToReload(mMaxWidth, mMaxHeight);
            if (DEBUG) {
                if (needToReload) {
                    Log.d(TAG, "Bitmap needs to be reloaded. {originalWidth="
                            + bitmapInfo.bitmap.getWidth() + ", originalHeight="
                            + bitmapInfo.bitmap.getHeight() + ", reqWidth=" + mMaxWidth
                            + ", reqHeight="
                            + mMaxHeight);
                }
            }
            return needToReload;
        }

        /**
         * Checks if a reload would be needed if the results of other was available.
         */
        private boolean isReloadNeeded(LoadBitmapTask other) {
            return mMaxHeight >= other.mMaxHeight * 2 || mMaxWidth >= other.mMaxWidth * 2;
        }

        @Nullable
        public final ScaledBitmapInfo getFromCache() {
            return mImageCache.get(mKey);
        }

        public LoadBitmapTask(ImageCache imageCache, String key, int maxHeight, int maxWidth) {
            if (maxWidth == 0 || maxHeight == 0) {
                throw new IllegalArgumentException("Image size should not be 0. {width=" + maxWidth
                        + ", height=" + maxHeight + "}");
            }
            mKey = key;
            mImageCache = imageCache;
            mMaxHeight = maxHeight;
            mMaxWidth = maxWidth;
        }

        /**
         * Loads the bitmap returning a possibly scaled down version.
         */
        @Nullable
        @WorkerThread
        public abstract ScaledBitmapInfo doGetBitmapInBackground();

        @Override
        @Nullable
        public final ScaledBitmapInfo doInBackground(Void... params) {
            ScaledBitmapInfo bitmapInfo = getFromCache();
            if (bitmapInfo != null && !isReloadNeeded()) {
                return bitmapInfo;
            }
            bitmapInfo = doGetBitmapInBackground();
            if (bitmapInfo != null) {
                mImageCache.putIfNeeded(bitmapInfo);
            }
            return bitmapInfo;
        }

        @Override
        public final void onPostExecute(ScaledBitmapInfo scaledBitmapInfo) {
            if (ImageLoader.DEBUG) {
                Log.d(ImageLoader.TAG, "Bitmap is loaded " + mKey);
            }
            for (ImageLoader.ImageLoaderCallback callback : mCallbacks) {
                callback.onBitmapLoaded(scaledBitmapInfo == null ? null : scaledBitmapInfo.bitmap);
            }
            ImageLoader.sPendingListMap.remove(mKey);
        }

        public final String getKey() {
            return mKey;
        }

        @Override
        public String toString() {
            return this.getClass().getSimpleName() + "(" + mKey + " "
                    + mMaxWidth + "x" + mMaxHeight + ")";
        }
    }

    private static final class LoadBitmapFromUriTask extends LoadBitmapTask {
        private final Context mContext;
        private LoadBitmapFromUriTask(Context context, ImageCache imageCache, String uriString,
                int maxWidth, int maxHeight) {
            super(imageCache, uriString, maxHeight, maxWidth);
            mContext = context;
        }

        @Override
        @Nullable
        public final ScaledBitmapInfo doGetBitmapInBackground() {
            return BitmapUtils
                    .decodeSampledBitmapFromUriString(mContext, getKey(), mMaxWidth, mMaxHeight);
        }
    }

    /**
     * Loads and caches the logo for a given {@link TvInputInfo}
     */
    public static final class LoadTvInputLogoTask extends LoadBitmapTask {
        private final TvInputInfo mInfo;
        private final Context mContext;

        public LoadTvInputLogoTask(Context context, ImageCache cache, TvInputInfo info) {
            super(cache,
                    info.getId() + "-logo",
                    context.getResources()
                            .getDimensionPixelSize(R.dimen.channel_banner_input_logo_size),
                    context.getResources()
                            .getDimensionPixelSize(R.dimen.channel_banner_input_logo_size)
            );
            mInfo = info;
            mContext = context;
        }

        @Nullable
        @Override
        public ScaledBitmapInfo doGetBitmapInBackground() {
            Drawable drawable = mInfo.loadIcon(mContext);
            if (!(drawable instanceof BitmapDrawable)) {
                return null;
            }
            Bitmap original = ((BitmapDrawable) drawable).getBitmap();
            if (original == null) {
                return null;
            }
            return BitmapUtils.createScaledBitmapInfo(getKey(), original, mMaxWidth, mMaxHeight);
        }
    }

    private ImageLoader() {
    }
}