1 /* 2 * Copyright (C) 2023 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 package com.android.systemui.clipboardoverlay 17 18 import android.content.Context 19 import android.graphics.Bitmap 20 import android.net.Uri 21 import android.util.Log 22 import android.util.Size 23 import com.android.systemui.res.R 24 import com.android.systemui.dagger.qualifiers.Application 25 import com.android.systemui.dagger.qualifiers.Background 26 import java.io.IOException 27 import java.util.function.Consumer 28 import javax.inject.Inject 29 import kotlinx.coroutines.CoroutineDispatcher 30 import kotlinx.coroutines.CoroutineScope 31 import kotlinx.coroutines.launch 32 import kotlinx.coroutines.withContext 33 import kotlinx.coroutines.withTimeoutOrNull 34 35 class ClipboardImageLoader 36 @Inject 37 constructor( 38 private val context: Context, 39 @Background private val bgDispatcher: CoroutineDispatcher, 40 @Application private val mainScope: CoroutineScope 41 ) { 42 private val TAG: String = "ClipboardImageLoader" 43 loadnull44 suspend fun load(uri: Uri, timeoutMs: Long = 300) = 45 withTimeoutOrNull(timeoutMs) { 46 withContext(bgDispatcher) { 47 try { 48 val size = context.resources.getDimensionPixelSize(R.dimen.overlay_x_scale) 49 context.contentResolver.loadThumbnail(uri, Size(size, size * 4), null) 50 } catch (e: IOException) { 51 Log.e(TAG, "Thumbnail loading failed!", e) 52 null 53 } 54 } 55 } 56 loadAsyncnull57 fun loadAsync(uri: Uri, callback: Consumer<Bitmap?>) { 58 mainScope.launch { callback.accept(load(uri)) } 59 } 60 } 61