OSDN Git Service

Disable changing lock when device is not provisioned.
[android-x86/packages-apps-Settings.git] / src / com / android / settings / MasterClear.java
1 /*
2  * Copyright (C) 2008 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 static com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
20
21 import android.accounts.Account;
22 import android.accounts.AccountManager;
23 import android.accounts.AuthenticatorDescription;
24 import android.annotation.Nullable;
25 import android.app.Activity;
26 import android.content.ComponentName;
27 import android.content.ContentResolver;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.content.pm.PackageManager;
31 import android.content.pm.ResolveInfo;
32 import android.content.pm.UserInfo;
33 import android.content.res.Resources;
34 import android.graphics.drawable.Drawable;
35 import android.os.Bundle;
36 import android.os.Environment;
37 import android.os.SystemProperties;
38 import android.os.UserHandle;
39 import android.os.UserManager;
40 import android.provider.Settings;
41 import android.support.annotation.VisibleForTesting;
42 import android.telephony.euicc.EuiccManager;
43 import android.text.TextUtils;
44 import android.util.Log;
45 import android.view.LayoutInflater;
46 import android.view.View;
47 import android.view.View.OnScrollChangeListener;
48 import android.view.ViewGroup;
49 import android.view.ViewTreeObserver.OnGlobalLayoutListener;
50 import android.widget.Button;
51 import android.widget.CheckBox;
52 import android.widget.ImageView;
53 import android.widget.LinearLayout;
54 import android.widget.ScrollView;
55 import android.widget.TextView;
56
57 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
58 import com.android.settings.core.InstrumentedFragment;
59 import com.android.settings.core.SubSettingLauncher;
60 import com.android.settings.enterprise.ActionDisabledByAdminDialogHelper;
61 import com.android.settings.password.ChooseLockSettingsHelper;
62 import com.android.settings.password.ConfirmLockPattern;
63 import com.android.settingslib.RestrictedLockUtils;
64
65 import java.util.List;
66
67 /**
68  * Confirm and execute a reset of the device to a clean "just out of the box"
69  * state.  Multiple confirmations are required: first, a general "are you sure
70  * you want to do this?" prompt, followed by a keyguard pattern trace if the user
71  * has defined one, followed by a final strongly-worded "THIS WILL ERASE EVERYTHING
72  * ON THE PHONE" prompt.  If at any time the phone is allowed to go to sleep, is
73  * locked, et cetera, then the confirmation sequence is abandoned.
74  *
75  * This is the initial screen.
76  */
77 public class MasterClear extends InstrumentedFragment implements OnGlobalLayoutListener {
78     private static final String TAG = "MasterClear";
79
80     @VisibleForTesting static final int KEYGUARD_REQUEST = 55;
81     @VisibleForTesting static final int CREDENTIAL_CONFIRM_REQUEST = 56;
82
83     private static final String KEY_SHOW_ESIM_RESET_CHECKBOX
84             = "masterclear.allow_retain_esim_profiles_after_fdr";
85
86     static final String ERASE_EXTERNAL_EXTRA = "erase_sd";
87     static final String ERASE_ESIMS_EXTRA = "erase_esim";
88
89     private View mContentView;
90     @VisibleForTesting Button mInitiateButton;
91     private View mExternalStorageContainer;
92     @VisibleForTesting CheckBox mExternalStorage;
93     private View mEsimStorageContainer;
94     @VisibleForTesting CheckBox mEsimStorage;
95     @VisibleForTesting ScrollView mScrollView;
96
97     @Override
98     public void onGlobalLayout() {
99         mInitiateButton.setEnabled(hasReachedBottom(mScrollView));
100     }
101
102     @Override
103     public void onCreate(@Nullable Bundle savedInstanceState) {
104         super.onCreate(savedInstanceState);
105         getActivity().setTitle(R.string.master_clear_short_title);
106     }
107
108     /**
109      * Keyguard validation is run using the standard {@link ConfirmLockPattern}
110      * component as a subactivity
111      * @param request the request code to be returned once confirmation finishes
112      * @return true if confirmation launched
113      */
114     private boolean runKeyguardConfirmation(int request) {
115         Resources res = getActivity().getResources();
116         return new ChooseLockSettingsHelper(getActivity(), this).launchConfirmationActivity(
117                 request, res.getText(R.string.master_clear_short_title));
118     }
119
120     @VisibleForTesting
121     boolean isValidRequestCode(int requestCode) {
122         return !((requestCode != KEYGUARD_REQUEST) && (requestCode != CREDENTIAL_CONFIRM_REQUEST));
123     }
124
125     @Override
126     public void onActivityResult(int requestCode, int resultCode, Intent data) {
127         super.onActivityResult(requestCode, resultCode, data);
128         onActivityResultInternal(requestCode, resultCode, data);
129     }
130
131     /*
132      * Internal method that allows easy testing without dealing with super references.
133      */
134     @VisibleForTesting
135     void onActivityResultInternal(int requestCode, int resultCode, Intent data) {
136         if (!isValidRequestCode(requestCode)) {
137             return;
138         }
139
140         if (resultCode != Activity.RESULT_OK) {
141             establishInitialState();
142             return;
143         }
144
145         Intent intent = null;
146         // If returning from a Keyguard request, try to show an account confirmation request if
147         // applciable.
148         if (CREDENTIAL_CONFIRM_REQUEST != requestCode
149                 && (intent = getAccountConfirmationIntent()) != null) {
150             showAccountCredentialConfirmation(intent);
151         } else {
152             showFinalConfirmation();
153         }
154     }
155
156     @VisibleForTesting
157     void showFinalConfirmation() {
158         final Bundle args = new Bundle();
159         args.putBoolean(ERASE_EXTERNAL_EXTRA, mExternalStorage.isChecked());
160         args.putBoolean(ERASE_ESIMS_EXTRA, mEsimStorage.isChecked());
161         new SubSettingLauncher(getContext())
162                 .setDestination(MasterClearConfirm.class.getName())
163                 .setArguments(args)
164                 .setTitle(R.string.master_clear_confirm_title)
165                 .setSourceMetricsCategory(getMetricsCategory())
166                 .launch();
167     }
168
169     @VisibleForTesting
170     void showAccountCredentialConfirmation(Intent intent) {
171         startActivityForResult(intent, CREDENTIAL_CONFIRM_REQUEST);
172     }
173
174     @VisibleForTesting
175     Intent getAccountConfirmationIntent() {
176         final Context context = getActivity();
177         final String accountType = context.getString(R.string.account_type);
178         final String packageName = context.getString(R.string.account_confirmation_package);
179         final String className = context.getString(R.string.account_confirmation_class);
180         if (TextUtils.isEmpty(accountType)
181                 || TextUtils.isEmpty(packageName)
182                 || TextUtils.isEmpty(className)) {
183             Log.i(TAG, "Resources not set for account confirmation.");
184             return null;
185         }
186         final AccountManager am = AccountManager.get(context);
187         Account[] accounts = am.getAccountsByType(accountType);
188         if (accounts != null && accounts.length > 0) {
189             final Intent requestAccountConfirmation = new Intent()
190                 .setPackage(packageName)
191                 .setComponent(new ComponentName(packageName, className));
192             // Check to make sure that the intent is supported.
193             final PackageManager pm = context.getPackageManager();
194             final ResolveInfo resolution = pm.resolveActivity(requestAccountConfirmation, 0);
195             if (resolution != null
196                     && resolution.activityInfo != null
197                     && packageName.equals(resolution.activityInfo.packageName)) {
198                 // Note that we need to check the packagename to make sure that an Activity resolver
199                 // wasn't returned.
200                 return requestAccountConfirmation;
201             } else {
202                 Log.i(TAG, "Unable to resolve Activity: " + packageName + "/" + className);
203             }
204         } else {
205             Log.d(TAG, "No " + accountType + " accounts installed!");
206         }
207         return null;
208     }
209
210     /**
211      * If the user clicks to begin the reset sequence, we next require a
212      * keyguard confirmation if the user has currently enabled one.  If there
213      * is no keyguard available, we simply go to the final confirmation prompt.
214      *
215      * If the user is in demo mode, route to the demo mode app for confirmation.
216      */
217     @VisibleForTesting
218     protected final Button.OnClickListener mInitiateListener = new Button.OnClickListener() {
219
220         public void onClick(View view) {
221             final Context context = view.getContext();
222             if (Utils.isDemoUser(context)) {
223                 final ComponentName componentName = Utils.getDeviceOwnerComponent(context);
224                 if (componentName != null) {
225                     final Intent requestFactoryReset = new Intent()
226                             .setPackage(componentName.getPackageName())
227                             .setAction(Intent.ACTION_FACTORY_RESET);
228                     context.startActivity(requestFactoryReset);
229                 }
230                 return;
231             }
232
233             if (runKeyguardConfirmation(KEYGUARD_REQUEST)) {
234                 return;
235             }
236
237             Intent intent = getAccountConfirmationIntent();
238             if (intent != null) {
239                 showAccountCredentialConfirmation(intent);
240             } else {
241                 showFinalConfirmation();
242             }
243         }
244     };
245
246     /**
247      * In its initial state, the activity presents a button for the user to
248      * click in order to initiate a confirmation sequence.  This method is
249      * called from various other points in the code to reset the activity to
250      * this base state.
251      *
252      * <p>Reinflating views from resources is expensive and prevents us from
253      * caching widget pointers, so we use a single-inflate pattern:  we lazy-
254      * inflate each view, caching all of the widget pointers we'll need at the
255      * time, then simply reuse the inflated views directly whenever we need
256      * to change contents.
257      */
258     @VisibleForTesting
259     void establishInitialState() {
260         mInitiateButton = mContentView.findViewById(R.id.initiate_master_clear);
261         mInitiateButton.setOnClickListener(mInitiateListener);
262         mExternalStorageContainer = mContentView.findViewById(R.id.erase_external_container);
263         mExternalStorage = mContentView.findViewById(R.id.erase_external);
264         mEsimStorageContainer = mContentView.findViewById(R.id.erase_esim_container);
265         mEsimStorage = mContentView.findViewById(R.id.erase_esim);
266         if (mScrollView != null) {
267             mScrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
268         }
269         mScrollView = mContentView.findViewById(R.id.master_clear_scrollview);
270
271         /*
272          * If the external storage is emulated, it will be erased with a factory
273          * reset at any rate. There is no need to have a separate option until
274          * we have a factory reset that only erases some directories and not
275          * others. Likewise, if it's non-removable storage, it could potentially have been
276          * encrypted, and will also need to be wiped.
277          */
278         boolean isExtStorageEmulated = Environment.isExternalStorageEmulated();
279         if (isExtStorageEmulated
280                 || (!Environment.isExternalStorageRemovable() && isExtStorageEncrypted())) {
281             mExternalStorageContainer.setVisibility(View.GONE);
282
283             final View externalOption = mContentView.findViewById(R.id.erase_external_option_text);
284             externalOption.setVisibility(View.GONE);
285
286             final View externalAlsoErased = mContentView.findViewById(R.id.also_erases_external);
287             externalAlsoErased.setVisibility(View.VISIBLE);
288
289             // If it's not emulated, it is on a separate partition but it means we're doing
290             // a force wipe due to encryption.
291             mExternalStorage.setChecked(!isExtStorageEmulated);
292         } else {
293             mExternalStorageContainer.setOnClickListener(new View.OnClickListener() {
294
295                 @Override
296                 public void onClick(View v) {
297                     mExternalStorage.toggle();
298                 }
299             });
300         }
301
302         if (showWipeEuicc()) {
303             if (showWipeEuiccCheckbox()) {
304                 TextView title = mContentView.findViewById(R.id.erase_esim_title);
305                 title.setText(R.string.erase_esim_storage);
306                 mEsimStorageContainer.setVisibility(View.VISIBLE);
307                 mEsimStorageContainer.setOnClickListener(new View.OnClickListener() {
308                     @Override
309                     public void onClick(View v) {
310                         mEsimStorage.toggle();
311                     }
312                 });
313             } else {
314                 final View esimAlsoErased = mContentView.findViewById(R.id.also_erases_esim);
315                 esimAlsoErased.setVisibility(View.VISIBLE);
316
317                 final View noCancelMobilePlan = mContentView.findViewById(
318                         R.id.no_cancel_mobile_plan);
319                 noCancelMobilePlan.setVisibility(View.VISIBLE);
320                 mEsimStorage.setChecked(true /* checked */);
321             }
322         }
323
324         final UserManager um = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
325         loadAccountList(um);
326         final StringBuffer contentDescription = new StringBuffer();
327         final View masterClearContainer = mContentView.findViewById(R.id.master_clear_container);
328         getContentDescription(masterClearContainer, contentDescription);
329         masterClearContainer.setContentDescription(contentDescription);
330
331         // Set the status of initiateButton based on scrollview
332         mScrollView.setOnScrollChangeListener(new OnScrollChangeListener() {
333             @Override
334             public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX,
335                 int oldScrollY) {
336                 if (v instanceof ScrollView && hasReachedBottom((ScrollView) v)) {
337                     mInitiateButton.setEnabled(true);
338                     mScrollView.setOnScrollChangeListener(null);
339                 }
340             }
341         });
342
343         // Set the initial state of the initiateButton
344         mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(this);
345     }
346
347     /**
348      * Whether to show strings indicating that the eUICC will be wiped.
349      *
350      * <p>We show the strings on any device which supports eUICC as long as the eUICC was ever
351      * provisioned (that is, at least one profile was ever downloaded onto it).
352      */
353     @VisibleForTesting
354     boolean showWipeEuicc() {
355         Context context = getContext();
356         if (!isEuiccEnabled(context)) {
357             return false;
358         }
359         ContentResolver cr = context.getContentResolver();
360         return Settings.Global.getInt(cr, Settings.Global.EUICC_PROVISIONED, 0) != 0
361                 ||  Settings.Global.getInt(
362                         cr, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
363     }
364
365     @VisibleForTesting
366     boolean showWipeEuiccCheckbox() {
367         return SystemProperties
368                 .getBoolean(KEY_SHOW_ESIM_RESET_CHECKBOX, false /* def */);
369     }
370
371     @VisibleForTesting
372     protected boolean isEuiccEnabled(Context context) {
373         EuiccManager euiccManager = (EuiccManager) context.getSystemService(Context.EUICC_SERVICE);
374         return euiccManager.isEnabled();
375     }
376
377     @VisibleForTesting
378     boolean hasReachedBottom(final ScrollView scrollView) {
379         if (scrollView.getChildCount() < 1) {
380             return true;
381         }
382
383         final View view = scrollView.getChildAt(0);
384         final int diff = view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY());
385
386         return diff <= 0;
387     }
388
389     private void getContentDescription(View v, StringBuffer description) {
390        if (v.getVisibility() != View.VISIBLE) {
391            return;
392        }
393        if (v instanceof ViewGroup) {
394            ViewGroup vGroup = (ViewGroup) v;
395            for (int i = 0; i < vGroup.getChildCount(); i++) {
396                View nextChild = vGroup.getChildAt(i);
397                getContentDescription(nextChild, description);
398            }
399        } else if (v instanceof TextView) {
400            TextView vText = (TextView) v;
401            description.append(vText.getText());
402            description.append(","); // Allow Talkback to pause between sections.
403        }
404     }
405
406     private boolean isExtStorageEncrypted() {
407         String state = SystemProperties.get("vold.decrypt");
408         return !"".equals(state);
409     }
410
411     private void loadAccountList(final UserManager um) {
412         View accountsLabel = mContentView.findViewById(R.id.accounts_label);
413         LinearLayout contents = (LinearLayout)mContentView.findViewById(R.id.accounts);
414         contents.removeAllViews();
415
416         Context context = getActivity();
417         final List<UserInfo> profiles = um.getProfiles(UserHandle.myUserId());
418         final int profilesSize = profiles.size();
419
420         AccountManager mgr = AccountManager.get(context);
421
422         LayoutInflater inflater = (LayoutInflater)context.getSystemService(
423                 Context.LAYOUT_INFLATER_SERVICE);
424
425         int accountsCount = 0;
426         for (int profileIndex = 0; profileIndex < profilesSize; profileIndex++) {
427             final UserInfo userInfo = profiles.get(profileIndex);
428             final int profileId = userInfo.id;
429             final UserHandle userHandle = new UserHandle(profileId);
430             Account[] accounts = mgr.getAccountsAsUser(profileId);
431             final int N = accounts.length;
432             if (N == 0) {
433                 continue;
434             }
435             accountsCount += N;
436
437             AuthenticatorDescription[] descs = AccountManager.get(context)
438                     .getAuthenticatorTypesAsUser(profileId);
439             final int M = descs.length;
440
441             if (profilesSize > 1) {
442                 View titleView = Utils.inflateCategoryHeader(inflater, contents);
443                 final TextView titleText = (TextView) titleView.findViewById(android.R.id.title);
444                 titleText.setText(userInfo.isManagedProfile() ? R.string.category_work
445                         : R.string.category_personal);
446                 contents.addView(titleView);
447             }
448
449             for (int i = 0; i < N; i++) {
450                 Account account = accounts[i];
451                 AuthenticatorDescription desc = null;
452                 for (int j = 0; j < M; j++) {
453                     if (account.type.equals(descs[j].type)) {
454                         desc = descs[j];
455                         break;
456                     }
457                 }
458                 if (desc == null) {
459                     Log.w(TAG, "No descriptor for account name=" + account.name
460                             + " type=" + account.type);
461                     continue;
462                 }
463                 Drawable icon = null;
464                 try {
465                     if (desc.iconId != 0) {
466                         Context authContext = context.createPackageContextAsUser(desc.packageName,
467                                 0, userHandle);
468                         icon = context.getPackageManager().getUserBadgedIcon(
469                                 authContext.getDrawable(desc.iconId), userHandle);
470                     }
471                 } catch (PackageManager.NameNotFoundException e) {
472                     Log.w(TAG, "Bad package name for account type " + desc.type);
473                 } catch (Resources.NotFoundException e) {
474                     Log.w(TAG, "Invalid icon id for account type " + desc.type, e);
475                 }
476                 if (icon == null) {
477                     icon = context.getPackageManager().getDefaultActivityIcon();
478                 }
479
480                 View child = inflater.inflate(R.layout.master_clear_account, contents, false);
481                 ((ImageView) child.findViewById(android.R.id.icon)).setImageDrawable(icon);
482                 ((TextView) child.findViewById(android.R.id.title)).setText(account.name);
483                 contents.addView(child);
484             }
485         }
486
487         if (accountsCount > 0) {
488             accountsLabel.setVisibility(View.VISIBLE);
489             contents.setVisibility(View.VISIBLE);
490         }
491         // Checking for all other users and their profiles if any.
492         View otherUsers = mContentView.findViewById(R.id.other_users_present);
493         final boolean hasOtherUsers = (um.getUserCount() - profilesSize) > 0;
494         otherUsers.setVisibility(hasOtherUsers ? View.VISIBLE : View.GONE);
495     }
496
497     @Override
498     public View onCreateView(LayoutInflater inflater, ViewGroup container,
499             Bundle savedInstanceState) {
500         final Context context = getContext();
501         final EnforcedAdmin admin = RestrictedLockUtils.checkIfRestrictionEnforced(context,
502                 UserManager.DISALLOW_FACTORY_RESET, UserHandle.myUserId());
503         final UserManager um = UserManager.get(context);
504         final boolean disallow = !um.isAdminUser() || RestrictedLockUtils.hasBaseUserRestriction(
505                 context, UserManager.DISALLOW_FACTORY_RESET, UserHandle.myUserId());
506         if (disallow && !Utils.isDemoUser(context)) {
507             return inflater.inflate(R.layout.master_clear_disallowed_screen, null);
508         } else if (admin != null) {
509             new ActionDisabledByAdminDialogHelper(getActivity())
510                     .prepareDialogBuilder(UserManager.DISALLOW_FACTORY_RESET, admin)
511                     .setOnDismissListener(__ -> getActivity().finish())
512                     .show();
513             return new View(getContext());
514         }
515
516         mContentView = inflater.inflate(R.layout.master_clear, null);
517
518         establishInitialState();
519         return mContentView;
520     }
521
522     @Override
523     public int getMetricsCategory() {
524         return MetricsEvent.MASTER_CLEAR;
525     }
526 }