summaryrefslogtreecommitdiff
path: root/packages/SettingsLib/src/com/android/settingslib/RestrictedSwitchPreference.java
blob: af06d7304160b7f190d0d29475310d78aeef1abe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.settingslib;

import static android.app.admin.DevicePolicyResources.Strings.Settings.DISABLED_BY_ADMIN_SWITCH_SUMMARY;
import static android.app.admin.DevicePolicyResources.Strings.Settings.ENABLED_BY_ADMIN_SWITCH_SUMMARY;

import static com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;

import android.annotation.NonNull;
import android.app.AppOpsManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Process;
import android.os.UserHandle;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.VisibleForTesting;
import androidx.core.content.res.TypedArrayUtils;
import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceViewHolder;
import androidx.preference.SwitchPreference;

import com.android.settingslib.utils.BuildCompatUtils;

/**
 * Version of SwitchPreference that can be disabled by a device admin
 * using a user restriction.
 */
public class RestrictedSwitchPreference extends SwitchPreference {
    RestrictedPreferenceHelper mHelper;
    AppOpsManager mAppOpsManager;
    boolean mUseAdditionalSummary = false;
    CharSequence mRestrictedSwitchSummary;
    private int mIconSize;

    public RestrictedSwitchPreference(Context context, AttributeSet attrs,
            int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mHelper = new RestrictedPreferenceHelper(context, this, attrs);
        if (attrs != null) {
            final TypedArray attributes = context.obtainStyledAttributes(attrs,
                    R.styleable.RestrictedSwitchPreference);
            final TypedValue useAdditionalSummary = attributes.peekValue(
                    R.styleable.RestrictedSwitchPreference_useAdditionalSummary);
            if (useAdditionalSummary != null) {
                mUseAdditionalSummary =
                        (useAdditionalSummary.type == TypedValue.TYPE_INT_BOOLEAN
                                && useAdditionalSummary.data != 0);
            }

            final TypedValue restrictedSwitchSummary = attributes.peekValue(
                    R.styleable.RestrictedSwitchPreference_restrictedSwitchSummary);
            attributes.recycle();
            if (restrictedSwitchSummary != null
                    && restrictedSwitchSummary.type == TypedValue.TYPE_STRING) {
                if (restrictedSwitchSummary.resourceId != 0) {
                    mRestrictedSwitchSummary =
                            context.getText(restrictedSwitchSummary.resourceId);
                } else {
                    mRestrictedSwitchSummary = restrictedSwitchSummary.string;
                }
            }
        }
        if (mUseAdditionalSummary) {
            setLayoutResource(R.layout.restricted_switch_preference);
            useAdminDisabledSummary(false);
        }
    }

    public RestrictedSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RestrictedSwitchPreference(Context context, AttributeSet attrs) {
        this(context, attrs, TypedArrayUtils.getAttr(context, R.attr.switchPreferenceStyle,
                android.R.attr.switchPreferenceStyle));
    }

    public RestrictedSwitchPreference(Context context) {
        this(context, null);
    }

    @VisibleForTesting
    public void setAppOps(AppOpsManager appOps) {
        mAppOpsManager = appOps;
    }

    public void setIconSize(int iconSize) {
        mIconSize = iconSize;
    }

    @Override
    public void onBindViewHolder(PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);
        final View switchView = holder.findViewById(android.R.id.switch_widget);
        if (switchView != null) {
            final View rootView = switchView.getRootView();
            rootView.setFilterTouchesWhenObscured(true);
        }

        mHelper.onBindViewHolder(holder);

        CharSequence switchSummary;
        if (mRestrictedSwitchSummary == null) {
            switchSummary = isChecked()
                    ? getUpdatableEnterpriseString(
                            getContext(), ENABLED_BY_ADMIN_SWITCH_SUMMARY,
                            R.string.enabled_by_admin)
                    : getUpdatableEnterpriseString(
                            getContext(), DISABLED_BY_ADMIN_SWITCH_SUMMARY,
                            R.string.disabled_by_admin);
        } else {
            switchSummary = mRestrictedSwitchSummary;
        }

        final ImageView icon = holder.itemView.findViewById(android.R.id.icon);

        if (mIconSize > 0) {
            icon.setLayoutParams(new LinearLayout.LayoutParams(mIconSize, mIconSize));
        }

