1/* 2 * Copyright (C) 2016 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 17package com.android.contacts.common; 18 19import android.app.ActivityManager; 20import android.content.ComponentCallbacks2; 21import android.content.ContentResolver; 22import android.content.ContentUris; 23import android.content.Context; 24import android.content.res.Resources; 25import android.database.Cursor; 26import android.graphics.Bitmap; 27import android.graphics.Canvas; 28import android.graphics.Color; 29import android.graphics.Paint; 30import android.graphics.Paint.Style; 31import android.graphics.drawable.BitmapDrawable; 32import android.graphics.drawable.Drawable; 33import android.graphics.drawable.TransitionDrawable; 34import android.media.ThumbnailUtils; 35import android.net.TrafficStats; 36import android.net.Uri; 37import android.os.Handler; 38import android.os.Handler.Callback; 39import android.os.HandlerThread; 40import android.os.Message; 41import android.provider.ContactsContract; 42import android.provider.ContactsContract.Contacts; 43import android.provider.ContactsContract.Contacts.Photo; 44import android.provider.ContactsContract.Data; 45import android.provider.ContactsContract.Directory; 46import android.support.annotation.UiThread; 47import android.support.annotation.WorkerThread; 48import android.support.v4.graphics.drawable.RoundedBitmapDrawable; 49import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; 50import android.text.TextUtils; 51import android.util.LruCache; 52import android.view.View; 53import android.view.ViewGroup; 54import android.widget.ImageView; 55import com.android.contacts.common.util.BitmapUtil; 56import com.android.contacts.common.util.UriUtils; 57import com.android.dialer.common.LogUtil; 58import com.android.dialer.constants.TrafficStatsTags; 59import com.android.dialer.util.PermissionsUtil; 60import java.io.ByteArrayOutputStream; 61import java.io.IOException; 62import java.io.InputStream; 63import java.lang.ref.Reference; 64import java.lang.ref.SoftReference; 65import java.net.HttpURLConnection; 66import java.net.URL; 67import java.util.ArrayList; 68import java.util.HashSet; 69import java.util.Iterator; 70import java.util.List; 71import java.util.Map.Entry; 72import java.util.Set; 73import java.util.concurrent.ConcurrentHashMap; 74import java.util.concurrent.atomic.AtomicInteger; 75 76class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { 77 78 private static final String LOADER_THREAD_NAME = "ContactPhotoLoader"; 79 80 private static final int FADE_TRANSITION_DURATION = 200; 81 82 /** 83 * Type of message sent by the UI thread to itself to indicate that some photos need to be loaded. 84 */ 85 private static final int MESSAGE_REQUEST_LOADING = 1; 86 87 /** Type of message sent by the loader thread to indicate that some photos have been loaded. */ 88 private static final int MESSAGE_PHOTOS_LOADED = 2; 89 90 private static final String[] EMPTY_STRING_ARRAY = new String[0]; 91 92 private static final String[] COLUMNS = new String[] {Photo._ID, Photo.PHOTO}; 93 94 /** 95 * Dummy object used to indicate that a bitmap for a given key could not be stored in the cache. 96 */ 97 private static final BitmapHolder BITMAP_UNAVAILABLE; 98 /** Cache size for {@link #mBitmapHolderCache} for devices with "large" RAM. */ 99 private static final int HOLDER_CACHE_SIZE = 2000000; 100 /** Cache size for {@link #mBitmapCache} for devices with "large" RAM. */ 101 private static final int BITMAP_CACHE_SIZE = 36864 * 48; // 1728K 102 /** Height/width of a thumbnail image */ 103 private static int mThumbnailSize; 104 105 static { 106 BITMAP_UNAVAILABLE = new BitmapHolder(new byte[0], 0); 107 BITMAP_UNAVAILABLE.bitmapRef = new SoftReference<Bitmap>(null); 108 } 109 110 private final Context mContext; 111 /** 112 * An LRU cache for bitmap holders. The cache contains bytes for photos just as they come from the 113 * database. Each holder has a soft reference to the actual bitmap. 114 */ 115 private final LruCache<Object, BitmapHolder> mBitmapHolderCache; 116 /** Cache size threshold at which bitmaps will not be preloaded. */ 117 private final int mBitmapHolderCacheRedZoneBytes; 118 /** 119 * Level 2 LRU cache for bitmaps. This is a smaller cache that holds the most recently used 120 * bitmaps to save time on decoding them from bytes (the bytes are stored in {@link 121 * #mBitmapHolderCache}. 122 */ 123 private final LruCache<Object, Bitmap> mBitmapCache; 124 /** 125 * A map from ImageView to the corresponding photo ID or uri, encapsulated in a request. The 126 * request may swapped out before the photo loading request is started. 127 */ 128 private final ConcurrentHashMap<ImageView, Request> mPendingRequests = 129 new ConcurrentHashMap<ImageView, Request>(); 130 /** Handler for messages sent to the UI thread. */ 131 private final Handler mMainThreadHandler = new Handler(this); 132 /** For debug: How many times we had to reload cached photo for a stale entry */ 133 private final AtomicInteger mStaleCacheOverwrite = new AtomicInteger(); 134 /** For debug: How many times we had to reload cached photo for a fresh entry. Should be 0. */ 135 private final AtomicInteger mFreshCacheOverwrite = new AtomicInteger(); 136 /** {@code true} if ALL entries in {@link #mBitmapHolderCache} are NOT fresh. */ 137 private volatile boolean mBitmapHolderCacheAllUnfresh = true; 138 /** Thread responsible for loading photos from the database. Created upon the first request. */ 139 private LoaderThread mLoaderThread; 140 /** A gate to make sure we only send one instance of MESSAGE_PHOTOS_NEEDED at a time. */ 141 private boolean mLoadingRequested; 142 /** Flag indicating if the image loading is paused. */ 143 private boolean mPaused; 144 /** The user agent string to use when loading URI based photos. */ 145 private String mUserAgent; 146 147 public ContactPhotoManagerImpl(Context context) { 148 mContext = context; 149 150 final ActivityManager am = 151 ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)); 152 153 final float cacheSizeAdjustment = (am.isLowRamDevice()) ? 0.5f : 1.0f; 154 155 final int bitmapCacheSize = (int) (cacheSizeAdjustment * BITMAP_CACHE_SIZE); 156 mBitmapCache = 157 new LruCache<Object, Bitmap>(bitmapCacheSize) { 158 @Override 159 protected int sizeOf(Object key, Bitmap value) { 160 return value.getByteCount(); 161 } 162 163 @Override 164 protected void entryRemoved( 165 boolean evicted, Object key, Bitmap oldValue, Bitmap newValue) { 166 if (DEBUG) { 167 dumpStats(); 168 } 169 } 170 }; 171 final int holderCacheSize = (int) (cacheSizeAdjustment * HOLDER_CACHE_SIZE); 172 mBitmapHolderCache = 173 new LruCache<Object, BitmapHolder>(holderCacheSize) { 174 @Override 175 protected int sizeOf(Object key, BitmapHolder value) { 176 return value.bytes != null ? value.bytes.length : 0; 177 } 178 179 @Override 180 protected void entryRemoved( 181 boolean evicted, Object key, BitmapHolder oldValue, BitmapHolder newValue) { 182 if (DEBUG) { 183 dumpStats(); 184 } 185 } 186 }; 187 mBitmapHolderCacheRedZoneBytes = (int) (holderCacheSize * 0.75); 188 LogUtil.i( 189 "ContactPhotoManagerImpl.ContactPhotoManagerImpl", "cache adj: " + cacheSizeAdjustment); 190 if (DEBUG) { 191 LogUtil.d( 192 "ContactPhotoManagerImpl.ContactPhotoManagerImpl", 193 "Cache size: " + btk(mBitmapHolderCache.maxSize()) + " + " + btk(mBitmapCache.maxSize())); 194 } 195 196 mThumbnailSize = 197 context.getResources().getDimensionPixelSize(R.dimen.contact_browser_list_item_photo_size); 198 199 // Get a user agent string to use for URI photo requests. 200 mUserAgent = Bindings.get(context).getUserAgent(); 201 if (mUserAgent == null) { 202 mUserAgent = ""; 203 } 204 } 205 206 /** Converts bytes to K bytes, rounding up. Used only for debug log. */ 207 private static String btk(int bytes) { 208 return ((bytes + 1023) / 1024) + "K"; 209 } 210 211 private static final int safeDiv(int dividend, int divisor) { 212 return (divisor == 0) ? 0 : (dividend / divisor); 213 } 214 215 private static boolean isChildView(View parent, View potentialChild) { 216 return potentialChild.getParent() != null 217 && (potentialChild.getParent() == parent 218 || (potentialChild.getParent() instanceof ViewGroup 219 && isChildView(parent, (ViewGroup) potentialChild.getParent()))); 220 } 221 222 /** 223 * If necessary, decodes bytes stored in the holder to Bitmap. As long as the bitmap is held 224 * either by {@link #mBitmapCache} or by a soft reference in the holder, it will not be necessary 225 * to decode the bitmap. 226 */ 227 private static void inflateBitmap(BitmapHolder holder, int requestedExtent) { 228 final int sampleSize = 229 BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent, requestedExtent); 230 byte[] bytes = holder.bytes; 231 if (bytes == null || bytes.length == 0) { 232 return; 233 } 234 235 if (sampleSize == holder.decodedSampleSize) { 236 // Check the soft reference. If will be retained if the bitmap is also 237 // in the LRU cache, so we don't need to check the LRU cache explicitly. 238 if (holder.bitmapRef != null) { 239 holder.bitmap = holder.bitmapRef.get(); 240 if (holder.bitmap != null) { 241 return; 242 } 243 } 244 } 245 246 try { 247 Bitmap bitmap = BitmapUtil.decodeBitmapFromBytes(bytes, sampleSize); 248 249 // TODO: As a temporary workaround while framework support is being added to 250 // clip non-square bitmaps into a perfect circle, manually crop the bitmap into 251 // into a square if it will be displayed as a thumbnail so that it can be cropped 252 // into a circle. 253 final int height = bitmap.getHeight(); 254 final int width = bitmap.getWidth(); 255 256 // The smaller dimension of a scaled bitmap can range from anywhere from 0 to just 257 // below twice the length of a thumbnail image due to the way we calculate the optimal 258 // sample size. 259 if (height != width && Math.min(height, width) <= mThumbnailSize * 2) { 260 final int dimension = Math.min(height, width); 261 bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension); 262 } 263 // make bitmap mutable and draw size onto it 264 if (DEBUG_SIZES) { 265 Bitmap original = bitmap; 266 bitmap = bitmap.copy(bitmap.getConfig(), true); 267 original.recycle(); 268 Canvas canvas = new Canvas(bitmap); 269 Paint paint = new Paint(); 270 paint.setTextSize(16); 271 paint.setColor(Color.BLUE); 272 paint.setStyle(Style.FILL); 273 canvas.drawRect(0.0f, 0.0f, 50.0f, 20.0f, paint); 274 paint.setColor(Color.WHITE); 275 paint.setAntiAlias(true); 276 canvas.drawText(bitmap.getWidth() + "/" + sampleSize, 0, 15, paint); 277 } 278 279 holder.decodedSampleSize = sampleSize; 280 holder.bitmap = bitmap; 281 holder.bitmapRef = new SoftReference<Bitmap>(bitmap); 282 if (DEBUG) { 283 LogUtil.d( 284 "ContactPhotoManagerImpl.inflateBitmap", 285 "inflateBitmap " 286 + btk(bytes.length) 287 + " -> " 288 + bitmap.getWidth() 289 + "x" 290 + bitmap.getHeight() 291 + ", " 292 + btk(bitmap.getByteCount())); 293 } 294 } catch (OutOfMemoryError e) { 295 // Do nothing - the photo will appear to be missing 296 } 297 } 298 299 /** Dump cache stats on logcat. */ 300 private void dumpStats() { 301 if (!DEBUG) { 302 return; 303 } 304 { 305 int numHolders = 0; 306 int rawBytes = 0; 307 int bitmapBytes = 0; 308 int numBitmaps = 0; 309 for (BitmapHolder h : mBitmapHolderCache.snapshot().values()) { 310 numHolders++; 311 if (h.bytes != null) { 312 rawBytes += h.bytes.length; 313 } 314 Bitmap b = h.bitmapRef != null ? h.bitmapRef.get() : null; 315 if (b != null) { 316 numBitmaps++; 317 bitmapBytes += b.getByteCount(); 318 } 319 } 320 LogUtil.d( 321 "ContactPhotoManagerImpl.dumpStats", 322 "L1: " 323 + btk(rawBytes) 324 + " + " 325 + btk(bitmapBytes) 326 + " = " 327 + btk(rawBytes + bitmapBytes) 328 + ", " 329 + numHolders 330 + " holders, " 331 + numBitmaps 332 + " bitmaps, avg: " 333 + btk(safeDiv(rawBytes, numHolders)) 334 + "," 335 + btk(safeDiv(bitmapBytes, numBitmaps))); 336 LogUtil.d( 337 "ContactPhotoManagerImpl.dumpStats", 338 "L1 Stats: " 339 + mBitmapHolderCache.toString() 340 + ", overwrite: fresh=" 341 + mFreshCacheOverwrite.get() 342 + " stale=" 343 + mStaleCacheOverwrite.get()); 344 } 345 346 { 347 int numBitmaps = 0; 348 int bitmapBytes = 0; 349 for (Bitmap b : mBitmapCache.snapshot().values()) { 350 numBitmaps++; 351 bitmapBytes += b.getByteCount(); 352 } 353 LogUtil.d( 354 "ContactPhotoManagerImpl.dumpStats", 355 "L2: " 356 + btk(bitmapBytes) 357 + ", " 358 + numBitmaps 359 + " bitmaps" 360 + ", avg: " 361 + btk(safeDiv(bitmapBytes, numBitmaps))); 362 // We don't get from L2 cache, so L2 stats is meaningless. 363 } 364 } 365 366 @Override 367 public void onTrimMemory(int level) { 368 if (DEBUG) { 369 LogUtil.d("ContactPhotoManagerImpl.onTrimMemory", "onTrimMemory: " + level); 370 } 371 if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) { 372 // Clear the caches. Note all pending requests will be removed too. 373 clear(); 374 } 375 } 376 377 @Override 378 public void preloadPhotosInBackground() { 379 ensureLoaderThread(); 380 mLoaderThread.requestPreloading(); 381 } 382 383 @Override 384 public void loadThumbnail( 385 ImageView view, 386 long photoId, 387 boolean darkTheme, 388 boolean isCircular, 389 DefaultImageRequest defaultImageRequest, 390 DefaultImageProvider defaultProvider) { 391 if (photoId == 0) { 392 // No photo is needed 393 defaultProvider.applyDefaultImage(view, -1, darkTheme, defaultImageRequest); 394 mPendingRequests.remove(view); 395 } else { 396 if (DEBUG) { 397 LogUtil.d("ContactPhotoManagerImpl.loadThumbnail", "loadPhoto request: " + photoId); 398 } 399 loadPhotoByIdOrUri( 400 view, Request.createFromThumbnailId(photoId, darkTheme, isCircular, defaultProvider)); 401 } 402 } 403 404 @Override 405 public void loadPhoto( 406 ImageView view, 407 Uri photoUri, 408 int requestedExtent, 409 boolean darkTheme, 410 boolean isCircular, 411 DefaultImageRequest defaultImageRequest, 412 DefaultImageProvider defaultProvider) { 413 if (photoUri == null) { 414 // No photo is needed 415 defaultProvider.applyDefaultImage(view, requestedExtent, darkTheme, defaultImageRequest); 416 mPendingRequests.remove(view); 417 } else { 418 if (DEBUG) { 419 LogUtil.d("ContactPhotoManagerImpl.loadPhoto", "loadPhoto request: " + photoUri); 420 } 421 if (isDefaultImageUri(photoUri)) { 422 createAndApplyDefaultImageForUri( 423 view, photoUri, requestedExtent, darkTheme, isCircular, defaultProvider); 424 } else { 425 loadPhotoByIdOrUri( 426 view, 427 Request.createFromUri( 428 photoUri, requestedExtent, darkTheme, isCircular, defaultProvider)); 429 } 430 } 431 } 432 433 private void createAndApplyDefaultImageForUri( 434 ImageView view, 435 Uri uri, 436 int requestedExtent, 437 boolean darkTheme, 438 boolean isCircular, 439 DefaultImageProvider defaultProvider) { 440 DefaultImageRequest request = getDefaultImageRequestFromUri(uri); 441 request.isCircular = isCircular; 442 defaultProvider.applyDefaultImage(view, requestedExtent, darkTheme, request); 443 } 444 445 private void loadPhotoByIdOrUri(ImageView view, Request request) { 446 boolean loaded = loadCachedPhoto(view, request, false); 447 if (loaded) { 448 mPendingRequests.remove(view); 449 } else { 450 mPendingRequests.put(view, request); 451 if (!mPaused) { 452 // Send a request to start loading photos 453 requestLoading(); 454 } 455 } 456 } 457 458 @Override 459 public void removePhoto(ImageView view) { 460 view.setImageDrawable(null); 461 mPendingRequests.remove(view); 462 } 463 464 /** 465 * Cancels pending requests to load photos asynchronously for views inside {@param 466 * fragmentRootView}. If {@param fragmentRootView} is null, cancels all requests. 467 */ 468 @Override 469 public void cancelPendingRequests(View fragmentRootView) { 470 if (fragmentRootView == null) { 471 mPendingRequests.clear(); 472 return; 473 } 474 final Iterator<Entry<ImageView, Request>> iterator = mPendingRequests.entrySet().iterator(); 475 while (iterator.hasNext()) { 476 final ImageView imageView = iterator.next().getKey(); 477 // If an ImageView is orphaned (currently scrap) or a child of fragmentRootView, then 478 // we can safely remove its request. 479 if (imageView.getParent() == null || isChildView(fragmentRootView, imageView)) { 480 iterator.remove(); 481 } 482 } 483 } 484 485 @Override 486 public void refreshCache() { 487 if (mBitmapHolderCacheAllUnfresh) { 488 if (DEBUG) { 489 LogUtil.d("ContactPhotoManagerImpl.refreshCache", "refreshCache -- no fresh entries."); 490 } 491 return; 492 } 493 if (DEBUG) { 494 LogUtil.d("ContactPhotoManagerImpl.refreshCache", "refreshCache"); 495 } 496 mBitmapHolderCacheAllUnfresh = true; 497 for (BitmapHolder holder : mBitmapHolderCache.snapshot().values()) { 498 if (holder != BITMAP_UNAVAILABLE) { 499 holder.fresh = false; 500 } 501 } 502 } 503 504 /** 505 * Checks if the photo is present in cache. If so, sets the photo on the view. 506 * 507 * @return false if the photo needs to be (re)loaded from the provider. 508 */ 509 @UiThread 510 private boolean loadCachedPhoto(ImageView view, Request request, boolean fadeIn) { 511 BitmapHolder holder = mBitmapHolderCache.get(request.getKey()); 512 if (holder == null) { 513 // The bitmap has not been loaded ==> show default avatar 514 request.applyDefaultImage(view, request.mIsCircular); 515 return false; 516 } 517 518 if (holder.bytes == null) { 519 request.applyDefaultImage(view, request.mIsCircular); 520 return holder.fresh; 521 } 522 523 Bitmap cachedBitmap = holder.bitmapRef == null ? null : holder.bitmapRef.get(); 524 if (cachedBitmap == null) { 525 request.applyDefaultImage(view, request.mIsCircular); 526 return false; 527 } 528 529 final Drawable previousDrawable = view.getDrawable(); 530 if (fadeIn && previousDrawable != null) { 531 final Drawable[] layers = new Drawable[2]; 532 // Prevent cascade of TransitionDrawables. 533 if (previousDrawable instanceof TransitionDrawable) { 534 final TransitionDrawable previousTransitionDrawable = (TransitionDrawable) previousDrawable; 535 layers[0] = 536 previousTransitionDrawable.getDrawable( 537 previousTransitionDrawable.getNumberOfLayers() - 1); 538 } else { 539 layers[0] = previousDrawable; 540 } 541 layers[1] = getDrawableForBitmap(mContext.getResources(), cachedBitmap, request); 542 TransitionDrawable drawable = new TransitionDrawable(layers); 543 view.setImageDrawable(drawable); 544 drawable.startTransition(FADE_TRANSITION_DURATION); 545 } else { 546 view.setImageDrawable(getDrawableForBitmap(mContext.getResources(), cachedBitmap, request)); 547 } 548 549 // Put the bitmap in the LRU cache. But only do this for images that are small enough 550 // (we require that at least six of those can be cached at the same time) 551 if (cachedBitmap.getByteCount() < mBitmapCache.maxSize() / 6) { 552 mBitmapCache.put(request.getKey(), cachedBitmap); 553 } 554 555 // Soften the reference 556 holder.bitmap = null; 557 558 return holder.fresh; 559 } 560 561 /** 562 * Given a bitmap, returns a drawable that is configured to display the bitmap based on the 563 * specified request. 564 */ 565 private Drawable getDrawableForBitmap(Resources resources, Bitmap bitmap, Request request) { 566 if (request.mIsCircular) { 567 final RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(resources, bitmap); 568 drawable.setAntiAlias(true); 569 drawable.setCornerRadius(bitmap.getHeight() / 2); 570 return drawable; 571 } else { 572 return new BitmapDrawable(resources, bitmap); 573 } 574 } 575 576 public void clear() { 577 if (DEBUG) { 578 LogUtil.d("ContactPhotoManagerImpl.clear", "clear"); 579 } 580 mPendingRequests.clear(); 581 mBitmapHolderCache.evictAll(); 582 mBitmapCache.evictAll(); 583 } 584 585 @Override 586 public void pause() { 587 mPaused = true; 588 } 589 590 @Override 591 public void resume() { 592 mPaused = false; 593 if (DEBUG) { 594 dumpStats(); 595 } 596 if (!mPendingRequests.isEmpty()) { 597 requestLoading(); 598 } 599 } 600 601 /** 602 * Sends a message to this thread itself to start loading images. If the current view contains 603 * multiple image views, all of those image views will get a chance to request their respective 604 * photos before any of those requests are executed. This allows us to load images in bulk. 605 */ 606 private void requestLoading() { 607 if (!mLoadingRequested) { 608 mLoadingRequested = true; 609 mMainThreadHandler.sendEmptyMessage(MESSAGE_REQUEST_LOADING); 610 } 611 } 612 613 /** Processes requests on the main thread. */ 614 @Override 615 public boolean handleMessage(Message msg) { 616 switch (msg.what) { 617 case MESSAGE_REQUEST_LOADING: 618 { 619 mLoadingRequested = false; 620 if (!mPaused) { 621 ensureLoaderThread(); 622 mLoaderThread.requestLoading(); 623 } 624 return true; 625 } 626 627 case MESSAGE_PHOTOS_LOADED: 628 { 629 if (!mPaused) { 630 processLoadedImages(); 631 } 632 if (DEBUG) { 633 dumpStats(); 634 } 635 return true; 636 } 637 default: 638 return false; 639 } 640 } 641 642 public void ensureLoaderThread() { 643 if (mLoaderThread == null) { 644 mLoaderThread = new LoaderThread(mContext.getContentResolver()); 645 mLoaderThread.start(); 646 } 647 } 648 649 /** 650 * Goes over pending loading requests and displays loaded photos. If some of the photos still 651 * haven't been loaded, sends another request for image loading. 652 */ 653 private void processLoadedImages() { 654 final Iterator<Entry<ImageView, Request>> iterator = mPendingRequests.entrySet().iterator(); 655 while (iterator.hasNext()) { 656 final Entry<ImageView, Request> entry = iterator.next(); 657 // TODO: Temporarily disable contact photo fading in, until issues with 658 // RoundedBitmapDrawables overlapping the default image drawables are resolved. 659 final boolean loaded = loadCachedPhoto(entry.getKey(), entry.getValue(), false); 660 if (loaded) { 661 iterator.remove(); 662 } 663 } 664 665 softenCache(); 666 667 if (!mPendingRequests.isEmpty()) { 668 requestLoading(); 669 } 670 } 671 672 /** 673 * Removes strong references to loaded bitmaps to allow them to be garbage collected if needed. 674 * Some of the bitmaps will still be retained by {@link #mBitmapCache}. 675 */ 676 private void softenCache() { 677 for (BitmapHolder holder : mBitmapHolderCache.snapshot().values()) { 678 holder.bitmap = null; 679 } 680 } 681 682 /** Stores the supplied bitmap in cache. */ 683 private void cacheBitmap(Object key, byte[] bytes, boolean preloading, int requestedExtent) { 684 if (DEBUG) { 685 BitmapHolder prev = mBitmapHolderCache.get(key); 686 if (prev != null && prev.bytes != null) { 687 LogUtil.d( 688 "ContactPhotoManagerImpl.cacheBitmap", 689 "overwriting cache: key=" + key + (prev.fresh ? " FRESH" : " stale")); 690 if (prev.fresh) { 691 mFreshCacheOverwrite.incrementAndGet(); 692 } else { 693 mStaleCacheOverwrite.incrementAndGet(); 694 } 695 } 696 LogUtil.d( 697 "ContactPhotoManagerImpl.cacheBitmap", 698 "caching data: key=" + key + ", " + (bytes == null ? "<null>" : btk(bytes.length))); 699 } 700 BitmapHolder holder = 701 new BitmapHolder(bytes, bytes == null ? -1 : BitmapUtil.getSmallerExtentFromBytes(bytes)); 702 703 // Unless this image is being preloaded, decode it right away while 704 // we are still on the background thread. 705 if (!preloading) { 706 inflateBitmap(holder, requestedExtent); 707 } 708 709 if (bytes != null) { 710 mBitmapHolderCache.put(key, holder); 711 if (mBitmapHolderCache.get(key) != holder) { 712 LogUtil.w("ContactPhotoManagerImpl.cacheBitmap", "bitmap too big to fit in cache."); 713 mBitmapHolderCache.put(key, BITMAP_UNAVAILABLE); 714 } 715 } else { 716 mBitmapHolderCache.put(key, BITMAP_UNAVAILABLE); 717 } 718 719 mBitmapHolderCacheAllUnfresh = false; 720 } 721 722 /** 723 * Populates an array of photo IDs that need to be loaded. Also decodes bitmaps that we have 724 * already loaded 725 */ 726 private void obtainPhotoIdsAndUrisToLoad( 727 Set<Long> photoIds, Set<String> photoIdsAsStrings, Set<Request> uris) { 728 photoIds.clear(); 729 photoIdsAsStrings.clear(); 730 uris.clear(); 731 732 boolean jpegsDecoded = false; 733 734 /* 735 * Since the call is made from the loader thread, the map could be 736 * changing during the iteration. That's not really a problem: 737 * ConcurrentHashMap will allow those changes to happen without throwing 738 * exceptions. Since we may miss some requests in the situation of 739 * concurrent change, we will need to check the map again once loading 740 * is complete. 741 */ 742 Iterator<Request> iterator = mPendingRequests.values().iterator(); 743 while (iterator.hasNext()) { 744 Request request = iterator.next(); 745 final BitmapHolder holder = mBitmapHolderCache.get(request.getKey()); 746 if (holder == BITMAP_UNAVAILABLE) { 747 continue; 748 } 749 if (holder != null 750 && holder.bytes != null 751 && holder.fresh 752 && (holder.bitmapRef == null || holder.bitmapRef.get() == null)) { 753 // This was previously loaded but we don't currently have the inflated Bitmap 754 inflateBitmap(holder, request.getRequestedExtent()); 755 jpegsDecoded = true; 756 } else { 757 if (holder == null || !holder.fresh) { 758 if (request.isUriRequest()) { 759 uris.add(request); 760 } else { 761 photoIds.add(request.getId()); 762 photoIdsAsStrings.add(String.valueOf(request.mId)); 763 } 764 } 765 } 766 } 767 768 if (jpegsDecoded) { 769 mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); 770 } 771 } 772 773 /** Maintains the state of a particular photo. */ 774 private static class BitmapHolder { 775 776 final byte[] bytes; 777 final int originalSmallerExtent; 778 779 volatile boolean fresh; 780 Bitmap bitmap; 781 Reference<Bitmap> bitmapRef; 782 int decodedSampleSize; 783 784 public BitmapHolder(byte[] bytes, int originalSmallerExtent) { 785 this.bytes = bytes; 786 this.fresh = true; 787 this.originalSmallerExtent = originalSmallerExtent; 788 } 789 } 790 791 /** 792 * A holder for either a Uri or an id and a flag whether this was requested for the dark or light 793 * theme 794 */ 795 private static final class Request { 796 797 private final long mId; 798 private final Uri mUri; 799 private final boolean mDarkTheme; 800 private final int mRequestedExtent; 801 private final DefaultImageProvider mDefaultProvider; 802 /** Whether or not the contact photo is to be displayed as a circle */ 803 private final boolean mIsCircular; 804 805 private Request( 806 long id, 807 Uri uri, 808 int requestedExtent, 809 boolean darkTheme, 810 boolean isCircular, 811 DefaultImageProvider defaultProvider) { 812 mId = id; 813 mUri = uri; 814 mDarkTheme = darkTheme; 815 mIsCircular = isCircular; 816 mRequestedExtent = requestedExtent; 817 mDefaultProvider = defaultProvider; 818 } 819 820 public static Request createFromThumbnailId( 821 long id, boolean darkTheme, boolean isCircular, DefaultImageProvider defaultProvider) { 822 return new Request(id, null /* no URI */, -1, darkTheme, isCircular, defaultProvider); 823 } 824 825 public static Request createFromUri( 826 Uri uri, 827 int requestedExtent, 828 boolean darkTheme, 829 boolean isCircular, 830 DefaultImageProvider defaultProvider) { 831 return new Request( 832 0 /* no ID */, uri, requestedExtent, darkTheme, isCircular, defaultProvider); 833 } 834 835 public boolean isUriRequest() { 836 return mUri != null; 837 } 838 839 public Uri getUri() { 840 return mUri; 841 } 842 843 public long getId() { 844 return mId; 845 } 846 847 public int getRequestedExtent() { 848 return mRequestedExtent; 849 } 850 851 @Override 852 public int hashCode() { 853 final int prime = 31; 854 int result = 1; 855 result = prime * result + (int) (mId ^ (mId >>> 32)); 856 result = prime * result + mRequestedExtent; 857 result = prime * result + ((mUri == null) ? 0 : mUri.hashCode()); 858 return result; 859 } 860 861 @Override 862 public boolean equals(Object obj) { 863 if (this == obj) { 864 return true; 865 } 866 if (obj == null) { 867 return false; 868 } 869 if (getClass() != obj.getClass()) { 870 return false; 871 } 872 final Request that = (Request) obj; 873 if (mId != that.mId) { 874 return false; 875 } 876 if (mRequestedExtent != that.mRequestedExtent) { 877 return false; 878 } 879 if (!UriUtils.areEqual(mUri, that.mUri)) { 880 return false; 881 } 882 // Don't compare equality of mDarkTheme because it is only used in the default contact 883 // photo case. When the contact does have a photo, the contact photo is the same 884 // regardless of mDarkTheme, so we shouldn't need to put the photo request on the queue 885 // twice. 886 return true; 887 } 888 889 public Object getKey() { 890 return mUri == null ? mId : mUri; 891 } 892 893 /** 894 * Applies the default image to the current view. If the request is URI-based, looks for the 895 * contact type encoded fragment to determine if this is a request for a business photo, in 896 * which case we will load the default business photo. 897 * 898 * @param view The current image view to apply the image to. 899 * @param isCircular Whether the image is circular or not. 900 */ 901 public void applyDefaultImage(ImageView view, boolean isCircular) { 902 final DefaultImageRequest request; 903 904 if (isCircular) { 905 request = 906 ContactPhotoManager.isBusinessContactUri(mUri) 907 ? DefaultImageRequest.EMPTY_CIRCULAR_BUSINESS_IMAGE_REQUEST 908 : DefaultImageRequest.EMPTY_CIRCULAR_DEFAULT_IMAGE_REQUEST; 909 } else { 910 request = 911 ContactPhotoManager.isBusinessContactUri(mUri) 912 ? DefaultImageRequest.EMPTY_DEFAULT_BUSINESS_IMAGE_REQUEST 913 : DefaultImageRequest.EMPTY_DEFAULT_IMAGE_REQUEST; 914 } 915 mDefaultProvider.applyDefaultImage(view, mRequestedExtent, mDarkTheme, request); 916 } 917 } 918 919 /** The thread that performs loading of photos from the database. */ 920 private class LoaderThread extends HandlerThread implements Callback { 921 922 private static final int BUFFER_SIZE = 1024 * 16; 923 private static final int MESSAGE_PRELOAD_PHOTOS = 0; 924 private static final int MESSAGE_LOAD_PHOTOS = 1; 925 926 /** A pause between preload batches that yields to the UI thread. */ 927 private static final int PHOTO_PRELOAD_DELAY = 1000; 928 929 /** Number of photos to preload per batch. */ 930 private static final int PRELOAD_BATCH = 25; 931 932 /** 933 * Maximum number of photos to preload. If the cache size is 2Mb and the expected average size 934 * of a photo is 4kb, then this number should be 2Mb/4kb = 500. 935 */ 936 private static final int MAX_PHOTOS_TO_PRELOAD = 100; 937 938 private static final int PRELOAD_STATUS_NOT_STARTED = 0; 939 private static final int PRELOAD_STATUS_IN_PROGRESS = 1; 940 private static final int PRELOAD_STATUS_DONE = 2; 941 private final ContentResolver mResolver; 942 private final StringBuilder mStringBuilder = new StringBuilder(); 943 private final Set<Long> mPhotoIds = new HashSet<>(); 944 private final Set<String> mPhotoIdsAsStrings = new HashSet<>(); 945 private final Set<Request> mPhotoUris = new HashSet<>(); 946 private final List<Long> mPreloadPhotoIds = new ArrayList<>(); 947 private Handler mLoaderThreadHandler; 948 private byte[] mBuffer; 949 private int mPreloadStatus = PRELOAD_STATUS_NOT_STARTED; 950 951 public LoaderThread(ContentResolver resolver) { 952 super(LOADER_THREAD_NAME); 953 mResolver = resolver; 954 } 955 956 public void ensureHandler() { 957 if (mLoaderThreadHandler == null) { 958 mLoaderThreadHandler = new Handler(getLooper(), this); 959 } 960 } 961 962 /** 963 * Kicks off preloading of the next batch of photos on the background thread. Preloading will 964 * happen after a delay: we want to yield to the UI thread as much as possible. 965 * 966 * <p>If preloading is already complete, does nothing. 967 */ 968 public void requestPreloading() { 969 if (mPreloadStatus == PRELOAD_STATUS_DONE) { 970 return; 971 } 972 973 ensureHandler(); 974 if (mLoaderThreadHandler.hasMessages(MESSAGE_LOAD_PHOTOS)) { 975 return; 976 } 977 978 mLoaderThreadHandler.sendEmptyMessageDelayed(MESSAGE_PRELOAD_PHOTOS, PHOTO_PRELOAD_DELAY); 979 } 980 981 /** 982 * Sends a message to this thread to load requested photos. Cancels a preloading request, if 983 * any: we don't want preloading to impede loading of the photos we need to display now. 984 */ 985 public void requestLoading() { 986 ensureHandler(); 987 mLoaderThreadHandler.removeMessages(MESSAGE_PRELOAD_PHOTOS); 988 mLoaderThreadHandler.sendEmptyMessage(MESSAGE_LOAD_PHOTOS); 989 } 990 991 /** 992 * Receives the above message, loads photos and then sends a message to the main thread to 993 * process them. 994 */ 995 @Override 996 public boolean handleMessage(Message msg) { 997 switch (msg.what) { 998 case MESSAGE_PRELOAD_PHOTOS: 999 preloadPhotosInBackground(); 1000 break; 1001 case MESSAGE_LOAD_PHOTOS: 1002 loadPhotosInBackground(); 1003 break; 1004 } 1005 return true; 1006 } 1007 1008 /** 1009 * The first time it is called, figures out which photos need to be preloaded. Each subsequent 1010 * call preloads the next batch of photos and requests another cycle of preloading after a 1011 * delay. The whole process ends when we either run out of photos to preload or fill up cache. 1012 */ 1013 @WorkerThread 1014 private void preloadPhotosInBackground() { 1015 if (!PermissionsUtil.hasPermission(mContext, android.Manifest.permission.READ_CONTACTS)) { 1016 return; 1017 } 1018 1019 if (mPreloadStatus == PRELOAD_STATUS_DONE) { 1020 return; 1021 } 1022 1023 if (mPreloadStatus == PRELOAD_STATUS_NOT_STARTED) { 1024 queryPhotosForPreload(); 1025 if (mPreloadPhotoIds.isEmpty()) { 1026 mPreloadStatus = PRELOAD_STATUS_DONE; 1027 } else { 1028 mPreloadStatus = PRELOAD_STATUS_IN_PROGRESS; 1029 } 1030 requestPreloading(); 1031 return; 1032 } 1033 1034 if (mBitmapHolderCache.size() > mBitmapHolderCacheRedZoneBytes) { 1035 mPreloadStatus = PRELOAD_STATUS_DONE; 1036 return; 1037 } 1038 1039 mPhotoIds.clear(); 1040 mPhotoIdsAsStrings.clear(); 1041 1042 int count = 0; 1043 int preloadSize = mPreloadPhotoIds.size(); 1044 while (preloadSize > 0 && mPhotoIds.size() < PRELOAD_BATCH) { 1045 preloadSize--; 1046 count++; 1047 Long photoId = mPreloadPhotoIds.get(preloadSize); 1048 mPhotoIds.add(photoId); 1049 mPhotoIdsAsStrings.add(photoId.toString()); 1050 mPreloadPhotoIds.remove(preloadSize); 1051 } 1052 1053 loadThumbnails(true); 1054 1055 if (preloadSize == 0) { 1056 mPreloadStatus = PRELOAD_STATUS_DONE; 1057 } 1058 1059 LogUtil.v( 1060 "ContactPhotoManagerImpl.preloadPhotosInBackground", 1061 "preloaded " + count + " photos. cached bytes: " + mBitmapHolderCache.size()); 1062 1063 requestPreloading(); 1064 } 1065 1066 @WorkerThread 1067 private void queryPhotosForPreload() { 1068 Cursor cursor = null; 1069 try { 1070 Uri uri = 1071 Contacts.CONTENT_URI 1072 .buildUpon() 1073 .appendQueryParameter( 1074 ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(Directory.DEFAULT)) 1075 .appendQueryParameter( 1076 ContactsContract.LIMIT_PARAM_KEY, String.valueOf(MAX_PHOTOS_TO_PRELOAD)) 1077 .build(); 1078 cursor = 1079 mResolver.query( 1080 uri, 1081 new String[] {Contacts.PHOTO_ID}, 1082 Contacts.PHOTO_ID + " NOT NULL AND " + Contacts.PHOTO_ID + "!=0", 1083 null, 1084 Contacts.STARRED + " DESC, " + Contacts.LAST_TIME_CONTACTED + " DESC"); 1085 1086 if (cursor != null) { 1087 while (cursor.moveToNext()) { 1088 // Insert them in reverse order, because we will be taking 1089 // them from the end of the list for loading. 1090 mPreloadPhotoIds.add(0, cursor.getLong(0)); 1091 } 1092 } 1093 } finally { 1094 if (cursor != null) { 1095 cursor.close(); 1096 } 1097 } 1098 } 1099 1100 @WorkerThread 1101 private void loadPhotosInBackground() { 1102 if (!PermissionsUtil.hasPermission(mContext, android.Manifest.permission.READ_CONTACTS)) { 1103 return; 1104 } 1105 obtainPhotoIdsAndUrisToLoad(mPhotoIds, mPhotoIdsAsStrings, mPhotoUris); 1106 loadThumbnails(false); 1107 loadUriBasedPhotos(); 1108 requestPreloading(); 1109 } 1110 1111 /** Loads thumbnail photos with ids */ 1112 @WorkerThread 1113 private void loadThumbnails(boolean preloading) { 1114 if (mPhotoIds.isEmpty()) { 1115 return; 1116 } 1117 1118 // Remove loaded photos from the preload queue: we don't want 1119 // the preloading process to load them again. 1120 if (!preloading && mPreloadStatus == PRELOAD_STATUS_IN_PROGRESS) { 1121 for (Long id : mPhotoIds) { 1122 mPreloadPhotoIds.remove(id); 1123 } 1124 if (mPreloadPhotoIds.isEmpty()) { 1125 mPreloadStatus = PRELOAD_STATUS_DONE; 1126 } 1127 } 1128 1129 mStringBuilder.setLength(0); 1130 mStringBuilder.append(Photo._ID + " IN("); 1131 for (int i = 0; i < mPhotoIds.size(); i++) { 1132 if (i != 0) { 1133 mStringBuilder.append(','); 1134 } 1135 mStringBuilder.append('?'); 1136 } 1137 mStringBuilder.append(')'); 1138 1139 Cursor cursor = null; 1140 try { 1141 if (DEBUG) { 1142 LogUtil.d( 1143 "ContactPhotoManagerImpl.loadThumbnails", 1144 "loading " + TextUtils.join(",", mPhotoIdsAsStrings)); 1145 } 1146 cursor = 1147 mResolver.query( 1148 Data.CONTENT_URI, 1149 COLUMNS, 1150 mStringBuilder.toString(), 1151 mPhotoIdsAsStrings.toArray(EMPTY_STRING_ARRAY), 1152 null); 1153 1154 if (cursor != null) { 1155 while (cursor.moveToNext()) { 1156 Long id = cursor.getLong(0); 1157 byte[] bytes = cursor.getBlob(1); 1158 cacheBitmap(id, bytes, preloading, -1); 1159 mPhotoIds.remove(id); 1160 } 1161 } 1162 } finally { 1163 if (cursor != null) { 1164 cursor.close(); 1165 } 1166 } 1167 1168 // Remaining photos were not found in the contacts database (but might be in profile). 1169 for (Long id : mPhotoIds) { 1170 if (ContactsContract.isProfileId(id)) { 1171 Cursor profileCursor = null; 1172 try { 1173 profileCursor = 1174 mResolver.query( 1175 ContentUris.withAppendedId(Data.CONTENT_URI, id), COLUMNS, null, null, null); 1176 if (profileCursor != null && profileCursor.moveToFirst()) { 1177 cacheBitmap(profileCursor.getLong(0), profileCursor.getBlob(1), preloading, -1); 1178 } else { 1179 // Couldn't load a photo this way either. 1180 cacheBitmap(id, null, preloading, -1); 1181 } 1182 } finally { 1183 if (profileCursor != null) { 1184 profileCursor.close(); 1185 } 1186 } 1187 } else { 1188 // Not a profile photo and not found - mark the cache accordingly 1189 cacheBitmap(id, null, preloading, -1); 1190 } 1191 } 1192 1193 mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); 1194 } 1195 1196 /** 1197 * Loads photos referenced with Uris. Those can be remote thumbnails (from directory searches), 1198 * display photos etc 1199 */ 1200 @WorkerThread 1201 private void loadUriBasedPhotos() { 1202 for (Request uriRequest : mPhotoUris) { 1203 // Keep the original URI and use this to key into the cache. Failure to do so will 1204 // result in an image being continually reloaded into cache if the original URI 1205 // has a contact type encodedFragment (eg nearby places business photo URLs). 1206 Uri originalUri = uriRequest.getUri(); 1207 1208 // Strip off the "contact type" we added to the URI to ensure it was identifiable as 1209 // a business photo -- there is no need to pass this on to the server. 1210 Uri uri = ContactPhotoManager.removeContactType(originalUri); 1211 1212 if (mBuffer == null) { 1213 mBuffer = new byte[BUFFER_SIZE]; 1214 } 1215 try { 1216 if (DEBUG) { 1217 LogUtil.d("ContactPhotoManagerImpl.loadUriBasedPhotos", "loading " + uri); 1218 } 1219 final String scheme = uri.getScheme(); 1220 InputStream is = null; 1221 if (scheme.equals("http") || scheme.equals("https")) { 1222 TrafficStats.setThreadStatsTag(TrafficStatsTags.CONTACT_PHOTO_DOWNLOAD_TAG); 1223 final HttpURLConnection connection = 1224 (HttpURLConnection) new URL(uri.toString()).openConnection(); 1225 1226 // Include the user agent if it is specified. 1227 if (!TextUtils.isEmpty(mUserAgent)) { 1228 connection.setRequestProperty("User-Agent", mUserAgent); 1229 } 1230 try { 1231 is = connection.getInputStream(); 1232 } catch (IOException e) { 1233 connection.disconnect(); 1234 is = null; 1235 } 1236 TrafficStats.clearThreadStatsTag(); 1237 } else { 1238 is = mResolver.openInputStream(uri); 1239 } 1240 if (is != null) { 1241 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 1242 try { 1243 int size; 1244 while ((size = is.read(mBuffer)) != -1) { 1245 baos.write(mBuffer, 0, size); 1246 } 1247 } finally { 1248 is.close(); 1249 } 1250 cacheBitmap(originalUri, baos.toByteArray(), false, uriRequest.getRequestedExtent()); 1251 mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); 1252 } else { 1253 LogUtil.v("ContactPhotoManagerImpl.loadUriBasedPhotos", "cannot load photo " + uri); 1254 cacheBitmap(originalUri, null, false, uriRequest.getRequestedExtent()); 1255 } 1256 } catch (final Exception | OutOfMemoryError ex) { 1257 LogUtil.v("ContactPhotoManagerImpl.loadUriBasedPhotos", "cannot load photo " + uri, ex); 1258 cacheBitmap(originalUri, null, false, uriRequest.getRequestedExtent()); 1259 } 1260 } 1261 } 1262 } 1263} 1264