OSDN Git Service

Settings: Add Superuser entry
[android-x86/packages-apps-Settings.git] / src / com / android / settings / SecuritySettings.java
1 /*
2  * Copyright (C) 2007 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.provider.Settings.System.SCREEN_OFF_TIMEOUT;
20
21 import static com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
22
23 import android.app.Activity;
24 import android.app.AlertDialog;
25 import android.app.Dialog;
26 import android.app.FragmentManager;
27 import android.app.admin.DevicePolicyManager;
28 import android.content.ComponentName;
29 import android.content.Context;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.pm.PackageManager;
33 import android.content.pm.ResolveInfo;
34 import android.content.res.Resources;
35 import android.hardware.fingerprint.FingerprintManager;
36 import android.os.Bundle;
37 import android.os.PersistableBundle;
38 import android.os.UserHandle;
39 import android.os.UserManager;
40 import android.os.storage.StorageManager;
41 import android.provider.SearchIndexableResource;
42 import android.provider.Settings;
43 import android.service.trust.TrustAgentService;
44 import android.support.annotation.VisibleForTesting;
45 import android.support.v14.preference.SwitchPreference;
46 import android.support.v7.preference.Preference;
47 import android.support.v7.preference.Preference.OnPreferenceChangeListener;
48 import android.support.v7.preference.PreferenceGroup;
49 import android.support.v7.preference.PreferenceScreen;
50 import android.telephony.CarrierConfigManager;
51 import android.telephony.SubscriptionInfo;
52 import android.telephony.SubscriptionManager;
53 import android.telephony.TelephonyManager;
54 import android.text.TextUtils;
55 import android.util.Log;
56
57 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
58 import com.android.internal.widget.LockPatternUtils;
59 import com.android.settings.TrustAgentUtils.TrustAgentComponentInfo;
60 import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
61 import com.android.settings.dashboard.DashboardFeatureProvider;
62 import com.android.settings.dashboard.SummaryLoader;
63 import com.android.settings.enterprise.EnterprisePrivacyPreferenceController;
64 import com.android.settings.enterprise.ManageDeviceAdminPreferenceController;
65 import com.android.settings.fingerprint.FingerprintSettings;
66 import com.android.settings.location.LocationPreferenceController;
67 import com.android.settings.notification.LockScreenNotificationPreferenceController;
68 import com.android.settings.overlay.FeatureFactory;
69 import com.android.settings.password.ChooseLockGeneric.ChooseLockGenericFragment;
70 import com.android.settings.password.ChooseLockSettingsHelper;
71 import com.android.settings.password.ManagedLockPasswordProvider;
72 import com.android.settings.search.BaseSearchIndexProvider;
73 import com.android.settings.search.Indexable;
74 import com.android.settings.search.SearchIndexableRaw;
75 import com.android.settings.security.OwnerInfoPreferenceController;
76 import com.android.settings.security.SecurityFeatureProvider;
77 import com.android.settings.trustagent.TrustAgentManager;
78 import com.android.settings.widget.GearPreference;
79 import com.android.settingslib.RestrictedLockUtils;
80 import com.android.settingslib.RestrictedPreference;
81 import com.android.settingslib.drawer.CategoryKey;
82
83 import java.util.ArrayList;
84 import java.util.List;
85
86 /**
87  * Gesture lock pattern settings.
88  */
89 public class SecuritySettings extends SettingsPreferenceFragment
90         implements OnPreferenceChangeListener, Indexable,
91         GearPreference.OnGearClickListener {
92
93     private static final String TAG = "SecuritySettings";
94
95     private static final String TRUST_AGENT_CLICK_INTENT = "trust_agent_click_intent";
96     private static final Intent TRUST_AGENT_INTENT =
97             new Intent(TrustAgentService.SERVICE_INTERFACE);
98
99     // Lock Settings
100     private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";
101     private static final String KEY_UNLOCK_SET_OR_CHANGE_PROFILE = "unlock_set_or_change_profile";
102     private static final String KEY_VISIBLE_PATTERN_PROFILE = "visiblepattern_profile";
103     private static final String KEY_SECURITY_CATEGORY = "security_category";
104     @VisibleForTesting
105     static final String KEY_MANAGE_TRUST_AGENTS = "manage_trust_agents";
106     private static final String KEY_UNIFICATION = "unification";
107     @VisibleForTesting
108     static final String KEY_LOCKSCREEN_PREFERENCES = "lockscreen_preferences";
109     private static final String KEY_ENCRYPTION_AND_CREDENTIALS = "encryption_and_credential";
110     private static final String KEY_LOCATION_SCANNING  = "location_scanning";
111     private static final String KEY_LOCATION = "location";
112
113     private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
114     private static final int CHANGE_TRUST_AGENT_SETTINGS = 126;
115     private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST_PROFILE = 127;
116     private static final int UNIFY_LOCK_CONFIRM_DEVICE_REQUEST = 128;
117     private static final int UNIFY_LOCK_CONFIRM_PROFILE_REQUEST = 129;
118     private static final int UNUNIFY_LOCK_CONFIRM_DEVICE_REQUEST = 130;
119     private static final String TAG_UNIFICATION_DIALOG = "unification_dialog";
120
121     // Misc Settings
122     private static final String KEY_SIM_LOCK = "sim_lock_settings";
123     private static final String KEY_SHOW_PASSWORD = "show_password";
124     private static final String KEY_TRUST_AGENT = "trust_agent";
125     private static final String KEY_SCREEN_PINNING = "screen_pinning_settings";
126
127     // Security status
128     private static final String KEY_SECURITY_STATUS = "security_status";
129     private static final String SECURITY_STATUS_KEY_PREFIX = "security_status_";
130
131     // Package verifier Settings
132     @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
133     static final String KEY_PACKAGE_VERIFIER_STATUS = "security_status_package_verifier";
134     private static final int PACKAGE_VERIFIER_STATE_ENABLED = 1;
135
136     // Device management settings
137     private static final String KEY_ENTERPRISE_PRIVACY = "enterprise_privacy";
138     private static final String KEY_MANAGE_DEVICE_ADMIN = "manage_device_admin";
139
140     // These switch preferences need special handling since they're not all stored in Settings.
141     private static final String SWITCH_PREFERENCE_KEYS[] = {
142             KEY_SHOW_PASSWORD, KEY_UNIFICATION, KEY_VISIBLE_PATTERN_PROFILE
143     };
144
145     // Only allow one trust agent on the platform.
146     private static final boolean ONLY_ONE_TRUST_AGENT = true;
147
148     private static final int MY_USER_ID = UserHandle.myUserId();
149
150     private DashboardFeatureProvider mDashboardFeatureProvider;
151     private DevicePolicyManager mDPM;
152     private SecurityFeatureProvider mSecurityFeatureProvider;
153     private TrustAgentManager mTrustAgentManager;
154     private SubscriptionManager mSubscriptionManager;
155     private UserManager mUm;
156
157     private ChooseLockSettingsHelper mChooseLockSettingsHelper;
158     private LockPatternUtils mLockPatternUtils;
159     private ManagedLockPasswordProvider mManagedPasswordProvider;
160
161     private SwitchPreference mVisiblePatternProfile;
162     private SwitchPreference mUnifyProfile;
163
164     private SwitchPreference mShowPassword;
165
166     private boolean mIsAdmin;
167
168     private Intent mTrustAgentClickIntent;
169
170     private int mProfileChallengeUserId;
171
172     private String mCurrentDevicePassword;
173     private String mCurrentProfilePassword;
174
175     private LocationPreferenceController mLocationcontroller;
176     private ManageDeviceAdminPreferenceController mManageDeviceAdminPreferenceController;
177     private EnterprisePrivacyPreferenceController mEnterprisePrivacyPreferenceController;
178     private LockScreenNotificationPreferenceController mLockScreenNotificationPreferenceController;
179
180     @Override
181     public int getMetricsCategory() {
182         return MetricsEvent.SECURITY;
183     }
184
185     @Override
186     public void onAttach(Context context) {
187         super.onAttach(context);
188         mLocationcontroller = new LocationPreferenceController(context, getLifecycle());
189     }
190
191     @Override
192     public void onCreate(Bundle savedInstanceState) {
193         super.onCreate(savedInstanceState);
194
195         final Activity activity = getActivity();
196
197         mSubscriptionManager = SubscriptionManager.from(activity);
198
199         mLockPatternUtils = new LockPatternUtils(activity);
200
201         mManagedPasswordProvider = ManagedLockPasswordProvider.get(activity, MY_USER_ID);
202
203         mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
204
205         mUm = UserManager.get(activity);
206
207         mChooseLockSettingsHelper = new ChooseLockSettingsHelper(activity);
208
209         mDashboardFeatureProvider = FeatureFactory.getFactory(activity)
210                 .getDashboardFeatureProvider(activity);
211
212         mSecurityFeatureProvider = FeatureFactory.getFactory(activity).getSecurityFeatureProvider();
213
214         mTrustAgentManager = mSecurityFeatureProvider.getTrustAgentManager();
215
216         if (savedInstanceState != null
217                 && savedInstanceState.containsKey(TRUST_AGENT_CLICK_INTENT)) {
218             mTrustAgentClickIntent = savedInstanceState.getParcelable(TRUST_AGENT_CLICK_INTENT);
219         }
220
221         mManageDeviceAdminPreferenceController
222                 = new ManageDeviceAdminPreferenceController(activity);
223         mEnterprisePrivacyPreferenceController
224                 = new EnterprisePrivacyPreferenceController(activity, null /* lifecycle */);
225         mLockScreenNotificationPreferenceController
226                 = new LockScreenNotificationPreferenceController(activity);
227     }
228
229     private static int getResIdForLockUnlockScreen(Context context,
230             LockPatternUtils lockPatternUtils, ManagedLockPasswordProvider managedPasswordProvider,
231             int userId) {
232         final boolean isMyUser = userId == MY_USER_ID;
233         int resid = 0;
234         if (!lockPatternUtils.isSecure(userId)) {
235             if (!isMyUser) {
236                 resid = R.xml.security_settings_lockscreen_profile;
237             } else if (lockPatternUtils.isLockScreenDisabled(userId)) {
238                 resid = R.xml.security_settings_lockscreen;
239             } else {
240                 resid = R.xml.security_settings_chooser;
241             }
242         } else {
243             switch (lockPatternUtils.getKeyguardStoredPasswordQuality(userId)) {
244                 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
245                     resid = isMyUser ? R.xml.security_settings_pattern
246                             : R.xml.security_settings_pattern_profile;
247                     break;
248                 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
249                 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
250                     resid = isMyUser ? R.xml.security_settings_pin
251                             : R.xml.security_settings_pin_profile;
252                     break;
253                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
254                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
255                 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
256                     resid = isMyUser ? R.xml.security_settings_password
257                             : R.xml.security_settings_password_profile;
258                     break;
259                 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
260                     resid = managedPasswordProvider.getResIdForLockUnlockScreen(!isMyUser);
261                     break;
262             }
263         }
264         return resid;
265     }
266
267     /**
268      * Important!
269      *
270      * Don't forget to update the SecuritySearchIndexProvider if you are doing any change in the
271      * logic or adding/removing preferences here.
272      */
273     private PreferenceScreen createPreferenceHierarchy() {
274         PreferenceScreen root = getPreferenceScreen();
275         if (root != null) {
276             root.removeAll();
277         }
278         addPreferencesFromResource(R.xml.security_settings);
279         root = getPreferenceScreen();
280
281         // Add category for security status
282         addPreferencesFromResource(R.xml.security_settings_status);
283
284         // Add options for lock/unlock screen
285         final int resid = getResIdForLockUnlockScreen(getActivity(), mLockPatternUtils,
286                 mManagedPasswordProvider, MY_USER_ID);
287         addPreferencesFromResource(resid);
288
289         // DO or PO installed in the user may disallow to change password.
290         disableIfPasswordQualityManaged(KEY_UNLOCK_SET_OR_CHANGE, MY_USER_ID);
291
292         mProfileChallengeUserId = Utils.getManagedProfileId(mUm, MY_USER_ID);
293         if (mProfileChallengeUserId != UserHandle.USER_NULL
294                 && mLockPatternUtils.isSeparateProfileChallengeAllowed(mProfileChallengeUserId)) {
295             addPreferencesFromResource(R.xml.security_settings_profile);
296             addPreferencesFromResource(R.xml.security_settings_unification);
297             final int profileResid = getResIdForLockUnlockScreen(
298                     getActivity(), mLockPatternUtils, mManagedPasswordProvider,
299                     mProfileChallengeUserId);
300             addPreferencesFromResource(profileResid);
301             maybeAddFingerprintPreference(root, mProfileChallengeUserId);
302             if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(mProfileChallengeUserId)) {
303                 final Preference lockPreference =
304                         root.findPreference(KEY_UNLOCK_SET_OR_CHANGE_PROFILE);
305                 final String summary = getContext().getString(
306                         R.string.lock_settings_profile_unified_summary);
307                 lockPreference.setSummary(summary);
308                 lockPreference.setEnabled(false);
309                 // PO may disallow to change password for the profile, but screen lock and managed
310                 // profile's lock is the same. Disable main "Screen lock" menu.
311                 disableIfPasswordQualityManaged(KEY_UNLOCK_SET_OR_CHANGE, mProfileChallengeUserId);
312             } else {
313                 // PO may disallow to change profile password, and the profile's password is
314                 // separated from screen lock password. Disable profile specific "Screen lock" menu.
315                 disableIfPasswordQualityManaged(KEY_UNLOCK_SET_OR_CHANGE_PROFILE,
316                         mProfileChallengeUserId);
317             }
318         }
319
320         Preference unlockSetOrChange = findPreference(KEY_UNLOCK_SET_OR_CHANGE);
321         if (unlockSetOrChange instanceof GearPreference) {
322             ((GearPreference) unlockSetOrChange).setOnGearClickListener(this);
323         }
324
325         mIsAdmin = mUm.isAdminUser();
326
327         // Fingerprint and trust agents
328         int numberOfTrustAgent = 0;
329         PreferenceGroup securityCategory = (PreferenceGroup)
330                 root.findPreference(KEY_SECURITY_CATEGORY);
331         if (securityCategory != null) {
332             maybeAddFingerprintPreference(securityCategory, UserHandle.myUserId());
333             numberOfTrustAgent = addTrustAgentSettings(securityCategory);
334             setLockscreenPreferencesSummary(securityCategory);
335         }
336
337         mVisiblePatternProfile =
338                 (SwitchPreference) root.findPreference(KEY_VISIBLE_PATTERN_PROFILE);
339         mUnifyProfile = (SwitchPreference) root.findPreference(KEY_UNIFICATION);
340
341         // Append the rest of the settings
342         addPreferencesFromResource(R.xml.security_settings_misc);
343
344         // Do not display SIM lock for devices without an Icc card
345         TelephonyManager tm = TelephonyManager.getDefault();
346         CarrierConfigManager cfgMgr = (CarrierConfigManager)
347                 getActivity().getSystemService(Context.CARRIER_CONFIG_SERVICE);
348         PersistableBundle b = cfgMgr.getConfig();
349         if (!mIsAdmin || !isSimIccReady() ||
350                 b.getBoolean(CarrierConfigManager.KEY_HIDE_SIM_LOCK_SETTINGS_BOOL)) {
351             root.removePreference(root.findPreference(KEY_SIM_LOCK));
352         } else {
353             // Disable SIM lock if there is no ready SIM card.
354             root.findPreference(KEY_SIM_LOCK).setEnabled(isSimReady());
355         }
356         if (Settings.System.getInt(getContentResolver(),
357                 Settings.System.LOCK_TO_APP_ENABLED, 0) != 0) {
358             root.findPreference(KEY_SCREEN_PINNING).setSummary(
359                     getResources().getString(R.string.switch_on_text));
360         }
361
362         // Encryption status of device
363         if (LockPatternUtils.isDeviceEncryptionEnabled()) {
364             root.findPreference(KEY_ENCRYPTION_AND_CREDENTIALS).setSummary(
365                 R.string.encryption_and_credential_settings_summary);
366         } else {
367             root.findPreference(KEY_ENCRYPTION_AND_CREDENTIALS).setSummary(
368                 R.string.summary_placeholder);
369         }
370
371         // Show password
372         mShowPassword = (SwitchPreference) root.findPreference(KEY_SHOW_PASSWORD);
373
374         // Credential storage
375         final UserManager um = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
376
377         // Advanced Security features
378         initTrustAgentPreference(root, numberOfTrustAgent);
379
380         // The above preferences come and go based on security state, so we need to update
381         // the index. This call is expected to be fairly cheap, but we may want to do something
382         // smarter in the future.
383         final Activity activity = getActivity();
384         FeatureFactory.getFactory(activity).getSearchFeatureProvider().getIndexingManager(activity)
385                 .updateFromClassNameResource(SecuritySettings.class.getName(),
386                         true /* includeInSearchResults */);
387
388         PreferenceGroup securityStatusPreferenceGroup =
389                 (PreferenceGroup) root.findPreference(KEY_SECURITY_STATUS);
390         final List<Preference> tilePrefs = mDashboardFeatureProvider.getPreferencesForCategory(
391             getActivity(), getPrefContext(), getMetricsCategory(),
392             CategoryKey.CATEGORY_SECURITY);
393         int numSecurityStatusPrefs = 0;
394         if (tilePrefs != null && !tilePrefs.isEmpty()) {
395             for (Preference preference : tilePrefs) {
396                 if (!TextUtils.isEmpty(preference.getKey())
397                     && preference.getKey().startsWith(SECURITY_STATUS_KEY_PREFIX)) {
398                     // Injected security status settings are placed under the Security status
399                     // category.
400                     securityStatusPreferenceGroup.addPreference(preference);
401                     numSecurityStatusPrefs++;
402                 } else {
403                     // Other injected settings are placed under the Security preference screen.
404                     root.addPreference(preference);
405                 }
406             }
407         }
408
409         if (numSecurityStatusPrefs == 0) {
410             root.removePreference(securityStatusPreferenceGroup);
411         } else if (numSecurityStatusPrefs > 0) {
412             // Update preference data with tile data. Security feature provider only updates the
413             // data if it actually needs to be changed.
414             mSecurityFeatureProvider.updatePreferences(getActivity(), root,
415                 mDashboardFeatureProvider.getTilesForCategory(
416                     CategoryKey.CATEGORY_SECURITY));
417         }
418
419         for (int i = 0; i < SWITCH_PREFERENCE_KEYS.length; i++) {
420             final Preference pref = findPreference(SWITCH_PREFERENCE_KEYS[i]);
421             if (pref != null) pref.setOnPreferenceChangeListener(this);
422         }
423
424         mLocationcontroller.displayPreference(root);
425         mManageDeviceAdminPreferenceController.updateState(
426                 root.findPreference(KEY_MANAGE_DEVICE_ADMIN));
427         mEnterprisePrivacyPreferenceController.displayPreference(root);
428         mEnterprisePrivacyPreferenceController.onResume();
429
430         return root;
431     }
432
433     @VisibleForTesting
434     void initTrustAgentPreference(PreferenceScreen root, int numberOfTrustAgent) {
435         Preference manageAgents = root.findPreference(KEY_MANAGE_TRUST_AGENTS);
436         if (manageAgents != null) {
437             if (!mLockPatternUtils.isSecure(MY_USER_ID)) {
438                 manageAgents.setEnabled(false);
439                 manageAgents.setSummary(R.string.disabled_because_no_backup_security);
440             } else if (numberOfTrustAgent > 0) {
441                 manageAgents.setSummary(getActivity().getResources().getQuantityString(
442                     R.plurals.manage_trust_agents_summary_on,
443                     numberOfTrustAgent, numberOfTrustAgent));
444             } else {
445                 manageAgents.setSummary(R.string.manage_trust_agents_summary);
446             }
447         }
448     }
449
450     @VisibleForTesting
451     void setLockscreenPreferencesSummary(PreferenceGroup group) {
452         final Preference lockscreenPreferences = group.findPreference(KEY_LOCKSCREEN_PREFERENCES);
453         if (lockscreenPreferences != null) {
454             lockscreenPreferences.setSummary(
455                 mLockScreenNotificationPreferenceController.getSummaryResource());
456         }
457     }
458
459     /*
460      * Sets the preference as disabled by admin if PASSWORD_QUALITY_MANAGED is set.
461      * The preference must be a RestrictedPreference.
462      */
463     private void disableIfPasswordQualityManaged(String preferenceKey, int userId) {
464         final EnforcedAdmin admin = RestrictedLockUtils.checkIfPasswordQualityIsSet(
465                 getActivity(), userId);
466         if (admin != null && mDPM.getPasswordQuality(admin.component, userId) ==
467                 DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
468             final RestrictedPreference pref =
469                     (RestrictedPreference) getPreferenceScreen().findPreference(preferenceKey);
470             pref.setDisabledByAdmin(admin);
471         }
472     }
473
474     private void maybeAddFingerprintPreference(PreferenceGroup securityCategory, int userId) {
475         Preference fingerprintPreference =
476                 FingerprintSettings.getFingerprintPreferenceForUser(
477                         securityCategory.getContext(), userId);
478         if (fingerprintPreference != null) {
479             securityCategory.addPreference(fingerprintPreference);
480         }
481     }
482
483     // Return the number of trust agents being added
484     private int addTrustAgentSettings(PreferenceGroup securityCategory) {
485         final boolean hasSecurity = mLockPatternUtils.isSecure(MY_USER_ID);
486         ArrayList<TrustAgentComponentInfo> agents = getActiveTrustAgents(
487             getActivity(), mTrustAgentManager, mLockPatternUtils, mDPM);
488         for (int i = 0; i < agents.size(); i++) {
489             final TrustAgentComponentInfo agent = agents.get(i);
490             RestrictedPreference trustAgentPreference =
491                     new RestrictedPreference(securityCategory.getContext());
492             trustAgentPreference.setKey(KEY_TRUST_AGENT);
493             trustAgentPreference.setTitle(agent.title);
494             trustAgentPreference.setSummary(agent.summary);
495             // Create intent for this preference.
496             Intent intent = new Intent();
497             intent.setComponent(agent.componentName);
498             intent.setAction(Intent.ACTION_MAIN);
499             trustAgentPreference.setIntent(intent);
500             // Add preference to the settings menu.
501             securityCategory.addPreference(trustAgentPreference);
502
503             trustAgentPreference.setDisabledByAdmin(agent.admin);
504             if (!trustAgentPreference.isDisabledByAdmin() && !hasSecurity) {
505                 trustAgentPreference.setEnabled(false);
506                 trustAgentPreference.setSummary(R.string.disabled_because_no_backup_security);
507             }
508         }
509         return agents.size();
510     }
511
512     /* Return true if a there is a Slot that has Icc.
513      */
514     private boolean isSimIccReady() {
515         TelephonyManager tm = TelephonyManager.getDefault();
516         final List<SubscriptionInfo> subInfoList =
517                 mSubscriptionManager.getActiveSubscriptionInfoList();
518
519         if (subInfoList != null) {
520             for (SubscriptionInfo subInfo : subInfoList) {
521                 if (tm.hasIccCard(subInfo.getSimSlotIndex())) {
522                     return true;
523                 }
524             }
525         }
526
527         return false;
528     }
529
530     /* Return true if a SIM is ready for locking.
531      * TODO: consider adding to TelephonyManager or SubscritpionManasger.
532      */
533     private boolean isSimReady() {
534         int simState = TelephonyManager.SIM_STATE_UNKNOWN;
535         final List<SubscriptionInfo> subInfoList =
536                 mSubscriptionManager.getActiveSubscriptionInfoList();
537         if (subInfoList != null) {
538             for (SubscriptionInfo subInfo : subInfoList) {
539                 simState = TelephonyManager.getDefault().getSimState(subInfo.getSimSlotIndex());
540                 if((simState != TelephonyManager.SIM_STATE_ABSENT) &&
541                             (simState != TelephonyManager.SIM_STATE_UNKNOWN)){
542                     return true;
543                 }
544             }
545         }
546         return false;
547     }
548
549     private static ArrayList<TrustAgentComponentInfo> getActiveTrustAgents(Context context,
550         TrustAgentManager trustAgentManager, LockPatternUtils utils,
551         DevicePolicyManager dpm) {
552         PackageManager pm = context.getPackageManager();
553         ArrayList<TrustAgentComponentInfo> result = new ArrayList<TrustAgentComponentInfo>();
554         List<ResolveInfo> resolveInfos = pm.queryIntentServices(TRUST_AGENT_INTENT,
555                 PackageManager.GET_META_DATA);
556         List<ComponentName> enabledTrustAgents = utils.getEnabledTrustAgents(MY_USER_ID);
557
558         EnforcedAdmin admin = RestrictedLockUtils.checkIfKeyguardFeaturesDisabled(context,
559                 DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS, UserHandle.myUserId());
560
561         if (enabledTrustAgents != null && !enabledTrustAgents.isEmpty()) {
562             for (int i = 0; i < resolveInfos.size(); i++) {
563                 ResolveInfo resolveInfo = resolveInfos.get(i);
564                 if (resolveInfo.serviceInfo == null) continue;
565                 if (!trustAgentManager.shouldProvideTrust(resolveInfo, pm)) {
566                     continue;
567                 }
568                 TrustAgentComponentInfo trustAgentComponentInfo =
569                         TrustAgentUtils.getSettingsComponent(pm, resolveInfo);
570                 if (trustAgentComponentInfo.componentName == null ||
571                         !enabledTrustAgents.contains(
572                                 TrustAgentUtils.getComponentName(resolveInfo)) ||
573                         TextUtils.isEmpty(trustAgentComponentInfo.title)) continue;
574                 if (admin != null && dpm.getTrustAgentConfiguration(
575                         null, TrustAgentUtils.getComponentName(resolveInfo)) == null) {
576                     trustAgentComponentInfo.admin = admin;
577                 }
578                 result.add(trustAgentComponentInfo);
579                 if (ONLY_ONE_TRUST_AGENT) break;
580             }
581         }
582         return result;
583     }
584
585     private static CharSequence getActiveTrustAgentLabel(Context context,
586             TrustAgentManager trustAgentManager, LockPatternUtils utils,
587             DevicePolicyManager dpm) {
588         ArrayList<TrustAgentComponentInfo> agents = getActiveTrustAgents(context,
589                 trustAgentManager, utils, dpm);
590         return agents.isEmpty() ? null : agents.get(0).title;
591     }
592
593     @Override
594     public void onGearClick(GearPreference p) {
595         if (KEY_UNLOCK_SET_OR_CHANGE.equals(p.getKey())) {
596             startFragment(this, SecuritySubSettings.class.getName(), 0, 0, null);
597         }
598     }
599
600     @Override
601     public void onSaveInstanceState(Bundle outState) {
602         super.onSaveInstanceState(outState);
603         if (mTrustAgentClickIntent != null) {
604             outState.putParcelable(TRUST_AGENT_CLICK_INTENT, mTrustAgentClickIntent);
605         }
606     }
607
608     @Override
609     public void onResume() {
610         super.onResume();
611
612         // Make sure we reload the preference hierarchy since some of these settings
613         // depend on others...
614         createPreferenceHierarchy();
615
616         if (mVisiblePatternProfile != null) {
617             mVisiblePatternProfile.setChecked(mLockPatternUtils.isVisiblePatternEnabled(
618                     mProfileChallengeUserId));
619         }
620
621         updateUnificationPreference();
622
623         if (mShowPassword != null) {
624             mShowPassword.setChecked(Settings.System.getInt(getContentResolver(),
625                     Settings.System.TEXT_SHOW_PASSWORD, 1) != 0);
626         }
627
628         mLocationcontroller.updateSummary();
629     }
630
631     private void updateUnificationPreference() {
632         if (mUnifyProfile != null) {
633             mUnifyProfile.setChecked(!mLockPatternUtils.isSeparateProfileChallengeEnabled(
634                     mProfileChallengeUserId));
635         }
636     }
637
638     @Override
639     public boolean onPreferenceTreeClick(Preference preference) {
640         final String key = preference.getKey();
641         if (KEY_UNLOCK_SET_OR_CHANGE.equals(key)) {
642             // TODO(b/35930129): Remove once existing password can be passed into vold directly.
643             // Currently we need this logic to ensure that the QUIET_MODE is off for any work
644             // profile with unified challenge on FBE-enabled devices. Otherwise, vold would not be
645             // able to complete the operation due to the lack of (old) encryption key.
646             if (mProfileChallengeUserId != UserHandle.USER_NULL
647                     && !mLockPatternUtils.isSeparateProfileChallengeEnabled(mProfileChallengeUserId)
648                     && StorageManager.isFileEncryptedNativeOnly()) {
649                 if (Utils.startQuietModeDialogIfNecessary(this.getActivity(), mUm,
650                         mProfileChallengeUserId)) {
651                     return false;
652                 }
653             }
654             startFragment(this, ChooseLockGenericFragment.class.getName(),
655                     R.string.lock_settings_picker_title, SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
656         } else if (KEY_UNLOCK_SET_OR_CHANGE_PROFILE.equals(key)) {
657             if (Utils.startQuietModeDialogIfNecessary(this.getActivity(), mUm,
658                     mProfileChallengeUserId)) {
659                 return false;
660             }
661             Bundle extras = new Bundle();
662             extras.putInt(Intent.EXTRA_USER_ID, mProfileChallengeUserId);
663             startFragment(this, ChooseLockGenericFragment.class.getName(),
664                     R.string.lock_settings_picker_title_profile,
665                     SET_OR_CHANGE_LOCK_METHOD_REQUEST_PROFILE, extras);
666         } else if (KEY_TRUST_AGENT.equals(key)) {
667             ChooseLockSettingsHelper helper =
668                     new ChooseLockSettingsHelper(this.getActivity(), this);
669             mTrustAgentClickIntent = preference.getIntent();
670             boolean confirmationLaunched = helper.launchConfirmationActivity(
671                     CHANGE_TRUST_AGENT_SETTINGS, preference.getTitle());
672             if (!confirmationLaunched&&  mTrustAgentClickIntent != null) {
673                 // If this returns false, it means no password confirmation is required.
674                 startActivity(mTrustAgentClickIntent);
675                 mTrustAgentClickIntent = null;
676             }
677         } else {
678             // If we didn't handle it, let preferences handle it.
679             return super.onPreferenceTreeClick(preference);
680         }
681         return true;
682     }
683
684     /**
685      * see confirmPatternThenDisableAndClear
686      */
687     @Override
688     public void onActivityResult(int requestCode, int resultCode, Intent data) {
689         super.onActivityResult(requestCode, resultCode, data);
690         if (requestCode == CHANGE_TRUST_AGENT_SETTINGS && resultCode == Activity.RESULT_OK) {
691             if (mTrustAgentClickIntent != null) {
692                 startActivity(mTrustAgentClickIntent);
693                 mTrustAgentClickIntent = null;
694             }
695             return;
696         } else if (requestCode == UNIFY_LOCK_CONFIRM_DEVICE_REQUEST
697                 && resultCode == Activity.RESULT_OK) {
698             mCurrentDevicePassword =
699                     data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD);
700             launchConfirmProfileLockForUnification();
701             return;
702         } else if (requestCode == UNIFY_LOCK_CONFIRM_PROFILE_REQUEST
703                 && resultCode == Activity.RESULT_OK) {
704             mCurrentProfilePassword =
705                     data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD);
706             unifyLocks();
707             return;
708         } else if (requestCode == UNUNIFY_LOCK_CONFIRM_DEVICE_REQUEST
709                 && resultCode == Activity.RESULT_OK) {
710             ununifyLocks();
711             return;
712         }
713         createPreferenceHierarchy();
714     }
715
716     private void launchConfirmDeviceLockForUnification() {
717         final String title = getActivity().getString(
718                 R.string.unlock_set_unlock_launch_picker_title);
719         final ChooseLockSettingsHelper helper =
720                 new ChooseLockSettingsHelper(getActivity(), this);
721         if (!helper.launchConfirmationActivity(
722                 UNIFY_LOCK_CONFIRM_DEVICE_REQUEST, title, true, MY_USER_ID)) {
723             launchConfirmProfileLockForUnification();
724         }
725     }
726
727     private void launchConfirmProfileLockForUnification() {
728         final String title = getActivity().getString(
729                 R.string.unlock_set_unlock_launch_picker_title_profile);
730         final ChooseLockSettingsHelper helper =
731                 new ChooseLockSettingsHelper(getActivity(), this);
732         if (!helper.launchConfirmationActivity(
733                 UNIFY_LOCK_CONFIRM_PROFILE_REQUEST, title, true, mProfileChallengeUserId)) {
734             unifyLocks();
735             createPreferenceHierarchy();
736         }
737     }
738
739     private void unifyLocks() {
740         int profileQuality =
741                 mLockPatternUtils.getKeyguardStoredPasswordQuality(mProfileChallengeUserId);
742         if (profileQuality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
743             mLockPatternUtils.saveLockPattern(
744                     LockPatternUtils.stringToPattern(mCurrentProfilePassword),
745                     mCurrentDevicePassword, MY_USER_ID);
746         } else {
747             mLockPatternUtils.saveLockPassword(
748                     mCurrentProfilePassword, mCurrentDevicePassword,
749                     profileQuality, MY_USER_ID);
750         }
751         mLockPatternUtils.setSeparateProfileChallengeEnabled(mProfileChallengeUserId, false,
752                 mCurrentProfilePassword);
753         final boolean profilePatternVisibility =
754                 mLockPatternUtils.isVisiblePatternEnabled(mProfileChallengeUserId);
755         mLockPatternUtils.setVisiblePatternEnabled(profilePatternVisibility, MY_USER_ID);
756         mCurrentDevicePassword = null;
757         mCurrentProfilePassword = null;
758     }
759
760     private void unifyUncompliantLocks() {
761         mLockPatternUtils.setSeparateProfileChallengeEnabled(mProfileChallengeUserId, false,
762                 mCurrentProfilePassword);
763         startFragment(this, ChooseLockGenericFragment.class.getName(),
764                 R.string.lock_settings_picker_title, SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
765     }
766
767     private void ununifyLocks() {
768         Bundle extras = new Bundle();
769         extras.putInt(Intent.EXTRA_USER_ID, mProfileChallengeUserId);
770         startFragment(this,
771                 ChooseLockGenericFragment.class.getName(),
772                 R.string.lock_settings_picker_title_profile,
773                 SET_OR_CHANGE_LOCK_METHOD_REQUEST_PROFILE, extras);
774     }
775
776     @Override
777     public boolean onPreferenceChange(Preference preference, Object value) {
778         boolean result = true;
779         final String key = preference.getKey();
780         final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
781         if (KEY_VISIBLE_PATTERN_PROFILE.equals(key)) {
782             if (Utils.startQuietModeDialogIfNecessary(this.getActivity(), mUm,
783                     mProfileChallengeUserId)) {
784                 return false;
785             }
786             lockPatternUtils.setVisiblePatternEnabled((Boolean) value, mProfileChallengeUserId);
787         } else if (KEY_UNIFICATION.equals(key)) {
788             if (Utils.startQuietModeDialogIfNecessary(this.getActivity(), mUm,
789                     mProfileChallengeUserId)) {
790                 return false;
791             }
792             if ((Boolean) value) {
793                 final boolean compliantForDevice =
794                         (mLockPatternUtils.getKeyguardStoredPasswordQuality(mProfileChallengeUserId)
795                                 >= DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
796                         && mLockPatternUtils.isSeparateProfileChallengeAllowedToUnify(
797                                 mProfileChallengeUserId));
798                 UnificationConfirmationDialog dialog =
799                         UnificationConfirmationDialog.newIntance(compliantForDevice);
800                 dialog.show(getChildFragmentManager(), TAG_UNIFICATION_DIALOG);
801             } else {
802                 final String title = getActivity().getString(
803                         R.string.unlock_set_unlock_launch_picker_title);
804                 final ChooseLockSettingsHelper helper =
805                         new ChooseLockSettingsHelper(getActivity(), this);
806                 if(!helper.launchConfirmationActivity(
807                         UNUNIFY_LOCK_CONFIRM_DEVICE_REQUEST, title, true, MY_USER_ID)) {
808                     ununifyLocks();
809                 }
810             }
811         } else if (KEY_SHOW_PASSWORD.equals(key)) {
812             Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
813                     ((Boolean) value) ? 1 : 0);
814             lockPatternUtils.setVisiblePasswordEnabled((Boolean) value, MY_USER_ID);
815         }
816         return result;
817     }
818
819     @Override
820     protected int getHelpResource() {
821         return R.string.help_url_security;
822     }
823
824     /**
825      * For Search. Please keep it in sync when updating "createPreferenceHierarchy()"
826      */
827     public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
828             new SecuritySearchIndexProvider();
829
830     private static class SecuritySearchIndexProvider extends BaseSearchIndexProvider {
831
832         @Override
833         public List<SearchIndexableResource> getXmlResourcesToIndex(
834                 Context context, boolean enabled) {
835             final List<SearchIndexableResource> index = new ArrayList<SearchIndexableResource>();
836
837             final LockPatternUtils lockPatternUtils = new LockPatternUtils(context);
838             final ManagedLockPasswordProvider managedPasswordProvider =
839                     ManagedLockPasswordProvider.get(context, MY_USER_ID);
840             final DevicePolicyManager dpm = (DevicePolicyManager)
841                     context.getSystemService(Context.DEVICE_POLICY_SERVICE);
842             final UserManager um = UserManager.get(context);
843             final int profileUserId = Utils.getManagedProfileId(um, MY_USER_ID);
844
845             // To add option for unlock screen, user's password must not be managed and
846             // must not be unified with managed profile, whose password is managed.
847             if (!isPasswordManaged(MY_USER_ID, context, dpm)
848                     && (profileUserId == UserHandle.USER_NULL
849                             || lockPatternUtils.isSeparateProfileChallengeAllowed(profileUserId)
850                             || !isPasswordManaged(profileUserId, context, dpm))) {
851                 // Add options for lock/unlock screen
852                 final int resId = getResIdForLockUnlockScreen(context, lockPatternUtils,
853                         managedPasswordProvider, MY_USER_ID);
854                 index.add(getSearchResource(context, resId));
855             }
856
857             if (profileUserId != UserHandle.USER_NULL
858                     && lockPatternUtils.isSeparateProfileChallengeAllowed(profileUserId)
859                     && !isPasswordManaged(profileUserId, context, dpm)) {
860                 index.add(getSearchResource(context, getResIdForLockUnlockScreen(context,
861                         lockPatternUtils, managedPasswordProvider, profileUserId)));
862             }
863
864             final SearchIndexableResource sir = getSearchResource(context,
865                     SecuritySubSettings.getResIdForLockUnlockSubScreen(context, lockPatternUtils,
866                             managedPasswordProvider));
867             sir.className = SecuritySubSettings.class.getName();
868             index.add(sir);
869
870             // Append the rest of the settings
871             index.add(getSearchResource(context, R.xml.security_settings_misc));
872
873             return index;
874         }
875
876         private SearchIndexableResource getSearchResource(Context context, int xmlResId) {
877             final SearchIndexableResource sir = new SearchIndexableResource(context);
878             sir.xmlResId = xmlResId;
879             return sir;
880         }
881
882         private boolean isPasswordManaged(int userId, Context context, DevicePolicyManager dpm) {
883             final EnforcedAdmin admin = RestrictedLockUtils.checkIfPasswordQualityIsSet(
884                     context, userId);
885             return admin != null && dpm.getPasswordQuality(admin.component, userId) ==
886                     DevicePolicyManager.PASSWORD_QUALITY_MANAGED;
887         }
888
889         @Override
890         public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) {
891             final List<SearchIndexableRaw> result = new ArrayList<SearchIndexableRaw>();
892             final Resources res = context.getResources();
893
894             final String screenTitle = res.getString(R.string.security_settings_title);
895
896             SearchIndexableRaw data = new SearchIndexableRaw(context);
897             data.title = screenTitle;
898             data.screenTitle = screenTitle;
899             result.add(data);
900
901             final UserManager um = UserManager.get(context);
902
903             // Fingerprint
904             final FingerprintManager fpm = Utils.getFingerprintManagerOrNull(context);
905             if (fpm != null && fpm.isHardwareDetected()) {
906                 // This catches the title which can be overloaded in an overlay
907                 data = new SearchIndexableRaw(context);
908                 data.title = res.getString(R.string.security_settings_fingerprint_preference_title);
909                 data.screenTitle = screenTitle;
910                 result.add(data);
911                 // Fallback for when the above doesn't contain "fingerprint"
912                 data = new SearchIndexableRaw(context);
913                 data.title = res.getString(R.string.fingerprint_manage_category_title);
914                 data.screenTitle = screenTitle;
915                 result.add(data);
916             }
917
918             final LockPatternUtils lockPatternUtils = new LockPatternUtils(context);
919             final int profileUserId = Utils.getManagedProfileId(um, MY_USER_ID);
920             if (profileUserId != UserHandle.USER_NULL
921                     && lockPatternUtils.isSeparateProfileChallengeAllowed(profileUserId)) {
922                 if (lockPatternUtils.getKeyguardStoredPasswordQuality(profileUserId)
923                         >= DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
924                         && lockPatternUtils.isSeparateProfileChallengeAllowedToUnify(
925                                 profileUserId)) {
926                     data = new SearchIndexableRaw(context);
927                     data.title = res.getString(R.string.lock_settings_profile_unification_title);
928                     data.screenTitle = screenTitle;
929                     result.add(data);
930                 }
931             }
932
933             // Advanced
934             if (lockPatternUtils.isSecure(MY_USER_ID)) {
935                 final TrustAgentManager trustAgentManager =
936                     FeatureFactory.getFactory(context).getSecurityFeatureProvider()
937                         .getTrustAgentManager();
938                 final List<TrustAgentComponentInfo> agents =
939                         getActiveTrustAgents(context, trustAgentManager, lockPatternUtils,
940                                 context.getSystemService(DevicePolicyManager.class));
941                 for (int i = 0; i < agents.size(); i++) {
942                     final TrustAgentComponentInfo agent = agents.get(i);
943                     data = new SearchIndexableRaw(context);
944                     data.title = agent.title;
945                     data.screenTitle = screenTitle;
946                     result.add(data);
947                 }
948             }
949             return result;
950         }
951
952         @Override
953         public List<String> getNonIndexableKeys(Context context) {
954             final List<String> keys = super.getNonIndexableKeys(context);
955
956             LockPatternUtils lockPatternUtils = new LockPatternUtils(context);
957
958             // Do not display SIM lock for devices without an Icc card
959             final UserManager um = UserManager.get(context);
960             final TelephonyManager tm = TelephonyManager.from(context);
961             if (!um.isAdminUser() || !tm.hasIccCard()) {
962                 keys.add(KEY_SIM_LOCK);
963             }
964
965             // TrustAgent settings disappear when the user has no primary security.
966             if (!lockPatternUtils.isSecure(MY_USER_ID)) {
967                 keys.add(KEY_TRUST_AGENT);
968                 keys.add(KEY_MANAGE_TRUST_AGENTS);
969             }
970
971             if (!(new EnterprisePrivacyPreferenceController(context, null /* lifecycle */))
972                     .isAvailable()) {
973                 keys.add(KEY_ENTERPRISE_PRIVACY);
974             }
975
976             // Duplicate in special app access
977             keys.add(KEY_MANAGE_DEVICE_ADMIN);
978             // Duplicates between parent-child
979             keys.add(KEY_LOCATION);
980             keys.add(KEY_ENCRYPTION_AND_CREDENTIALS);
981             keys.add(KEY_SCREEN_PINNING);
982             keys.add(KEY_LOCATION_SCANNING);
983
984             return keys;
985         }
986     }
987
988     public static class SecuritySubSettings extends SettingsPreferenceFragment
989             implements OnPreferenceChangeListener, OwnerInfoPreferenceController.OwnerInfoCallback {
990
991         private static final String KEY_VISIBLE_PATTERN = "visiblepattern";
992         private static final String KEY_LOCK_AFTER_TIMEOUT = "lock_after_timeout";
993         private static final String KEY_POWER_INSTANTLY_LOCKS = "power_button_instantly_locks";
994
995         // These switch preferences need special handling since they're not all stored in Settings.
996         private static final String SWITCH_PREFERENCE_KEYS[] = { KEY_LOCK_AFTER_TIMEOUT,
997                 KEY_VISIBLE_PATTERN, KEY_POWER_INSTANTLY_LOCKS };
998
999         private TimeoutListPreference mLockAfter;
1000         private SwitchPreference mVisiblePattern;
1001         private SwitchPreference mPowerButtonInstantlyLocks;
1002
1003         private TrustAgentManager mTrustAgentManager;
1004         private LockPatternUtils mLockPatternUtils;
1005         private DevicePolicyManager mDPM;
1006         private OwnerInfoPreferenceController mOwnerInfoPreferenceController;
1007
1008         @Override
1009         public int getMetricsCategory() {
1010             return MetricsEvent.SECURITY;
1011         }
1012
1013         @Override
1014         public void onCreate(Bundle icicle) {
1015             super.onCreate(icicle);
1016             SecurityFeatureProvider securityFeatureProvider =
1017                     FeatureFactory.getFactory(getActivity()).getSecurityFeatureProvider();
1018             mTrustAgentManager = securityFeatureProvider.getTrustAgentManager();
1019             mLockPatternUtils = new LockPatternUtils(getContext());
1020             mDPM = getContext().getSystemService(DevicePolicyManager.class);
1021             mOwnerInfoPreferenceController =
1022                 new OwnerInfoPreferenceController(getContext(), this, null /* lifecycle */);
1023             createPreferenceHierarchy();
1024         }
1025
1026         @Override
1027         public void onResume() {
1028             super.onResume();
1029
1030             createPreferenceHierarchy();
1031
1032             if (mVisiblePattern != null) {
1033                 mVisiblePattern.setChecked(mLockPatternUtils.isVisiblePatternEnabled(
1034                         MY_USER_ID));
1035             }
1036             if (mPowerButtonInstantlyLocks != null) {
1037                 mPowerButtonInstantlyLocks.setChecked(
1038                         mLockPatternUtils.getPowerButtonInstantlyLocks(MY_USER_ID));
1039             }
1040
1041             mOwnerInfoPreferenceController.updateSummary();
1042         }
1043
1044         @Override
1045         public void onActivityResult(int requestCode, int resultCode, Intent data) {
1046             super.onActivityResult(requestCode, resultCode, data);
1047
1048             createPreferenceHierarchy();
1049         }
1050
1051         private void createPreferenceHierarchy() {
1052             PreferenceScreen root = getPreferenceScreen();
1053             if (root != null) {
1054                 root.removeAll();
1055             }
1056
1057             final int resid = getResIdForLockUnlockSubScreen(getActivity(),
1058                     new LockPatternUtils(getContext()),
1059                     ManagedLockPasswordProvider.get(getContext(), MY_USER_ID));
1060             addPreferencesFromResource(resid);
1061
1062             // lock after preference
1063             mLockAfter = (TimeoutListPreference) findPreference(KEY_LOCK_AFTER_TIMEOUT);
1064             if (mLockAfter != null) {
1065                 setupLockAfterPreference();
1066                 updateLockAfterPreferenceSummary();
1067             }
1068
1069             // visible pattern
1070             mVisiblePattern = (SwitchPreference) findPreference(KEY_VISIBLE_PATTERN);
1071
1072             // lock instantly on power key press
1073             mPowerButtonInstantlyLocks = (SwitchPreference) findPreference(
1074                     KEY_POWER_INSTANTLY_LOCKS);
1075             CharSequence trustAgentLabel = getActiveTrustAgentLabel(getContext(),
1076                     mTrustAgentManager, mLockPatternUtils, mDPM);
1077             if (mPowerButtonInstantlyLocks != null && !TextUtils.isEmpty(trustAgentLabel)) {
1078                 mPowerButtonInstantlyLocks.setSummary(getString(
1079                         R.string.lockpattern_settings_power_button_instantly_locks_summary,
1080                         trustAgentLabel));
1081             }
1082
1083             mOwnerInfoPreferenceController.displayPreference(getPreferenceScreen());
1084             mOwnerInfoPreferenceController.updateEnableState();
1085
1086             for (int i = 0; i < SWITCH_PREFERENCE_KEYS.length; i++) {
1087                 final Preference pref = findPreference(SWITCH_PREFERENCE_KEYS[i]);
1088                 if (pref != null) pref.setOnPreferenceChangeListener(this);
1089             }
1090         }
1091
1092         private void setupLockAfterPreference() {
1093             // Compatible with pre-Froyo
1094             long currentTimeout = Settings.Secure.getLong(getContentResolver(),
1095                     Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
1096             mLockAfter.setValue(String.valueOf(currentTimeout));
1097             mLockAfter.setOnPreferenceChangeListener(this);
1098             if (mDPM != null) {
1099                 final EnforcedAdmin admin = RestrictedLockUtils.checkIfMaximumTimeToLockIsSet(
1100                         getActivity());
1101                 final long adminTimeout = mDPM
1102                         .getMaximumTimeToLockForUserAndProfiles(UserHandle.myUserId());
1103                 final long displayTimeout = Math.max(0,
1104                         Settings.System.getInt(getContentResolver(), SCREEN_OFF_TIMEOUT, 0));
1105                 // This setting is a slave to display timeout when a device policy is enforced.
1106                 // As such, maxLockTimeout = adminTimeout - displayTimeout.
1107                 // If there isn't enough time, shows "immediately" setting.
1108                 final long maxTimeout = Math.max(0, adminTimeout - displayTimeout);
1109                 mLockAfter.removeUnusableTimeouts(maxTimeout, admin);
1110             }
1111         }
1112
1113         private void updateLockAfterPreferenceSummary() {
1114             final String summary;
1115             if (mLockAfter.isDisabledByAdmin()) {
1116                 summary = getString(R.string.disabled_by_policy_title);
1117             } else {
1118                 // Update summary message with current value
1119                 long currentTimeout = Settings.Secure.getLong(getContentResolver(),
1120                         Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
1121                 final CharSequence[] entries = mLockAfter.getEntries();
1122                 final CharSequence[] values = mLockAfter.getEntryValues();
1123                 int best = 0;
1124                 for (int i = 0; i < values.length; i++) {
1125                     long timeout = Long.valueOf(values[i].toString());
1126                     if (currentTimeout >= timeout) {
1127                         best = i;
1128                     }
1129                 }
1130
1131                 CharSequence trustAgentLabel = getActiveTrustAgentLabel(getContext(),
1132                         mTrustAgentManager, mLockPatternUtils, mDPM);
1133                 if (!TextUtils.isEmpty(trustAgentLabel)) {
1134                     if (Long.valueOf(values[best].toString()) == 0) {
1135                         summary = getString(R.string.lock_immediately_summary_with_exception,
1136                                 trustAgentLabel);
1137                     } else {
1138                         summary = getString(R.string.lock_after_timeout_summary_with_exception,
1139                                 entries[best], trustAgentLabel);
1140                     }
1141                 } else {
1142                     summary = getString(R.string.lock_after_timeout_summary, entries[best]);
1143                 }
1144             }
1145             mLockAfter.setSummary(summary);
1146         }
1147
1148         @Override
1149         public void onOwnerInfoUpdated() {
1150             mOwnerInfoPreferenceController.updateSummary();
1151         }
1152
1153         private static int getResIdForLockUnlockSubScreen(Context context,
1154                 LockPatternUtils lockPatternUtils,
1155                 ManagedLockPasswordProvider managedPasswordProvider) {
1156             if (lockPatternUtils.isSecure(MY_USER_ID)) {
1157                 switch (lockPatternUtils.getKeyguardStoredPasswordQuality(MY_USER_ID)) {
1158                     case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
1159                         return R.xml.security_settings_pattern_sub;
1160                     case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
1161                     case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
1162                         return R.xml.security_settings_pin_sub;
1163                     case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
1164                     case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
1165                     case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
1166                         return R.xml.security_settings_password_sub;
1167                     case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
1168                         return managedPasswordProvider.getResIdForLockUnlockSubScreen();
1169                 }
1170             } else if (!lockPatternUtils.isLockScreenDisabled(MY_USER_ID)) {
1171                 return R.xml.security_settings_slide_sub;
1172             }
1173             return 0;
1174         }
1175
1176         @Override
1177         public boolean onPreferenceChange(Preference preference, Object value) {
1178             String key = preference.getKey();
1179             if (KEY_POWER_INSTANTLY_LOCKS.equals(key)) {
1180                 mLockPatternUtils.setPowerButtonInstantlyLocks((Boolean) value, MY_USER_ID);
1181             } else if (KEY_LOCK_AFTER_TIMEOUT.equals(key)) {
1182                 int timeout = Integer.parseInt((String) value);
1183                 try {
1184                     Settings.Secure.putInt(getContentResolver(),
1185                             Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, timeout);
1186                 } catch (NumberFormatException e) {
1187                     Log.e("SecuritySettings", "could not persist lockAfter timeout setting", e);
1188                 }
1189                 setupLockAfterPreference();
1190                 updateLockAfterPreferenceSummary();
1191             } else if (KEY_VISIBLE_PATTERN.equals(key)) {
1192                 mLockPatternUtils.setVisiblePatternEnabled((Boolean) value, MY_USER_ID);
1193             }
1194             return true;
1195         }
1196     }
1197
1198     public static class UnificationConfirmationDialog extends InstrumentedDialogFragment {
1199         private static final String EXTRA_COMPLIANT = "compliant";
1200
1201         public static UnificationConfirmationDialog newIntance(boolean compliant) {
1202             UnificationConfirmationDialog dialog = new UnificationConfirmationDialog();
1203             Bundle args = new Bundle();
1204             args.putBoolean(EXTRA_COMPLIANT, compliant);
1205             dialog.setArguments(args);
1206             return dialog;
1207         }
1208
1209         @Override
1210         public void show(FragmentManager manager, String tag) {
1211             if (manager.findFragmentByTag(tag) == null) {
1212                 // Prevent opening multiple dialogs if tapped on button quickly
1213                 super.show(manager, tag);
1214             }
1215         }
1216
1217         @Override
1218         public Dialog onCreateDialog(Bundle savedInstanceState) {
1219             final SecuritySettings parentFragment = ((SecuritySettings) getParentFragment());
1220             final boolean compliant = getArguments().getBoolean(EXTRA_COMPLIANT);
1221             return new AlertDialog.Builder(getActivity())
1222                     .setTitle(R.string.lock_settings_profile_unification_dialog_title)
1223                     .setMessage(compliant ? R.string.lock_settings_profile_unification_dialog_body
1224                             : R.string.lock_settings_profile_unification_dialog_uncompliant_body)
1225                     .setPositiveButton(
1226                             compliant ? R.string.lock_settings_profile_unification_dialog_confirm
1227                             : R.string.lock_settings_profile_unification_dialog_uncompliant_confirm,
1228                             new DialogInterface.OnClickListener() {
1229                                 @Override
1230                                 public void onClick(DialogInterface dialog, int whichButton) {
1231                                     if (compliant) {
1232                                         parentFragment.launchConfirmDeviceLockForUnification();
1233                                     }    else {
1234                                         parentFragment.unifyUncompliantLocks();
1235                                     }
1236                                 }
1237                             }
1238                     )
1239                     .setNegativeButton(R.string.cancel, null)
1240                     .create();
1241         }
1242
1243         @Override
1244         public void onDismiss(DialogInterface dialog) {
1245             super.onDismiss(dialog);
1246             ((SecuritySettings) getParentFragment()).updateUnificationPreference();
1247         }
1248
1249         @Override
1250         public int getMetricsCategory() {
1251             return MetricsEvent.DIALOG_UNIFICATION_CONFIRMATION;
1252         }
1253     }
1254
1255     static class SummaryProvider implements SummaryLoader.SummaryProvider {
1256
1257         private final Context mContext;
1258         private final SummaryLoader mSummaryLoader;
1259
1260         public SummaryProvider(Context context, SummaryLoader summaryLoader) {
1261             mContext = context;
1262             mSummaryLoader = summaryLoader;
1263         }
1264
1265         @Override
1266         public void setListening(boolean listening) {
1267             if (listening) {
1268                 final FingerprintManager fpm =
1269                     Utils.getFingerprintManagerOrNull(mContext);
1270                 if (fpm != null && fpm.isHardwareDetected()) {
1271                     mSummaryLoader.setSummary(this,
1272                         mContext.getString(R.string.security_dashboard_summary));
1273                 } else {
1274                     mSummaryLoader.setSummary(this, mContext.getString(
1275                         R.string.security_dashboard_summary_no_fingerprint));
1276                 }
1277             }
1278         }
1279     }
1280
1281     public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY =
1282             new SummaryLoader.SummaryProviderFactory() {
1283         @Override
1284         public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
1285                 SummaryLoader summaryLoader) {
1286             return new SummaryProvider(activity, summaryLoader);
1287         }
1288     };
1289
1290 }