ChooseLockPassword.java revision 46c7f6d6f32efec26bc9343f591ad1ddbe8f3b4a
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings;
18
19import com.android.internal.widget.LockPatternUtils;
20import com.android.internal.widget.PasswordEntryKeyboardHelper;
21import com.android.internal.widget.PasswordEntryKeyboardView;
22import com.android.settings.notification.RedactionInterstitial;
23
24import android.app.Activity;
25import android.app.Fragment;
26import android.app.admin.DevicePolicyManager;
27import android.content.ContentResolver;
28import android.content.Intent;
29import android.inputmethodservice.KeyboardView;
30import android.os.Bundle;
31import android.os.Handler;
32import android.os.Message;
33import android.provider.Settings;
34import android.text.Editable;
35import android.text.InputType;
36import android.text.Selection;
37import android.text.Spannable;
38import android.text.TextUtils;
39import android.text.TextWatcher;
40import android.view.KeyEvent;
41import android.view.LayoutInflater;
42import android.view.View;
43import android.view.ViewGroup;
44import android.view.View.OnClickListener;
45import android.view.inputmethod.EditorInfo;
46import android.widget.Button;
47import android.widget.TextView;
48import android.widget.TextView.OnEditorActionListener;
49
50public class ChooseLockPassword extends SettingsActivity {
51    public static final String PASSWORD_MIN_KEY = "lockscreen.password_min";
52    public static final String PASSWORD_MAX_KEY = "lockscreen.password_max";
53    public static final String PASSWORD_MIN_LETTERS_KEY = "lockscreen.password_min_letters";
54    public static final String PASSWORD_MIN_LOWERCASE_KEY = "lockscreen.password_min_lowercase";
55    public static final String PASSWORD_MIN_UPPERCASE_KEY = "lockscreen.password_min_uppercase";
56    public static final String PASSWORD_MIN_NUMERIC_KEY = "lockscreen.password_min_numeric";
57    public static final String PASSWORD_MIN_SYMBOLS_KEY = "lockscreen.password_min_symbols";
58    public static final String PASSWORD_MIN_NONLETTER_KEY = "lockscreen.password_min_nonletter";
59
60    @Override
61    public Intent getIntent() {
62        Intent modIntent = new Intent(super.getIntent());
63        modIntent.putExtra(EXTRA_SHOW_FRAGMENT, ChooseLockPasswordFragment.class.getName());
64        return modIntent;
65    }
66
67    @Override
68    protected boolean isValidFragment(String fragmentName) {
69        if (ChooseLockPasswordFragment.class.getName().equals(fragmentName)) return true;
70        return false;
71    }
72
73    @Override
74    public void onCreate(Bundle savedInstanceState) {
75        // TODO: Fix on phones
76        // Disable IME on our window since we provide our own keyboard
77        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
78                //WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
79        super.onCreate(savedInstanceState);
80        CharSequence msg = getText(R.string.lockpassword_choose_your_password_header);
81        setTitle(msg);
82    }
83
84    public static class ChooseLockPasswordFragment extends Fragment
85            implements OnClickListener, OnEditorActionListener,  TextWatcher {
86        private static final String KEY_FIRST_PIN = "first_pin";
87        private static final String KEY_UI_STAGE = "ui_stage";
88        private TextView mPasswordEntry;
89        private int mPasswordMinLength = 4;
90        private int mPasswordMaxLength = 16;
91        private int mPasswordMinLetters = 0;
92        private int mPasswordMinUpperCase = 0;
93        private int mPasswordMinLowerCase = 0;
94        private int mPasswordMinSymbols = 0;
95        private int mPasswordMinNumeric = 0;
96        private int mPasswordMinNonLetter = 0;
97        private LockPatternUtils mLockPatternUtils;
98        private int mRequestedQuality = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
99        private ChooseLockSettingsHelper mChooseLockSettingsHelper;
100        private Stage mUiStage = Stage.Introduction;
101        private boolean mDone = false;
102        private TextView mHeaderText;
103        private String mFirstPin;
104        private KeyboardView mKeyboardView;
105        private PasswordEntryKeyboardHelper mKeyboardHelper;
106        private boolean mIsAlphaMode;
107        private Button mCancelButton;
108        private Button mNextButton;
109        private static final int CONFIRM_EXISTING_REQUEST = 58;
110        static final int RESULT_FINISHED = RESULT_FIRST_USER;
111        private static final long ERROR_MESSAGE_TIMEOUT = 3000;
112        private static final int MSG_SHOW_ERROR = 1;
113
114        private Handler mHandler = new Handler() {
115            @Override
116            public void handleMessage(Message msg) {
117                if (msg.what == MSG_SHOW_ERROR) {
118                    updateStage((Stage) msg.obj);
119                }
120            }
121        };
122
123        /**
124         * Keep track internally of where the user is in choosing a pattern.
125         */
126        protected enum Stage {
127
128            Introduction(R.string.lockpassword_choose_your_password_header,
129                    R.string.lockpassword_choose_your_pin_header,
130                    R.string.lockpassword_continue_label),
131
132            NeedToConfirm(R.string.lockpassword_confirm_your_password_header,
133                    R.string.lockpassword_confirm_your_pin_header,
134                    R.string.lockpassword_ok_label),
135
136            ConfirmWrong(R.string.lockpassword_confirm_passwords_dont_match,
137                    R.string.lockpassword_confirm_pins_dont_match,
138                    R.string.lockpassword_continue_label);
139
140            Stage(int hintInAlpha, int hintInNumeric, int nextButtonText) {
141                this.alphaHint = hintInAlpha;
142                this.numericHint = hintInNumeric;
143                this.buttonText = nextButtonText;
144            }
145
146            public final int alphaHint;
147            public final int numericHint;
148            public final int buttonText;
149        }
150
151        // required constructor for fragments
152        public ChooseLockPasswordFragment() {
153
154        }
155
156        @Override
157        public void onCreate(Bundle savedInstanceState) {
158            super.onCreate(savedInstanceState);
159            mLockPatternUtils = new LockPatternUtils(getActivity());
160            Intent intent = getActivity().getIntent();
161            if (!(getActivity() instanceof ChooseLockPassword)) {
162                throw new SecurityException("Fragment contained in wrong activity");
163            }
164            mRequestedQuality = Math.max(intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY,
165                    mRequestedQuality), mLockPatternUtils.getRequestedPasswordQuality());
166            mPasswordMinLength = Math.max(
167                    intent.getIntExtra(PASSWORD_MIN_KEY, mPasswordMinLength), mLockPatternUtils
168                            .getRequestedMinimumPasswordLength());
169            mPasswordMaxLength = intent.getIntExtra(PASSWORD_MAX_KEY, mPasswordMaxLength);
170            mPasswordMinLetters = Math.max(intent.getIntExtra(PASSWORD_MIN_LETTERS_KEY,
171                    mPasswordMinLetters), mLockPatternUtils.getRequestedPasswordMinimumLetters());
172            mPasswordMinUpperCase = Math.max(intent.getIntExtra(PASSWORD_MIN_UPPERCASE_KEY,
173                    mPasswordMinUpperCase), mLockPatternUtils.getRequestedPasswordMinimumUpperCase());
174            mPasswordMinLowerCase = Math.max(intent.getIntExtra(PASSWORD_MIN_LOWERCASE_KEY,
175                    mPasswordMinLowerCase), mLockPatternUtils.getRequestedPasswordMinimumLowerCase());
176            mPasswordMinNumeric = Math.max(intent.getIntExtra(PASSWORD_MIN_NUMERIC_KEY,
177                    mPasswordMinNumeric), mLockPatternUtils.getRequestedPasswordMinimumNumeric());
178            mPasswordMinSymbols = Math.max(intent.getIntExtra(PASSWORD_MIN_SYMBOLS_KEY,
179                    mPasswordMinSymbols), mLockPatternUtils.getRequestedPasswordMinimumSymbols());
180            mPasswordMinNonLetter = Math.max(intent.getIntExtra(PASSWORD_MIN_NONLETTER_KEY,
181                    mPasswordMinNonLetter), mLockPatternUtils.getRequestedPasswordMinimumNonLetter());
182
183            mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity());
184        }
185
186        @Override
187        public View onCreateView(LayoutInflater inflater, ViewGroup container,
188                Bundle savedInstanceState) {
189
190            View view = inflater.inflate(R.layout.choose_lock_password, null);
191
192            mCancelButton = (Button) view.findViewById(R.id.cancel_button);
193            mCancelButton.setOnClickListener(this);
194            mNextButton = (Button) view.findViewById(R.id.next_button);
195            mNextButton.setOnClickListener(this);
196
197            mIsAlphaMode = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality
198                    || DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality
199                    || DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality;
200            mKeyboardView = (PasswordEntryKeyboardView) view.findViewById(R.id.keyboard);
201            mPasswordEntry = (TextView) view.findViewById(R.id.password_entry);
202            mPasswordEntry.setOnEditorActionListener(this);
203            mPasswordEntry.addTextChangedListener(this);
204
205            final Activity activity = getActivity();
206            mKeyboardHelper = new PasswordEntryKeyboardHelper(activity,
207                    mKeyboardView, mPasswordEntry);
208            mKeyboardHelper.setKeyboardMode(mIsAlphaMode ?
209                    PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA
210                    : PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC);
211
212            mHeaderText = (TextView) view.findViewById(R.id.headerText);
213            mKeyboardView.requestFocus();
214
215            int currentType = mPasswordEntry.getInputType();
216            mPasswordEntry.setInputType(mIsAlphaMode ? currentType
217                    : (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
218
219            Intent intent = getActivity().getIntent();
220            final boolean confirmCredentials = intent.getBooleanExtra("confirm_credentials", true);
221            if (savedInstanceState == null) {
222                updateStage(Stage.Introduction);
223                if (confirmCredentials) {
224                    mChooseLockSettingsHelper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST,
225                            null, null);
226                }
227            } else {
228                mFirstPin = savedInstanceState.getString(KEY_FIRST_PIN);
229                final String state = savedInstanceState.getString(KEY_UI_STAGE);
230                if (state != null) {
231                    mUiStage = Stage.valueOf(state);
232                    updateStage(mUiStage);
233                }
234            }
235            mDone = false;
236            if (activity instanceof SettingsActivity) {
237                final SettingsActivity sa = (SettingsActivity) activity;
238                int id = mIsAlphaMode ? R.string.lockpassword_choose_your_password_header
239                        : R.string.lockpassword_choose_your_pin_header;
240                CharSequence title = getText(id);
241                sa.setTitle(title);
242            }
243
244            return view;
245        }
246
247        @Override
248        public void onResume() {
249            super.onResume();
250            updateStage(mUiStage);
251            mKeyboardView.requestFocus();
252        }
253
254        @Override
255        public void onPause() {
256            mHandler.removeMessages(MSG_SHOW_ERROR);
257
258            super.onPause();
259        }
260
261        @Override
262        public void onSaveInstanceState(Bundle outState) {
263            super.onSaveInstanceState(outState);
264            outState.putString(KEY_UI_STAGE, mUiStage.name());
265            outState.putString(KEY_FIRST_PIN, mFirstPin);
266        }
267
268        @Override
269        public void onActivityResult(int requestCode, int resultCode,
270                Intent data) {
271            super.onActivityResult(requestCode, resultCode, data);
272            switch (requestCode) {
273                case CONFIRM_EXISTING_REQUEST:
274                    if (resultCode != Activity.RESULT_OK) {
275                        getActivity().setResult(RESULT_FINISHED);
276                        getActivity().finish();
277                    }
278                    break;
279            }
280        }
281
282        protected void updateStage(Stage stage) {
283            final Stage previousStage = mUiStage;
284            mUiStage = stage;
285            updateUi();
286
287            // If the stage changed, announce the header for accessibility. This
288            // is a no-op when accessibility is disabled.
289            if (previousStage != stage) {
290                mHeaderText.announceForAccessibility(mHeaderText.getText());
291            }
292        }
293
294        /**
295         * Validates PIN and returns a message to display if PIN fails test.
296         * @param password the raw password the user typed in
297         * @return error message to show to user or null if password is OK
298         */
299        private String validatePassword(String password) {
300            if (password.length() < mPasswordMinLength) {
301                return getString(mIsAlphaMode ?
302                        R.string.lockpassword_password_too_short
303                        : R.string.lockpassword_pin_too_short, mPasswordMinLength);
304            }
305            if (password.length() > mPasswordMaxLength) {
306                return getString(mIsAlphaMode ?
307                        R.string.lockpassword_password_too_long
308                        : R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1);
309            }
310            int letters = 0;
311            int numbers = 0;
312            int lowercase = 0;
313            int symbols = 0;
314            int uppercase = 0;
315            int nonletter = 0;
316            for (int i = 0; i < password.length(); i++) {
317                char c = password.charAt(i);
318                // allow non control Latin-1 characters only
319                if (c < 32 || c > 127) {
320                    return getString(R.string.lockpassword_illegal_character);
321                }
322                if (c >= '0' && c <= '9') {
323                    numbers++;
324                    nonletter++;
325                } else if (c >= 'A' && c <= 'Z') {
326                    letters++;
327                    uppercase++;
328                } else if (c >= 'a' && c <= 'z') {
329                    letters++;
330                    lowercase++;
331                } else {
332                    symbols++;
333                    nonletter++;
334                }
335            }
336            if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality
337                    || DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX == mRequestedQuality) {
338                if (letters > 0 || symbols > 0) {
339                    // This shouldn't be possible unless user finds some way to bring up
340                    // soft keyboard
341                    return getString(R.string.lockpassword_pin_contains_non_digits);
342                }
343                // Check for repeated characters or sequences (e.g. '1234', '0000', '2468')
344                final int sequence = LockPatternUtils.maxLengthSequence(password);
345                if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX == mRequestedQuality
346                        && sequence > LockPatternUtils.MAX_ALLOWED_SEQUENCE) {
347                    return getString(R.string.lockpassword_pin_no_sequential_digits);
348                }
349            } else if (DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality) {
350                if (letters < mPasswordMinLetters) {
351                    return String.format(getResources().getQuantityString(
352                            R.plurals.lockpassword_password_requires_letters, mPasswordMinLetters),
353                            mPasswordMinLetters);
354                } else if (numbers < mPasswordMinNumeric) {
355                    return String.format(getResources().getQuantityString(
356                            R.plurals.lockpassword_password_requires_numeric, mPasswordMinNumeric),
357                            mPasswordMinNumeric);
358                } else if (lowercase < mPasswordMinLowerCase) {
359                    return String.format(getResources().getQuantityString(
360                            R.plurals.lockpassword_password_requires_lowercase, mPasswordMinLowerCase),
361                            mPasswordMinLowerCase);
362                } else if (uppercase < mPasswordMinUpperCase) {
363                    return String.format(getResources().getQuantityString(
364                            R.plurals.lockpassword_password_requires_uppercase, mPasswordMinUpperCase),
365                            mPasswordMinUpperCase);
366                } else if (symbols < mPasswordMinSymbols) {
367                    return String.format(getResources().getQuantityString(
368                            R.plurals.lockpassword_password_requires_symbols, mPasswordMinSymbols),
369                            mPasswordMinSymbols);
370                } else if (nonletter < mPasswordMinNonLetter) {
371                    return String.format(getResources().getQuantityString(
372                            R.plurals.lockpassword_password_requires_nonletter, mPasswordMinNonLetter),
373                            mPasswordMinNonLetter);
374                }
375            } else {
376                final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC
377                        == mRequestedQuality;
378                final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
379                        == mRequestedQuality;
380                if ((alphabetic || alphanumeric) && letters == 0) {
381                    return getString(R.string.lockpassword_password_requires_alpha);
382                }
383                if (alphanumeric && numbers == 0) {
384                    return getString(R.string.lockpassword_password_requires_digit);
385                }
386            }
387            if(mLockPatternUtils.checkPasswordHistory(password)) {
388                return getString(mIsAlphaMode ? R.string.lockpassword_password_recently_used
389                        : R.string.lockpassword_pin_recently_used);
390            }
391
392            return null;
393        }
394
395        private void handleNext() {
396            if (mDone) return;
397
398            final String pin = mPasswordEntry.getText().toString();
399            if (TextUtils.isEmpty(pin)) {
400                return;
401            }
402            String errorMsg = null;
403            if (mUiStage == Stage.Introduction) {
404                errorMsg = validatePassword(pin);
405                if (errorMsg == null) {
406                    mFirstPin = pin;
407                    mPasswordEntry.setText("");
408                    updateStage(Stage.NeedToConfirm);
409                }
410            } else if (mUiStage == Stage.NeedToConfirm) {
411                if (mFirstPin.equals(pin)) {
412                    final boolean isFallback = getActivity().getIntent().getBooleanExtra(
413                            LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);
414                    mLockPatternUtils.clearLock(isFallback);
415                    mLockPatternUtils.saveLockPassword(pin, mRequestedQuality, isFallback);
416                    getActivity().setResult(RESULT_FINISHED);
417                    getActivity().finish();
418                    mDone = true;
419                    startActivity(RedactionInterstitial.createStartIntent(getActivity()));
420                } else {
421                    CharSequence tmp = mPasswordEntry.getText();
422                    if (tmp != null) {
423                        Selection.setSelection((Spannable) tmp, 0, tmp.length());
424                    }
425                    updateStage(Stage.ConfirmWrong);
426                }
427            }
428            if (errorMsg != null) {
429                showError(errorMsg, mUiStage);
430            }
431        }
432
433        public void onClick(View v) {
434            switch (v.getId()) {
435                case R.id.next_button:
436                    handleNext();
437                    break;
438
439                case R.id.cancel_button:
440                    getActivity().finish();
441                    break;
442            }
443        }
444
445        private void showError(String msg, final Stage next) {
446            mHeaderText.setText(msg);
447            mHeaderText.announceForAccessibility(mHeaderText.getText());
448            Message mesg = mHandler.obtainMessage(MSG_SHOW_ERROR, next);
449            mHandler.removeMessages(MSG_SHOW_ERROR);
450            mHandler.sendMessageDelayed(mesg, ERROR_MESSAGE_TIMEOUT);
451        }
452
453        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
454            // Check if this was the result of hitting the enter or "done" key
455            if (actionId == EditorInfo.IME_NULL
456                    || actionId == EditorInfo.IME_ACTION_DONE
457                    || actionId == EditorInfo.IME_ACTION_NEXT) {
458                handleNext();
459                return true;
460            }
461            return false;
462        }
463
464        /**
465         * Update the hint based on current Stage and length of password entry
466         */
467        private void updateUi() {
468            String password = mPasswordEntry.getText().toString();
469            final int length = password.length();
470            if (mUiStage == Stage.Introduction && length > 0) {
471                if (length < mPasswordMinLength) {
472                    String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short
473                            : R.string.lockpassword_pin_too_short, mPasswordMinLength);
474                    mHeaderText.setText(msg);
475                    mNextButton.setEnabled(false);
476                } else {
477                    String error = validatePassword(password);
478                    if (error != null) {
479                        mHeaderText.setText(error);
480                        mNextButton.setEnabled(false);
481                    } else {
482                        mHeaderText.setText(R.string.lockpassword_press_continue);
483                        mNextButton.setEnabled(true);
484                    }
485                }
486            } else {
487                mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint);
488                mNextButton.setEnabled(length > 0);
489            }
490            mNextButton.setText(mUiStage.buttonText);
491        }
492
493        public void afterTextChanged(Editable s) {
494            // Changing the text while error displayed resets to NeedToConfirm state
495            if (mUiStage == Stage.ConfirmWrong) {
496                mUiStage = Stage.NeedToConfirm;
497            }
498            updateUi();
499        }
500
501        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
502
503        }
504
505        public void onTextChanged(CharSequence s, int start, int before, int count) {
506
507        }
508    }
509}
510