OSDN Git Service

Merge "calling back SetupFaceLock to clean up temporary gallery"
[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
20 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
21
22 import android.app.AlertDialog;
23 import android.app.admin.DevicePolicyManager;
24 import android.content.Context;
25 import android.content.DialogInterface;
26 import android.content.Intent;
27 import android.os.Bundle;
28 import android.os.Vibrator;
29 import android.preference.CheckBoxPreference;
30 import android.preference.ListPreference;
31 import android.preference.Preference;
32 import android.preference.Preference.OnPreferenceChangeListener;
33 import android.preference.PreferenceGroup;
34 import android.preference.PreferenceScreen;
35 import android.provider.Settings;
36 import android.security.KeyStore;
37 import android.telephony.TelephonyManager;
38 import android.util.Log;
39
40 import com.android.internal.telephony.Phone;
41 import com.android.internal.widget.LockPatternUtils;
42
43 import java.util.ArrayList;
44
45 /**
46  * Gesture lock pattern settings.
47  */
48 public class SecuritySettings extends SettingsPreferenceFragment
49         implements OnPreferenceChangeListener, DialogInterface.OnClickListener {
50
51     // Lock Settings
52     private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";
53     private static final String KEY_LOCK_ENABLED = "lockenabled";
54     private static final String KEY_VISIBLE_PATTERN = "visiblepattern";
55     private static final String KEY_TACTILE_FEEDBACK_ENABLED = "unlock_tactile_feedback";
56     private static final String KEY_SECURITY_CATEGORY = "security_category";
57     private static final String KEY_LOCK_AFTER_TIMEOUT = "lock_after_timeout";
58     private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
59
60     // Misc Settings
61     private static final String KEY_SIM_LOCK = "sim_lock";
62     private static final String KEY_SHOW_PASSWORD = "show_password";
63     private static final String KEY_RESET_CREDENTIALS = "reset_credentials";
64     private static final String KEY_TOGGLE_INSTALL_APPLICATIONS = "toggle_install_applications";
65
66     DevicePolicyManager mDPM;
67
68     private ChooseLockSettingsHelper mChooseLockSettingsHelper;
69     private LockPatternUtils mLockPatternUtils;
70     private ListPreference mLockAfter;
71
72     private CheckBoxPreference mVisiblePattern;
73     private CheckBoxPreference mTactileFeedback;
74
75     private CheckBoxPreference mShowPassword;
76
77     private Preference mResetCredentials;
78
79     private CheckBoxPreference mToggleAppInstallation;
80     private DialogInterface mWarnInstallApps;
81
82     @Override
83     public void onCreate(Bundle savedInstanceState) {
84         super.onCreate(savedInstanceState);
85
86         mLockPatternUtils = new LockPatternUtils(getActivity());
87
88         mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
89
90         mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity());
91     }
92
93     private PreferenceScreen createPreferenceHierarchy() {
94         PreferenceScreen root = getPreferenceScreen();
95         if (root != null) {
96             root.removeAll();
97         }
98         addPreferencesFromResource(R.xml.security_settings);
99         root = getPreferenceScreen();
100
101         // Add options for lock/unlock screen
102         int resid = 0;
103         if (!mLockPatternUtils.isSecure()) {
104             if (mLockPatternUtils.isLockScreenDisabled()) {
105                 resid = R.xml.security_settings_lockscreen;
106             } else {
107                 resid = R.xml.security_settings_chooser;
108             }
109         } else if (mLockPatternUtils.usingBiometricWeak()) {
110             resid = R.xml.security_settings_biometric_weak;
111         } else {
112             switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
113                 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
114                     resid = R.xml.security_settings_pattern;
115                     break;
116                 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
117                     resid = R.xml.security_settings_pin;
118                     break;
119                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
120                 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
121                 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
122                     resid = R.xml.security_settings_password;
123                     break;
124             }
125             // TODO: enable facepass options
126         }
127         addPreferencesFromResource(resid);
128
129
130         // Add options for device encryption
131         DevicePolicyManager dpm =
132                 (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
133
134         switch (dpm.getStorageEncryptionStatus()) {
135         case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
136             // The device is currently encrypted.
137             addPreferencesFromResource(R.xml.security_settings_encrypted);
138             break;
139         case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
140             // This device supports encryption but isn't encrypted.
141             addPreferencesFromResource(R.xml.security_settings_unencrypted);
142             break;
143         }
144
145         // lock after preference
146         mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
147         if (mLockAfter != null) {
148             setupLockAfterPreference();
149             updateLockAfterPreferenceSummary();
150         }
151
152         // visible pattern
153         mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
154
155         // tactile feedback. Should be common to all unlock preference screens.
156         mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
157         if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
158             PreferenceGroup securityCategory = (PreferenceGroup)
159                     root.findPreference(KEY_SECURITY_CATEGORY);
160             if (securityCategory != null && mTactileFeedback != null) {
161                 securityCategory.removePreference(mTactileFeedback);
162             }
163         }
164
165         // Append the rest of the settings
166         addPreferencesFromResource(R.xml.security_settings_misc);
167
168         // Do not display SIM lock for CDMA phone
169         TelephonyManager tm = TelephonyManager.getDefault();
170         if ((TelephonyManager.PHONE_TYPE_CDMA == tm.getCurrentPhoneType()) &&
171                 (tm.getLteOnCdmaMode() != Phone.LTE_ON_CDMA_TRUE)) {
172             root.removePreference(root.findPreference(KEY_SIM_LOCK));
173         }
174
175         // Show password
176         mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
177
178         // Credential storage
179         mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
180
181         mToggleAppInstallation = (CheckBoxPreference) findPreference(
182                 KEY_TOGGLE_INSTALL_APPLICATIONS);
183         mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
184
185         return root;
186     }
187
188     private boolean isNonMarketAppsAllowed() {
189         return Settings.Secure.getInt(getContentResolver(),
190                                       Settings.Secure.INSTALL_NON_MARKET_APPS, 0) > 0;
191     }
192
193     private void setNonMarketAppsAllowed(boolean enabled) {
194         // Change the system setting
195         Settings.Secure.putInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS,
196                                 enabled ? 1 : 0);
197     }
198
199     private void warnAppInstallation() {
200         // TODO: DialogFragment?
201         mWarnInstallApps = new AlertDialog.Builder(getActivity()).setTitle(
202                 getResources().getString(R.string.error_title))
203                 .setIcon(com.android.internal.R.drawable.ic_dialog_alert)
204                 .setMessage(getResources().getString(R.string.install_all_warning))
205                 .setPositiveButton(android.R.string.yes, this)
206                 .setNegativeButton(android.R.string.no, null)
207                 .show();
208     }
209
210     public void onClick(DialogInterface dialog, int which) {
211         if (dialog == mWarnInstallApps && which == DialogInterface.BUTTON_POSITIVE) {
212             setNonMarketAppsAllowed(true);
213             mToggleAppInstallation.setChecked(true);
214         }
215     }
216
217     @Override
218     public void onDestroy() {
219         super.onDestroy();
220         if (mWarnInstallApps != null) {
221             mWarnInstallApps.dismiss();
222         }
223     }
224
225     private void setupLockAfterPreference() {
226         // Compatible with pre-Froyo
227         long currentTimeout = Settings.Secure.getLong(getContentResolver(),
228                 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
229         mLockAfter.setValue(String.valueOf(currentTimeout));
230         mLockAfter.setOnPreferenceChangeListener(this);
231         final long adminTimeout = (mDPM != null ? mDPM.getMaximumTimeToLock(null) : 0);
232         final long displayTimeout = Math.max(0,
233                 Settings.System.getInt(getContentResolver(), SCREEN_OFF_TIMEOUT, 0));
234         if (adminTimeout > 0) {
235             // This setting is a slave to display timeout when a device policy is enforced.
236             // As such, maxLockTimeout = adminTimeout - displayTimeout.
237             // If there isn't enough time, shows "immediately" setting.
238             disableUnusableTimeouts(Math.max(0, adminTimeout - displayTimeout));
239         }
240     }
241
242     private void updateLockAfterPreferenceSummary() {
243         // Update summary message with current value
244         long currentTimeout = Settings.Secure.getLong(getContentResolver(),
245                 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
246         final CharSequence[] entries = mLockAfter.getEntries();
247         final CharSequence[] values = mLockAfter.getEntryValues();
248         int best = 0;
249         for (int i = 0; i < values.length; i++) {
250             long timeout = Long.valueOf(values[i].toString());
251             if (currentTimeout >= timeout) {
252                 best = i;
253             }
254         }
255         mLockAfter.setSummary(getString(R.string.lock_after_timeout_summary, entries[best]));
256     }
257
258     private void disableUnusableTimeouts(long maxTimeout) {
259         final CharSequence[] entries = mLockAfter.getEntries();
260         final CharSequence[] values = mLockAfter.getEntryValues();
261         ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
262         ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
263         for (int i = 0; i < values.length; i++) {
264             long timeout = Long.valueOf(values[i].toString());
265             if (timeout <= maxTimeout) {
266                 revisedEntries.add(entries[i]);
267                 revisedValues.add(values[i]);
268             }
269         }
270         if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
271             mLockAfter.setEntries(
272                     revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
273             mLockAfter.setEntryValues(
274                     revisedValues.toArray(new CharSequence[revisedValues.size()]));
275             final int userPreference = Integer.valueOf(mLockAfter.getValue());
276             if (userPreference <= maxTimeout) {
277                 mLockAfter.setValue(String.valueOf(userPreference));
278             } else {
279                 // There will be no highlighted selection since nothing in the list matches
280                 // maxTimeout. The user can still select anything less than maxTimeout.
281                 // TODO: maybe append maxTimeout to the list and mark selected.
282             }
283         }
284         mLockAfter.setEnabled(revisedEntries.size() > 0);
285     }
286
287     @Override
288     public void onResume() {
289         super.onResume();
290
291         // Make sure we reload the preference hierarchy since some of these settings
292         // depend on others...
293         createPreferenceHierarchy();
294
295         final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
296         if (mVisiblePattern != null) {
297             mVisiblePattern.setChecked(lockPatternUtils.isVisiblePatternEnabled());
298         }
299         if (mTactileFeedback != null) {
300             mTactileFeedback.setChecked(lockPatternUtils.isTactileFeedbackEnabled());
301         }
302
303         mShowPassword.setChecked(Settings.System.getInt(getContentResolver(),
304                 Settings.System.TEXT_SHOW_PASSWORD, 1) != 0);
305
306         KeyStore.State state = KeyStore.getInstance().state();
307         mResetCredentials.setEnabled(state != KeyStore.State.UNINITIALIZED);
308     }
309
310     @Override
311     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
312         final String key = preference.getKey();
313
314         final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
315         if (KEY_UNLOCK_SET_OR_CHANGE.equals(key)) {
316             startFragment(this, "com.android.settings.ChooseLockGeneric$ChooseLockGenericFragment",
317                     SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
318         } else if (KEY_LOCK_ENABLED.equals(key)) {
319             lockPatternUtils.setLockPatternEnabled(isToggled(preference));
320         } else if (KEY_VISIBLE_PATTERN.equals(key)) {
321             lockPatternUtils.setVisiblePatternEnabled(isToggled(preference));
322         } else if (KEY_TACTILE_FEEDBACK_ENABLED.equals(key)) {
323             lockPatternUtils.setTactileFeedbackEnabled(isToggled(preference));
324         } else if (preference == mShowPassword) {
325             Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
326                     mShowPassword.isChecked() ? 1 : 0);
327         } else if (preference == mToggleAppInstallation) {
328             if (mToggleAppInstallation.isChecked()) {
329                 mToggleAppInstallation.setChecked(false);
330                 warnAppInstallation();
331             } else {
332                 setNonMarketAppsAllowed(false);
333             }
334         } else {
335             // If we didn't handle it, let preferences handle it.
336             return super.onPreferenceTreeClick(preferenceScreen, preference);
337         }
338
339         return true;
340     }
341
342     private boolean isToggled(Preference pref) {
343         return ((CheckBoxPreference) pref).isChecked();
344     }
345
346     /**
347      * see confirmPatternThenDisableAndClear
348      */
349     @Override
350     public void onActivityResult(int requestCode, int resultCode, Intent data) {
351         super.onActivityResult(requestCode, resultCode, data);
352         mChooseLockSettingsHelper.utils().deleteTempGallery();
353         createPreferenceHierarchy();
354     }
355
356     public boolean onPreferenceChange(Preference preference, Object value) {
357         if (preference == mLockAfter) {
358             int timeout = Integer.parseInt((String) value);
359             try {
360                 Settings.Secure.putInt(getContentResolver(),
361                         Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, timeout);
362             } catch (NumberFormatException e) {
363                 Log.e("SecuritySettings", "could not persist lockAfter timeout setting", e);
364             }
365             updateLockAfterPreferenceSummary();
366         }
367         return true;
368     }
369 }