ChooseLockPassword.java revision af366a3ed66dcb3c3ecb1dd101e5d8869b518598
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;
22
23import android.app.Activity;
24import android.app.admin.DevicePolicyManager;
25import android.content.Intent;
26import android.inputmethodservice.KeyboardView;
27import android.os.Bundle;
28import android.os.Handler;
29import android.text.Editable;
30import android.text.Selection;
31import android.text.Spannable;
32import android.text.TextUtils;
33import android.text.TextWatcher;
34import android.view.KeyEvent;
35import android.view.View;
36import android.view.WindowManager;
37import android.view.View.OnClickListener;
38import android.view.inputmethod.EditorInfo;
39import android.widget.Button;
40import android.widget.TextView;
41import android.widget.TextView.OnEditorActionListener;
42
43
44public class ChooseLockPassword extends Activity implements OnClickListener, OnEditorActionListener,
45        TextWatcher {
46    private static final String KEY_FIRST_PIN = "first_pin";
47    private static final String KEY_UI_STAGE = "ui_stage";
48    private TextView mPasswordEntry;
49    private int mPasswordMinLength = 4;
50    private int mPasswordMaxLength = 16;
51    private LockPatternUtils mLockPatternUtils;
52    private int mRequestedQuality = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
53    private ChooseLockSettingsHelper mChooseLockSettingsHelper;
54    private com.android.settings.ChooseLockPassword.Stage mUiStage = Stage.Introduction;
55    private TextView mHeaderText;
56    private String mFirstPin;
57    private KeyboardView mKeyboardView;
58    private PasswordEntryKeyboardHelper mKeyboardHelper;
59    private boolean mIsAlphaMode;
60    private Button mCancelButton;
61    private Button mNextButton;
62    public static final String PASSWORD_MIN_KEY = "lockscreen.password_min";
63    public static final String PASSWORD_MAX_KEY = "lockscreen.password_max";
64    private static Handler mHandler = new Handler();
65    private static final int CONFIRM_EXISTING_REQUEST = 58;
66    static final int RESULT_FINISHED = RESULT_FIRST_USER;
67    private static final long ERROR_MESSAGE_TIMEOUT = 3000;
68
69    /**
70     * Keep track internally of where the user is in choosing a pattern.
71     */
72    protected enum Stage {
73
74        Introduction(R.string.lockpassword_choose_your_password_header,
75                R.string.lockpassword_choose_your_pin_header,
76                R.string.lockpassword_continue_label),
77
78        NeedToConfirm(R.string.lockpassword_confirm_your_password_header,
79                R.string.lockpassword_confirm_your_pin_header,
80                R.string.lockpassword_ok_label),
81
82        ConfirmWrong(R.string.lockpassword_confirm_passwords_dont_match,
83                R.string.lockpassword_confirm_pins_dont_match,
84                R.string.lockpassword_continue_label);
85
86        /**
87         * @param headerMessage The message displayed at the top.
88         */
89        Stage(int hintInAlpha, int hintInNumeric, int nextButtonText) {
90            this.alphaHint = hintInAlpha;
91            this.numericHint = hintInNumeric;
92            this.buttonText = nextButtonText;
93        }
94
95        public final int alphaHint;
96        public final int numericHint;
97        public final int buttonText;
98    }
99
100    @Override
101    protected void onCreate(Bundle savedInstanceState) {
102        super.onCreate(savedInstanceState);
103        mLockPatternUtils = new LockPatternUtils(this);
104        mRequestedQuality = getIntent().getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY, mRequestedQuality);
105        mPasswordMinLength = getIntent().getIntExtra(PASSWORD_MIN_KEY, mPasswordMinLength);
106        mPasswordMaxLength = getIntent().getIntExtra(PASSWORD_MAX_KEY, mPasswordMaxLength);
107        int minMode = mLockPatternUtils.getRequestedPasswordQuality();
108        if (mRequestedQuality < minMode) {
109            mRequestedQuality = minMode;
110        }
111        int minLength = mLockPatternUtils.getRequestedMinimumPasswordLength();
112        if (mPasswordMinLength < minLength) {
113            mPasswordMinLength = minLength;
114        }
115        initViews();
116        mChooseLockSettingsHelper = new ChooseLockSettingsHelper(this);
117        if (savedInstanceState == null) {
118            updateStage(Stage.Introduction);
119            mChooseLockSettingsHelper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST);
120        }
121    }
122
123    private void initViews() {
124        setContentView(R.layout.choose_lock_password);
125        // Disable IME on our window since we provide our own keyboard
126        getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
127                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
128
129        mCancelButton = (Button) findViewById(R.id.cancel_button);
130        mCancelButton.setOnClickListener(this);
131        mNextButton = (Button) findViewById(R.id.next_button);
132        mNextButton.setOnClickListener(this);
133
134        mKeyboardView = (PasswordEntryKeyboardView) findViewById(R.id.keyboard);
135        mPasswordEntry = (TextView) findViewById(R.id.password_entry);
136        mPasswordEntry.setOnEditorActionListener(this);
137        mPasswordEntry.addTextChangedListener(this);
138
139        mIsAlphaMode = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality
140            || DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality;
141        mKeyboardHelper = new PasswordEntryKeyboardHelper(this, mKeyboardView, mPasswordEntry);
142        mKeyboardHelper.setKeyboardMode(mIsAlphaMode ?
143                PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA
144                : PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC);
145
146        mHeaderText = (TextView) findViewById(R.id.headerText);
147        mKeyboardView.requestFocus();
148    }
149
150    @Override
151    protected void onResume() {
152        super.onResume();
153        updateStage(mUiStage);
154        mKeyboardView.requestFocus();
155    }
156
157    @Override
158    protected void onSaveInstanceState(Bundle outState) {
159        super.onSaveInstanceState(outState);
160        outState.putString(KEY_UI_STAGE, mUiStage.name());
161        outState.putString(KEY_FIRST_PIN, mFirstPin);
162    }
163
164    @Override
165    protected void onRestoreInstanceState(Bundle savedInstanceState) {
166        super.onRestoreInstanceState(savedInstanceState);
167        String state = savedInstanceState.getString(KEY_UI_STAGE);
168        mFirstPin = savedInstanceState.getString(KEY_FIRST_PIN);
169        if (state != null) {
170            mUiStage = Stage.valueOf(state);
171            updateStage(mUiStage);
172        }
173    }
174
175    @Override
176    protected void onActivityResult(int requestCode, int resultCode,
177            Intent data) {
178        super.onActivityResult(requestCode, resultCode, data);
179        switch (requestCode) {
180            case CONFIRM_EXISTING_REQUEST:
181                if (resultCode != Activity.RESULT_OK) {
182                    setResult(RESULT_FINISHED);
183                    finish();
184                }
185                break;
186        }
187    }
188
189    protected void updateStage(Stage stage) {
190        mUiStage = stage;
191        updateUi();
192    }
193
194    /**
195     * Validates PIN and returns a message to display if PIN fails test.
196     * @param password the raw password the user typed in
197     * @return error message to show to user or null if password is OK
198     */
199    private String validatePassword(String password) {
200        if (password.length() < mPasswordMinLength) {
201            return getString(mIsAlphaMode ?
202                    R.string.lockpassword_password_too_short
203                    : R.string.lockpassword_pin_too_short, mPasswordMinLength);
204        }
205        if (password.length() > mPasswordMaxLength) {
206            return getString(mIsAlphaMode ?
207                    R.string.lockpassword_password_too_long
208                    : R.string.lockpassword_pin_too_long, mPasswordMaxLength);
209        }
210        boolean hasAlpha = false;
211        boolean hasDigit = false;
212        boolean hasSymbol = false;
213        for (int i = 0; i < password.length(); i++) {
214            char c = password.charAt(i);
215            // allow non white space Latin-1 characters only
216            if (c <= 32 || c > 127) {
217                return getString(R.string.lockpassword_illegal_character);
218            }
219            if (c >= '0' && c <= '9') {
220                hasDigit = true;
221            } else if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
222                hasAlpha = true;
223            } else {
224                hasSymbol = true;
225            }
226        }
227        if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality
228                && (hasAlpha | hasSymbol)) {
229            // This shouldn't be possible unless user finds some way to bring up soft keyboard
230            return getString(R.string.lockpassword_pin_contains_non_digits);
231        } else {
232            final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC
233                    == mRequestedQuality;
234            final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
235                    == mRequestedQuality;
236            final boolean symbolic = false; // not yet
237            if ((alphabetic || alphanumeric) && !hasAlpha) {
238                return getString(R.string.lockpassword_password_requires_alpha);
239            }
240            if (alphanumeric && !hasDigit) {
241                return getString(R.string.lockpassword_password_requires_digit);
242            }
243            if (symbolic && !hasSymbol) {
244                return getString(R.string.lockpassword_password_requires_symbol);
245            }
246        }
247        return null;
248    }
249
250    private void handleNext() {
251        final String pin = mPasswordEntry.getText().toString();
252        if (TextUtils.isEmpty(pin)) {
253            return;
254        }
255        String errorMsg = null;
256        if (mUiStage == Stage.Introduction) {
257            errorMsg = validatePassword(pin);
258            if (errorMsg == null) {
259                mFirstPin = pin;
260                updateStage(Stage.NeedToConfirm);
261                mPasswordEntry.setText("");
262            }
263        } else if (mUiStage == Stage.NeedToConfirm) {
264            if (mFirstPin.equals(pin)) {
265                mLockPatternUtils.clearLock();
266                mLockPatternUtils.saveLockPassword(pin, mRequestedQuality);
267                finish();
268            } else {
269                updateStage(Stage.ConfirmWrong);
270                CharSequence tmp = mPasswordEntry.getText();
271                if (tmp != null) {
272                    Selection.setSelection((Spannable) tmp, 0, tmp.length());
273                }
274            }
275        }
276        if (errorMsg != null) {
277            showError(errorMsg, mUiStage);
278        }
279    }
280
281    public void onClick(View v) {
282        switch (v.getId()) {
283            case R.id.next_button:
284                handleNext();
285                break;
286
287            case R.id.cancel_button:
288                finish();
289                break;
290        }
291    }
292
293    private void showError(String msg, final Stage next) {
294        mHeaderText.setText(msg);
295        mHandler.postDelayed(new Runnable() {
296            public void run() {
297                updateStage(next);
298            }
299        }, ERROR_MESSAGE_TIMEOUT);
300    }
301
302    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
303        // Check if this was the result of hitting the enter key
304        if (actionId == EditorInfo.IME_NULL) {
305            handleNext();
306            return true;
307        }
308        return false;
309    }
310
311    /**
312     * Update the hint based on current Stage and length of password entry
313     */
314    private void updateUi() {
315        String password = mPasswordEntry.getText().toString();
316        final int length = password.length();
317        if (mUiStage == Stage.Introduction && length > 0) {
318            if (length < mPasswordMinLength) {
319                String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short
320                        : R.string.lockpassword_pin_too_short, mPasswordMinLength);
321                mHeaderText.setText(msg);
322                mNextButton.setEnabled(false);
323            } else {
324                String error = validatePassword(password);
325                if (error != null) {
326                    mHeaderText.setText(error);
327                    mNextButton.setEnabled(false);
328                } else {
329                    mHeaderText.setText(R.string.lockpassword_press_continue);
330                    mNextButton.setEnabled(true);
331                }
332            }
333        } else {
334            mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint);
335            mNextButton.setEnabled(length > 0);
336        }
337        mNextButton.setText(mUiStage.buttonText);
338    }
339
340    public void afterTextChanged(Editable s) {
341        // Changing the text while error displayed resets to NeedToConfirm state
342        if (mUiStage == Stage.ConfirmWrong) {
343            mUiStage = Stage.NeedToConfirm;
344        }
345        updateUi();
346    }
347
348    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
349
350    }
351
352    public void onTextChanged(CharSequence s, int start, int before, int count) {
353
354    }
355}
356