OSDN Git Service

Merge "Update text of wifi to cell autoswitch toggle" into nyc-mr1-dev
[android-x86/packages-apps-Settings.git] / src / com / android / settings / ChooseLockGeneric.java
1 /*
2  * Copyright (C) 2010 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 android.app.admin.DevicePolicyManager.ACTION_SET_NEW_PARENT_PROFILE_PASSWORD;
20 import static android.app.admin.DevicePolicyManager.ACTION_SET_NEW_PASSWORD;
21 import static com.android.settings.ChooseLockPassword.ChooseLockPasswordFragment.RESULT_FINISHED;
22 import static com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
23
24 import android.accessibilityservice.AccessibilityServiceInfo;
25 import android.app.Activity;
26 import android.app.AlertDialog;
27 import android.app.Dialog;
28 import android.app.DialogFragment;
29 import android.app.Fragment;
30 import android.app.FragmentManager;
31 import android.app.admin.DevicePolicyManager;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.Intent;
35 import android.content.pm.UserInfo;
36 import android.hardware.fingerprint.Fingerprint;
37 import android.hardware.fingerprint.FingerprintManager;
38 import android.hardware.fingerprint.FingerprintManager.RemovalCallback;
39 import android.os.Bundle;
40 import android.os.UserHandle;
41 import android.os.UserManager;
42 import android.os.storage.StorageManager;
43 import android.security.KeyStore;
44 import android.support.v7.preference.Preference;
45 import android.support.v7.preference.PreferenceScreen;
46 import android.text.TextUtils;
47 import android.util.EventLog;
48 import android.util.Log;
49 import android.view.accessibility.AccessibilityManager;
50 import android.widget.TextView;
51
52 import com.android.internal.logging.MetricsProto.MetricsEvent;
53 import com.android.internal.widget.LockPatternUtils;
54 import com.android.settings.fingerprint.FingerprintEnrollBase;
55 import com.android.settings.fingerprint.FingerprintEnrollFindSensor;
56 import com.android.settingslib.RestrictedLockUtils;
57 import com.android.settingslib.RestrictedPreference;
58
59 import java.util.List;
60
61 public class ChooseLockGeneric extends SettingsActivity {
62     public static final String CONFIRM_CREDENTIALS = "confirm_credentials";
63
64     @Override
65     public Intent getIntent() {
66         Intent modIntent = new Intent(super.getIntent());
67         modIntent.putExtra(EXTRA_SHOW_FRAGMENT, getFragmentClass().getName());
68
69         String action = modIntent.getAction();
70         if (ACTION_SET_NEW_PASSWORD.equals(action)
71                 || ACTION_SET_NEW_PARENT_PROFILE_PASSWORD.equals(action)) {
72             modIntent.putExtra(EXTRA_HIDE_DRAWER, true);
73         }
74         return modIntent;
75     }
76
77     @Override
78     protected boolean isValidFragment(String fragmentName) {
79         if (ChooseLockGenericFragment.class.getName().equals(fragmentName)) return true;
80         return false;
81     }
82
83     /* package */ Class<? extends Fragment> getFragmentClass() {
84         return ChooseLockGenericFragment.class;
85     }
86
87     public static class InternalActivity extends ChooseLockGeneric {
88     }
89
90     public static class ChooseLockGenericFragment extends SettingsPreferenceFragment {
91         private static final String TAG = "ChooseLockGenericFragment";
92         private static final int MIN_PASSWORD_LENGTH = 4;
93         private static final String KEY_UNLOCK_SET_OFF = "unlock_set_off";
94         private static final String KEY_UNLOCK_SET_NONE = "unlock_set_none";
95         private static final String KEY_UNLOCK_SET_PIN = "unlock_set_pin";
96         private static final String KEY_UNLOCK_SET_PASSWORD = "unlock_set_password";
97         private static final String KEY_UNLOCK_SET_PATTERN = "unlock_set_pattern";
98         private static final String KEY_UNLOCK_SET_MANAGED = "unlock_set_managed";
99         private static final String KEY_SKIP_FINGERPRINT = "unlock_skip_fingerprint";
100         private static final String PASSWORD_CONFIRMED = "password_confirmed";
101         private static final String WAITING_FOR_CONFIRMATION = "waiting_for_confirmation";
102         public static final String MINIMUM_QUALITY_KEY = "minimum_quality";
103         public static final String HIDE_DISABLED_PREFS = "hide_disabled_prefs";
104         public static final String ENCRYPT_REQUESTED_QUALITY = "encrypt_requested_quality";
105         public static final String ENCRYPT_REQUESTED_DISABLED = "encrypt_requested_disabled";
106         public static final String TAG_FRP_WARNING_DIALOG = "frp_warning_dialog";
107
108         private static final int CONFIRM_EXISTING_REQUEST = 100;
109         private static final int ENABLE_ENCRYPTION_REQUEST = 101;
110         private static final int CHOOSE_LOCK_REQUEST = 102;
111         private static final int CHOOSE_LOCK_BEFORE_FINGERPRINT_REQUEST = 103;
112         private static final int SKIP_FINGERPRINT_REQUEST = 104;
113
114         private ChooseLockSettingsHelper mChooseLockSettingsHelper;
115         private DevicePolicyManager mDPM;
116         private KeyStore mKeyStore;
117         private boolean mHasChallenge = false;
118         private long mChallenge;
119         private boolean mPasswordConfirmed = false;
120         private boolean mWaitingForConfirmation = false;
121         private int mEncryptionRequestQuality;
122         private boolean mEncryptionRequestDisabled;
123         private boolean mRequirePassword;
124         private boolean mForChangeCredRequiredForBoot = false;
125         private String mUserPassword;
126         private LockPatternUtils mLockPatternUtils;
127         private FingerprintManager mFingerprintManager;
128         private int mUserId;
129         private boolean mHideDrawer = false;
130         private ManagedLockPasswordProvider mManagedPasswordProvider;
131         private boolean mIsSetNewPassword = false;
132
133         protected boolean mForFingerprint = false;
134
135         @Override
136         protected int getMetricsCategory() {
137             return MetricsEvent.CHOOSE_LOCK_GENERIC;
138         }
139
140         @Override
141         public void onCreate(Bundle savedInstanceState) {
142             super.onCreate(savedInstanceState);
143
144             String chooseLockAction = getActivity().getIntent().getAction();
145             mFingerprintManager =
146                 (FingerprintManager) getActivity().getSystemService(Context.FINGERPRINT_SERVICE);
147             mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
148             mKeyStore = KeyStore.getInstance();
149             mChooseLockSettingsHelper = new ChooseLockSettingsHelper(this.getActivity());
150             mLockPatternUtils = new LockPatternUtils(getActivity());
151             mIsSetNewPassword = ACTION_SET_NEW_PARENT_PROFILE_PASSWORD.equals(chooseLockAction)
152                     || ACTION_SET_NEW_PASSWORD.equals(chooseLockAction);
153
154             // Defaults to needing to confirm credentials
155             final boolean confirmCredentials = getActivity().getIntent()
156                 .getBooleanExtra(CONFIRM_CREDENTIALS, true);
157             if (getActivity() instanceof ChooseLockGeneric.InternalActivity) {
158                 mPasswordConfirmed = !confirmCredentials;
159             }
160             mHideDrawer = getActivity().getIntent().getBooleanExtra(EXTRA_HIDE_DRAWER, false);
161
162             mHasChallenge = getActivity().getIntent().getBooleanExtra(
163                     ChooseLockSettingsHelper.EXTRA_KEY_HAS_CHALLENGE, false);
164             mChallenge = getActivity().getIntent().getLongExtra(
165                     ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE, 0);
166             mForFingerprint = getActivity().getIntent().getBooleanExtra(
167                     ChooseLockSettingsHelper.EXTRA_KEY_FOR_FINGERPRINT, false);
168             mForChangeCredRequiredForBoot = getArguments() != null && getArguments().getBoolean(
169                     ChooseLockSettingsHelper.EXTRA_KEY_FOR_CHANGE_CRED_REQUIRED_FOR_BOOT);
170             if (mIsSetNewPassword) {
171                 // In ACTION_SET_NEW_PARENT_PROFILE_PASSWORD or ACTION_SET_NEW_PASSWORD, the user
172                 // will be asked to confirm the password if one has been set.
173                 // On fingerprint supported device, fingerprint options are represented in the
174                 // options. If the user chooses to skip fingerprint setup, ChooseLockGeneric is
175                 // relaunched to only show options without fingerprint. In this case, we shouldn't
176                 // ask the user to confirm the password again.
177                 mPasswordConfirmed = getActivity().getIntent().getBooleanExtra(
178                         PASSWORD_CONFIRMED, false);
179             }
180
181             if (savedInstanceState != null) {
182                 mPasswordConfirmed = savedInstanceState.getBoolean(PASSWORD_CONFIRMED);
183                 mWaitingForConfirmation = savedInstanceState.getBoolean(WAITING_FOR_CONFIRMATION);
184                 mEncryptionRequestQuality = savedInstanceState.getInt(ENCRYPT_REQUESTED_QUALITY);
185                 mEncryptionRequestDisabled = savedInstanceState.getBoolean(
186                         ENCRYPT_REQUESTED_DISABLED);
187             }
188
189             int targetUser = Utils.getSecureTargetUser(
190                     getActivity().getActivityToken(),
191                     UserManager.get(getActivity()),
192                     null,
193                     getActivity().getIntent().getExtras()).getIdentifier();
194             if (ACTION_SET_NEW_PARENT_PROFILE_PASSWORD.equals(chooseLockAction)
195                     || !mLockPatternUtils.isSeparateProfileChallengeAllowed(targetUser)) {
196                 // Always use parent if explicitely requested or if profile challenge is not
197                 // supported
198                 Bundle arguments = getArguments();
199                 mUserId = Utils.getUserIdFromBundle(getContext(), arguments != null ? arguments
200                         : getActivity().getIntent().getExtras());
201             } else {
202                 mUserId = targetUser;
203             }
204
205             if (ACTION_SET_NEW_PASSWORD.equals(chooseLockAction)
206                     && Utils.isManagedProfile(UserManager.get(getActivity()), mUserId)
207                     && mLockPatternUtils.isSeparateProfileChallengeEnabled(mUserId)) {
208                 getActivity().setTitle(R.string.lock_settings_picker_title_profile);
209             }
210
211             mManagedPasswordProvider = ManagedLockPasswordProvider.get(getActivity(), mUserId);
212
213             if (mPasswordConfirmed) {
214                 updatePreferencesOrFinish();
215                 if (mForChangeCredRequiredForBoot) {
216                     maybeEnableEncryption(mLockPatternUtils.getKeyguardStoredPasswordQuality(
217                             mUserId), false);
218                 }
219             } else if (!mWaitingForConfirmation) {
220                 ChooseLockSettingsHelper helper =
221                         new ChooseLockSettingsHelper(this.getActivity(), this);
222                 boolean managedProfileWithUnifiedLock = Utils
223                         .isManagedProfile(UserManager.get(getActivity()), mUserId)
224                         && !mLockPatternUtils.isSeparateProfileChallengeEnabled(mUserId);
225                 if (managedProfileWithUnifiedLock
226                         || !helper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST,
227                         getString(R.string.unlock_set_unlock_launch_picker_title), true, mUserId)) {
228                     mPasswordConfirmed = true; // no password set, so no need to confirm
229                     updatePreferencesOrFinish();
230                 } else {
231                     mWaitingForConfirmation = true;
232                 }
233             }
234             addHeaderView();
235         }
236
237         protected void addHeaderView() {
238             if (mForFingerprint) {
239                 setHeaderView(R.layout.choose_lock_generic_fingerprint_header);
240                 if (mIsSetNewPassword) {
241                     ((TextView) getHeaderView().findViewById(R.id.fingerprint_header_description))
242                             .setText(R.string.fingerprint_unlock_title);
243                 }
244             }
245         }
246
247         @Override
248         public boolean onPreferenceTreeClick(Preference preference) {
249             final String key = preference.getKey();
250
251             if (!isUnlockMethodSecure(key) && mLockPatternUtils.isSecure(mUserId)) {
252                 // Show the disabling FRP warning only when the user is switching from a secure
253                 // unlock method to an insecure one
254                 showFactoryResetProtectionWarningDialog(key);
255                 return true;
256             } else if (KEY_SKIP_FINGERPRINT.equals(key)) {
257                 Intent chooseLockGenericIntent = new Intent(getActivity(), ChooseLockGeneric.class);
258                 chooseLockGenericIntent.setAction(getIntent().getAction());
259                 chooseLockGenericIntent.putExtra(PASSWORD_CONFIRMED, mPasswordConfirmed);
260                 startActivityForResult(chooseLockGenericIntent, SKIP_FINGERPRINT_REQUEST);
261                 return true;
262             } else {
263                 return setUnlockMethod(key);
264             }
265         }
266
267         /**
268          * If the device has encryption already enabled, then ask the user if they
269          * also want to encrypt the phone with this password.
270          *
271          * @param quality
272          * @param disabled
273          */
274         // TODO: why does this take disabled, its always called with a quality higher than
275         // what makes sense with disabled == true
276         private void maybeEnableEncryption(int quality, boolean disabled) {
277             DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
278             if (UserManager.get(getActivity()).isAdminUser()
279                     && mUserId == UserHandle.myUserId()
280                     && LockPatternUtils.isDeviceEncryptionEnabled()
281                     && !LockPatternUtils.isFileEncryptionEnabled()
282                     && !dpm.getDoNotAskCredentialsOnBoot()) {
283                 mEncryptionRequestQuality = quality;
284                 mEncryptionRequestDisabled = disabled;
285                 // Get the intent that the encryption interstitial should start for creating
286                 // the new unlock method.
287                 Intent unlockMethodIntent = getIntentForUnlockMethod(quality, disabled);
288                 unlockMethodIntent.putExtra(
289                         ChooseLockSettingsHelper.EXTRA_KEY_FOR_CHANGE_CRED_REQUIRED_FOR_BOOT,
290                         mForChangeCredRequiredForBoot);
291                 final Context context = getActivity();
292                 // If accessibility is enabled and the user hasn't seen this dialog before, set the
293                 // default state to agree with that which is compatible with accessibility
294                 // (password not required).
295                 final boolean accEn = AccessibilityManager.getInstance(context).isEnabled();
296                 final boolean required = mLockPatternUtils.isCredentialRequiredToDecrypt(!accEn);
297                 Intent intent = getEncryptionInterstitialIntent(context, quality, required,
298                         unlockMethodIntent);
299                 intent.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_FOR_FINGERPRINT,
300                         mForFingerprint);
301                 intent.putExtra(EXTRA_HIDE_DRAWER, mHideDrawer);
302                 startActivityForResult(intent, ENABLE_ENCRYPTION_REQUEST);
303             } else {
304                 if (mForChangeCredRequiredForBoot) {
305                     // Welp, couldn't change it. Oh well.
306                     finish();
307                     return;
308                 }
309                 mRequirePassword = false; // device encryption not enabled or not device owner.
310                 updateUnlockMethodAndFinish(quality, disabled);
311             }
312         }
313
314         @Override
315         public void onActivityResult(int requestCode, int resultCode, Intent data) {
316             super.onActivityResult(requestCode, resultCode, data);
317             mWaitingForConfirmation = false;
318             if (requestCode == CONFIRM_EXISTING_REQUEST && resultCode == Activity.RESULT_OK) {
319                 mPasswordConfirmed = true;
320                 mUserPassword = data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD);
321                 updatePreferencesOrFinish();
322                 if (mForChangeCredRequiredForBoot) {
323                     if (!TextUtils.isEmpty(mUserPassword)) {
324                         maybeEnableEncryption(
325                                 mLockPatternUtils.getKeyguardStoredPasswordQuality(mUserId), false);
326                     } else {
327                         finish();
328                     }
329                 }
330             } else if (requestCode == CHOOSE_LOCK_REQUEST
331                     || requestCode == ENABLE_ENCRYPTION_REQUEST) {
332                 if (resultCode != RESULT_CANCELED || mForChangeCredRequiredForBoot) {
333                     getActivity().setResult(resultCode, data);
334                     finish();
335                 }
336             } else if (requestCode == CHOOSE_LOCK_BEFORE_FINGERPRINT_REQUEST
337                     && resultCode == FingerprintEnrollBase.RESULT_FINISHED) {
338                 Intent intent = new Intent(getActivity(), FingerprintEnrollFindSensor.class);
339                 if (data != null) {
340                     intent.putExtras(data.getExtras());
341                 }
342                 startActivity(intent);
343                 finish();
344             } else if (requestCode == SKIP_FINGERPRINT_REQUEST) {
345                 if (resultCode != RESULT_CANCELED) {
346                     getActivity().setResult(
347                             resultCode == RESULT_FINISHED ? RESULT_OK : resultCode, data);
348                     finish();
349                 }
350             } else {
351                 getActivity().setResult(Activity.RESULT_CANCELED);
352                 finish();
353             }
354             if (requestCode == Activity.RESULT_CANCELED && mForChangeCredRequiredForBoot) {
355                 finish();
356             }
357         }
358
359         @Override
360         public void onSaveInstanceState(Bundle outState) {
361             super.onSaveInstanceState(outState);
362             // Saved so we don't force user to re-enter their password if configuration changes
363             outState.putBoolean(PASSWORD_CONFIRMED, mPasswordConfirmed);
364             outState.putBoolean(WAITING_FOR_CONFIRMATION, mWaitingForConfirmation);
365             outState.putInt(ENCRYPT_REQUESTED_QUALITY, mEncryptionRequestQuality);
366             outState.putBoolean(ENCRYPT_REQUESTED_DISABLED, mEncryptionRequestDisabled);
367         }
368
369         private void updatePreferencesOrFinish() {
370             Intent intent = getActivity().getIntent();
371             int quality = intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY, -1);
372             if (quality == -1) {
373                 // If caller didn't specify password quality, show UI and allow the user to choose.
374                 quality = intent.getIntExtra(MINIMUM_QUALITY_KEY, -1);
375                 quality = upgradeQuality(quality);
376                 final boolean hideDisabledPrefs = intent.getBooleanExtra(
377                         HIDE_DISABLED_PREFS, false);
378                 final PreferenceScreen prefScreen = getPreferenceScreen();
379                 if (prefScreen != null) {
380                     prefScreen.removeAll();
381                 }
382                 addPreferences();
383                 disableUnusablePreferences(quality, hideDisabledPrefs);
384                 updatePreferenceText();
385                 updateCurrentPreference();
386                 updatePreferenceSummaryIfNeeded();
387             } else {
388                 updateUnlockMethodAndFinish(quality, false);
389             }
390         }
391
392         protected void addPreferences() {
393             addPreferencesFromResource(R.xml.security_settings_picker);
394
395             // Used for testing purposes
396             findPreference(KEY_UNLOCK_SET_NONE).setViewId(R.id.lock_none);
397             findPreference(KEY_UNLOCK_SET_PIN).setViewId(R.id.lock_pin);
398             findPreference(KEY_UNLOCK_SET_PASSWORD).setViewId(R.id.lock_password);
399         }
400
401         private void updatePreferenceText() {
402             if (mForFingerprint) {
403                 final String key[] = { KEY_UNLOCK_SET_PATTERN,
404                         KEY_UNLOCK_SET_PIN,
405                         KEY_UNLOCK_SET_PASSWORD };
406                 final int res[] = { R.string.fingerprint_unlock_set_unlock_pattern,
407                         R.string.fingerprint_unlock_set_unlock_pin,
408                         R.string.fingerprint_unlock_set_unlock_password };
409                 for (int i = 0; i < key.length; i++) {
410                     Preference pref = findPreference(key[i]);
411                     if (pref != null) { // can be removed by device admin
412                         pref.setTitle(res[i]);
413                     }
414                 }
415             }
416
417             if (mManagedPasswordProvider.isSettingManagedPasswordSupported()) {
418                 Preference managed = findPreference(KEY_UNLOCK_SET_MANAGED);
419                 managed.setTitle(mManagedPasswordProvider.getPickerOptionTitle(mForFingerprint));
420             } else {
421                 removePreference(KEY_UNLOCK_SET_MANAGED);
422             }
423
424             if (!(mForFingerprint && mIsSetNewPassword)) {
425                 removePreference(KEY_SKIP_FINGERPRINT);
426             }
427         }
428
429         private void updateCurrentPreference() {
430             String currentKey = getKeyForCurrent();
431             Preference preference = findPreference(currentKey);
432             if (preference != null) {
433                 preference.setSummary(R.string.current_screen_lock);
434             }
435         }
436
437         private String getKeyForCurrent() {
438             final int credentialOwner = UserManager.get(getContext())
439                     .getCredentialOwnerProfile(mUserId);
440             if (mLockPatternUtils.isLockScreenDisabled(credentialOwner)) {
441                 return KEY_UNLOCK_SET_OFF;
442             }
443             switch (mLockPatternUtils.getKeyguardStoredPasswordQuality(credentialOwner)) {
444                 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
445                     return KEY_UNLOCK_SET_PATTERN;
446                 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
447                 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
448                     return KEY_UNLOCK_SET_PIN;
449                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
450                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
451                 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
452                     return KEY_UNLOCK_SET_PASSWORD;
453                 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
454                     return KEY_UNLOCK_SET_MANAGED;
455                 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
456                     return KEY_UNLOCK_SET_NONE;
457             }
458             return null;
459         }
460
461         /** increases the quality if necessary */
462         private int upgradeQuality(int quality) {
463             quality = upgradeQualityForDPM(quality);
464             return quality;
465         }
466
467         private int upgradeQualityForDPM(int quality) {
468             // Compare min allowed password quality
469             int minQuality = mDPM.getPasswordQuality(null, mUserId);
470             if (quality < minQuality) {
471                 quality = minQuality;
472             }
473             return quality;
474         }
475
476         /***
477          * Disables preferences that are less secure than required quality. The actual
478          * implementation is in disableUnusablePreferenceImpl.
479          *
480          * @param quality the requested quality.
481          * @param hideDisabledPrefs if false preferences show why they were disabled; otherwise
482          * they're not shown at all.
483          */
484         protected void disableUnusablePreferences(final int quality, boolean hideDisabledPrefs) {
485             disableUnusablePreferencesImpl(quality, hideDisabledPrefs);
486         }
487
488         /***
489          * Disables preferences that are less secure than required quality.
490          *
491          * @param quality the requested quality.
492          * @param hideDisabled whether to hide disable screen lock options.
493          */
494         protected void disableUnusablePreferencesImpl(final int quality,
495                 boolean hideDisabled) {
496             final PreferenceScreen entries = getPreferenceScreen();
497
498             int adminEnforcedQuality = mDPM.getPasswordQuality(null, mUserId);
499             EnforcedAdmin enforcedAdmin = RestrictedLockUtils.checkIfPasswordQualityIsSet(
500                     getActivity(), mUserId);
501             for (int i = entries.getPreferenceCount() - 1; i >= 0; --i) {
502                 Preference pref = entries.getPreference(i);
503                 if (pref instanceof RestrictedPreference) {
504                     final String key = pref.getKey();
505                     boolean enabled = true;
506                     boolean visible = true;
507                     boolean disabledByAdmin = false;
508                     if (KEY_UNLOCK_SET_OFF.equals(key)) {
509                         enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
510                         if (getResources().getBoolean(R.bool.config_hide_none_security_option)) {
511                             enabled = false;
512                             visible = false;
513                         }
514                         disabledByAdmin = adminEnforcedQuality
515                                 > DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
516                     } else if (KEY_UNLOCK_SET_NONE.equals(key)) {
517                         if (mUserId != UserHandle.myUserId()) {
518                             // Swipe doesn't make sense for profiles.
519                             visible = false;
520                         }
521                         enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
522                         disabledByAdmin = adminEnforcedQuality
523                                 > DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
524                     } else if (KEY_UNLOCK_SET_PATTERN.equals(key)) {
525                         enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
526                         disabledByAdmin = adminEnforcedQuality
527                                 > DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
528                     } else if (KEY_UNLOCK_SET_PIN.equals(key)) {
529                         enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
530                         disabledByAdmin = adminEnforcedQuality
531                                 > DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
532                     } else if (KEY_UNLOCK_SET_PASSWORD.equals(key)) {
533                         enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
534                         disabledByAdmin = adminEnforcedQuality
535                                 > DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
536                     } else if (KEY_UNLOCK_SET_MANAGED.equals(key)) {
537                         enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_MANAGED
538                                 && mManagedPasswordProvider.isManagedPasswordChoosable();
539                         disabledByAdmin = adminEnforcedQuality
540                                 > DevicePolicyManager.PASSWORD_QUALITY_MANAGED;
541                     }
542                     if (hideDisabled) {
543                         visible = enabled;
544                     }
545                     if (!visible) {
546                         entries.removePreference(pref);
547                     } else if (disabledByAdmin && enforcedAdmin != null) {
548                         ((RestrictedPreference) pref).setDisabledByAdmin(enforcedAdmin);
549                     } else if (!enabled) {
550                         // we need to setDisabledByAdmin to null first to disable the padlock
551                         // in case it was set earlier.
552                         ((RestrictedPreference) pref).setDisabledByAdmin(null);
553                         pref.setSummary(R.string.unlock_set_unlock_disabled_summary);
554                         pref.setEnabled(false);
555                     } else {
556                         ((RestrictedPreference) pref).setDisabledByAdmin(null);
557                     }
558                 }
559             }
560         }
561
562         private void updatePreferenceSummaryIfNeeded() {
563             // On a default block encrypted device with accessibility, add a warning
564             // that your data is not credential encrypted
565             if (!StorageManager.isBlockEncrypted()) {
566                 return;
567             }
568
569             if (StorageManager.isNonDefaultBlockEncrypted()) {
570                 return;
571             }
572
573             if (AccessibilityManager.getInstance(getActivity()).getEnabledAccessibilityServiceList(
574                     AccessibilityServiceInfo.FEEDBACK_ALL_MASK).isEmpty()) {
575                 return;
576             }
577
578             CharSequence summary = getString(R.string.secure_lock_encryption_warning);
579
580             PreferenceScreen screen = getPreferenceScreen();
581             final int preferenceCount = screen.getPreferenceCount();
582             for (int i = 0; i < preferenceCount; i++) {
583                 Preference preference = screen.getPreference(i);
584                 switch (preference.getKey()) {
585                     case KEY_UNLOCK_SET_PATTERN:
586                     case KEY_UNLOCK_SET_PIN:
587                     case KEY_UNLOCK_SET_PASSWORD:
588                     case KEY_UNLOCK_SET_MANAGED: {
589                         preference.setSummary(summary);
590                     } break;
591                 }
592             }
593         }
594
595         protected Intent getLockManagedPasswordIntent(boolean requirePassword, String password) {
596             return mManagedPasswordProvider.createIntent(requirePassword, password);
597         }
598
599         protected Intent getLockPasswordIntent(Context context, int quality,
600                 int minLength, final int maxLength,
601                 boolean requirePasswordToDecrypt, boolean confirmCredentials, int userId) {
602             return ChooseLockPassword.createIntent(context, quality, minLength,
603                     maxLength, requirePasswordToDecrypt, confirmCredentials, userId);
604         }
605
606         protected Intent getLockPasswordIntent(Context context, int quality,
607                 int minLength, final int maxLength,
608                 boolean requirePasswordToDecrypt, long challenge, int userId) {
609             return ChooseLockPassword.createIntent(context, quality, minLength,
610                     maxLength, requirePasswordToDecrypt, challenge, userId);
611         }
612
613         protected Intent getLockPasswordIntent(Context context, int quality, int minLength,
614                 int maxLength, boolean requirePasswordToDecrypt, String password, int userId) {
615             return ChooseLockPassword.createIntent(context, quality, minLength, maxLength,
616                     requirePasswordToDecrypt, password, userId);
617         }
618
619         protected Intent getLockPatternIntent(Context context, final boolean requirePassword,
620                 final boolean confirmCredentials, int userId) {
621             return ChooseLockPattern.createIntent(context, requirePassword,
622                     confirmCredentials, userId);
623         }
624
625         protected Intent getLockPatternIntent(Context context, final boolean requirePassword,
626                long challenge, int userId) {
627             return ChooseLockPattern.createIntent(context, requirePassword, challenge, userId);
628         }
629
630         protected Intent getLockPatternIntent(Context context, final boolean requirePassword,
631                 final String pattern, int userId) {
632             return ChooseLockPattern.createIntent(context, requirePassword, pattern, userId);
633         }
634
635         protected Intent getEncryptionInterstitialIntent(Context context, int quality,
636                 boolean required, Intent unlockMethodIntent) {
637             return EncryptionInterstitial.createStartIntent(context, quality, required,
638                     unlockMethodIntent);
639         }
640
641         /**
642          * Invokes an activity to change the user's pattern, password or PIN based on given quality
643          * and minimum quality specified by DevicePolicyManager. If quality is
644          * {@link DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, password is cleared.
645          *
646          * @param quality the desired quality. Ignored if DevicePolicyManager requires more security
647          * @param disabled whether or not to show LockScreen at all. Only meaningful when quality is
648          * {@link DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}
649          */
650         void updateUnlockMethodAndFinish(int quality, boolean disabled) {
651             // Sanity check. We should never get here without confirming user's existing password.
652             if (!mPasswordConfirmed) {
653                 throw new IllegalStateException("Tried to update password without confirming it");
654             }
655
656             quality = upgradeQuality(quality);
657             Intent intent = getIntentForUnlockMethod(quality, disabled);
658             if (intent != null) {
659                 startActivityForResult(intent,
660                         mIsSetNewPassword && mHasChallenge
661                                 ? CHOOSE_LOCK_BEFORE_FINGERPRINT_REQUEST
662                                 : CHOOSE_LOCK_REQUEST);
663                 return;
664             }
665
666             if (quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
667                 mLockPatternUtils.setSeparateProfileChallengeEnabled(mUserId, true, mUserPassword);
668                 mChooseLockSettingsHelper.utils().clearLock(mUserId);
669                 mChooseLockSettingsHelper.utils().setLockScreenDisabled(disabled, mUserId);
670                 getActivity().setResult(Activity.RESULT_OK);
671                 removeAllFingerprintForUserAndFinish(mUserId);
672             } else {
673                 removeAllFingerprintForUserAndFinish(mUserId);
674             }
675         }
676
677         private Intent getIntentForUnlockMethod(int quality, boolean disabled) {
678             Intent intent = null;
679             final Context context = getActivity();
680             if (quality >= DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
681                 intent = getLockManagedPasswordIntent(mRequirePassword, mUserPassword);
682             } else if (quality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC) {
683                 int minLength = mDPM.getPasswordMinimumLength(null, mUserId);
684                 if (minLength < MIN_PASSWORD_LENGTH) {
685                     minLength = MIN_PASSWORD_LENGTH;
686                 }
687                 final int maxLength = mDPM.getPasswordMaximumLength(quality);
688                 if (mHasChallenge) {
689                     intent = getLockPasswordIntent(context, quality, minLength,
690                             maxLength, mRequirePassword, mChallenge, mUserId);
691                 } else {
692                     intent = getLockPasswordIntent(context, quality, minLength,
693                             maxLength, mRequirePassword, mUserPassword, mUserId);
694                 }
695             } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
696                 if (mHasChallenge) {
697                     intent = getLockPatternIntent(context, mRequirePassword,
698                             mChallenge, mUserId);
699                 } else {
700                     intent = getLockPatternIntent(context, mRequirePassword,
701                             mUserPassword, mUserId);
702                 }
703             }
704             if (intent != null) {
705                 intent.putExtra(EXTRA_HIDE_DRAWER, mHideDrawer);
706             }
707             return intent;
708         }
709
710         private void removeAllFingerprintForUserAndFinish(final int userId) {
711             if (mFingerprintManager != null && mFingerprintManager.isHardwareDetected()) {
712                 if (mFingerprintManager.hasEnrolledFingerprints(userId)) {
713                     mFingerprintManager.setActiveUser(userId);
714                     // For the purposes of M and N, groupId is the same as userId.
715                     final int groupId = userId;
716                     Fingerprint finger = new Fingerprint(null, groupId, 0, 0);
717                     mFingerprintManager.remove(finger, userId,
718                             new RemovalCallback() {
719                                 @Override
720                                 public void onRemovalError(Fingerprint fp, int errMsgId,
721                                         CharSequence errString) {
722                                     Log.v(TAG, "Fingerprint removed: " + fp.getFingerId());
723                                     if (fp.getFingerId() == 0) {
724                                         removeManagedProfileFingerprintsAndFinishIfNecessary(userId);
725                                     }
726                                 }
727
728                                 @Override
729                                 public void onRemovalSucceeded(Fingerprint fingerprint) {
730                                     if (fingerprint.getFingerId() == 0) {
731                                         removeManagedProfileFingerprintsAndFinishIfNecessary(userId);
732                                     }
733                                 }
734                             });
735                 } else {
736                     // No fingerprints in this user, we may also want to delete managed profile
737                     // fingerprints
738                     removeManagedProfileFingerprintsAndFinishIfNecessary(userId);
739                 }
740             } else {
741                 // The removal callback will call finish, once all fingerprints are removed.
742                 // We need to wait for that to occur, otherwise, the UI will still show that
743                 // fingerprints exist even though they are (about to) be removed depending on
744                 // the race condition.
745                 finish();
746             }
747         }
748
749         private void removeManagedProfileFingerprintsAndFinishIfNecessary(final int parentUserId) {
750             mFingerprintManager.setActiveUser(UserHandle.myUserId());
751             final UserManager um = UserManager.get(getActivity());
752             boolean hasChildProfile = false;
753             if (!um.getUserInfo(parentUserId).isManagedProfile()) {
754                 // Current user is primary profile, remove work profile fingerprints if necessary
755                 final List<UserInfo> profiles = um.getProfiles(parentUserId);
756                 final int profilesSize = profiles.size();
757                 for (int i = 0; i < profilesSize; i++) {
758                     final UserInfo userInfo = profiles.get(i);
759                     if (userInfo.isManagedProfile() && !mLockPatternUtils
760                             .isSeparateProfileChallengeEnabled(userInfo.id)) {
761                         removeAllFingerprintForUserAndFinish(userInfo.id);
762                         hasChildProfile = true;
763                         break;
764                     }
765                 }
766             }
767             if (!hasChildProfile) {
768                 finish();
769             }
770         }
771
772         @Override
773         public void onDestroy() {
774             super.onDestroy();
775         }
776
777         @Override
778         protected int getHelpResource() {
779             return R.string.help_url_choose_lockscreen;
780         }
781
782         private int getResIdForFactoryResetProtectionWarningTitle() {
783             boolean isProfile = Utils.isManagedProfile(UserManager.get(getActivity()), mUserId);
784             return isProfile ? R.string.unlock_disable_frp_warning_title_profile
785                     : R.string.unlock_disable_frp_warning_title;
786         }
787
788         private int getResIdForFactoryResetProtectionWarningMessage() {
789             boolean hasFingerprints = mFingerprintManager.hasEnrolledFingerprints(mUserId);
790             boolean isProfile = Utils.isManagedProfile(UserManager.get(getActivity()), mUserId);
791             switch (mLockPatternUtils.getKeyguardStoredPasswordQuality(mUserId)) {
792                 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
793                     if (hasFingerprints && isProfile) {
794                         return R.string
795                                 .unlock_disable_frp_warning_content_pattern_fingerprint_profile;
796                     } else if (hasFingerprints && !isProfile) {
797                         return R.string.unlock_disable_frp_warning_content_pattern_fingerprint;
798                     } else if (isProfile) {
799                         return R.string.unlock_disable_frp_warning_content_pattern_profile;
800                     } else {
801                         return R.string.unlock_disable_frp_warning_content_pattern;
802                     }
803                 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
804                 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
805                     if (hasFingerprints && isProfile) {
806                         return R.string.unlock_disable_frp_warning_content_pin_fingerprint_profile;
807                     } else if (hasFingerprints && !isProfile) {
808                         return R.string.unlock_disable_frp_warning_content_pin_fingerprint;
809                     } else if (isProfile) {
810                         return R.string.unlock_disable_frp_warning_content_pin_profile;
811                     } else {
812                         return R.string.unlock_disable_frp_warning_content_pin;
813                     }
814                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
815                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
816                 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
817                 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
818                     if (hasFingerprints && isProfile) {
819                         return R.string
820                                 .unlock_disable_frp_warning_content_password_fingerprint_profile;
821                     } else if (hasFingerprints && !isProfile) {
822                         return R.string.unlock_disable_frp_warning_content_password_fingerprint;
823                     } else if (isProfile) {
824                         return R.string.unlock_disable_frp_warning_content_password_profile;
825                     } else {
826                         return R.string.unlock_disable_frp_warning_content_password;
827                     }
828                 default:
829                     if (hasFingerprints && isProfile) {
830                         return R.string
831                                 .unlock_disable_frp_warning_content_unknown_fingerprint_profile;
832                     } else if (hasFingerprints && !isProfile) {
833                         return R.string.unlock_disable_frp_warning_content_unknown_fingerprint;
834                     } else if (isProfile) {
835                         return R.string.unlock_disable_frp_warning_content_unknown_profile;
836                     } else {
837                         return R.string.unlock_disable_frp_warning_content_unknown;
838                     }
839             }
840         }
841
842         private boolean isUnlockMethodSecure(String unlockMethod) {
843             return !(KEY_UNLOCK_SET_OFF.equals(unlockMethod) ||
844                     KEY_UNLOCK_SET_NONE.equals(unlockMethod));
845         }
846
847         private boolean setUnlockMethod(String unlockMethod) {
848             EventLog.writeEvent(EventLogTags.LOCK_SCREEN_TYPE, unlockMethod);
849
850             if (KEY_UNLOCK_SET_OFF.equals(unlockMethod)) {
851                 updateUnlockMethodAndFinish(
852                         DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, true /* disabled */ );
853             } else if (KEY_UNLOCK_SET_NONE.equals(unlockMethod)) {
854                 updateUnlockMethodAndFinish(
855                         DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, false /* disabled */ );
856             } else if (KEY_UNLOCK_SET_MANAGED.equals(unlockMethod)) {
857                 maybeEnableEncryption(DevicePolicyManager.PASSWORD_QUALITY_MANAGED, false);
858             } else if (KEY_UNLOCK_SET_PATTERN.equals(unlockMethod)) {
859                 maybeEnableEncryption(
860                         DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, false);
861             } else if (KEY_UNLOCK_SET_PIN.equals(unlockMethod)) {
862                 maybeEnableEncryption(
863                         DevicePolicyManager.PASSWORD_QUALITY_NUMERIC, false);
864             } else if (KEY_UNLOCK_SET_PASSWORD.equals(unlockMethod)) {
865                 maybeEnableEncryption(
866                         DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC, false);
867             } else {
868                 Log.e(TAG, "Encountered unknown unlock method to set: " + unlockMethod);
869                 return false;
870             }
871             return true;
872         }
873
874         private void showFactoryResetProtectionWarningDialog(String unlockMethodToSet) {
875             int title = getResIdForFactoryResetProtectionWarningTitle();
876             int message = getResIdForFactoryResetProtectionWarningMessage();
877             FactoryResetProtectionWarningDialog dialog =
878                     FactoryResetProtectionWarningDialog.newInstance(
879                             title, message, unlockMethodToSet);
880             dialog.show(getChildFragmentManager(), TAG_FRP_WARNING_DIALOG);
881         }
882
883         public static class FactoryResetProtectionWarningDialog extends DialogFragment {
884
885             private static final String ARG_TITLE_RES = "titleRes";
886             private static final String ARG_MESSAGE_RES = "messageRes";
887             private static final String ARG_UNLOCK_METHOD_TO_SET = "unlockMethodToSet";
888
889             public static FactoryResetProtectionWarningDialog newInstance(
890                     int titleRes, int messageRes, String unlockMethodToSet) {
891                 FactoryResetProtectionWarningDialog frag =
892                         new FactoryResetProtectionWarningDialog();
893                 Bundle args = new Bundle();
894                 args.putInt(ARG_TITLE_RES, titleRes);
895                 args.putInt(ARG_MESSAGE_RES, messageRes);
896                 args.putString(ARG_UNLOCK_METHOD_TO_SET, unlockMethodToSet);
897                 frag.setArguments(args);
898                 return frag;
899             }
900
901             @Override
902             public void show(FragmentManager manager, String tag) {
903                 if (manager.findFragmentByTag(tag) == null) {
904                     // Prevent opening multiple dialogs if tapped on button quickly
905                     super.show(manager, tag);
906                 }
907             }
908
909             @Override
910             public Dialog onCreateDialog(Bundle savedInstanceState) {
911                 final Bundle args = getArguments();
912
913                 return new AlertDialog.Builder(getActivity())
914                         .setTitle(args.getInt(ARG_TITLE_RES))
915                         .setMessage(args.getInt(ARG_MESSAGE_RES))
916                         .setPositiveButton(R.string.unlock_disable_frp_warning_ok,
917                                 new DialogInterface.OnClickListener() {
918                                     @Override
919                                     public void onClick(DialogInterface dialog, int whichButton) {
920                                         ((ChooseLockGenericFragment) getParentFragment())
921                                                 .setUnlockMethod(
922                                                         args.getString(ARG_UNLOCK_METHOD_TO_SET));
923                                     }
924                                 }
925                         )
926                         .setNegativeButton(R.string.cancel,
927                                 new DialogInterface.OnClickListener() {
928                                     @Override
929                                     public void onClick(DialogInterface dialog, int whichButton) {
930                                         dismiss();
931                                     }
932                                 }
933                         )
934                         .create();
935             }
936         }
937     }
938 }