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 
17 @file:OptIn(InternalNoteTaskApi::class)
18 
19 package com.android.systemui.notetask
20 
21 import android.app.role.RoleManager
22 import android.app.role.RoleManager.ROLE_NOTES
23 import android.content.pm.PackageManager
24 import android.content.pm.PackageManager.ApplicationInfoFlags
25 import android.os.UserHandle
26 import android.util.Log
27 import com.android.systemui.notetask.NoteTaskRoleManagerExt.getDefaultRoleHolderAsUser
28 import javax.inject.Inject
29 
30 class NoteTaskInfoResolver
31 @Inject
32 constructor(
33     private val roleManager: RoleManager,
34     private val packageManager: PackageManager,
35 ) {
36 
resolveInfonull37     fun resolveInfo(
38         entryPoint: NoteTaskEntryPoint? = null,
39         isKeyguardLocked: Boolean = false,
40         user: UserHandle,
41     ): NoteTaskInfo? {
42         val packageName = roleManager.getDefaultRoleHolderAsUser(ROLE_NOTES, user)
43 
44         if (packageName.isNullOrEmpty()) return null
45 
46         return NoteTaskInfo(
47             packageName = packageName,
48             uid = packageManager.getUidOf(packageName, user),
49             user = user,
50             entryPoint = entryPoint,
51             isKeyguardLocked = isKeyguardLocked,
52         )
53     }
54 
55     companion object {
56         private val TAG = NoteTaskInfoResolver::class.simpleName.orEmpty()
57 
58         private val EMPTY_APPLICATION_INFO_FLAGS = ApplicationInfoFlags.of(0)!!
59 
60         /**
61          * Returns the kernel user-ID of [packageName] for a [user]. Returns zero if the app cannot
62          * be found.
63          */
PackageManagernull64         private fun PackageManager.getUidOf(packageName: String, user: UserHandle): Int =
65             try {
66                 getApplicationInfoAsUser(packageName, EMPTY_APPLICATION_INFO_FLAGS, user).uid
67             } catch (e: PackageManager.NameNotFoundException) {
68                 Log.e(TAG, "Couldn't find notes app UID", e)
69                 0
70             }
71     }
72 }
73