blob: 8688426688bcc9ed17096376ac8187149b183143 [file] [log] [blame]
Dmitri Plotnikove8643852010-02-17 10:49:05 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dmitri Plotnikov022b62d2011-01-28 12:16:07 -080017package com.android.contacts;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080018
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -080019import com.android.contacts.model.AccountTypeManager;
Daniel Lehmann2f77c852012-03-30 15:25:31 -070020import com.android.contacts.util.BitmapUtil;
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -080021import com.android.contacts.util.MemoryUtils;
Daniel Lehmannecfc26c2011-09-12 17:44:35 -070022import com.android.contacts.util.UriUtils;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080023import com.google.android.collect.Lists;
Flavio Lerdad33b18c2011-07-17 22:03:15 +010024import com.google.android.collect.Sets;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080025
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -080026import android.content.ComponentCallbacks2;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080027import android.content.ContentResolver;
Dave Santoro84cac442011-08-24 15:23:10 -070028import android.content.ContentUris;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080029import android.content.Context;
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -080030import android.content.res.Configuration;
Daniel Lehmann2f77c852012-03-30 15:25:31 -070031import android.content.res.Resources;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080032import android.database.Cursor;
33import android.graphics.Bitmap;
Daniel Lehmann2f77c852012-03-30 15:25:31 -070034import android.graphics.Canvas;
35import android.graphics.Color;
36import android.graphics.Paint;
37import android.graphics.Paint.Style;
Daniel Lehmann7a46cde2012-02-01 17:53:44 -080038import android.graphics.drawable.BitmapDrawable;
Makoto Onuki3d3a15c2011-09-22 10:55:08 -070039import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
Daniel Lehmann7a46cde2012-02-01 17:53:44 -080041import android.graphics.drawable.TransitionDrawable;
Dmitri Plotnikoveb689432010-09-24 10:10:57 -070042import android.net.Uri;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080043import android.os.Handler;
Dmitri Plotnikoveb689432010-09-24 10:10:57 -070044import android.os.Handler.Callback;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080045import android.os.HandlerThread;
46import android.os.Message;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -080047import android.provider.ContactsContract;
48import android.provider.ContactsContract.Contacts;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080049import android.provider.ContactsContract.Contacts.Photo;
Dmitri Plotnikoveb689432010-09-24 10:10:57 -070050import android.provider.ContactsContract.Data;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -080051import android.provider.ContactsContract.Directory;
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -080052import android.text.TextUtils;
Dmitri Plotnikoveb689432010-09-24 10:10:57 -070053import android.util.Log;
Jesse Wilsonfb231aa2011-02-07 15:15:56 -080054import android.util.LruCache;
Daniel Lehmann2f77c852012-03-30 15:25:31 -070055import android.util.TypedValue;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080056import android.widget.ImageView;
57
Dmitri Plotnikoveb689432010-09-24 10:10:57 -070058import java.io.ByteArrayOutputStream;
59import java.io.InputStream;
Makoto Onuki173f2812011-09-06 14:49:27 -070060import java.lang.ref.Reference;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080061import java.lang.ref.SoftReference;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080062import java.util.Iterator;
Flavio Lerdad33b18c2011-07-17 22:03:15 +010063import java.util.List;
64import java.util.Set;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080065import java.util.concurrent.ConcurrentHashMap;
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -080066import java.util.concurrent.atomic.AtomicInteger;
Dmitri Plotnikove8643852010-02-17 10:49:05 -080067
68/**
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -080069 * Asynchronously loads contact photos and maintains a cache of photos.
Dmitri Plotnikove8643852010-02-17 10:49:05 -080070 */
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -080071public abstract class ContactPhotoManager implements ComponentCallbacks2 {
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -080072 static final String TAG = "ContactPhotoManager";
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -080073 static final boolean DEBUG = false; // Don't submit with true
Daniel Lehmann2f77c852012-03-30 15:25:31 -070074 static final boolean DEBUG_SIZES = false; // Don't submit with true
75
76 /** Caches 180dip in pixel. This is used to detect whether to show the hires or lores version
77 * of the default avatar */
78 private static int s180DipInPixel = -1;
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -080079
80 public static final String CONTACT_PHOTO_SERVICE = "contactPhotos";
81
Daniel Lehmann2f77c852012-03-30 15:25:31 -070082 /**
83 * Returns the resource id of the default avatar. Tries to find a resource that is bigger
84 * than the given extent (width or height). If extent=-1, a thumbnail avatar is returned
85 */
86 public static int getDefaultAvatarResId(Context context, int extent, boolean darkTheme) {
87 // TODO: Is it worth finding a nicer way to do hires/lores here? In practice, the
88 // default avatar doesn't look too different when stretched
89 if (s180DipInPixel == -1) {
90 Resources r = context.getResources();
91 s180DipInPixel = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 180,
92 r.getDisplayMetrics());
93 }
94
95 final boolean hires = (extent != -1) && (extent > s180DipInPixel);
96 return getDefaultAvatarResId(hires, darkTheme);
97 }
98
Daniel Lehmannecfc26c2011-09-12 17:44:35 -070099 public static int getDefaultAvatarResId(boolean hires, boolean darkTheme) {
100 if (hires && darkTheme) return R.drawable.ic_contact_picture_180_holo_dark;
101 if (hires) return R.drawable.ic_contact_picture_180_holo_light;
102 if (darkTheme) return R.drawable.ic_contact_picture_holo_dark;
103 return R.drawable.ic_contact_picture_holo_light;
104 }
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800105
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700106 public static abstract class DefaultImageProvider {
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700107 /**
108 * Applies the default avatar to the ImageView. Extent is an indicator for the size (width
109 * or height). If darkTheme is set, the avatar is one that looks better on dark background
110 */
111 public abstract void applyDefaultImage(ImageView view, int extent, boolean darkTheme);
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700112 }
113
114 private static class AvatarDefaultImageProvider extends DefaultImageProvider {
115 @Override
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700116 public void applyDefaultImage(ImageView view, int extent, boolean darkTheme) {
117 view.setImageResource(getDefaultAvatarResId(view.getContext(), extent, darkTheme));
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700118 }
119 }
120
121 private static class BlankDefaultImageProvider extends DefaultImageProvider {
122 private static Drawable sDrawable;
123
124 @Override
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700125 public void applyDefaultImage(ImageView view, int extent, boolean darkTheme) {
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700126 if (sDrawable == null) {
127 Context context = view.getContext();
128 sDrawable = new ColorDrawable(context.getResources().getColor(
129 R.color.image_placeholder));
130 }
131 view.setImageDrawable(sDrawable);
132 }
133 }
134
Daniel Lehmann2d73de02012-02-21 19:51:38 -0800135 public static final DefaultImageProvider DEFAULT_AVATAR = new AvatarDefaultImageProvider();
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700136
137 public static final DefaultImageProvider DEFAULT_BLANK = new BlankDefaultImageProvider();
138
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800139 /**
140 * Requests the singleton instance of {@link AccountTypeManager} with data bound from
141 * the available authenticators. This method can safely be called from the UI thread.
142 */
143 public static ContactPhotoManager getInstance(Context context) {
Flavio Lerda82e4a562011-07-08 17:05:31 +0100144 Context applicationContext = context.getApplicationContext();
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800145 ContactPhotoManager service =
Flavio Lerda82e4a562011-07-08 17:05:31 +0100146 (ContactPhotoManager) applicationContext.getSystemService(CONTACT_PHOTO_SERVICE);
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800147 if (service == null) {
Flavio Lerda82e4a562011-07-08 17:05:31 +0100148 service = createContactPhotoManager(applicationContext);
149 Log.e(TAG, "No contact photo service in context: " + applicationContext);
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800150 }
151 return service;
152 }
153
154 public static synchronized ContactPhotoManager createContactPhotoManager(Context context) {
155 return new ContactPhotoManagerImpl(context);
156 }
157
158 /**
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700159 * Load thumbnail image into the supplied image view. If the photo is already cached,
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800160 * it is displayed immediately. Otherwise a request is sent to load the photo
161 * from the database.
162 */
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700163 public abstract void loadThumbnail(ImageView view, long photoId, boolean darkTheme,
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700164 DefaultImageProvider defaultProvider);
165
166 /**
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700167 * Calls {@link #loadThumbnail(ImageView, long, boolean, DefaultImageProvider)} with
Daniel Lehmann2d73de02012-02-21 19:51:38 -0800168 * {@link #DEFAULT_AVATAR}.
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700169 */
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700170 public final void loadThumbnail(ImageView view, long photoId, boolean darkTheme) {
171 loadThumbnail(view, photoId, darkTheme, DEFAULT_AVATAR);
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700172 }
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800173
174 /**
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700175 * Load photo into the supplied image view. If the photo is already cached,
176 * it is displayed immediately. Otherwise a request is sent to load the photo
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800177 * from the location specified by the URI.
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700178 * @param view The target view
179 * @param photoUri The uri of the photo to load
180 * @param requestedExtent Specifies an approximate Max(width, height) of the targetView.
181 * This is useful if the source image can be a lot bigger that the target, so that the decoding
182 * is done using efficient sampling. If requestedExtent is specified, no sampling of the image
183 * is performed
184 * @param darkTheme Whether the background is dark. This is used for default avatars
185 * @param defaultProvider The provider of default avatars (this is used if photoUri doesn't
186 * refer to an existing image)
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800187 */
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700188 public abstract void loadPhoto(ImageView view, Uri photoUri, int requestedExtent,
189 boolean darkTheme, DefaultImageProvider defaultProvider);
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700190
191 /**
192 * Calls {@link #loadPhoto(ImageView, Uri, boolean, boolean, DefaultImageProvider)} with
Daniel Lehmann2d73de02012-02-21 19:51:38 -0800193 * {@link #DEFAULT_AVATAR}.
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700194 */
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700195 public final void loadPhoto(ImageView view, Uri photoUri, int requestedExtent,
196 boolean darkTheme) {
197 loadPhoto(view, photoUri, requestedExtent, darkTheme, DEFAULT_AVATAR);
198 }
199
200 /**
201 * Calls {@link #loadPhoto(ImageView, Uri, boolean, boolean, DefaultImageProvider)} with
202 * {@link #DEFAULT_AVATAR} and with the assumption, that the image is a thumbnail
203 */
204 public final void loadDirectoryPhoto(ImageView view, Uri photoUri, boolean darkTheme) {
205 loadPhoto(view, photoUri, -1, darkTheme, DEFAULT_AVATAR);
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700206 }
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800207
208 /**
Daisuke Miyakawaf5be9ba2011-08-05 09:17:07 -0700209 * Remove photo from the supplied image view. This also cancels current pending load request
210 * inside this photo manager.
211 */
212 public abstract void removePhoto(ImageView view);
213
214 /**
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800215 * Temporarily stops loading photos from the database.
216 */
217 public abstract void pause();
218
219 /**
220 * Resumes loading photos from the database.
221 */
222 public abstract void resume();
223
224 /**
225 * Marks all cached photos for reloading. We can continue using cache but should
226 * also make sure the photos haven't changed in the background and notify the views
227 * if so.
228 */
229 public abstract void refreshCache();
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800230
231 /**
Dave Santoro14d20832011-12-02 18:14:52 -0800232 * Stores the given bitmap directly in the LRU bitmap cache.
233 * @param photoUri The URI of the photo (for future requests).
234 * @param bitmap The bitmap.
235 * @param photoBytes The bytes that were parsed to create the bitmap.
236 */
237 public abstract void cacheBitmap(Uri photoUri, Bitmap bitmap, byte[] photoBytes);
238
239 /**
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800240 * Initiates a background process that over time will fill up cache with
241 * preload photos.
242 */
243 public abstract void preloadPhotosInBackground();
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800244
245 // ComponentCallbacks2
246 @Override
247 public void onConfigurationChanged(Configuration newConfig) {
248 }
249
250 // ComponentCallbacks2
251 @Override
252 public void onLowMemory() {
253 }
254
255 // ComponentCallbacks2
256 @Override
257 public void onTrimMemory(int level) {
258 }
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800259}
260
261class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback {
Dmitri Plotnikov33409852010-02-20 15:02:32 -0800262 private static final String LOADER_THREAD_NAME = "ContactPhotoLoader";
263
Daniel Lehmann7a46cde2012-02-01 17:53:44 -0800264 private static final int FADE_TRANSITION_DURATION = 200;
265
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800266 /**
267 * Type of message sent by the UI thread to itself to indicate that some photos
268 * need to be loaded.
269 */
270 private static final int MESSAGE_REQUEST_LOADING = 1;
271
272 /**
273 * Type of message sent by the loader thread to indicate that some photos have
274 * been loaded.
275 */
276 private static final int MESSAGE_PHOTOS_LOADED = 2;
277
278 private static final String[] EMPTY_STRING_ARRAY = new String[0];
279
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800280 private static final String[] COLUMNS = new String[] { Photo._ID, Photo.PHOTO };
Dmitri Plotnikov33409852010-02-20 15:02:32 -0800281
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800282 /**
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800283 * Maintains the state of a particular photo.
284 */
285 private static class BitmapHolder {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800286 final byte[] bytes;
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700287 final int originalSmallerExtent;
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800288
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800289 volatile boolean fresh;
Dmitri Plotnikov37dc7cf2010-12-17 19:25:08 -0800290 Bitmap bitmap;
Makoto Onuki173f2812011-09-06 14:49:27 -0700291 Reference<Bitmap> bitmapRef;
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700292 int decodedSampleSize;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800293
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700294 public BitmapHolder(byte[] bytes, int originalSmallerExtent) {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800295 this.bytes = bytes;
296 this.fresh = true;
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700297 this.originalSmallerExtent = originalSmallerExtent;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800298 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800299 }
300
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800301 private final Context mContext;
302
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800303 /**
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800304 * An LRU cache for bitmap holders. The cache contains bytes for photos just
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800305 * as they come from the database. Each holder has a soft reference to the
306 * actual bitmap.
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800307 */
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800308 private final LruCache<Object, BitmapHolder> mBitmapHolderCache;
309
310 /**
Makoto Onuki1f0239e2012-02-27 17:13:47 -0800311 * {@code true} if ALL entries in {@link #mBitmapHolderCache} are NOT fresh.
312 */
313 private volatile boolean mBitmapHolderCacheAllUnfresh = true;
314
315 /**
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800316 * Cache size threshold at which bitmaps will not be preloaded.
317 */
318 private final int mBitmapHolderCacheRedZoneBytes;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800319
320 /**
321 * Level 2 LRU cache for bitmaps. This is a smaller cache that holds
322 * the most recently used bitmaps to save time on decoding
323 * them from bytes (the bytes are stored in {@link #mBitmapHolderCache}.
324 */
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800325 private final LruCache<Object, Bitmap> mBitmapCache;
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800326
327 /**
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700328 * A map from ImageView to the corresponding photo ID or uri, encapsulated in a request.
329 * The request may swapped out before the photo loading request is started.
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800330 */
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700331 private final ConcurrentHashMap<ImageView, Request> mPendingRequests =
332 new ConcurrentHashMap<ImageView, Request>();
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800333
334 /**
335 * Handler for messages sent to the UI thread.
336 */
337 private final Handler mMainThreadHandler = new Handler(this);
338
339 /**
340 * Thread responsible for loading photos from the database. Created upon
341 * the first request.
342 */
343 private LoaderThread mLoaderThread;
344
345 /**
346 * A gate to make sure we only send one instance of MESSAGE_PHOTOS_NEEDED at a time.
347 */
348 private boolean mLoadingRequested;
349
350 /**
351 * Flag indicating if the image loading is paused.
352 */
353 private boolean mPaused;
354
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800355 /** Cache size for {@link #mBitmapHolderCache} for devices with "large" RAM. */
356 private static final int HOLDER_CACHE_SIZE = 2000000;
357
358 /** Cache size for {@link #mBitmapCache} for devices with "large" RAM. */
359 private static final int BITMAP_CACHE_SIZE = 36864 * 48; // 1728K
360
361 private static final int LARGE_RAM_THRESHOLD = 640 * 1024 * 1024;
362
363 /** For debug: How many times we had to reload cached photo for a stale entry */
364 private final AtomicInteger mStaleCacheOverwrite = new AtomicInteger();
365
366 /** For debug: How many times we had to reload cached photo for a fresh entry. Should be 0. */
367 private final AtomicInteger mFreshCacheOverwrite = new AtomicInteger();
368
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800369 public ContactPhotoManagerImpl(Context context) {
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800370 mContext = context;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800371
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800372 final float cacheSizeAdjustment =
373 (MemoryUtils.getTotalMemorySize() >= LARGE_RAM_THRESHOLD) ? 1.0f : 0.5f;
374 final int bitmapCacheSize = (int) (cacheSizeAdjustment * BITMAP_CACHE_SIZE);
375 mBitmapCache = new LruCache<Object, Bitmap>(bitmapCacheSize) {
376 @Override protected int sizeOf(Object key, Bitmap value) {
377 return value.getByteCount();
378 }
379
380 @Override protected void entryRemoved(
381 boolean evicted, Object key, Bitmap oldValue, Bitmap newValue) {
382 if (DEBUG) dumpStats();
383 }
384 };
385 final int holderCacheSize = (int) (cacheSizeAdjustment * HOLDER_CACHE_SIZE);
386 mBitmapHolderCache = new LruCache<Object, BitmapHolder>(holderCacheSize) {
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800387 @Override protected int sizeOf(Object key, BitmapHolder value) {
Jesse Wilsonab79a262011-02-09 15:34:31 -0800388 return value.bytes != null ? value.bytes.length : 0;
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800389 }
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800390
391 @Override protected void entryRemoved(
392 boolean evicted, Object key, BitmapHolder oldValue, BitmapHolder newValue) {
393 if (DEBUG) dumpStats();
394 }
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800395 };
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800396 mBitmapHolderCacheRedZoneBytes = (int) (holderCacheSize * 0.75);
397 Log.i(TAG, "Cache adj: " + cacheSizeAdjustment);
398 if (DEBUG) {
399 Log.d(TAG, "Cache size: " + btk(mBitmapHolderCache.maxSize())
400 + " + " + btk(mBitmapCache.maxSize()));
401 }
402 }
403
404 /** Converts bytes to K bytes, rounding up. Used only for debug log. */
405 private static String btk(int bytes) {
406 return ((bytes + 1023) / 1024) + "K";
407 }
408
409 private static final int safeDiv(int dividend, int divisor) {
410 return (divisor == 0) ? 0 : (dividend / divisor);
411 }
412
413 /**
414 * Dump cache stats on logcat.
415 */
416 private void dumpStats() {
417 if (!DEBUG) return;
418 {
419 int numHolders = 0;
420 int rawBytes = 0;
421 int bitmapBytes = 0;
422 int numBitmaps = 0;
423 for (BitmapHolder h : mBitmapHolderCache.snapshot().values()) {
424 numHolders++;
425 if (h.bytes != null) {
426 rawBytes += h.bytes.length;
427 }
428 Bitmap b = h.bitmapRef != null ? h.bitmapRef.get() : null;
429 if (b != null) {
430 numBitmaps++;
431 bitmapBytes += b.getByteCount();
432 }
433 }
434 Log.d(TAG, "L1: " + btk(rawBytes) + " + " + btk(bitmapBytes) + " = "
435 + btk(rawBytes + bitmapBytes) + ", " + numHolders + " holders, "
436 + numBitmaps + " bitmaps, avg: "
437 + btk(safeDiv(rawBytes, numHolders))
438 + "," + btk(safeDiv(bitmapBytes,numBitmaps)));
439 Log.d(TAG, "L1 Stats: " + mBitmapHolderCache.toString()
440 + ", overwrite: fresh=" + mFreshCacheOverwrite.get()
441 + " stale=" + mStaleCacheOverwrite.get());
442 }
443
444 {
445 int numBitmaps = 0;
446 int bitmapBytes = 0;
447 for (Bitmap b : mBitmapCache.snapshot().values()) {
448 numBitmaps++;
449 bitmapBytes += b.getByteCount();
450 }
451 Log.d(TAG, "L2: " + btk(bitmapBytes) + ", " + numBitmaps + " bitmaps"
452 + ", avg: " + btk(safeDiv(bitmapBytes, numBitmaps)));
453 // We don't get from L2 cache, so L2 stats is meaningless.
454 }
455 }
456
457 @Override
458 public void onTrimMemory(int level) {
459 if (DEBUG) Log.d(TAG, "onTrimMemory: " + level);
460 if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
461 // Clear the caches. Note all pending requests will be removed too.
462 clear();
463 }
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800464 }
465
466 @Override
467 public void preloadPhotosInBackground() {
468 ensureLoaderThread();
469 mLoaderThread.requestPreloading();
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800470 }
471
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800472 @Override
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700473 public void loadThumbnail(ImageView view, long photoId, boolean darkTheme,
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700474 DefaultImageProvider defaultProvider) {
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800475 if (photoId == 0) {
476 // No photo is needed
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700477 defaultProvider.applyDefaultImage(view, -1, darkTheme);
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800478 mPendingRequests.remove(view);
479 } else {
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800480 if (DEBUG) Log.d(TAG, "loadPhoto request: " + photoId);
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700481 loadPhotoByIdOrUri(view, Request.createFromThumbnailId(photoId, darkTheme,
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700482 defaultProvider));
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700483 }
484 }
485
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800486 @Override
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700487 public void loadPhoto(ImageView view, Uri photoUri, int requestedExtent, boolean darkTheme,
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700488 DefaultImageProvider defaultProvider) {
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700489 if (photoUri == null) {
490 // No photo is needed
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700491 defaultProvider.applyDefaultImage(view, requestedExtent, darkTheme);
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700492 mPendingRequests.remove(view);
493 } else {
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800494 if (DEBUG) Log.d(TAG, "loadPhoto request: " + photoUri);
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700495 loadPhotoByIdOrUri(view, Request.createFromUri(photoUri, requestedExtent, darkTheme,
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700496 defaultProvider));
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700497 }
498 }
499
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700500 private void loadPhotoByIdOrUri(ImageView view, Request request) {
Daniel Lehmann7a46cde2012-02-01 17:53:44 -0800501 boolean loaded = loadCachedPhoto(view, request, false);
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700502 if (loaded) {
503 mPendingRequests.remove(view);
504 } else {
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700505 mPendingRequests.put(view, request);
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700506 if (!mPaused) {
507 // Send a request to start loading photos
508 requestLoading();
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800509 }
510 }
511 }
512
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800513 @Override
Daisuke Miyakawaf5be9ba2011-08-05 09:17:07 -0700514 public void removePhoto(ImageView view) {
515 view.setImageDrawable(null);
516 mPendingRequests.remove(view);
517 }
518
519 @Override
Dmitri Plotnikov718a2502010-11-23 17:56:28 -0800520 public void refreshCache() {
Makoto Onuki1f0239e2012-02-27 17:13:47 -0800521 if (mBitmapHolderCacheAllUnfresh) {
522 if (DEBUG) Log.d(TAG, "refreshCache -- no fresh entries.");
523 return;
524 }
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800525 if (DEBUG) Log.d(TAG, "refreshCache");
Makoto Onuki1f0239e2012-02-27 17:13:47 -0800526 mBitmapHolderCacheAllUnfresh = true;
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800527 for (BitmapHolder holder : mBitmapHolderCache.snapshot().values()) {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800528 holder.fresh = false;
Dmitri Plotnikov718a2502010-11-23 17:56:28 -0800529 }
530 }
531
532 /**
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800533 * Checks if the photo is present in cache. If so, sets the photo on the view.
534 *
535 * @return false if the photo needs to be (re)loaded from the provider.
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800536 */
Daniel Lehmann7a46cde2012-02-01 17:53:44 -0800537 private boolean loadCachedPhoto(ImageView view, Request request, boolean fadeIn) {
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700538 BitmapHolder holder = mBitmapHolderCache.get(request.getKey());
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800539 if (holder == null) {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800540 // The bitmap has not been loaded - should display the placeholder image.
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700541 request.applyDefaultImage(view);
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800542 return false;
543 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800544
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800545 if (holder.bytes == null) {
Makoto Onuki3d3a15c2011-09-22 10:55:08 -0700546 request.applyDefaultImage(view);
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800547 return holder.fresh;
548 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800549
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800550 // Optionally decode bytes into a bitmap
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700551 final long inflateStart = System.currentTimeMillis();
552 final boolean decodingPicture = holder.bitmap == null;
553 inflateBitmap(holder, request.getRequestedExtent());
554 if (decodingPicture && DEBUG) {
555 Log.d(TAG, "Inflated a picture on the foreground thread. Took " +
556 (System.currentTimeMillis() - inflateStart) + "ms");
557 }
Dmitri Plotnikov718a2502010-11-23 17:56:28 -0800558
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700559 final Drawable previousDrawable = view.getDrawable();
560 if (fadeIn && previousDrawable != null) {
561 final Drawable[] layers = new Drawable[2];
562 // Prevent cascade of TransitionDrawables.
563 if (previousDrawable instanceof TransitionDrawable) {
564 final TransitionDrawable transitionDrawable = (TransitionDrawable) previousDrawable;
565 layers[0] =
566 transitionDrawable.getDrawable(transitionDrawable.getNumberOfLayers() - 1);
567 } else {
568 layers[0] = previousDrawable;
569 }
Daniel Lehmann7a46cde2012-02-01 17:53:44 -0800570 layers[1] = new BitmapDrawable(mContext.getResources(), holder.bitmap);
571 TransitionDrawable drawable = new TransitionDrawable(layers);
572 view.setImageDrawable(drawable);
573 drawable.startTransition(FADE_TRANSITION_DURATION);
574 } else {
575 view.setImageBitmap(holder.bitmap);
576 }
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800577
Daisuke Miyakawabf9b2132011-10-11 19:03:52 -0700578 if (holder.bitmap != null) {
579 // Put the bitmap in the LRU cache
Daniel Lehmann7a46cde2012-02-01 17:53:44 -0800580 mBitmapCache.put(request.getKey(), holder.bitmap);
Daisuke Miyakawabf9b2132011-10-11 19:03:52 -0700581 }
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800582
583 // Soften the reference
584 holder.bitmap = null;
585
586 return holder.fresh;
587 }
588
589 /**
590 * If necessary, decodes bytes stored in the holder to Bitmap. As long as the
591 * bitmap is held either by {@link #mBitmapCache} or by a soft reference in
592 * the holder, it will not be necessary to decode the bitmap.
593 */
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700594 private static void inflateBitmap(BitmapHolder holder, int requestedExtent) {
595 final int sampleSize =
596 BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent, requestedExtent);
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800597 byte[] bytes = holder.bytes;
598 if (bytes == null || bytes.length == 0) {
599 return;
600 }
601
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700602 if (sampleSize == holder.decodedSampleSize) {
603 // Check the soft reference. If will be retained if the bitmap is also
604 // in the LRU cache, so we don't need to check the LRU cache explicitly.
605 if (holder.bitmapRef != null) {
606 holder.bitmap = holder.bitmapRef.get();
607 if (holder.bitmap != null) {
608 return;
609 }
Dmitri Plotnikov718a2502010-11-23 17:56:28 -0800610 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800611 }
612
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800613 try {
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700614 Bitmap bitmap = BitmapUtil.decodeBitmapFromBytes(bytes, sampleSize);
615
616 // make bitmap mutable and draw size onto it
617 if (DEBUG_SIZES) {
618 Bitmap original = bitmap;
619 bitmap = bitmap.copy(bitmap.getConfig(), true);
620 original.recycle();
621 Canvas canvas = new Canvas(bitmap);
622 Paint paint = new Paint();
623 paint.setTextSize(16);
624 paint.setColor(Color.BLUE);
625 paint.setStyle(Style.FILL);
626 canvas.drawRect(0.0f, 0.0f, 50.0f, 20.0f, paint);
627 paint.setColor(Color.WHITE);
628 paint.setAntiAlias(true);
629 canvas.drawText(bitmap.getWidth() + "/" + sampleSize, 0, 15, paint);
630 }
631
632 holder.decodedSampleSize = sampleSize;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800633 holder.bitmap = bitmap;
634 holder.bitmapRef = new SoftReference<Bitmap>(bitmap);
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800635 if (DEBUG) {
636 Log.d(TAG, "inflateBitmap " + btk(bytes.length) + " -> "
637 + bitmap.getWidth() + "x" + bitmap.getHeight()
638 + ", " + btk(bitmap.getByteCount()));
639 }
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800640 } catch (OutOfMemoryError e) {
641 // Do nothing - the photo will appear to be missing
642 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800643 }
644
Dmitri Plotnikovb369c492010-03-24 18:11:24 -0700645 public void clear() {
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800646 if (DEBUG) Log.d(TAG, "clear");
Dmitri Plotnikovb369c492010-03-24 18:11:24 -0700647 mPendingRequests.clear();
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800648 mBitmapHolderCache.evictAll();
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800649 mBitmapCache.evictAll();
Dmitri Plotnikovb369c492010-03-24 18:11:24 -0700650 }
651
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800652 @Override
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800653 public void pause() {
654 mPaused = true;
655 }
656
Dmitri Plotnikov34b24ef2011-01-28 13:41:07 -0800657 @Override
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800658 public void resume() {
659 mPaused = false;
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800660 if (DEBUG) dumpStats();
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800661 if (!mPendingRequests.isEmpty()) {
662 requestLoading();
663 }
664 }
665
666 /**
667 * Sends a message to this thread itself to start loading images. If the current
668 * view contains multiple image views, all of those image views will get a chance
669 * to request their respective photos before any of those requests are executed.
670 * This allows us to load images in bulk.
671 */
672 private void requestLoading() {
673 if (!mLoadingRequested) {
674 mLoadingRequested = true;
675 mMainThreadHandler.sendEmptyMessage(MESSAGE_REQUEST_LOADING);
676 }
677 }
678
679 /**
680 * Processes requests on the main thread.
681 */
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700682 @Override
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800683 public boolean handleMessage(Message msg) {
684 switch (msg.what) {
685 case MESSAGE_REQUEST_LOADING: {
686 mLoadingRequested = false;
687 if (!mPaused) {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800688 ensureLoaderThread();
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800689 mLoaderThread.requestLoading();
690 }
691 return true;
692 }
693
694 case MESSAGE_PHOTOS_LOADED: {
695 if (!mPaused) {
696 processLoadedImages();
697 }
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800698 if (DEBUG) dumpStats();
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800699 return true;
700 }
701 }
702 return false;
703 }
704
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800705 public void ensureLoaderThread() {
706 if (mLoaderThread == null) {
707 mLoaderThread = new LoaderThread(mContext.getContentResolver());
708 mLoaderThread.start();
709 }
710 }
711
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800712 /**
713 * Goes over pending loading requests and displays loaded photos. If some of the
714 * photos still haven't been loaded, sends another request for image loading.
715 */
716 private void processLoadedImages() {
717 Iterator<ImageView> iterator = mPendingRequests.keySet().iterator();
718 while (iterator.hasNext()) {
719 ImageView view = iterator.next();
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700720 Request key = mPendingRequests.get(view);
Daniel Lehmann7a46cde2012-02-01 17:53:44 -0800721 boolean loaded = loadCachedPhoto(view, key, true);
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800722 if (loaded) {
723 iterator.remove();
724 }
725 }
726
Dmitri Plotnikov37dc7cf2010-12-17 19:25:08 -0800727 softenCache();
728
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800729 if (!mPendingRequests.isEmpty()) {
730 requestLoading();
731 }
732 }
733
734 /**
Dmitri Plotnikov37dc7cf2010-12-17 19:25:08 -0800735 * Removes strong references to loaded bitmaps to allow them to be garbage collected
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800736 * if needed. Some of the bitmaps will still be retained by {@link #mBitmapCache}.
Dmitri Plotnikov37dc7cf2010-12-17 19:25:08 -0800737 */
738 private void softenCache() {
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800739 for (BitmapHolder holder : mBitmapHolderCache.snapshot().values()) {
Dmitri Plotnikov37dc7cf2010-12-17 19:25:08 -0800740 holder.bitmap = null;
741 }
742 }
743
744 /**
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800745 * Stores the supplied bitmap in cache.
746 */
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700747 private void cacheBitmap(Object key, byte[] bytes, boolean preloading, int requestedExtent) {
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800748 if (DEBUG) {
749 BitmapHolder prev = mBitmapHolderCache.get(key);
750 if (prev != null && prev.bytes != null) {
751 Log.d(TAG, "Overwriting cache: key=" + key + (prev.fresh ? " FRESH" : " stale"));
752 if (prev.fresh) {
753 mFreshCacheOverwrite.incrementAndGet();
754 } else {
755 mStaleCacheOverwrite.incrementAndGet();
756 }
757 }
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700758 Log.d(TAG, "Caching data: key=" + key + ", " +
759 (bytes == null ? "<null>" : btk(bytes.length)));
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -0800760 }
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700761 BitmapHolder holder = new BitmapHolder(bytes,
762 bytes == null ? -1 : BitmapUtil.getSmallerExtentFromBytes(bytes));
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800763
764 // Unless this image is being preloaded, decode it right away while
765 // we are still on the background thread.
766 if (!preloading) {
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700767 inflateBitmap(holder, requestedExtent);
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800768 }
769
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800770 mBitmapHolderCache.put(key, holder);
Makoto Onuki1f0239e2012-02-27 17:13:47 -0800771 mBitmapHolderCacheAllUnfresh = false;
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800772 }
773
Dave Santoro14d20832011-12-02 18:14:52 -0800774 @Override
775 public void cacheBitmap(Uri photoUri, Bitmap bitmap, byte[] photoBytes) {
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700776 final int smallerExtent = Math.min(bitmap.getWidth(), bitmap.getHeight());
777 // We can pretend here that the extent of the photo was the size that we originally
778 // requested
779 Request request = Request.createFromUri(photoUri, smallerExtent, false, DEFAULT_AVATAR);
780 BitmapHolder holder = new BitmapHolder(photoBytes, smallerExtent);
Dave Santoro14d20832011-12-02 18:14:52 -0800781 mBitmapHolderCache.put(request.getKey(), holder);
Makoto Onuki1f0239e2012-02-27 17:13:47 -0800782 mBitmapHolderCacheAllUnfresh = false;
Daniel Lehmann7a46cde2012-02-01 17:53:44 -0800783 mBitmapCache.put(request.getKey(), bitmap);
Dave Santoro14d20832011-12-02 18:14:52 -0800784 }
785
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800786 /**
787 * Populates an array of photo IDs that need to be loaded.
788 */
Flavio Lerdad33b18c2011-07-17 22:03:15 +0100789 private void obtainPhotoIdsAndUrisToLoad(Set<Long> photoIds,
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700790 Set<String> photoIdsAsStrings, Set<Request> uris) {
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800791 photoIds.clear();
Dmitri Plotnikov33409852010-02-20 15:02:32 -0800792 photoIdsAsStrings.clear();
Dmitri Plotnikov0f7462c2010-10-20 14:41:18 -0700793 uris.clear();
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800794
795 /*
796 * Since the call is made from the loader thread, the map could be
797 * changing during the iteration. That's not really a problem:
798 * ConcurrentHashMap will allow those changes to happen without throwing
799 * exceptions. Since we may miss some requests in the situation of
800 * concurrent change, we will need to check the map again once loading
801 * is complete.
802 */
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700803 Iterator<Request> iterator = mPendingRequests.values().iterator();
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800804 while (iterator.hasNext()) {
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700805 Request request = iterator.next();
806 BitmapHolder holder = mBitmapHolderCache.get(request);
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800807 if (holder == null || !holder.fresh) {
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700808 if (request.isUriRequest()) {
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700809 uris.add(request);
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700810 } else {
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700811 photoIds.add(request.getId());
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700812 photoIdsAsStrings.add(String.valueOf(request.mId));
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700813 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800814 }
815 }
816 }
817
818 /**
819 * The thread that performs loading of photos from the database.
820 */
821 private class LoaderThread extends HandlerThread implements Callback {
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700822 private static final int BUFFER_SIZE = 1024*16;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800823 private static final int MESSAGE_PRELOAD_PHOTOS = 0;
824 private static final int MESSAGE_LOAD_PHOTOS = 1;
825
826 /**
827 * A pause between preload batches that yields to the UI thread.
828 */
Makoto Onuki173f2812011-09-06 14:49:27 -0700829 private static final int PHOTO_PRELOAD_DELAY = 1000;
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800830
831 /**
832 * Number of photos to preload per batch.
833 */
834 private static final int PRELOAD_BATCH = 25;
835
836 /**
837 * Maximum number of photos to preload. If the cache size is 2Mb and
838 * the expected average size of a photo is 4kb, then this number should be 2Mb/4kb = 500.
839 */
Makoto Onuki173f2812011-09-06 14:49:27 -0700840 private static final int MAX_PHOTOS_TO_PRELOAD = 100;
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700841
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800842 private final ContentResolver mResolver;
843 private final StringBuilder mStringBuilder = new StringBuilder();
Flavio Lerdad33b18c2011-07-17 22:03:15 +0100844 private final Set<Long> mPhotoIds = Sets.newHashSet();
845 private final Set<String> mPhotoIdsAsStrings = Sets.newHashSet();
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700846 private final Set<Request> mPhotoUris = Sets.newHashSet();
Flavio Lerdad33b18c2011-07-17 22:03:15 +0100847 private final List<Long> mPreloadPhotoIds = Lists.newArrayList();
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800848
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800849 private Handler mLoaderThreadHandler;
Dmitri Plotnikoveb689432010-09-24 10:10:57 -0700850 private byte mBuffer[];
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800851
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800852 private static final int PRELOAD_STATUS_NOT_STARTED = 0;
853 private static final int PRELOAD_STATUS_IN_PROGRESS = 1;
854 private static final int PRELOAD_STATUS_DONE = 2;
855
856 private int mPreloadStatus = PRELOAD_STATUS_NOT_STARTED;
857
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800858 public LoaderThread(ContentResolver resolver) {
859 super(LOADER_THREAD_NAME);
860 mResolver = resolver;
861 }
862
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800863 public void ensureHandler() {
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800864 if (mLoaderThreadHandler == null) {
865 mLoaderThreadHandler = new Handler(getLooper(), this);
866 }
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800867 }
868
869 /**
870 * Kicks off preloading of the next batch of photos on the background thread.
871 * Preloading will happen after a delay: we want to yield to the UI thread
872 * as much as possible.
873 * <p>
874 * If preloading is already complete, does nothing.
875 */
876 public void requestPreloading() {
877 if (mPreloadStatus == PRELOAD_STATUS_DONE) {
878 return;
879 }
880
881 ensureHandler();
882 if (mLoaderThreadHandler.hasMessages(MESSAGE_LOAD_PHOTOS)) {
883 return;
884 }
885
886 mLoaderThreadHandler.sendEmptyMessageDelayed(
887 MESSAGE_PRELOAD_PHOTOS, PHOTO_PRELOAD_DELAY);
888 }
889
890 /**
891 * Sends a message to this thread to load requested photos. Cancels a preloading
892 * request, if any: we don't want preloading to impede loading of the photos
893 * we need to display now.
894 */
895 public void requestLoading() {
896 ensureHandler();
897 mLoaderThreadHandler.removeMessages(MESSAGE_PRELOAD_PHOTOS);
898 mLoaderThreadHandler.sendEmptyMessage(MESSAGE_LOAD_PHOTOS);
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800899 }
900
901 /**
902 * Receives the above message, loads photos and then sends a message
903 * to the main thread to process them.
904 */
Daniel Lehmannecfc26c2011-09-12 17:44:35 -0700905 @Override
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800906 public boolean handleMessage(Message msg) {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800907 switch (msg.what) {
908 case MESSAGE_PRELOAD_PHOTOS:
909 preloadPhotosInBackground();
910 break;
911 case MESSAGE_LOAD_PHOTOS:
912 loadPhotosInBackground();
913 break;
914 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800915 return true;
916 }
917
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800918 /**
919 * The first time it is called, figures out which photos need to be preloaded.
920 * Each subsequent call preloads the next batch of photos and requests
921 * another cycle of preloading after a delay. The whole process ends when
922 * we either run out of photos to preload or fill up cache.
923 */
924 private void preloadPhotosInBackground() {
925 if (mPreloadStatus == PRELOAD_STATUS_DONE) {
926 return;
Dmitri Plotnikove8643852010-02-17 10:49:05 -0800927 }
Dmitri Plotnikov33409852010-02-20 15:02:32 -0800928
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800929 if (mPreloadStatus == PRELOAD_STATUS_NOT_STARTED) {
930 queryPhotosForPreload();
931 if (mPreloadPhotoIds.isEmpty()) {
932 mPreloadStatus = PRELOAD_STATUS_DONE;
933 } else {
934 mPreloadStatus = PRELOAD_STATUS_IN_PROGRESS;
935 }
936 requestPreloading();
937 return;
938 }
939
Jesse Wilsonfb231aa2011-02-07 15:15:56 -0800940 if (mBitmapHolderCache.size() > mBitmapHolderCacheRedZoneBytes) {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800941 mPreloadStatus = PRELOAD_STATUS_DONE;
942 return;
943 }
944
945 mPhotoIds.clear();
946 mPhotoIdsAsStrings.clear();
947
948 int count = 0;
949 int preloadSize = mPreloadPhotoIds.size();
950 while(preloadSize > 0 && mPhotoIds.size() < PRELOAD_BATCH) {
951 preloadSize--;
952 count++;
953 Long photoId = mPreloadPhotoIds.get(preloadSize);
954 mPhotoIds.add(photoId);
955 mPhotoIdsAsStrings.add(photoId.toString());
956 mPreloadPhotoIds.remove(preloadSize);
957 }
958
Daniel Lehmann2f77c852012-03-30 15:25:31 -0700959 loadThumbnails(true);
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800960
961 if (preloadSize == 0) {
962 mPreloadStatus = PRELOAD_STATUS_DONE;
963 }
964
Makoto Onuki173f2812011-09-06 14:49:27 -0700965 Log.v(TAG, "Preloaded " + count + " photos. Cached bytes: "
966 + mBitmapHolderCache.size());
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800967
968 requestPreloading();
969 }
970
971 private void queryPhotosForPreload() {
972 Cursor cursor = null;
973 try {
974 Uri uri = Contacts.CONTENT_URI.buildUpon().appendQueryParameter(
975 ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(Directory.DEFAULT))
Daniel Lehmann4ccae562011-05-02 16:39:01 -0700976 .appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY,
977 String.valueOf(MAX_PHOTOS_TO_PRELOAD))
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800978 .build();
979 cursor = mResolver.query(uri, new String[] { Contacts.PHOTO_ID },
980 Contacts.PHOTO_ID + " NOT NULL AND " + Contacts.PHOTO_ID + "!=0",
981 null,
Daniel Lehmann4ccae562011-05-02 16:39:01 -0700982 Contacts.STARRED + " DESC, " + Contacts.LAST_TIME_CONTACTED + " DESC");
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -0800983
984 if (cursor != null) {
985 while (cursor.moveToNext()) {
986 // Insert them in reverse order, because we will be taking
987 // them from the end of the list for loading.
988 mPreloadPhotoIds.add(0, cursor.getLong(0));
989 }
990 }
991 } finally {
992 if (cursor != null) {
993 cursor.close();
994 }
995 }
996 }
997
998 private void loadPhotosInBackground() {
999 obtainPhotoIdsAndUrisToLoad(mPhotoIds, mPhotoIdsAsStrings, mPhotoUris);
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001000 loadThumbnails(false);
1001 loadUriBasedPhotos();
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -08001002 requestPreloading();
1003 }
1004
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001005 /** Loads thumbnail photos with ids */
1006 private void loadThumbnails(boolean preloading) {
Flavio Lerdad33b18c2011-07-17 22:03:15 +01001007 if (mPhotoIds.isEmpty()) {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -08001008 return;
1009 }
1010
1011 // Remove loaded photos from the preload queue: we don't want
1012 // the preloading process to load them again.
1013 if (!preloading && mPreloadStatus == PRELOAD_STATUS_IN_PROGRESS) {
Flavio Lerdad33b18c2011-07-17 22:03:15 +01001014 for (Long id : mPhotoIds) {
1015 mPreloadPhotoIds.remove(id);
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -08001016 }
1017 if (mPreloadPhotoIds.isEmpty()) {
1018 mPreloadStatus = PRELOAD_STATUS_DONE;
1019 }
1020 }
1021
1022 mStringBuilder.setLength(0);
1023 mStringBuilder.append(Photo._ID + " IN(");
Flavio Lerdad33b18c2011-07-17 22:03:15 +01001024 for (int i = 0; i < mPhotoIds.size(); i++) {
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -08001025 if (i != 0) {
1026 mStringBuilder.append(',');
1027 }
1028 mStringBuilder.append('?');
1029 }
1030 mStringBuilder.append(')');
1031
1032 Cursor cursor = null;
1033 try {
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -08001034 if (DEBUG) Log.d(TAG, "Loading " + TextUtils.join(",", mPhotoIdsAsStrings));
Dave Santoro84cac442011-08-24 15:23:10 -07001035 cursor = mResolver.query(Data.CONTENT_URI,
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -08001036 COLUMNS,
1037 mStringBuilder.toString(),
1038 mPhotoIdsAsStrings.toArray(EMPTY_STRING_ARRAY),
1039 null);
1040
1041 if (cursor != null) {
1042 while (cursor.moveToNext()) {
1043 Long id = cursor.getLong(0);
1044 byte[] bytes = cursor.getBlob(1);
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001045 cacheBitmap(id, bytes, preloading, -1);
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -08001046 mPhotoIds.remove(id);
1047 }
1048 }
1049 } finally {
1050 if (cursor != null) {
1051 cursor.close();
1052 }
1053 }
1054
Dave Santoro84cac442011-08-24 15:23:10 -07001055 // Remaining photos were not found in the contacts database (but might be in profile).
Flavio Lerdad33b18c2011-07-17 22:03:15 +01001056 for (Long id : mPhotoIds) {
Dave Santoro84cac442011-08-24 15:23:10 -07001057 if (ContactsContract.isProfileId(id)) {
1058 Cursor profileCursor = null;
1059 try {
1060 profileCursor = mResolver.query(
1061 ContentUris.withAppendedId(Data.CONTENT_URI, id),
1062 COLUMNS, null, null, null);
1063 if (profileCursor != null && profileCursor.moveToFirst()) {
1064 cacheBitmap(profileCursor.getLong(0), profileCursor.getBlob(1),
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001065 preloading, -1);
Dave Santoro84cac442011-08-24 15:23:10 -07001066 } else {
1067 // Couldn't load a photo this way either.
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001068 cacheBitmap(id, null, preloading, -1);
Dave Santoro84cac442011-08-24 15:23:10 -07001069 }
1070 } finally {
1071 if (profileCursor != null) {
1072 profileCursor.close();
1073 }
1074 }
1075 } else {
1076 // Not a profile photo and not found - mark the cache accordingly
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001077 cacheBitmap(id, null, preloading, -1);
Dave Santoro84cac442011-08-24 15:23:10 -07001078 }
Dmitri Plotnikov7edf2382011-01-31 16:15:48 -08001079 }
1080
1081 mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED);
1082 }
1083
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001084 /**
1085 * Loads photos referenced with Uris. Those can be remote thumbnails
1086 * (from directory searches), display photos etc
1087 */
1088 private void loadUriBasedPhotos() {
1089 for (Request uriRequest : mPhotoUris) {
1090 Uri uri = uriRequest.getUri();
Dmitri Plotnikoveb689432010-09-24 10:10:57 -07001091 if (mBuffer == null) {
1092 mBuffer = new byte[BUFFER_SIZE];
1093 }
1094 try {
Makoto Onuki8f8bd6d2011-11-08 14:09:01 -08001095 if (DEBUG) Log.d(TAG, "Loading " + uri);
Dmitri Plotnikoveb689432010-09-24 10:10:57 -07001096 InputStream is = mResolver.openInputStream(uri);
1097 if (is != null) {
1098 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1099 try {
1100 int size;
1101 while ((size = is.read(mBuffer)) != -1) {
1102 baos.write(mBuffer, 0, size);
1103 }
1104 } finally {
1105 is.close();
1106 }
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001107 cacheBitmap(uri, baos.toByteArray(), false,
1108 uriRequest.getRequestedExtent());
Dmitri Plotnikoveb689432010-09-24 10:10:57 -07001109 mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED);
Dmitri Plotnikov0f7462c2010-10-20 14:41:18 -07001110 } else {
1111 Log.v(TAG, "Cannot load photo " + uri);
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001112 cacheBitmap(uri, null, false, uriRequest.getRequestedExtent());
Dmitri Plotnikoveb689432010-09-24 10:10:57 -07001113 }
1114 } catch (Exception ex) {
1115 Log.v(TAG, "Cannot load photo " + uri, ex);
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001116 cacheBitmap(uri, null, false, uriRequest.getRequestedExtent());
Dmitri Plotnikoveb689432010-09-24 10:10:57 -07001117 }
Dmitri Plotnikov33409852010-02-20 15:02:32 -08001118 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -08001119 }
1120 }
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001121
1122 /**
1123 * A holder for either a Uri or an id and a flag whether this was requested for the dark or
1124 * light theme
1125 */
1126 private static final class Request {
1127 private final long mId;
1128 private final Uri mUri;
1129 private final boolean mDarkTheme;
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001130 private final int mRequestedExtent;
Makoto Onuki3d3a15c2011-09-22 10:55:08 -07001131 private final DefaultImageProvider mDefaultProvider;
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001132
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001133 private Request(long id, Uri uri, int requestedExtent, boolean darkTheme,
Makoto Onuki3d3a15c2011-09-22 10:55:08 -07001134 DefaultImageProvider defaultProvider) {
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001135 mId = id;
1136 mUri = uri;
1137 mDarkTheme = darkTheme;
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001138 mRequestedExtent = requestedExtent;
Makoto Onuki3d3a15c2011-09-22 10:55:08 -07001139 mDefaultProvider = defaultProvider;
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001140 }
1141
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001142 public static Request createFromThumbnailId(long id, boolean darkTheme,
Makoto Onuki3d3a15c2011-09-22 10:55:08 -07001143 DefaultImageProvider defaultProvider) {
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001144 return new Request(id, null /* no URI */, -1, darkTheme, defaultProvider);
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001145 }
1146
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001147 public static Request createFromUri(Uri uri, int requestedExtent, boolean darkTheme,
Makoto Onuki3d3a15c2011-09-22 10:55:08 -07001148 DefaultImageProvider defaultProvider) {
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001149 return new Request(0 /* no ID */, uri, requestedExtent, darkTheme, defaultProvider);
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001150 }
1151
1152 public boolean isUriRequest() {
1153 return mUri != null;
1154 }
1155
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001156 public Uri getUri() {
1157 return mUri;
1158 }
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001159
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001160 public long getId() {
1161 return mId;
1162 }
1163
1164 public int getRequestedExtent() {
1165 return mRequestedExtent;
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001166 }
1167
1168 @Override
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001169 public int hashCode() {
1170 final int prime = 31;
1171 int result = 1;
1172 result = prime * result + (int) (mId ^ (mId >>> 32));
1173 result = prime * result + mRequestedExtent;
1174 result = prime * result + ((mUri == null) ? 0 : mUri.hashCode());
1175 return result;
1176 }
1177
1178 @Override
1179 public boolean equals(Object obj) {
1180 if (this == obj) return true;
1181 if (obj == null) return false;
1182 if (getClass() != obj.getClass()) return false;
1183 final Request that = (Request) obj;
1184 if (mId != that.mId) return false;
1185 if (mRequestedExtent != that.mRequestedExtent) return false;
1186 if (!UriUtils.areEqual(mUri, that.mUri)) return false;
1187 // Don't compare equality of mDarkTheme because it is only used in the default contact
1188 // photo case. When the contact does have a photo, the contact photo is the same
1189 // regardless of mDarkTheme, so we shouldn't need to put the photo request on the queue
1190 // twice.
1191 return true;
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001192 }
1193
1194 public Object getKey() {
1195 return mUri == null ? mId : mUri;
1196 }
Makoto Onuki3d3a15c2011-09-22 10:55:08 -07001197
1198 public void applyDefaultImage(ImageView view) {
Daniel Lehmann2f77c852012-03-30 15:25:31 -07001199 mDefaultProvider.applyDefaultImage(view, mRequestedExtent, mDarkTheme);
Makoto Onuki3d3a15c2011-09-22 10:55:08 -07001200 }
Daniel Lehmannecfc26c2011-09-12 17:44:35 -07001201 }
Dmitri Plotnikove8643852010-02-17 10:49:05 -08001202}