        if (mUseAdditionalSummary) {
            final TextView additionalSummaryView = (TextView) holder.findViewById(
                    R.id.additional_summary);
            if (additionalSummaryView != null) {
                if (isDisabledByAdmin()) {
                    additionalSummaryView.setText(switchSummary);
                    additionalSummaryView.setVisibility(View.VISIBLE);
                } else {
                    additionalSummaryView.setVisibility(View.GONE);
                }
            }
        } else {
            final TextView summaryView = (TextView) holder.findViewById(android.R.id.summary);
            if (summaryView != null) {
                if (isDisabledByAdmin()) {
                    summaryView.setText(switchSummary);
                    summaryView.setVisibility(View.VISIBLE);
                }
                // No need to change the visibility to GONE in the else case here since Preference
                // class would have already changed it if there is no summary to display.
            }
        }
    }

    private static String getUpdatableEnterpriseString(
            Context context, String updatableStringId, int resId) {
        if (!BuildCompatUtils.isAtLeastT()) {
            return context.getString(resId);
        }
        return context.getSystemService(DevicePolicyManager.class).getResources().getString(
                updatableStringId,
                () -> context.getString(resId));
    }

    @Override
    public void performClick() {
        if (!mHelper.performClick()) {
            super.performClick();
        }
    }

    public void useAdminDisabledSummary(boolean useSummary) {
        mHelper.useAdminDisabledSummary(useSummary);
    }

    @Override
    protected void onAttachedToHierarchy(PreferenceManager preferenceManager) {
        mHelper.onAttachedToHierarchy();
        super.onAttachedToHierarchy(preferenceManager);
    }

    public void checkRestrictionAndSetDisabled(String userRestriction) {
        mHelper.checkRestrictionAndSetDisabled(userRestriction, UserHandle.myUserId());
    }

    public void checkRestrictionAndSetDisabled(String userRestriction, int userId) {
        mHelper.checkRestrictionAndSetDisabled(userRestriction, userId);
    }

    @Override
    public void setEnabled(boolean enabled) {
        boolean changed = false;
        if (enabled && isDisabledByAdmin()) {
            mHelper.setDisabledByAdmin(null);
            changed = true;
        }
        if (enabled && isDisabledByAppOps()) {
            mHelper.setDisabledByAppOps(false);
            changed = true;
        }
        if (!changed) {
            super.setEnabled(enabled);
        }
    }

    public void setDisabledByAdmin(EnforcedAdmin admin) {
        if (mHelper.setDisabledByAdmin(admin)) {
            notifyChanged();
        }
    }

    public boolean isDisabledByAdmin() {
        return mHelper.isDisabledByAdmin();
    }

    private void setDisabledByAppOps(boolean disabled) {
        if (mHelper.setDisabledByAppOps(disabled)) {
            notifyChanged();
        }
    }

    public boolean isDisabledByAppOps() {
        return mHelper.isDisabledByAppOps();
    }

    public int getUid() {
        return mHelper != null ? mHelper.uid : Process.INVALID_UID;
    }

    public String getPackageName() {
        return mHelper != null ? mHelper.packageName : null;
    }

    /** Updates enabled state based on associated package. */
    public void updateState(
            @NonNull String packageName, int uid, boolean isEnableAllowed, boolean isEnabled) {
        mHelper.updatePackageDetails(packageName, uid);
        if (mAppOpsManager == null) {
            mAppOpsManager = getContext().getSystemService(AppOpsManager.class);
        }
        final int mode = mAppOpsManager.noteOpNoThrow(
                AppOpsManager.OP_ACCESS_RESTRICTED_SETTINGS,
                uid, packageName);
        final boolean ecmEnabled = getContext().getResources().getBoolean(
                com.android.internal.R.bool.config_enhancedConfirmationModeEnabled);
        final boolean appOpsAllowed = !ecmEnabled || mode == AppOpsManager.MODE_ALLOWED;
        if (!isEnableAllowed && !isEnabled) {
            setEnabled(false);
        } else if (isEnabled) {
            setEnabled(true);
        } else if (appOpsAllowed && isDisabledByAppOps()) {
            setEnabled(true);
        } else if (!appOpsAllowed){
            setDisabledByAppOps(true);
        }
    }
}