ChooseLockPassword.java revision bbb4afa19f75694c585506b0c091372d60e07ca7
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
108        final boolean confirmCredentials = getIntent().getBooleanExtra("confirm_credentials", true);
109        int minMode = mLockPatternUtils.getRequestedPasswordQuality();
110        if (mRequestedQuality < minMode) {
111            mRequestedQuality = minMode;
112        }
113        int minLength = mLockPatternUtils.getRequestedMinimumPasswordLength();
114        if (mPasswordMinLength < minLength) {
115            mPasswordMinLength = minLength;
116        }
117        initViews();
118        mChooseLockSettingsHelper = new ChooseLockSettingsHelper(this);
119        if (savedInstanceState == null) {
120            updateStage(Stage.Introduction);
121            if (confirmCredentials) {
122                mChooseLockSettingsHelper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST);
123            }
124        }
125    }
126
127    private void initViews() {
128        setContentView(R.layout.choose_lock_password);
129        // Disable IME on our window since we provide our own keyboard
130        getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
131                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
132
133        mCancelButton = (Button) findViewById(R.id.cancel_button);
134        mCancelButton.setOnClickListener(this);
135        mNextButton = (Button) findViewById(R.id.next_button);
136        mNextButton.setOnClickListener(this);
137
138        mKeyboardView = (PasswordEntryKeyboardView) findViewById(R.id.keyboard);
139        mPasswordEntry = (TextView) findViewById(R.id.password_entry);
140        mPasswordEntry.setOnEditorActionListener(this);
141        mPasswordEntry.addTextChangedListener(this);
142
143        mIsAlphaMode = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality
144            || DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality;
145        mKeyboardHelper = new PasswordEntryKeyboardHelper(this, mKeyboardView, mPasswordEntry);
146        mKeyboardHelper.setKeyboardMode(mIsAlphaMode ?
147                PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA
148                : PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC);
149
150        mHeaderText = (TextView) findViewById(R.id.headerText);
151        mKeyboardView.requestFocus();
152    }
153
154    @Override
155    protected void onResume() {
156        super.onResume();
157        updateStage(mUiStage);
158        mKeyboardView.requestFocus();
159    }
160
161    @Override
162    protected void onSaveInstanceState(Bundle outState) {
163        super.onSaveInstanceState(outState);
164        outState.putString(KEY_UI_STAGE, mUiStage.name());
165        outState.putString(KEY_FIRST_PIN, mFirstPin);
166    }
167
168    @Override
169    protected void onRestoreInstanceState(Bundle savedInstanceState) {
170        super.onRestoreInstanceState(savedInstanceState);
171        String state = savedInstanceState.getString(KEY_UI_STAGE);
172        mFirstPin = savedInstanceState.getString(KEY_FIRST_PIN);
173        if (state != null) {
174            mUiStage = Stage.valueOf(state);
175            updateStage(mUiStage);
176        }
177    }
178
179    @Override
180    protected void onActivityResult(int requestCode, int resultCode,
181            Intent data) {
182        super.onActivityResult(requestCode, resultCode, data);
183        switch (requestCode) {
184            case CONFIRM_EXISTING_REQUEST:
185                if (resultCode != Activity.RESULT_OK) {
186                    setResult(RESULT_FINISHED);
187                    finish();
188                }
189                break;
190        }
191    }
192
193    protected void updateStage(Stage stage) {
194        mUiStage = stage;
195        updateUi();
196    }
197
198    /**
199     * Validates PIN and returns a message to display if PIN fails test.
200     * @param password the raw password the user typed in
201     * @return error message to show to user or null if password is OK
202     */
203    private String validatePassword(String password) {
204        if (password.length() < mPasswordMinLength) {
205            return getString(mIsAlphaMode ?
206                    R.string.lockpassword_password_too_short
207                    : R.string.lockpassword_pin_too_short, mPasswordMinLength);
208        }
209        if (password.length() > mPasswordMaxLength) {
210            return getString(mIsAlphaMode ?
211                    R.string.lockpassword_password_too_long
212                    : R.string.lockpassword_pin_too_long, mPasswordMaxLength);
213        }
214        boolean hasAlpha = false;
215        boolean hasDigit = false;
216        boolean hasSymbol = false;
217        for (int i = 0; i < password.length(); i++) {
218            char c = password.charAt(i);
219            // allow non white space Latin-1 characters only
220            if (c <= 32 || c > 127) {
221                return getString(R.string.lockpassword_illegal_character);
222            }
223            if (c >= '0' && c <= '9') {
224                hasDigit = true;
225            } else if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
226                hasAlpha = true;
227            } else {
228                hasSymbol = true;
229            }
230        }
231        if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality
232                && (hasAlpha | hasSymbol)) {
233            // This shouldn't be possible unless user finds some way to bring up soft keyboard
234            return getString(R.string.lockpassword_pin_contains_non_digits);
235        } else {
236            final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC
237                    == mRequestedQuality;
238            final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
239                    == mRequestedQuality;
240            final boolean symbolic = false; // not yet
241            if ((alphabetic || alphanumeric) && !hasAlpha) {
242                return getString(R.string.lockpassword_password_requires_alpha);
243            }
244            if (alphanumeric && !hasDigit) {
245                return getString(R.string.lockpassword_password_requires_digit);
246            }
247            if (symbolic && !hasSymbol) {
248                return getString(R.string.lockpassword_password_requires_symbol);
249            }
250        }
251        return null;
252    }
253
254    private void handleNext() {
255        final String pin = mPasswordEntry.getText().toString();
256        if (TextUtils.isEmpty(pin)) {
257            return;
258        }
259        String errorMsg = null;
260        if (mUiStage == Stage.Introduction) {
261            errorMsg = validatePassword(pin);
262            if (errorMsg == null) {
263                mFirstPin = pin;
264                updateStage(Stage.NeedToConfirm);
265                mPasswordEntry.setText("");
266            }
267        } else if (mUiStage == Stage.NeedToConfirm) {
268            if (mFirstPin.equals(pin)) {
269                mLockPatternUtils.clearLock();
270                mLockPatternUtils.saveLockPassword(pin, mRequestedQuality);
271                finish();
272            } else {
273                updateStage(Stage.ConfirmWrong);
274                CharSequence tmp = mPasswordEntry.getText();
275                if (tmp != null) {
276                    Selection.setSelection((Spannable) tmp, 0, tmp.length());
277                }
278            }
279        }
280        if (errorMsg != null) {
281            showError(errorMsg, mUiStage);
282        }
283    }
284
285    public void onClick(View v) {
286        switch (v.getId()) {
287            case R.id.next_button:
288                handleNext();
289                break;
290
291            case R.id.cancel_button:
292                finish();
293                break;
294        }
295    }
296
297    private void showError(String msg, final Stage next) {
298        mHeaderText.setText(msg);
299        mHandler.postDelayed(new Runnable() {
300            public void run() {
301                updateStage(next);
302            }
303        }, ERROR_MESSAGE_TIMEOUT);
304    }
305
306    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
307        // Check if this was the result of hitting the enter key
308        if (actionId == EditorInfo.IME_NULL) {
309            handleNext();
310            return true;
311        }
312        return false;
313    }
314
315    /**
316     * Update the hint based on current Stage and length of password entry
317     */
318    private void updateUi() {
319        String password = mPasswordEntry.getText().toString();
320        final int length = password.length();
321        if (mUiStage == Stage.Introduction && length > 0) {
322            if (length < mPasswordMinLength) {
323                String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short
324                        : R.string.lockpassword_pin_too_short, mPasswordMinLength);
325                mHeaderText.setText(msg);
326                mNextButton.setEnabled(false);
327            } else {
328                String error = validatePassword(password);
329                if (error != null) {
330                    mHeaderText.setText(error);
331                    mNextButton.setEnabled(false);
332                } else {
333                    mHeaderText.setText(R.string.lockpassword_press_continue);
334                    mNextButton.setEnabled(true);
335                }
336            }
337        } else {
338            mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint);
339            mNextButton.setEnabled(length > 0);
340        }
341        mNextButton.setText(mUiStage.buttonText);
342    }
343
344    public void afterTextChanged(Editable s) {
345        // Changing the text while error displayed resets to NeedToConfirm state
346        if (mUiStage == Stage.ConfirmWrong) {
347            mUiStage = Stage.NeedToConfirm;
348        }
349        updateUi();
350    }
351
352    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
353
354    }
355
356    public void onTextChanged(CharSequence s, int start, int before, int count) {
357
358    }
359}
360