KeyguardPatternView.java revision 3af630c8d18bcf4b23a5a308917319dd04cc8ed2
1/*
2 * Copyright (C) 2012 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 */
16package com.android.internal.policy.impl.keyguard;
17
18import android.accounts.Account;
19import android.accounts.AccountManager;
20import android.accounts.AccountManagerCallback;
21import android.accounts.AccountManagerFuture;
22import android.accounts.AuthenticatorException;
23import android.accounts.OperationCanceledException;
24import android.content.Context;
25import android.graphics.Rect;
26import android.os.Bundle;
27import android.os.CountDownTimer;
28import android.os.SystemClock;
29import android.util.AttributeSet;
30import android.util.Log;
31import android.view.MotionEvent;
32import android.view.View;
33import android.widget.Button;
34import android.widget.LinearLayout;
35
36import com.android.internal.widget.LockPatternUtils;
37import com.android.internal.widget.LockPatternView;
38import com.android.internal.R;
39
40import java.io.IOException;
41import java.util.List;
42
43public class KeyguardPatternView extends LinearLayout implements KeyguardSecurityView {
44
45    private static final String TAG = "SecurityPatternView";
46    private static final boolean DEBUG = false;
47
48    // how long before we clear the wrong pattern
49    private static final int PATTERN_CLEAR_TIMEOUT_MS = 2000;
50
51    // how long we stay awake after each key beyond MIN_PATTERN_BEFORE_POKE_WAKELOCK
52    private static final int UNLOCK_PATTERN_WAKE_INTERVAL_MS = 7000;
53
54    // how long we stay awake after the user hits the first dot.
55    private static final int UNLOCK_PATTERN_WAKE_INTERVAL_FIRST_DOTS_MS = 2000;
56
57    // how many cells the user has to cross before we poke the wakelock
58    private static final int MIN_PATTERN_BEFORE_POKE_WAKELOCK = 2;
59
60    private int mFailedPatternAttemptsSinceLastTimeout = 0;
61    private int mTotalFailedPatternAttempts = 0;
62    private CountDownTimer mCountdownTimer = null;
63    private LockPatternUtils mLockPatternUtils;
64    private LockPatternView mLockPatternView;
65    private Button mForgotPatternButton;
66    private KeyguardSecurityCallback mCallback;
67    private boolean mEnableFallback;
68    private KeyguardNavigationManager mNavigationManager;
69
70    /**
71     * Keeps track of the last time we poked the wake lock during dispatching of the touch event.
72     * Initialized to something guaranteed to make us poke the wakelock when the user starts
73     * drawing the pattern.
74     * @see #dispatchTouchEvent(android.view.MotionEvent)
75     */
76    private long mLastPokeTime = -UNLOCK_PATTERN_WAKE_INTERVAL_MS;
77
78    /**
79     * Useful for clearing out the wrong pattern after a delay
80     */
81    private Runnable mCancelPatternRunnable = new Runnable() {
82        public void run() {
83            mLockPatternView.clearPattern();
84        }
85    };
86    private Rect mTempRect = new Rect();
87
88    enum FooterMode {
89        Normal,
90        ForgotLockPattern,
91        VerifyUnlocked
92    }
93
94    public KeyguardPatternView(Context context) {
95        this(context, null);
96    }
97
98    public KeyguardPatternView(Context context, AttributeSet attrs) {
99        super(context, attrs);
100    }
101
102    public void setKeyguardCallback(KeyguardSecurityCallback callback) {
103        mCallback = callback;
104    }
105
106    public void setLockPatternUtils(LockPatternUtils utils) {
107        mLockPatternUtils = utils;
108    }
109
110    @Override
111    protected void onFinishInflate() {
112        super.onFinishInflate();
113
114        mNavigationManager = new KeyguardNavigationManager(this);
115        mLockPatternUtils = mLockPatternUtils == null
116                ? new LockPatternUtils(mContext) : mLockPatternUtils;
117
118        mLockPatternView = (LockPatternView) findViewById(R.id.lockPatternView);
119        mLockPatternView.setSaveEnabled(false);
120        mLockPatternView.setFocusable(false);
121        mLockPatternView.setOnPatternListener(new UnlockPatternListener());
122
123        // stealth mode will be the same for the life of this screen
124        mLockPatternView.setInStealthMode(!mLockPatternUtils.isVisiblePatternEnabled());
125
126        // vibrate mode will be the same for the life of this screen
127        mLockPatternView.setTactileFeedbackEnabled(mLockPatternUtils.isTactileFeedbackEnabled());
128
129        mForgotPatternButton = (Button) findViewById(R.id.forgot_password_button);
130        mForgotPatternButton.setText(R.string.kg_forgot_pattern_button_text);
131        mForgotPatternButton.setOnClickListener(new OnClickListener() {
132            public void onClick(View v) {
133                mCallback.showBackupSecurity();
134            }
135        });
136
137        setFocusableInTouchMode(true);
138
139        maybeEnableFallback(mContext);
140    }
141
142    private void updateFooter(FooterMode mode) {
143        switch (mode) {
144            case Normal:
145                if (DEBUG) Log.d(TAG, "mode normal");
146                mForgotPatternButton.setVisibility(View.GONE);
147                break;
148            case ForgotLockPattern:
149                if (DEBUG) Log.d(TAG, "mode ForgotLockPattern");
150                mForgotPatternButton.setVisibility(View.VISIBLE);
151                break;
152            case VerifyUnlocked:
153                if (DEBUG) Log.d(TAG, "mode VerifyUnlocked");
154                mForgotPatternButton.setVisibility(View.GONE);
155        }
156    }
157
158    @Override
159    public boolean onTouchEvent(MotionEvent ev) {
160        boolean result = super.onTouchEvent(ev);
161        // as long as the user is entering a pattern (i.e sending a touch event that was handled
162        // by this screen), keep poking the wake lock so that the screen will stay on.
163        final long elapsed = SystemClock.elapsedRealtime() - mLastPokeTime;
164        if (result && (elapsed > (UNLOCK_PATTERN_WAKE_INTERVAL_MS - 100))) {
165            mLastPokeTime = SystemClock.elapsedRealtime();
166        }
167        mTempRect.set(0, 0, 0, 0);
168        offsetRectIntoDescendantCoords(mLockPatternView, mTempRect);
169        ev.offsetLocation(mTempRect.left, mTempRect.top);
170        result = mLockPatternView.dispatchTouchEvent(ev) || result;
171        ev.offsetLocation(-mTempRect.left, -mTempRect.top);
172        return result;
173    }
174
175    public void reset() {
176        // reset lock pattern
177        mLockPatternView.enableInput();
178        mLockPatternView.setEnabled(true);
179        mLockPatternView.clearPattern();
180
181        // if the user is currently locked out, enforce it.
182        long deadline = mLockPatternUtils.getLockoutAttemptDeadline();
183        if (deadline != 0) {
184            handleAttemptLockout(deadline);
185        } else {
186            mNavigationManager.setMessage(R.string.kg_pattern_instructions);
187        }
188
189        // the footer depends on how many total attempts the user has failed
190        if (mCallback.isVerifyUnlockOnly()) {
191            updateFooter(FooterMode.VerifyUnlocked);
192        } else if (mEnableFallback &&
193                (mTotalFailedPatternAttempts >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT)) {
194            updateFooter(FooterMode.ForgotLockPattern);
195        } else {
196            updateFooter(FooterMode.Normal);
197        }
198
199    }
200
201    /** TODO: hook this up */
202    public void cleanUp() {
203        if (DEBUG) Log.v(TAG, "Cleanup() called on " + this);
204        mLockPatternUtils = null;
205        mLockPatternView.setOnPatternListener(null);
206    }
207
208    @Override
209    public void onWindowFocusChanged(boolean hasWindowFocus) {
210        super.onWindowFocusChanged(hasWindowFocus);
211        if (hasWindowFocus) {
212            // when timeout dialog closes we want to update our state
213            reset();
214        }
215    }
216
217    private class UnlockPatternListener implements LockPatternView.OnPatternListener {
218
219        public void onPatternStart() {
220            mLockPatternView.removeCallbacks(mCancelPatternRunnable);
221        }
222
223        public void onPatternCleared() {
224        }
225
226        public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {
227            // To guard against accidental poking of the wakelock, look for
228            // the user actually trying to draw a pattern of some minimal length.
229            if (pattern.size() > MIN_PATTERN_BEFORE_POKE_WAKELOCK) {
230                mCallback.userActivity(UNLOCK_PATTERN_WAKE_INTERVAL_MS);
231            } else {
232                // Give just a little extra time if they hit one of the first few dots
233                mCallback.userActivity(UNLOCK_PATTERN_WAKE_INTERVAL_FIRST_DOTS_MS);
234            }
235        }
236
237        public void onPatternDetected(List<LockPatternView.Cell> pattern) {
238            if (mLockPatternUtils.checkPattern(pattern)) {
239                mCallback.reportSuccessfulUnlockAttempt();
240                mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct);
241                mTotalFailedPatternAttempts = 0;
242                mCallback.dismiss(true);
243            } else {
244                if (pattern.size() > MIN_PATTERN_BEFORE_POKE_WAKELOCK) {
245                    mCallback.userActivity(UNLOCK_PATTERN_WAKE_INTERVAL_MS);
246                }
247                mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
248                if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
249                    mTotalFailedPatternAttempts++;
250                    mFailedPatternAttemptsSinceLastTimeout++;
251                    mCallback.reportFailedUnlockAttempt();
252                }
253                if (mFailedPatternAttemptsSinceLastTimeout
254                        >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
255                    long deadline = mLockPatternUtils.setLockoutAttemptDeadline();
256                    handleAttemptLockout(deadline);
257                } else {
258                    mNavigationManager.setMessage(R.string.kg_wrong_pattern);
259                    mLockPatternView.postDelayed(mCancelPatternRunnable, PATTERN_CLEAR_TIMEOUT_MS);
260                }
261            }
262        }
263    }
264
265    private void maybeEnableFallback(Context context) {
266        // Ask the account manager if we have an account that can be used as a
267        // fallback in case the user forgets his pattern.
268        AccountAnalyzer accountAnalyzer = new AccountAnalyzer(AccountManager.get(context));
269        accountAnalyzer.start();
270    }
271
272    private class AccountAnalyzer implements AccountManagerCallback<Bundle> {
273        private final AccountManager mAccountManager;
274        private final Account[] mAccounts;
275        private int mAccountIndex;
276
277        private AccountAnalyzer(AccountManager accountManager) {
278            mAccountManager = accountManager;
279            mAccounts = accountManager.getAccountsByType("com.google");
280        }
281
282        private void next() {
283            // if we are ready to enable the fallback or if we depleted the list of accounts
284            // then finish and get out
285            if (mAccountIndex >= mAccounts.length) {
286                mEnableFallback = true;
287                return;
288            }
289
290            // lookup the confirmCredentials intent for the current account
291            mAccountManager.confirmCredentials(mAccounts[mAccountIndex], null, null, this, null);
292        }
293
294        public void start() {
295            mEnableFallback = false;
296            mAccountIndex = 0;
297            next();
298        }
299
300        public void run(AccountManagerFuture<Bundle> future) {
301            try {
302                Bundle result = future.getResult();
303                if (result.getParcelable(AccountManager.KEY_INTENT) != null) {
304                    mEnableFallback = true;
305                }
306            } catch (OperationCanceledException e) {
307                // just skip the account if we are unable to query it
308            } catch (IOException e) {
309                // just skip the account if we are unable to query it
310            } catch (AuthenticatorException e) {
311                // just skip the account if we are unable to query it
312            } finally {
313                mAccountIndex++;
314                next();
315            }
316        }
317    }
318
319    private void handleAttemptLockout(long elapsedRealtimeDeadline) {
320        mLockPatternView.clearPattern();
321        mLockPatternView.setEnabled(false);
322        final long elapsedRealtime = SystemClock.elapsedRealtime();
323        updateFooter(FooterMode.ForgotLockPattern);
324
325        mCountdownTimer = new CountDownTimer(elapsedRealtimeDeadline - elapsedRealtime, 1000) {
326
327            @Override
328            public void onTick(long millisUntilFinished) {
329                final int secondsRemaining = (int) (millisUntilFinished / 1000);
330                mNavigationManager.setMessage(
331                        R.string.kg_too_many_failed_attempts_countdown, secondsRemaining);
332            }
333
334            @Override
335            public void onFinish() {
336                mLockPatternView.setEnabled(true);
337                mNavigationManager.setMessage(R.string.kg_pattern_instructions);
338                // TODO mUnlockIcon.setVisibility(View.VISIBLE);
339                mFailedPatternAttemptsSinceLastTimeout = 0;
340                if (mEnableFallback) {
341                    updateFooter(FooterMode.ForgotLockPattern);
342                } else {
343                    updateFooter(FooterMode.Normal);
344                }
345            }
346
347        }.start();
348    }
349
350    @Override
351    public boolean needsInput() {
352        return false;
353    }
354
355    @Override
356    public void onPause() {
357        if (mCountdownTimer != null) {
358            mCountdownTimer.cancel();
359            mCountdownTimer = null;
360        }
361    }
362
363    @Override
364    public void onResume() {
365        reset();
366    }
367
368    @Override
369    public KeyguardSecurityCallback getCallback() {
370        return mCallback;
371    }
372
373}
374
375
376
377