1 /*
2  * Copyright (C) 2024 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.settings
18 
19 import android.content.Context
20 import android.os.UserHandle
21 import android.os.UserManager
22 import androidx.annotation.CallSuper
23 import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin
24 import com.android.settingslib.RestrictedLockUtilsInternal
25 import com.android.settingslib.metadata.PreferenceRestrictionProvider
26 
27 /** Mixin to support restriction. */
28 interface PreferenceRestrictionMixin : PreferenceRestrictionProvider {
29 
30     /**
31      * Keys for restriction.
32      *
33      * Preference is restricted when **ANY** key in the list is restricted.
34      */
35     val restrictionKeys: Array<String>
36 
37     val useAdminDisabledSummary: Boolean
38         get() = false
39 
isEnablednull40     @CallSuper fun isEnabled(context: Context) = !context.hasBaseUserRestriction(restrictionKeys)
41 
42     override fun isRestricted(context: Context) =
43         context.getRestrictionEnforcedAdmin(restrictionKeys) != null
44 }
45 
46 /** Returns the admin that has enforced restriction on given keys. */
47 fun Context.getRestrictionEnforcedAdmin(restrictionKeys: Array<String>): EnforcedAdmin? {
48     val userId = UserHandle.myUserId()
49     return restrictionKeys.firstNotNullOfOrNull {
50         RestrictedLockUtilsInternal.checkIfRestrictionEnforced(this, it, userId)
51     }
52 }
53 
54 /** Returns if there is **any** base user restriction on given keys. */
Contextnull55 fun Context.hasBaseUserRestriction(restrictionKeys: Array<String>): Boolean {
56     val userManager = getSystemService(UserManager::class.java) ?: return false
57     val userHandle = UserHandle.of(UserHandle.myUserId())
58     return restrictionKeys.any { userManager.hasBaseUserRestriction(it, userHandle) }
59 }
60