1 /*
2  * 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.systemui.mediaprojection.appselector.data
18 
19 import android.content.ComponentName
20 import android.content.Context
21 import android.content.pm.PackageManager
22 import android.graphics.drawable.Drawable
23 import android.os.UserHandle
24 import com.android.launcher3.icons.BaseIconFactory.IconOptions
25 import com.android.launcher3.icons.IconFactory
26 import com.android.systemui.dagger.qualifiers.Background
27 import com.android.systemui.shared.system.PackageManagerWrapper
28 import javax.inject.Inject
29 import javax.inject.Provider
30 import kotlinx.coroutines.CoroutineDispatcher
31 import kotlinx.coroutines.withContext
32 
33 interface AppIconLoader {
34     suspend fun loadIcon(userId: Int, component: ComponentName): Drawable?
35 }
36 
37 class IconLoaderLibAppIconLoader
38 @Inject
39 constructor(
40     @Background private val backgroundDispatcher: CoroutineDispatcher,
41     private val context: Context,
42     // Use wrapper to access hidden API that allows to get ActivityInfo for any user id
43     private val packageManagerWrapper: PackageManagerWrapper,
44     private val packageManager: PackageManager,
45     private val iconFactoryProvider: Provider<IconFactory>
46 ) : AppIconLoader {
47 
48     override suspend fun loadIcon(userId: Int, component: ComponentName): Drawable? =
49         withContext(backgroundDispatcher) {
50             iconFactoryProvider.get().use<IconFactory, Drawable?> { iconFactory ->
51                 val activityInfo =
52                     packageManagerWrapper.getActivityInfo(component, userId)
53                         ?: return@withContext null
54                 val icon = activityInfo.loadIcon(packageManager) ?: return@withContext null
55                 val userHandler = UserHandle.of(userId)
56                 val options = IconOptions().apply { setUser(userHandler) }
57                 val badgedIcon = iconFactory.createBadgedIconBitmap(icon, options)
58                 badgedIcon.newIcon(context)
59             }
60         }
61 }
62