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