LockPatternUtils.java revision fc753c0cf676000b1c2d3cb2728af85a9b49f795
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
17package com.android.internal.widget;
18
19import android.app.ActivityManagerNative;
20import android.app.admin.DevicePolicyManager;
21import android.content.ContentResolver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.pm.PackageManager;
25import android.os.Binder;
26import android.os.Bundle;
27import android.os.IBinder;
28import android.os.RemoteException;
29import android.os.ServiceManager;
30import android.os.SystemClock;
31import android.os.UserHandle;
32import android.os.storage.IMountService;
33import android.provider.Settings;
34import android.security.KeyStore;
35import android.telephony.TelephonyManager;
36import android.text.TextUtils;
37import android.util.Log;
38import android.view.View;
39import android.widget.Button;
40
41import com.android.internal.R;
42import com.android.internal.telephony.ITelephony;
43import com.google.android.collect.Lists;
44
45import java.security.MessageDigest;
46import java.security.NoSuchAlgorithmException;
47import java.security.SecureRandom;
48import java.util.List;
49
50/**
51 * Utilities for the lock pattern and its settings.
52 */
53public class LockPatternUtils {
54
55    private static final String OPTION_ENABLE_FACELOCK = "enable_facelock";
56
57    private static final String TAG = "LockPatternUtils";
58
59    /**
60     * The maximum number of incorrect attempts before the user is prevented
61     * from trying again for {@link #FAILED_ATTEMPT_TIMEOUT_MS}.
62     */
63    public static final int FAILED_ATTEMPTS_BEFORE_TIMEOUT = 5;
64
65    /**
66     * The number of incorrect attempts before which we fall back on an alternative
67     * method of verifying the user, and resetting their lock pattern.
68     */
69    public static final int FAILED_ATTEMPTS_BEFORE_RESET = 20;
70
71    /**
72     * How long the user is prevented from trying again after entering the
73     * wrong pattern too many times.
74     */
75    public static final long FAILED_ATTEMPT_TIMEOUT_MS = 30000L;
76
77    /**
78     * The interval of the countdown for showing progress of the lockout.
79     */
80    public static final long FAILED_ATTEMPT_COUNTDOWN_INTERVAL_MS = 1000L;
81
82
83    /**
84     * This dictates when we start telling the user that continued failed attempts will wipe
85     * their device.
86     */
87    public static final int FAILED_ATTEMPTS_BEFORE_WIPE_GRACE = 5;
88
89    /**
90     * The minimum number of dots in a valid pattern.
91     */
92    public static final int MIN_LOCK_PATTERN_SIZE = 4;
93
94    /**
95     * The minimum number of dots the user must include in a wrong pattern
96     * attempt for it to be counted against the counts that affect
97     * {@link #FAILED_ATTEMPTS_BEFORE_TIMEOUT} and {@link #FAILED_ATTEMPTS_BEFORE_RESET}
98     */
99    public static final int MIN_PATTERN_REGISTER_FAIL = MIN_LOCK_PATTERN_SIZE;
100
101    /**
102     * Tells the keyguard to show the user switcher when the keyguard is created.
103     */
104    public static final String KEYGUARD_SHOW_USER_SWITCHER = "showuserswitcher";
105
106    /**
107     * Tells the keyguard to show the security challenge when the keyguard is created.
108     */
109    public static final String KEYGUARD_SHOW_SECURITY_CHALLENGE = "showsecuritychallenge";
110
111    /**
112     * Options used to lock the device upon user switch.
113     */
114    public static final Bundle USER_SWITCH_LOCK_OPTIONS = new Bundle();
115
116    static {
117        USER_SWITCH_LOCK_OPTIONS.putBoolean(KEYGUARD_SHOW_USER_SWITCHER, true);
118        USER_SWITCH_LOCK_OPTIONS.putBoolean(KEYGUARD_SHOW_SECURITY_CHALLENGE, true);
119    }
120
121    /**
122     * The bit in LOCK_BIOMETRIC_WEAK_FLAGS to be used to indicate whether liveliness should
123     * be used
124     */
125    public static final int FLAG_BIOMETRIC_WEAK_LIVELINESS = 0x1;
126
127    /**
128     * Pseudo-appwidget id we use to represent the default clock status widget
129     */
130    public static final int ID_DEFAULT_STATUS_WIDGET = -2;
131
132    /**
133     * Intent extra that's used to tag the default widget when using the picker
134     */
135    public static final String EXTRA_DEFAULT_WIDGET = "com.android.settings.DEFAULT_WIDGET";
136
137    protected final static String LOCKOUT_PERMANENT_KEY = "lockscreen.lockedoutpermanently";
138    protected final static String LOCKOUT_ATTEMPT_DEADLINE = "lockscreen.lockoutattemptdeadline";
139    protected final static String PATTERN_EVER_CHOSEN_KEY = "lockscreen.patterneverchosen";
140    public final static String PASSWORD_TYPE_KEY = "lockscreen.password_type";
141    public static final String PASSWORD_TYPE_ALTERNATE_KEY = "lockscreen.password_type_alternate";
142    protected final static String LOCK_PASSWORD_SALT_KEY = "lockscreen.password_salt";
143    protected final static String DISABLE_LOCKSCREEN_KEY = "lockscreen.disabled";
144    protected final static String LOCKSCREEN_OPTIONS = "lockscreen.options";
145    public final static String LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK
146            = "lockscreen.biometric_weak_fallback";
147    public final static String BIOMETRIC_WEAK_EVER_CHOSEN_KEY
148            = "lockscreen.biometricweakeverchosen";
149    public final static String LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS
150            = "lockscreen.power_button_instantly_locks";
151
152    protected final static String PASSWORD_HISTORY_KEY = "lockscreen.passwordhistory";
153
154    private final Context mContext;
155    private final ContentResolver mContentResolver;
156    private DevicePolicyManager mDevicePolicyManager;
157    private ILockSettings mLockSettingsService;
158
159    // The current user is set by KeyguardViewMediator and shared by all LockPatternUtils.
160    private static volatile int sCurrentUserId = UserHandle.USER_NULL;
161
162    public DevicePolicyManager getDevicePolicyManager() {
163        if (mDevicePolicyManager == null) {
164            mDevicePolicyManager =
165                (DevicePolicyManager)mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
166            if (mDevicePolicyManager == null) {
167                Log.e(TAG, "Can't get DevicePolicyManagerService: is it running?",
168                        new IllegalStateException("Stack trace:"));
169            }
170        }
171        return mDevicePolicyManager;
172    }
173
174    /**
175     * @param contentResolver Used to look up and save settings.
176     */
177    public LockPatternUtils(Context context) {
178        mContext = context;
179        mContentResolver = context.getContentResolver();
180    }
181
182    private ILockSettings getLockSettings() {
183        if (mLockSettingsService == null) {
184            mLockSettingsService = ILockSettings.Stub.asInterface(
185                (IBinder) ServiceManager.getService("lock_settings"));
186        }
187        return mLockSettingsService;
188    }
189
190    public int getRequestedMinimumPasswordLength() {
191        return getDevicePolicyManager().getPasswordMinimumLength(null, getCurrentOrCallingUserId());
192    }
193
194    /**
195     * Gets the device policy password mode. If the mode is non-specific, returns
196     * MODE_PATTERN which allows the user to choose anything.
197     */
198    public int getRequestedPasswordQuality() {
199        return getDevicePolicyManager().getPasswordQuality(null, getCurrentOrCallingUserId());
200    }
201
202    public int getRequestedPasswordHistoryLength() {
203        return getDevicePolicyManager().getPasswordHistoryLength(null, getCurrentOrCallingUserId());
204    }
205
206    public int getRequestedPasswordMinimumLetters() {
207        return getDevicePolicyManager().getPasswordMinimumLetters(null,
208                getCurrentOrCallingUserId());
209    }
210
211    public int getRequestedPasswordMinimumUpperCase() {
212        return getDevicePolicyManager().getPasswordMinimumUpperCase(null,
213                getCurrentOrCallingUserId());
214    }
215
216    public int getRequestedPasswordMinimumLowerCase() {
217        return getDevicePolicyManager().getPasswordMinimumLowerCase(null,
218                getCurrentOrCallingUserId());
219    }
220
221    public int getRequestedPasswordMinimumNumeric() {
222        return getDevicePolicyManager().getPasswordMinimumNumeric(null,
223                getCurrentOrCallingUserId());
224    }
225
226    public int getRequestedPasswordMinimumSymbols() {
227        return getDevicePolicyManager().getPasswordMinimumSymbols(null,
228                getCurrentOrCallingUserId());
229    }
230
231    public int getRequestedPasswordMinimumNonLetter() {
232        return getDevicePolicyManager().getPasswordMinimumNonLetter(null,
233                getCurrentOrCallingUserId());
234    }
235
236    /**
237     * Returns the actual password mode, as set by keyguard after updating the password.
238     *
239     * @return
240     */
241    public void reportFailedPasswordAttempt() {
242        getDevicePolicyManager().reportFailedPasswordAttempt(getCurrentOrCallingUserId());
243    }
244
245    public void reportSuccessfulPasswordAttempt() {
246        getDevicePolicyManager().reportSuccessfulPasswordAttempt(getCurrentOrCallingUserId());
247    }
248
249    public void setCurrentUser(int userId) {
250        sCurrentUserId = userId;
251    }
252
253    public int getCurrentUser() {
254        if (sCurrentUserId != UserHandle.USER_NULL) {
255            // Someone is regularly updating using setCurrentUser() use that value.
256            return sCurrentUserId;
257        }
258        try {
259            return ActivityManagerNative.getDefault().getCurrentUser().id;
260        } catch (RemoteException re) {
261            return UserHandle.USER_OWNER;
262        }
263    }
264
265    public void removeUser(int userId) {
266        try {
267            getLockSettings().removeUser(userId);
268        } catch (RemoteException re) {
269            Log.e(TAG, "Couldn't remove lock settings for user " + userId);
270        }
271    }
272
273    private int getCurrentOrCallingUserId() {
274        int callingUid = Binder.getCallingUid();
275        if (callingUid == android.os.Process.SYSTEM_UID) {
276            // TODO: This is a little inefficient. See if all users of this are able to
277            // handle USER_CURRENT and pass that instead.
278            return getCurrentUser();
279        } else {
280            return UserHandle.getUserId(callingUid);
281        }
282    }
283
284    /**
285     * Check to see if a pattern matches the saved pattern.  If no pattern exists,
286     * always returns true.
287     * @param pattern The pattern to check.
288     * @return Whether the pattern matches the stored one.
289     */
290    public boolean checkPattern(List<LockPatternView.Cell> pattern) {
291        final int userId = getCurrentOrCallingUserId();
292        try {
293            final boolean matched = getLockSettings().checkPattern(patternToHash(pattern), userId);
294            if (matched && (userId == UserHandle.USER_OWNER)) {
295                KeyStore.getInstance().password(patternToString(pattern));
296            }
297            return matched;
298        } catch (RemoteException re) {
299            return true;
300        }
301    }
302
303    /**
304     * Check to see if a password matches the saved password.  If no password exists,
305     * always returns true.
306     * @param password The password to check.
307     * @return Whether the password matches the stored one.
308     */
309    public boolean checkPassword(String password) {
310        final int userId = getCurrentOrCallingUserId();
311        try {
312            final boolean matched = getLockSettings().checkPassword(passwordToHash(password),
313                    userId);
314            if (matched && (userId == UserHandle.USER_OWNER)) {
315                KeyStore.getInstance().password(password);
316            }
317            return matched;
318        } catch (RemoteException re) {
319            return true;
320        }
321    }
322
323    /**
324     * Check to see if a password matches any of the passwords stored in the
325     * password history.
326     *
327     * @param password The password to check.
328     * @return Whether the password matches any in the history.
329     */
330    public boolean checkPasswordHistory(String password) {
331        String passwordHashString = new String(passwordToHash(password));
332        String passwordHistory = getString(PASSWORD_HISTORY_KEY);
333        if (passwordHistory == null) {
334            return false;
335        }
336        // Password History may be too long...
337        int passwordHashLength = passwordHashString.length();
338        int passwordHistoryLength = getRequestedPasswordHistoryLength();
339        if(passwordHistoryLength == 0) {
340            return false;
341        }
342        int neededPasswordHistoryLength = passwordHashLength * passwordHistoryLength
343                + passwordHistoryLength - 1;
344        if (passwordHistory.length() > neededPasswordHistoryLength) {
345            passwordHistory = passwordHistory.substring(0, neededPasswordHistoryLength);
346        }
347        return passwordHistory.contains(passwordHashString);
348    }
349
350    /**
351     * Check to see if the user has stored a lock pattern.
352     * @return Whether a saved pattern exists.
353     */
354    public boolean savedPatternExists() {
355        try {
356            return getLockSettings().havePattern(getCurrentOrCallingUserId());
357        } catch (RemoteException re) {
358            return false;
359        }
360    }
361
362    /**
363     * Check to see if the user has stored a lock pattern.
364     * @return Whether a saved pattern exists.
365     */
366    public boolean savedPasswordExists() {
367        try {
368            return getLockSettings().havePassword(getCurrentOrCallingUserId());
369        } catch (RemoteException re) {
370            return false;
371        }
372    }
373
374    /**
375     * Return true if the user has ever chosen a pattern.  This is true even if the pattern is
376     * currently cleared.
377     *
378     * @return True if the user has ever chosen a pattern.
379     */
380    public boolean isPatternEverChosen() {
381        return getBoolean(PATTERN_EVER_CHOSEN_KEY, false);
382    }
383
384    /**
385     * Return true if the user has ever chosen biometric weak.  This is true even if biometric
386     * weak is not current set.
387     *
388     * @return True if the user has ever chosen biometric weak.
389     */
390    public boolean isBiometricWeakEverChosen() {
391        return getBoolean(BIOMETRIC_WEAK_EVER_CHOSEN_KEY, false);
392    }
393
394    /**
395     * Used by device policy manager to validate the current password
396     * information it has.
397     */
398    public int getActivePasswordQuality() {
399        int activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
400        // Note we don't want to use getKeyguardStoredPasswordQuality() because we want this to
401        // return biometric_weak if that is being used instead of the backup
402        int quality =
403                (int) getLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
404        switch (quality) {
405            case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
406                if (isLockPatternEnabled()) {
407                    activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
408                }
409                break;
410            case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
411                if (isBiometricWeakInstalled()) {
412                    activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK;
413                }
414                break;
415            case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
416                if (isLockPasswordEnabled()) {
417                    activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
418                }
419                break;
420            case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
421                if (isLockPasswordEnabled()) {
422                    activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
423                }
424                break;
425            case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
426                if (isLockPasswordEnabled()) {
427                    activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
428                }
429                break;
430            case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
431                if (isLockPasswordEnabled()) {
432                    activePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
433                }
434                break;
435        }
436
437        return activePasswordQuality;
438    }
439
440    /**
441     * Clear any lock pattern or password.
442     */
443    public void clearLock(boolean isFallback) {
444        if(!isFallback) deleteGallery();
445        saveLockPassword(null, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
446        setLockPatternEnabled(false);
447        saveLockPattern(null);
448        setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
449        setLong(PASSWORD_TYPE_ALTERNATE_KEY, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
450    }
451
452    /**
453     * Disable showing lock screen at all when the DevicePolicyManager allows it.
454     * This is only meaningful if pattern, pin or password are not set.
455     *
456     * @param disable Disables lock screen when true
457     */
458    public void setLockScreenDisabled(boolean disable) {
459        setLong(DISABLE_LOCKSCREEN_KEY, disable ? 1 : 0);
460    }
461
462    /**
463     * Determine if LockScreen can be disabled. This is used, for example, to tell if we should
464     * show LockScreen or go straight to the home screen.
465     *
466     * @return true if lock screen is can be disabled
467     */
468    public boolean isLockScreenDisabled() {
469        return !isSecure() && getLong(DISABLE_LOCKSCREEN_KEY, 0) != 0;
470    }
471
472    /**
473     * Calls back SetupFaceLock to delete the temporary gallery file
474     */
475    public void deleteTempGallery() {
476        Intent intent = new Intent().setAction("com.android.facelock.DELETE_GALLERY");
477        intent.putExtra("deleteTempGallery", true);
478        mContext.sendBroadcast(intent);
479    }
480
481    /**
482     * Calls back SetupFaceLock to delete the gallery file when the lock type is changed
483    */
484    void deleteGallery() {
485        if(usingBiometricWeak()) {
486            Intent intent = new Intent().setAction("com.android.facelock.DELETE_GALLERY");
487            intent.putExtra("deleteGallery", true);
488            mContext.sendBroadcast(intent);
489        }
490    }
491
492    /**
493     * Save a lock pattern.
494     * @param pattern The new pattern to save.
495     */
496    public void saveLockPattern(List<LockPatternView.Cell> pattern) {
497        this.saveLockPattern(pattern, false);
498    }
499
500    /**
501     * Save a lock pattern.
502     * @param pattern The new pattern to save.
503     * @param isFallback Specifies if this is a fallback to biometric weak
504     */
505    public void saveLockPattern(List<LockPatternView.Cell> pattern, boolean isFallback) {
506        // Compute the hash
507        final byte[] hash = LockPatternUtils.patternToHash(pattern);
508        try {
509            getLockSettings().setLockPattern(hash, getCurrentOrCallingUserId());
510            DevicePolicyManager dpm = getDevicePolicyManager();
511            KeyStore keyStore = KeyStore.getInstance();
512            if (pattern != null) {
513                keyStore.password(patternToString(pattern));
514                setBoolean(PATTERN_EVER_CHOSEN_KEY, true);
515                if (!isFallback) {
516                    deleteGallery();
517                    setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
518                    dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_SOMETHING,
519                            pattern.size(), 0, 0, 0, 0, 0, 0, getCurrentOrCallingUserId());
520                } else {
521                    setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK);
522                    setLong(PASSWORD_TYPE_ALTERNATE_KEY,
523                            DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
524                    finishBiometricWeak();
525                    dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK,
526                            0, 0, 0, 0, 0, 0, 0, getCurrentOrCallingUserId());
527                }
528            } else {
529                if (keyStore.isEmpty()) {
530                    keyStore.reset();
531                }
532                dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0,
533                        0, 0, 0, 0, 0, getCurrentOrCallingUserId());
534            }
535        } catch (RemoteException re) {
536            Log.e(TAG, "Couldn't save lock pattern " + re);
537        }
538    }
539
540    /**
541     * Compute the password quality from the given password string.
542     */
543    static public int computePasswordQuality(String password) {
544        boolean hasDigit = false;
545        boolean hasNonDigit = false;
546        final int len = password.length();
547        for (int i = 0; i < len; i++) {
548            if (Character.isDigit(password.charAt(i))) {
549                hasDigit = true;
550            } else {
551                hasNonDigit = true;
552            }
553        }
554
555        if (hasNonDigit && hasDigit) {
556            return DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
557        }
558        if (hasNonDigit) {
559            return DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
560        }
561        if (hasDigit) {
562            return DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
563        }
564        return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
565    }
566
567    /** Update the encryption password if it is enabled **/
568    private void updateEncryptionPassword(String password) {
569        DevicePolicyManager dpm = getDevicePolicyManager();
570        if (dpm.getStorageEncryptionStatus(getCurrentOrCallingUserId())
571                != DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE) {
572            return;
573        }
574
575        IBinder service = ServiceManager.getService("mount");
576        if (service == null) {
577            Log.e(TAG, "Could not find the mount service to update the encryption password");
578            return;
579        }
580
581        IMountService mountService = IMountService.Stub.asInterface(service);
582        try {
583            mountService.changeEncryptionPassword(password);
584        } catch (RemoteException e) {
585            Log.e(TAG, "Error changing encryption password", e);
586        }
587    }
588
589    /**
590     * Save a lock password.  Does not ensure that the password is as good
591     * as the requested mode, but will adjust the mode to be as good as the
592     * pattern.
593     * @param password The password to save
594     * @param quality {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)}
595     */
596    public void saveLockPassword(String password, int quality) {
597        this.saveLockPassword(password, quality, false, getCurrentOrCallingUserId());
598    }
599
600    /**
601     * Save a lock password.  Does not ensure that the password is as good
602     * as the requested mode, but will adjust the mode to be as good as the
603     * pattern.
604     * @param password The password to save
605     * @param quality {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)}
606     * @param isFallback Specifies if this is a fallback to biometric weak
607     */
608    public void saveLockPassword(String password, int quality, boolean isFallback) {
609        saveLockPassword(password, quality, isFallback, getCurrentOrCallingUserId());
610    }
611
612    /**
613     * Save a lock password.  Does not ensure that the password is as good
614     * as the requested mode, but will adjust the mode to be as good as the
615     * pattern.
616     * @param password The password to save
617     * @param quality {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)}
618     * @param isFallback Specifies if this is a fallback to biometric weak
619     * @param userHandle The userId of the user to change the password for
620     */
621    public void saveLockPassword(String password, int quality, boolean isFallback, int userHandle) {
622        // Compute the hash
623        final byte[] hash = passwordToHash(password);
624        try {
625            getLockSettings().setLockPassword(hash, userHandle);
626            DevicePolicyManager dpm = getDevicePolicyManager();
627            KeyStore keyStore = KeyStore.getInstance();
628            if (password != null) {
629                if (userHandle == UserHandle.USER_OWNER) {
630                    // Update the encryption password.
631                    updateEncryptionPassword(password);
632
633                    // Update the keystore password
634                    keyStore.password(password);
635                }
636
637                int computedQuality = computePasswordQuality(password);
638                if (!isFallback) {
639                    deleteGallery();
640                    setLong(PASSWORD_TYPE_KEY, Math.max(quality, computedQuality), userHandle);
641                    if (computedQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
642                        int letters = 0;
643                        int uppercase = 0;
644                        int lowercase = 0;
645                        int numbers = 0;
646                        int symbols = 0;
647                        int nonletter = 0;
648                        for (int i = 0; i < password.length(); i++) {
649                            char c = password.charAt(i);
650                            if (c >= 'A' && c <= 'Z') {
651                                letters++;
652                                uppercase++;
653                            } else if (c >= 'a' && c <= 'z') {
654                                letters++;
655                                lowercase++;
656                            } else if (c >= '0' && c <= '9') {
657                                numbers++;
658                                nonletter++;
659                            } else {
660                                symbols++;
661                                nonletter++;
662                            }
663                        }
664                        dpm.setActivePasswordState(Math.max(quality, computedQuality),
665                                password.length(), letters, uppercase, lowercase,
666                                numbers, symbols, nonletter, userHandle);
667                    } else {
668                        // The password is not anything.
669                        dpm.setActivePasswordState(
670                                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
671                                0, 0, 0, 0, 0, 0, 0, userHandle);
672                    }
673                } else {
674                    // Case where it's a fallback for biometric weak
675                    setLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK,
676                            userHandle);
677                    setLong(PASSWORD_TYPE_ALTERNATE_KEY, Math.max(quality, computedQuality),
678                            userHandle);
679                    finishBiometricWeak();
680                    dpm.setActivePasswordState(DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK,
681                            0, 0, 0, 0, 0, 0, 0, userHandle);
682                }
683                // Add the password to the password history. We assume all
684                // password
685                // hashes have the same length for simplicity of implementation.
686                String passwordHistory = getString(PASSWORD_HISTORY_KEY, userHandle);
687                if (passwordHistory == null) {
688                    passwordHistory = new String();
689                }
690                int passwordHistoryLength = getRequestedPasswordHistoryLength();
691                if (passwordHistoryLength == 0) {
692                    passwordHistory = "";
693                } else {
694                    passwordHistory = new String(hash) + "," + passwordHistory;
695                    // Cut it to contain passwordHistoryLength hashes
696                    // and passwordHistoryLength -1 commas.
697                    passwordHistory = passwordHistory.substring(0, Math.min(hash.length
698                            * passwordHistoryLength + passwordHistoryLength - 1, passwordHistory
699                            .length()));
700                }
701                setString(PASSWORD_HISTORY_KEY, passwordHistory, userHandle);
702            } else {
703                // Conditionally reset the keystore if empty. If
704                // non-empty, we are just switching key guard type
705                if (keyStore.isEmpty()) {
706                    keyStore.reset();
707                }
708                dpm.setActivePasswordState(
709                        DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, 0, 0, 0, 0, 0, 0, 0,
710                        userHandle);
711            }
712        } catch (RemoteException re) {
713            // Cant do much
714            Log.e(TAG, "Unable to save lock password " + re);
715        }
716    }
717
718    /**
719     * Retrieves the quality mode we're in.
720     * {@see DevicePolicyManager#getPasswordQuality(android.content.ComponentName)}
721     *
722     * @return stored password quality
723     */
724    public int getKeyguardStoredPasswordQuality() {
725        int quality =
726                (int) getLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
727        // If the user has chosen to use weak biometric sensor, then return the backup locking
728        // method and treat biometric as a special case.
729        if (quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) {
730            quality =
731                (int) getLong(PASSWORD_TYPE_ALTERNATE_KEY,
732                        DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
733        }
734        return quality;
735    }
736
737    /**
738     * @return true if the lockscreen method is set to biometric weak
739     */
740    public boolean usingBiometricWeak() {
741        int quality =
742                (int) getLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
743        return quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK;
744    }
745
746    /**
747     * Deserialize a pattern.
748     * @param string The pattern serialized with {@link #patternToString}
749     * @return The pattern.
750     */
751    public static List<LockPatternView.Cell> stringToPattern(String string) {
752        List<LockPatternView.Cell> result = Lists.newArrayList();
753
754        final byte[] bytes = string.getBytes();
755        for (int i = 0; i < bytes.length; i++) {
756            byte b = bytes[i];
757            result.add(LockPatternView.Cell.of(b / 3, b % 3));
758        }
759        return result;
760    }
761
762    /**
763     * Serialize a pattern.
764     * @param pattern The pattern.
765     * @return The pattern in string form.
766     */
767    public static String patternToString(List<LockPatternView.Cell> pattern) {
768        if (pattern == null) {
769            return "";
770        }
771        final int patternSize = pattern.size();
772
773        byte[] res = new byte[patternSize];
774        for (int i = 0; i < patternSize; i++) {
775            LockPatternView.Cell cell = pattern.get(i);
776            res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
777        }
778        return new String(res);
779    }
780
781    /*
782     * Generate an SHA-1 hash for the pattern. Not the most secure, but it is
783     * at least a second level of protection. First level is that the file
784     * is in a location only readable by the system process.
785     * @param pattern the gesture pattern.
786     * @return the hash of the pattern in a byte array.
787     */
788    private static byte[] patternToHash(List<LockPatternView.Cell> pattern) {
789        if (pattern == null) {
790            return null;
791        }
792
793        final int patternSize = pattern.size();
794        byte[] res = new byte[patternSize];
795        for (int i = 0; i < patternSize; i++) {
796            LockPatternView.Cell cell = pattern.get(i);
797            res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
798        }
799        try {
800            MessageDigest md = MessageDigest.getInstance("SHA-1");
801            byte[] hash = md.digest(res);
802            return hash;
803        } catch (NoSuchAlgorithmException nsa) {
804            return res;
805        }
806    }
807
808    private String getSalt() {
809        long salt = getLong(LOCK_PASSWORD_SALT_KEY, 0);
810        if (salt == 0) {
811            try {
812                salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
813                setLong(LOCK_PASSWORD_SALT_KEY, salt);
814                Log.v(TAG, "Initialized lock password salt");
815            } catch (NoSuchAlgorithmException e) {
816                // Throw an exception rather than storing a password we'll never be able to recover
817                throw new IllegalStateException("Couldn't get SecureRandom number", e);
818            }
819        }
820        return Long.toHexString(salt);
821    }
822
823    /*
824     * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
825     * Not the most secure, but it is at least a second level of protection. First level is that
826     * the file is in a location only readable by the system process.
827     * @param password the gesture pattern.
828     * @return the hash of the pattern in a byte array.
829     */
830    public byte[] passwordToHash(String password) {
831        if (password == null) {
832            return null;
833        }
834        String algo = null;
835        byte[] hashed = null;
836        try {
837            byte[] saltedPassword = (password + getSalt()).getBytes();
838            byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
839            byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
840            hashed = (toHex(sha1) + toHex(md5)).getBytes();
841        } catch (NoSuchAlgorithmException e) {
842            Log.w(TAG, "Failed to encode string because of missing algorithm: " + algo);
843        }
844        return hashed;
845    }
846
847    private static String toHex(byte[] ary) {
848        final String hex = "0123456789ABCDEF";
849        String ret = "";
850        for (int i = 0; i < ary.length; i++) {
851            ret += hex.charAt((ary[i] >> 4) & 0xf);
852            ret += hex.charAt(ary[i] & 0xf);
853        }
854        return ret;
855    }
856
857    /**
858     * @return Whether the lock password is enabled, or if it is set as a backup for biometric weak
859     */
860    public boolean isLockPasswordEnabled() {
861        long mode = getLong(PASSWORD_TYPE_KEY, 0);
862        long backupMode = getLong(PASSWORD_TYPE_ALTERNATE_KEY, 0);
863        final boolean passwordEnabled = mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC
864                || mode == DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
865                || mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
866                || mode == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
867        final boolean backupEnabled = backupMode == DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC
868                || backupMode == DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
869                || backupMode == DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
870                || backupMode == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
871
872        return savedPasswordExists() && (passwordEnabled ||
873                (usingBiometricWeak() && backupEnabled));
874    }
875
876    /**
877     * @return Whether the lock pattern is enabled, or if it is set as a backup for biometric weak
878     */
879    public boolean isLockPatternEnabled() {
880        final boolean backupEnabled =
881                getLong(PASSWORD_TYPE_ALTERNATE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING)
882                == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
883
884        return getBoolean(Settings.Secure.LOCK_PATTERN_ENABLED, false)
885                && (getLong(PASSWORD_TYPE_KEY, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING)
886                        == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING ||
887                        (usingBiometricWeak() && backupEnabled));
888    }
889
890    /**
891     * @return Whether biometric weak lock is installed and that the front facing camera exists
892     */
893    public boolean isBiometricWeakInstalled() {
894        // Check that it's installed
895        PackageManager pm = mContext.getPackageManager();
896        try {
897            pm.getPackageInfo("com.android.facelock", PackageManager.GET_ACTIVITIES);
898        } catch (PackageManager.NameNotFoundException e) {
899            return false;
900        }
901
902        // Check that the camera is enabled
903        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
904            return false;
905        }
906        if (getDevicePolicyManager().getCameraDisabled(null, getCurrentOrCallingUserId())) {
907            return false;
908        }
909
910
911        return true;
912    }
913
914    /**
915     * Set whether biometric weak liveliness is enabled.
916     */
917    public void setBiometricWeakLivelinessEnabled(boolean enabled) {
918        long currentFlag = getLong(Settings.Secure.LOCK_BIOMETRIC_WEAK_FLAGS, 0L);
919        long newFlag;
920        if (enabled) {
921            newFlag = currentFlag | FLAG_BIOMETRIC_WEAK_LIVELINESS;
922        } else {
923            newFlag = currentFlag & ~FLAG_BIOMETRIC_WEAK_LIVELINESS;
924        }
925        setLong(Settings.Secure.LOCK_BIOMETRIC_WEAK_FLAGS, newFlag);
926    }
927
928    /**
929     * @return Whether the biometric weak liveliness is enabled.
930     */
931    public boolean isBiometricWeakLivelinessEnabled() {
932        long currentFlag = getLong(Settings.Secure.LOCK_BIOMETRIC_WEAK_FLAGS, 0L);
933        return ((currentFlag & FLAG_BIOMETRIC_WEAK_LIVELINESS) != 0);
934    }
935
936    /**
937     * Set whether the lock pattern is enabled.
938     */
939    public void setLockPatternEnabled(boolean enabled) {
940        setBoolean(Settings.Secure.LOCK_PATTERN_ENABLED, enabled);
941    }
942
943    /**
944     * @return Whether the visible pattern is enabled.
945     */
946    public boolean isVisiblePatternEnabled() {
947        return getBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, false);
948    }
949
950    /**
951     * Set whether the visible pattern is enabled.
952     */
953    public void setVisiblePatternEnabled(boolean enabled) {
954        setBoolean(Settings.Secure.LOCK_PATTERN_VISIBLE, enabled);
955    }
956
957    /**
958     * @return Whether tactile feedback for the pattern is enabled.
959     */
960    public boolean isTactileFeedbackEnabled() {
961        return Settings.System.getIntForUser(mContentResolver,
962                Settings.System.HAPTIC_FEEDBACK_ENABLED, 1, UserHandle.USER_CURRENT) != 0;
963    }
964
965    /**
966     * Set and store the lockout deadline, meaning the user can't attempt his/her unlock
967     * pattern until the deadline has passed.
968     * @return the chosen deadline.
969     */
970    public long setLockoutAttemptDeadline() {
971        final long deadline = SystemClock.elapsedRealtime() + FAILED_ATTEMPT_TIMEOUT_MS;
972        setLong(LOCKOUT_ATTEMPT_DEADLINE, deadline);
973        return deadline;
974    }
975
976    /**
977     * @return The elapsed time in millis in the future when the user is allowed to
978     *   attempt to enter his/her lock pattern, or 0 if the user is welcome to
979     *   enter a pattern.
980     */
981    public long getLockoutAttemptDeadline() {
982        final long deadline = getLong(LOCKOUT_ATTEMPT_DEADLINE, 0L);
983        final long now = SystemClock.elapsedRealtime();
984        if (deadline < now || deadline > (now + FAILED_ATTEMPT_TIMEOUT_MS)) {
985            return 0L;
986        }
987        return deadline;
988    }
989
990    /**
991     * @return Whether the user is permanently locked out until they verify their
992     *   credentials.  Occurs after {@link #FAILED_ATTEMPTS_BEFORE_RESET} failed
993     *   attempts.
994     */
995    public boolean isPermanentlyLocked() {
996        return getBoolean(LOCKOUT_PERMANENT_KEY, false);
997    }
998
999    /**
1000     * Set the state of whether the device is permanently locked, meaning the user
1001     * must authenticate via other means.
1002     *
1003     * @param locked Whether the user is permanently locked out until they verify their
1004     *   credentials.  Occurs after {@link #FAILED_ATTEMPTS_BEFORE_RESET} failed
1005     *   attempts.
1006     */
1007    public void setPermanentlyLocked(boolean locked) {
1008        setBoolean(LOCKOUT_PERMANENT_KEY, locked);
1009    }
1010
1011    public boolean isEmergencyCallCapable() {
1012        return mContext.getResources().getBoolean(
1013                com.android.internal.R.bool.config_voice_capable);
1014    }
1015
1016    public boolean isPukUnlockScreenEnable() {
1017        return mContext.getResources().getBoolean(
1018                com.android.internal.R.bool.config_enable_puk_unlock_screen);
1019    }
1020
1021    public boolean isEmergencyCallEnabledWhileSimLocked() {
1022        return mContext.getResources().getBoolean(
1023                com.android.internal.R.bool.config_enable_emergency_call_while_sim_locked);
1024    }
1025
1026    /**
1027     * @return A formatted string of the next alarm (for showing on the lock screen),
1028     *   or null if there is no next alarm.
1029     */
1030    public String getNextAlarm() {
1031        String nextAlarm = Settings.System.getStringForUser(mContentResolver,
1032                Settings.System.NEXT_ALARM_FORMATTED, UserHandle.USER_CURRENT);
1033        if (nextAlarm == null || TextUtils.isEmpty(nextAlarm)) {
1034            return null;
1035        }
1036        return nextAlarm;
1037    }
1038
1039    private boolean getBoolean(String secureSettingKey, boolean defaultValue) {
1040        try {
1041            return getLockSettings().getBoolean(secureSettingKey, defaultValue,
1042                    getCurrentOrCallingUserId());
1043        } catch (RemoteException re) {
1044            return defaultValue;
1045        }
1046    }
1047
1048    private void setBoolean(String secureSettingKey, boolean enabled) {
1049        try {
1050            getLockSettings().setBoolean(secureSettingKey, enabled, getCurrentOrCallingUserId());
1051        } catch (RemoteException re) {
1052            // What can we do?
1053            Log.e(TAG, "Couldn't write boolean " + secureSettingKey + re);
1054        }
1055    }
1056
1057    public int[] getAppWidgets() {
1058        String appWidgetIdString = Settings.Secure.getStringForUser(
1059                mContentResolver, Settings.Secure.LOCK_SCREEN_APPWIDGET_IDS,
1060                UserHandle.USER_CURRENT);
1061        String delims = ",";
1062        if (appWidgetIdString != null && appWidgetIdString.length() > 0) {
1063            String[] appWidgetStringIds = appWidgetIdString.split(delims);
1064            int[] appWidgetIds = new int[appWidgetStringIds.length];
1065            for (int i = 0; i < appWidgetStringIds.length; i++) {
1066                String appWidget = appWidgetStringIds[i];
1067                try {
1068                    appWidgetIds[i] = Integer.decode(appWidget);
1069                } catch (NumberFormatException e) {
1070                    Log.d(TAG, "Error when parsing widget id " + appWidget);
1071                    return null;
1072                }
1073            }
1074            return appWidgetIds;
1075        }
1076        if (appWidgetIdString == null) {
1077            return new int[] { LockPatternUtils.ID_DEFAULT_STATUS_WIDGET };
1078        } else {
1079            return new int[0];
1080        }
1081    }
1082
1083    private static String combineStrings(int[] list, String separator) {
1084        int listLength = list.length;
1085
1086        switch (listLength) {
1087            case 0: {
1088                return "";
1089            }
1090            case 1: {
1091                return Integer.toString(list[0]);
1092            }
1093        }
1094
1095        int strLength = 0;
1096        int separatorLength = separator.length();
1097
1098        String[] stringList = new String[list.length];
1099        for (int i = 0; i < listLength; i++) {
1100            stringList[i] = Integer.toString(list[i]);
1101            strLength += stringList[i].length();
1102            if (i < listLength - 1) {
1103                strLength += separatorLength;
1104            }
1105        }
1106
1107        StringBuilder sb = new StringBuilder(strLength);
1108
1109        for (int i = 0; i < listLength; i++) {
1110            sb.append(list[i]);
1111            if (i < listLength - 1) {
1112                sb.append(separator);
1113            }
1114        }
1115
1116        return sb.toString();
1117    }
1118
1119    private void writeAppWidgets(int[] appWidgetIds) {
1120        Settings.Secure.putStringForUser(mContentResolver,
1121                        Settings.Secure.LOCK_SCREEN_APPWIDGET_IDS,
1122                        combineStrings(appWidgetIds, ","),
1123                        UserHandle.USER_CURRENT);
1124    }
1125
1126    // TODO: log an error if this returns false
1127    public boolean addAppWidget(int widgetId, int index) {
1128        int[] widgets = getAppWidgets();
1129        if (widgets == null) {
1130            return false;
1131        }
1132        if (index < 0 || index > widgets.length) {
1133            return false;
1134        }
1135        int[] newWidgets = new int[widgets.length + 1];
1136        for (int i = 0, j = 0; i < newWidgets.length; i++) {
1137            if (index == i) {
1138                newWidgets[i] = widgetId;
1139                i++;
1140            }
1141            if (i < newWidgets.length) {
1142                newWidgets[i] = widgets[j];
1143                j++;
1144            }
1145        }
1146        writeAppWidgets(newWidgets);
1147        return true;
1148    }
1149
1150    public boolean removeAppWidget(int widgetId) {
1151        int[] widgets = getAppWidgets();
1152
1153        int[] newWidgets = new int[widgets.length - 1];
1154        for (int i = 0, j = 0; i < widgets.length; i++) {
1155            if (widgets[i] == widgetId) {
1156                // continue...
1157            } else if (j >= newWidgets.length) {
1158                // we couldn't find the widget
1159                return false;
1160            } else {
1161                newWidgets[j] = widgets[i];
1162                j++;
1163            }
1164        }
1165        writeAppWidgets(newWidgets);
1166        return true;
1167    }
1168
1169    public int getStickyAppWidgetIndex() {
1170        return Settings.Secure.getIntForUser(
1171                mContentResolver,
1172                Settings.Secure.LOCK_SCREEN_STICKY_APPWIDGET,
1173                -1,
1174                UserHandle.USER_CURRENT);
1175    }
1176
1177    public void setStickyAppWidgetIndex(int value) {
1178        Settings.Secure.putIntForUser(mContentResolver,
1179                Settings.Secure.LOCK_SCREEN_STICKY_APPWIDGET,
1180                value,
1181                UserHandle.USER_CURRENT);
1182    }
1183
1184    private long getLong(String secureSettingKey, long defaultValue) {
1185        try {
1186            return getLockSettings().getLong(secureSettingKey, defaultValue,
1187                    getCurrentOrCallingUserId());
1188        } catch (RemoteException re) {
1189            return defaultValue;
1190        }
1191    }
1192
1193    private void setLong(String secureSettingKey, long value) {
1194        setLong(secureSettingKey, value, getCurrentOrCallingUserId());
1195    }
1196
1197    private void setLong(String secureSettingKey, long value, int userHandle) {
1198        try {
1199            getLockSettings().setLong(secureSettingKey, value, getCurrentOrCallingUserId());
1200        } catch (RemoteException re) {
1201            // What can we do?
1202            Log.e(TAG, "Couldn't write long " + secureSettingKey + re);
1203        }
1204    }
1205
1206    private String getString(String secureSettingKey) {
1207        return getString(secureSettingKey, getCurrentOrCallingUserId());
1208    }
1209
1210    private String getString(String secureSettingKey, int userHandle) {
1211        try {
1212            return getLockSettings().getString(secureSettingKey, null, userHandle);
1213        } catch (RemoteException re) {
1214            return null;
1215        }
1216    }
1217
1218    private void setString(String secureSettingKey, String value, int userHandle) {
1219        try {
1220            getLockSettings().setString(secureSettingKey, value, userHandle);
1221        } catch (RemoteException re) {
1222            // What can we do?
1223            Log.e(TAG, "Couldn't write string " + secureSettingKey + re);
1224        }
1225    }
1226
1227    public boolean isSecure() {
1228        long mode = getKeyguardStoredPasswordQuality();
1229        final boolean isPattern = mode == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
1230        final boolean isPassword = mode == DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
1231                || mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC
1232                || mode == DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
1233                || mode == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
1234        final boolean secure = isPattern && isLockPatternEnabled() && savedPatternExists()
1235                || isPassword && savedPasswordExists();
1236        return secure;
1237    }
1238
1239    /**
1240     * Sets the emergency button visibility based on isEmergencyCallCapable().
1241     *
1242     * If the emergency button is visible, sets the text on the emergency button
1243     * to indicate what action will be taken.
1244     *
1245     * If there's currently a call in progress, the button will take them to the call
1246     * @param button the button to update
1247     * @param the phone state:
1248     *  {@link TelephonyManager#CALL_STATE_IDLE}
1249     *  {@link TelephonyManager#CALL_STATE_RINGING}
1250     *  {@link TelephonyManager#CALL_STATE_OFFHOOK}
1251     * @param shown indicates whether the given screen wants the emergency button to show at all
1252     * @param button
1253     * @param phoneState
1254     * @param shown shown if true; hidden if false
1255     * @param upperCase if true, converts button label string to upper case
1256     */
1257    public void updateEmergencyCallButtonState(Button button, int  phoneState, boolean shown,
1258            boolean upperCase, boolean showIcon) {
1259        if (isEmergencyCallCapable() && shown) {
1260            button.setVisibility(View.VISIBLE);
1261        } else {
1262            button.setVisibility(View.GONE);
1263            return;
1264        }
1265
1266        int textId;
1267        if (phoneState == TelephonyManager.CALL_STATE_OFFHOOK) {
1268            // show "return to call" text and show phone icon
1269            textId = R.string.lockscreen_return_to_call;
1270            int phoneCallIcon = showIcon ? R.drawable.stat_sys_phone_call : 0;
1271            button.setCompoundDrawablesWithIntrinsicBounds(phoneCallIcon, 0, 0, 0);
1272        } else {
1273            textId = R.string.lockscreen_emergency_call;
1274            int emergencyIcon = showIcon ? R.drawable.ic_emergency : 0;
1275            button.setCompoundDrawablesWithIntrinsicBounds(emergencyIcon, 0, 0, 0);
1276        }
1277        if (upperCase) {
1278            CharSequence original = mContext.getResources().getText(textId);
1279            String upper = original != null ? original.toString().toUpperCase() : null;
1280            button.setText(upper);
1281        } else {
1282            button.setText(textId);
1283        }
1284    }
1285
1286    /**
1287     * @deprecated
1288     * @param button
1289     * @param phoneState
1290     * @param shown
1291     */
1292    public void updateEmergencyCallButtonState(Button button, int  phoneState, boolean shown) {
1293        updateEmergencyCallButtonState(button, phoneState, shown, false, true);
1294    }
1295
1296    /**
1297     * Resumes a call in progress. Typically launched from the EmergencyCall button
1298     * on various lockscreens.
1299     *
1300     * @return true if we were able to tell InCallScreen to show.
1301     */
1302    public boolean resumeCall() {
1303        ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
1304        try {
1305            if (phone != null && phone.showCallScreen()) {
1306                return true;
1307            }
1308        } catch (RemoteException e) {
1309            // What can we do?
1310        }
1311        return false;
1312    }
1313
1314    private void finishBiometricWeak() {
1315        setBoolean(BIOMETRIC_WEAK_EVER_CHOSEN_KEY, true);
1316
1317        // Launch intent to show final screen, this also
1318        // moves the temporary gallery to the actual gallery
1319        Intent intent = new Intent();
1320        intent.setClassName("com.android.facelock",
1321                "com.android.facelock.SetupEndScreen");
1322        mContext.startActivity(intent);
1323    }
1324
1325    public void setPowerButtonInstantlyLocks(boolean enabled) {
1326        setBoolean(LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS, enabled);
1327    }
1328
1329    public boolean getPowerButtonInstantlyLocks() {
1330        return getBoolean(LOCKSCREEN_POWER_BUTTON_INSTANTLY_LOCKS, true);
1331    }
1332
1333}
1334