1 /* <lambda>null2 * Copyright (C) 2022 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 17 package com.android.intentresolver 18 19 import android.content.Context 20 import android.graphics.Bitmap 21 import android.net.Uri 22 import android.util.Size 23 import androidx.annotation.GuardedBy 24 import androidx.annotation.VisibleForTesting 25 import androidx.collection.LruCache 26 import androidx.lifecycle.Lifecycle 27 import androidx.lifecycle.coroutineScope 28 import kotlinx.coroutines.CompletableDeferred 29 import kotlinx.coroutines.CoroutineDispatcher 30 import kotlinx.coroutines.Dispatchers 31 import kotlinx.coroutines.isActive 32 import kotlinx.coroutines.launch 33 import java.util.function.Consumer 34 35 @VisibleForTesting 36 class ImagePreviewImageLoader @JvmOverloads constructor( 37 private val context: Context, 38 private val lifecycle: Lifecycle, 39 cacheSize: Int, 40 private val dispatcher: CoroutineDispatcher = Dispatchers.IO 41 ) : ImageLoader { 42 43 private val thumbnailSize: Size = 44 context.resources.getDimensionPixelSize(R.dimen.chooser_preview_image_max_dimen).let { 45 Size(it, it) 46 } 47 48 @GuardedBy("self") 49 private val cache = LruCache<Uri, CompletableDeferred<Bitmap?>>(cacheSize) 50 51 override suspend fun invoke(uri: Uri): Bitmap? = loadImageAsync(uri) 52 53 override fun loadImage(uri: Uri, callback: Consumer<Bitmap?>) { 54 lifecycle.coroutineScope.launch { 55 val image = loadImageAsync(uri) 56 if (isActive) { 57 callback.accept(image) 58 } 59 } 60 } 61 62 override fun prePopulate(uris: List<Uri>) { 63 uris.asSequence().take(cache.maxSize()).forEach { uri -> 64 lifecycle.coroutineScope.launch { 65 loadImageAsync(uri) 66 } 67 } 68 } 69 70 private suspend fun loadImageAsync(uri: Uri): Bitmap? { 71 return synchronized(cache) { 72 cache.get(uri) ?: CompletableDeferred<Bitmap?>().also { result -> 73 cache.put(uri, result) 74 lifecycle.coroutineScope.launch(dispatcher) { 75 result.loadBitmap(uri) 76 } 77 } 78 }.await() 79 } 80 81 private fun CompletableDeferred<Bitmap?>.loadBitmap(uri: Uri) { 82 val bitmap = runCatching { 83 context.contentResolver.loadThumbnail(uri, thumbnailSize, null) 84 }.getOrNull() 85 complete(bitmap) 86 } 87 } 88