1/*
2 * Copyright (C) 2007 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.keyguard;
18
19import android.graphics.Bitmap;
20import com.android.internal.policy.IKeyguardExitCallback;
21import com.android.internal.policy.IKeyguardShowCallback;
22import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
23
24import android.app.Activity;
25import android.app.ActivityManagerNative;
26import android.app.AlarmManager;
27import android.app.PendingIntent;
28import android.app.SearchManager;
29import android.app.StatusBarManager;
30import android.content.BroadcastReceiver;
31import android.content.ContentResolver;
32import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
35import android.media.AudioManager;
36import android.media.SoundPool;
37import android.os.Bundle;
38import android.os.Handler;
39import android.os.Looper;
40import android.os.Message;
41import android.os.PowerManager;
42import android.os.RemoteException;
43import android.os.SystemClock;
44import android.os.SystemProperties;
45import android.os.UserHandle;
46import android.os.UserManager;
47import android.provider.Settings;
48import android.telephony.TelephonyManager;
49import android.util.EventLog;
50import android.util.Log;
51import android.util.Slog;
52import android.view.KeyEvent;
53import android.view.MotionEvent;
54import android.view.WindowManager;
55import android.view.WindowManagerPolicy;
56
57import com.android.internal.telephony.IccCardConstants;
58import com.android.internal.widget.LockPatternUtils;
59
60
61/**
62 * Mediates requests related to the keyguard.  This includes queries about the
63 * state of the keyguard, power management events that effect whether the keyguard
64 * should be shown or reset, callbacks to the phone window manager to notify
65 * it of when the keyguard is showing, and events from the keyguard view itself
66 * stating that the keyguard was succesfully unlocked.
67 *
68 * Note that the keyguard view is shown when the screen is off (as appropriate)
69 * so that once the screen comes on, it will be ready immediately.
70 *
71 * Example queries about the keyguard:
72 * - is {movement, key} one that should wake the keygaurd?
73 * - is the keyguard showing?
74 * - are input events restricted due to the state of the keyguard?
75 *
76 * Callbacks to the phone window manager:
77 * - the keyguard is showing
78 *
79 * Example external events that translate to keyguard view changes:
80 * - screen turned off -> reset the keyguard, and show it so it will be ready
81 *   next time the screen turns on
82 * - keyboard is slid open -> if the keyguard is not secure, hide it
83 *
84 * Events from the keyguard view:
85 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
86 *   restrict input events.
87 *
88 * Note: in addition to normal power managment events that effect the state of
89 * whether the keyguard should be showing, external apps and services may request
90 * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}.  When
91 * false, this will override all other conditions for turning on the keyguard.
92 *
93 * Threading and synchronization:
94 * This class is created by the initialization routine of the {@link WindowManagerPolicy},
95 * and runs on its thread.  The keyguard UI is created from that thread in the
96 * constructor of this class.  The apis may be called from other threads, including the
97 * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s.
98 * Therefore, methods on this class are synchronized, and any action that is pointed
99 * directly to the keyguard UI is posted to a {@link Handler} to ensure it is taken on the UI
100 * thread of the keyguard.
101 */
102public class KeyguardViewMediator {
103    private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
104    final static boolean DEBUG = false;
105    private final static boolean DBG_WAKE = false;
106
107    private final static String TAG = "KeyguardViewMediator";
108
109    private static final String DELAYED_KEYGUARD_ACTION =
110        "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
111
112    // used for handler messages
113    private static final int SHOW = 2;
114    private static final int HIDE = 3;
115    private static final int RESET = 4;
116    private static final int VERIFY_UNLOCK = 5;
117    private static final int NOTIFY_SCREEN_OFF = 6;
118    private static final int NOTIFY_SCREEN_ON = 7;
119    private static final int KEYGUARD_DONE = 9;
120    private static final int KEYGUARD_DONE_DRAWING = 10;
121    private static final int KEYGUARD_DONE_AUTHENTICATING = 11;
122    private static final int SET_HIDDEN = 12;
123    private static final int KEYGUARD_TIMEOUT = 13;
124    private static final int SHOW_ASSISTANT = 14;
125    private static final int DISPATCH_EVENT = 15;
126    private static final int LAUNCH_CAMERA = 16;
127    private static final int DISMISS = 17;
128
129    /**
130     * The default amount of time we stay awake (used for all key input)
131     */
132    protected static final int AWAKE_INTERVAL_DEFAULT_MS = 10000;
133
134    /**
135     * How long to wait after the screen turns off due to timeout before
136     * turning on the keyguard (i.e, the user has this much time to turn
137     * the screen back on without having to face the keyguard).
138     */
139    private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000;
140
141    /**
142     * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()}
143     * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)}
144     * that is reenabling the keyguard.
145     */
146    private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
147
148    /**
149     * Allow the user to expand the status bar when the keyguard is engaged
150     * (without a pattern or password).
151     */
152    private static final boolean ENABLE_INSECURE_STATUS_BAR_EXPAND = true;
153
154    /** The stream type that the lock sounds are tied to. */
155    private int mMasterStreamType;
156
157    private Context mContext;
158    private AlarmManager mAlarmManager;
159    private AudioManager mAudioManager;
160    private StatusBarManager mStatusBarManager;
161    private boolean mSwitchingUser;
162
163    private boolean mSystemReady;
164
165    // Whether the next call to playSounds() should be skipped.  Defaults to
166    // true because the first lock (on boot) should be silent.
167    private boolean mSuppressNextLockSound = true;
168
169
170    /** High level access to the power manager for WakeLocks */
171    private PowerManager mPM;
172
173    /** UserManager for querying number of users */
174    private UserManager mUserManager;
175
176    /** SearchManager for determining whether or not search assistant is available */
177    private SearchManager mSearchManager;
178
179    /**
180     * Used to keep the device awake while to ensure the keyguard finishes opening before
181     * we sleep.
182     */
183    private PowerManager.WakeLock mShowKeyguardWakeLock;
184
185    private KeyguardViewManager mKeyguardViewManager;
186
187    // these are protected by synchronized (this)
188
189    /**
190     * External apps (like the phone app) can tell us to disable the keygaurd.
191     */
192    private boolean mExternallyEnabled = true;
193
194    /**
195     * Remember if an external call to {@link #setKeyguardEnabled} with value
196     * false caused us to hide the keyguard, so that we need to reshow it once
197     * the keygaurd is reenabled with another call with value true.
198     */
199    private boolean mNeedToReshowWhenReenabled = false;
200
201    // cached value of whether we are showing (need to know this to quickly
202    // answer whether the input should be restricted)
203    private boolean mShowing = false;
204
205    // true if the keyguard is hidden by another window
206    private boolean mHidden = false;
207
208    /**
209     * Helps remember whether the screen has turned on since the last time
210     * it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
211     */
212    private int mDelayedShowingSequence;
213
214    /**
215     * If the user has disabled the keyguard, then requests to exit, this is
216     * how we'll ultimately let them know whether it was successful.  We use this
217     * var being non-null as an indicator that there is an in progress request.
218     */
219    private IKeyguardExitCallback mExitSecureCallback;
220
221    // the properties of the keyguard
222
223    private KeyguardUpdateMonitor mUpdateMonitor;
224
225    private boolean mScreenOn;
226
227    // last known state of the cellular connection
228    private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE;
229
230    /**
231     * we send this intent when the keyguard is dismissed.
232     */
233    private static final Intent USER_PRESENT_INTENT = new Intent(Intent.ACTION_USER_PRESENT)
234            .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
235                    | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
236
237    /**
238     * {@link #setKeyguardEnabled} waits on this condition when it reenables
239     * the keyguard.
240     */
241    private boolean mWaitingUntilKeyguardVisible = false;
242    private LockPatternUtils mLockPatternUtils;
243    private boolean mKeyguardDonePending = false;
244
245    private SoundPool mLockSounds;
246    private int mLockSoundId;
247    private int mUnlockSoundId;
248    private int mLockSoundStreamId;
249
250    /**
251     * The volume applied to the lock/unlock sounds.
252     */
253    private final float mLockSoundVolume;
254
255    /**
256     * Cache of avatar drawables, for use by KeyguardMultiUserAvatar.
257     */
258    private static MultiUserAvatarCache sMultiUserAvatarCache = new MultiUserAvatarCache();
259
260    /**
261     * The callback used by the keyguard view to tell the {@link KeyguardViewMediator}
262     * various things.
263     */
264    public interface ViewMediatorCallback {
265        /**
266         * Reports user activity and requests that the screen stay on.
267         */
268        void userActivity();
269
270        /**
271         * Reports user activity and requests that the screen stay on for at least
272         * the specified amount of time.
273         * @param millis The amount of time in millis.  This value is currently ignored.
274         */
275        void userActivity(long millis);
276
277        /**
278         * Report that the keyguard is done.
279         * @param authenticated Whether the user securely got past the keyguard.
280         *   the only reason for this to be false is if the keyguard was instructed
281         *   to appear temporarily to verify the user is supposed to get past the
282         *   keyguard, and the user fails to do so.
283         */
284        void keyguardDone(boolean authenticated);
285
286        /**
287         * Report that the keyguard is done drawing.
288         */
289        void keyguardDoneDrawing();
290
291        /**
292         * Tell ViewMediator that the current view needs IME input
293         * @param needsInput
294         */
295        void setNeedsInput(boolean needsInput);
296
297        /**
298         * Tell view mediator that the keyguard view's desired user activity timeout
299         * has changed and needs to be reapplied to the window.
300         */
301        void onUserActivityTimeoutChanged();
302
303        /**
304         * Report that the keyguard is dismissable, pending the next keyguardDone call.
305         */
306        void keyguardDonePending();
307    }
308
309    KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
310
311        @Override
312        public void onUserSwitching(int userId) {
313            // Note that the mLockPatternUtils user has already been updated from setCurrentUser.
314            // We need to force a reset of the views, since lockNow (called by
315            // ActivityManagerService) will not reconstruct the keyguard if it is already showing.
316            synchronized (KeyguardViewMediator.this) {
317                mSwitchingUser = true;
318                resetStateLocked(null);
319                adjustStatusBarLocked();
320                // When we switch users we want to bring the new user to the biometric unlock even
321                // if the current user has gone to the backup.
322                KeyguardUpdateMonitor.getInstance(mContext).setAlternateUnlockEnabled(true);
323            }
324        }
325
326        @Override
327        public void onUserSwitchComplete(int userId) {
328            mSwitchingUser = false;
329        }
330
331        @Override
332        public void onUserRemoved(int userId) {
333            mLockPatternUtils.removeUser(userId);
334            sMultiUserAvatarCache.clear(userId);
335        }
336
337        @Override
338        public void onUserInfoChanged(int userId) {
339            sMultiUserAvatarCache.clear(userId);
340        }
341
342        @Override
343        void onPhoneStateChanged(int phoneState) {
344            synchronized (KeyguardViewMediator.this) {
345                if (TelephonyManager.CALL_STATE_IDLE == phoneState  // call ending
346                        && !mScreenOn                           // screen off
347                        && mExternallyEnabled) {                // not disabled by any app
348
349                    // note: this is a way to gracefully reenable the keyguard when the call
350                    // ends and the screen is off without always reenabling the keyguard
351                    // each time the screen turns off while in call (and having an occasional ugly
352                    // flicker while turning back on the screen and disabling the keyguard again).
353                    if (DEBUG) Log.d(TAG, "screen is off and call ended, let's make sure the "
354                            + "keyguard is showing");
355                    doKeyguardLocked(null);
356                }
357            }
358        };
359
360        @Override
361        public void onClockVisibilityChanged() {
362            adjustStatusBarLocked();
363        }
364
365        @Override
366        public void onDeviceProvisioned() {
367            sendUserPresentBroadcast();
368        }
369
370        @Override
371        public void onSimStateChanged(IccCardConstants.State simState) {
372            if (DEBUG) Log.d(TAG, "onSimStateChanged: " + simState);
373
374            switch (simState) {
375                case NOT_READY:
376                case ABSENT:
377                    // only force lock screen in case of missing sim if user hasn't
378                    // gone through setup wizard
379                    synchronized (this) {
380                        if (!mUpdateMonitor.isDeviceProvisioned()) {
381                            if (!isShowing()) {
382                                if (DEBUG) Log.d(TAG, "ICC_ABSENT isn't showing,"
383                                        + " we need to show the keyguard since the "
384                                        + "device isn't provisioned yet.");
385                                doKeyguardLocked(null);
386                            } else {
387                                resetStateLocked(null);
388                            }
389                        }
390                    }
391                    break;
392                case PIN_REQUIRED:
393                case PUK_REQUIRED:
394                    synchronized (this) {
395                        if (!isShowing()) {
396                            if (DEBUG) Log.d(TAG, "INTENT_VALUE_ICC_LOCKED and keygaurd isn't "
397                                    + "showing; need to show keyguard so user can enter sim pin");
398                            doKeyguardLocked(null);
399                        } else {
400                            resetStateLocked(null);
401                        }
402                    }
403                    break;
404                case PERM_DISABLED:
405                    synchronized (this) {
406                        if (!isShowing()) {
407                            if (DEBUG) Log.d(TAG, "PERM_DISABLED and "
408                                  + "keygaurd isn't showing.");
409                            doKeyguardLocked(null);
410                        } else {
411                            if (DEBUG) Log.d(TAG, "PERM_DISABLED, resetStateLocked to"
412                                  + "show permanently disabled message in lockscreen.");
413                            resetStateLocked(null);
414                        }
415                    }
416                    break;
417                case READY:
418                    synchronized (this) {
419                        if (isShowing()) {
420                            resetStateLocked(null);
421                        }
422                    }
423                    break;
424            }
425        }
426
427    };
428
429    ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
430        public void userActivity() {
431            KeyguardViewMediator.this.userActivity();
432        }
433
434        public void userActivity(long holdMs) {
435            KeyguardViewMediator.this.userActivity(holdMs);
436        }
437
438        public void keyguardDone(boolean authenticated) {
439            KeyguardViewMediator.this.keyguardDone(authenticated, true);
440        }
441
442        public void keyguardDoneDrawing() {
443            mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
444        }
445
446        @Override
447        public void setNeedsInput(boolean needsInput) {
448            mKeyguardViewManager.setNeedsInput(needsInput);
449        }
450
451        @Override
452        public void onUserActivityTimeoutChanged() {
453            mKeyguardViewManager.updateUserActivityTimeout();
454        }
455
456        @Override
457        public void keyguardDonePending() {
458            mKeyguardDonePending = true;
459        }
460    };
461
462    private void userActivity() {
463        userActivity(AWAKE_INTERVAL_DEFAULT_MS);
464    }
465
466    public void userActivity(long holdMs) {
467        // We ignore the hold time.  Eventually we should remove it.
468        // Instead, the keyguard window has an explicit user activity timeout set on it.
469        mPM.userActivity(SystemClock.uptimeMillis(), false);
470    }
471
472    /**
473     * Construct a KeyguardViewMediator
474     * @param context
475     * @param lockPatternUtils optional mock interface for LockPatternUtils
476     */
477    public KeyguardViewMediator(Context context, LockPatternUtils lockPatternUtils) {
478        mContext = context;
479        mPM = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
480        mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
481        mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
482        mShowKeyguardWakeLock.setReferenceCounted(false);
483
484        mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
485
486        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
487
488        mUpdateMonitor = KeyguardUpdateMonitor.getInstance(context);
489
490        mLockPatternUtils = lockPatternUtils != null
491                ? lockPatternUtils : new LockPatternUtils(mContext);
492        mLockPatternUtils.setCurrentUser(UserHandle.USER_OWNER);
493
494        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
495
496        mKeyguardViewManager = new KeyguardViewManager(context, wm, mViewMediatorCallback,
497                mLockPatternUtils);
498
499        final ContentResolver cr = mContext.getContentResolver();
500
501        mScreenOn = mPM.isScreenOn();
502
503        mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
504        String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
505        if (soundPath != null) {
506            mLockSoundId = mLockSounds.load(soundPath, 1);
507        }
508        if (soundPath == null || mLockSoundId == 0) {
509            Log.w(TAG, "failed to load lock sound from " + soundPath);
510        }
511        soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
512        if (soundPath != null) {
513            mUnlockSoundId = mLockSounds.load(soundPath, 1);
514        }
515        if (soundPath == null || mUnlockSoundId == 0) {
516            Log.w(TAG, "failed to load unlock sound from " + soundPath);
517        }
518        int lockSoundDefaultAttenuation = context.getResources().getInteger(
519                com.android.internal.R.integer.config_lockSoundVolumeDb);
520        mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
521    }
522
523    /**
524     * Let us know that the system is ready after startup.
525     */
526    public void onSystemReady() {
527        mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
528        synchronized (this) {
529            if (DEBUG) Log.d(TAG, "onSystemReady");
530            mSystemReady = true;
531            mUpdateMonitor.registerCallback(mUpdateCallback);
532
533            // Suppress biometric unlock right after boot until things have settled if it is the
534            // selected security method, otherwise unsuppress it.  It must be unsuppressed if it is
535            // not the selected security method for the following reason:  if the user starts
536            // without a screen lock selected, the biometric unlock would be suppressed the first
537            // time they try to use it.
538            //
539            // Note that the biometric unlock will still not show if it is not the selected method.
540            // Calling setAlternateUnlockEnabled(true) simply says don't suppress it if it is the
541            // selected method.
542            if (mLockPatternUtils.usingBiometricWeak()
543                    && mLockPatternUtils.isBiometricWeakInstalled()) {
544                if (DEBUG) Log.d(TAG, "suppressing biometric unlock during boot");
545                mUpdateMonitor.setAlternateUnlockEnabled(false);
546            } else {
547                mUpdateMonitor.setAlternateUnlockEnabled(true);
548            }
549
550            doKeyguardLocked(null);
551        }
552        // Most services aren't available until the system reaches the ready state, so we
553        // send it here when the device first boots.
554        maybeSendUserPresentBroadcast();
555    }
556
557    /**
558     * Called to let us know the screen was turned off.
559     * @param why either {@link WindowManagerPolicy#OFF_BECAUSE_OF_USER},
560     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT} or
561     *   {@link WindowManagerPolicy#OFF_BECAUSE_OF_PROX_SENSOR}.
562     */
563    public void onScreenTurnedOff(int why) {
564        synchronized (this) {
565            mScreenOn = false;
566            if (DEBUG) Log.d(TAG, "onScreenTurnedOff(" + why + ")");
567
568            mKeyguardDonePending = false;
569
570            // Lock immediately based on setting if secure (user has a pin/pattern/password).
571            // This also "locks" the device when not secure to provide easy access to the
572            // camera while preventing unwanted input.
573            final boolean lockImmediately =
574                mLockPatternUtils.getPowerButtonInstantlyLocks() || !mLockPatternUtils.isSecure();
575
576            if (mExitSecureCallback != null) {
577                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
578                try {
579                    mExitSecureCallback.onKeyguardExitResult(false);
580                } catch (RemoteException e) {
581                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
582                }
583                mExitSecureCallback = null;
584                if (!mExternallyEnabled) {
585                    hideLocked();
586                }
587            } else if (mShowing) {
588                notifyScreenOffLocked();
589                resetStateLocked(null);
590            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT
591                   || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
592                doKeyguardLaterLocked();
593            } else if (why == WindowManagerPolicy.OFF_BECAUSE_OF_PROX_SENSOR) {
594                // Do not enable the keyguard if the prox sensor forced the screen off.
595            } else {
596                doKeyguardLocked(null);
597            }
598        }
599        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurndOff(why);
600    }
601
602    private void doKeyguardLaterLocked() {
603        // if the screen turned off because of timeout or the user hit the power button
604        // and we don't need to lock immediately, set an alarm
605        // to enable it a little bit later (i.e, give the user a chance
606        // to turn the screen back on within a certain window without
607        // having to unlock the screen)
608        final ContentResolver cr = mContext.getContentResolver();
609
610        // From DisplaySettings
611        long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
612                KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
613
614        // From SecuritySettings
615        final long lockAfterTimeout = Settings.Secure.getInt(cr,
616                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
617                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
618
619        // From DevicePolicyAdmin
620        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
621                .getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());
622
623        long timeout;
624        if (policyTimeout > 0) {
625            // policy in effect. Make sure we don't go beyond policy limit.
626            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
627            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
628        } else {
629            timeout = lockAfterTimeout;
630        }
631
632        if (timeout <= 0) {
633            // Lock now
634            mSuppressNextLockSound = true;
635            doKeyguardLocked(null);
636        } else {
637            // Lock in the future
638            long when = SystemClock.elapsedRealtime() + timeout;
639            Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
640            intent.putExtra("seq", mDelayedShowingSequence);
641            PendingIntent sender = PendingIntent.getBroadcast(mContext,
642                    0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
643            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
644            if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
645                             + mDelayedShowingSequence);
646        }
647    }
648
649    private void cancelDoKeyguardLaterLocked() {
650        mDelayedShowingSequence++;
651    }
652
653    /**
654     * Let's us know the screen was turned on.
655     */
656    public void onScreenTurnedOn(IKeyguardShowCallback callback) {
657        synchronized (this) {
658            mScreenOn = true;
659            cancelDoKeyguardLaterLocked();
660            if (DEBUG) Log.d(TAG, "onScreenTurnedOn, seq = " + mDelayedShowingSequence);
661            if (callback != null) {
662                notifyScreenOnLocked(callback);
663            }
664        }
665        KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
666        maybeSendUserPresentBroadcast();
667    }
668
669    private void maybeSendUserPresentBroadcast() {
670        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled()
671                && mUserManager.getUsers(true).size() == 1) {
672            // Lock screen is disabled because the user has set the preference to "None".
673            // In this case, send out ACTION_USER_PRESENT here instead of in
674            // handleKeyguardDone()
675            sendUserPresentBroadcast();
676        }
677    }
678
679    /**
680     * A dream started.  We should lock after the usual screen-off lock timeout but only
681     * if there is a secure lock pattern.
682     */
683    public void onDreamingStarted() {
684        synchronized (this) {
685            if (mScreenOn && mLockPatternUtils.isSecure()) {
686                doKeyguardLaterLocked();
687            }
688        }
689    }
690
691    /**
692     * A dream stopped.
693     */
694    public void onDreamingStopped() {
695        synchronized (this) {
696            if (mScreenOn) {
697                cancelDoKeyguardLaterLocked();
698            }
699        }
700    }
701
702    /**
703     * Same semantics as {@link WindowManagerPolicy#enableKeyguard}; provide
704     * a way for external stuff to override normal keyguard behavior.  For instance
705     * the phone app disables the keyguard when it receives incoming calls.
706     */
707    public void setKeyguardEnabled(boolean enabled) {
708        synchronized (this) {
709            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
710
711            mExternallyEnabled = enabled;
712
713            if (!enabled && mShowing) {
714                if (mExitSecureCallback != null) {
715                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
716                    // we're in the process of handling a request to verify the user
717                    // can get past the keyguard. ignore extraneous requests to disable / reenable
718                    return;
719                }
720
721                // hiding keyguard that is showing, remember to reshow later
722                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
723                        + "disabling status bar expansion");
724                mNeedToReshowWhenReenabled = true;
725                hideLocked();
726            } else if (enabled && mNeedToReshowWhenReenabled) {
727                // reenabled after previously hidden, reshow
728                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
729                        + "status bar expansion");
730                mNeedToReshowWhenReenabled = false;
731
732                if (mExitSecureCallback != null) {
733                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
734                    try {
735                        mExitSecureCallback.onKeyguardExitResult(false);
736                    } catch (RemoteException e) {
737                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
738                    }
739                    mExitSecureCallback = null;
740                    resetStateLocked(null);
741                } else {
742                    showLocked(null);
743
744                    // block until we know the keygaurd is done drawing (and post a message
745                    // to unblock us after a timeout so we don't risk blocking too long
746                    // and causing an ANR).
747                    mWaitingUntilKeyguardVisible = true;
748                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
749                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
750                    while (mWaitingUntilKeyguardVisible) {
751                        try {
752                            wait();
753                        } catch (InterruptedException e) {
754                            Thread.currentThread().interrupt();
755                        }
756                    }
757                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
758                }
759            }
760        }
761    }
762
763    /**
764     * @see android.app.KeyguardManager#exitKeyguardSecurely
765     */
766    public void verifyUnlock(IKeyguardExitCallback callback) {
767        synchronized (this) {
768            if (DEBUG) Log.d(TAG, "verifyUnlock");
769            if (!mUpdateMonitor.isDeviceProvisioned()) {
770                // don't allow this api when the device isn't provisioned
771                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
772                try {
773                    callback.onKeyguardExitResult(false);
774                } catch (RemoteException e) {
775                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
776                }
777            } else if (mExternallyEnabled) {
778                // this only applies when the user has externally disabled the
779                // keyguard.  this is unexpected and means the user is not
780                // using the api properly.
781                Log.w(TAG, "verifyUnlock called when not externally disabled");
782                try {
783                    callback.onKeyguardExitResult(false);
784                } catch (RemoteException e) {
785                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
786                }
787            } else if (mExitSecureCallback != null) {
788                // already in progress with someone else
789                try {
790                    callback.onKeyguardExitResult(false);
791                } catch (RemoteException e) {
792                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
793                }
794            } else {
795                mExitSecureCallback = callback;
796                verifyUnlockLocked();
797            }
798        }
799    }
800
801    /**
802     * Is the keyguard currently showing?
803     */
804    public boolean isShowing() {
805        return mShowing;
806    }
807
808    /**
809     * Is the keyguard currently showing and not being force hidden?
810     */
811    public boolean isShowingAndNotHidden() {
812        return mShowing && !mHidden;
813    }
814
815    /**
816     * Notify us when the keyguard is hidden by another window
817     */
818    public void setHidden(boolean isHidden) {
819        if (DEBUG) Log.d(TAG, "setHidden " + isHidden);
820        mUpdateMonitor.sendKeyguardVisibilityChanged(!isHidden);
821        mHandler.removeMessages(SET_HIDDEN);
822        Message msg = mHandler.obtainMessage(SET_HIDDEN, (isHidden ? 1 : 0), 0);
823        mHandler.sendMessage(msg);
824    }
825
826    /**
827     * Handles SET_HIDDEN message sent by setHidden()
828     */
829    private void handleSetHidden(boolean isHidden) {
830        synchronized (KeyguardViewMediator.this) {
831            if (mHidden != isHidden) {
832                mHidden = isHidden;
833                updateActivityLockScreenState();
834                adjustStatusBarLocked();
835            }
836        }
837    }
838
839    /**
840     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
841     * This must be safe to call from any thread and with any window manager locks held.
842     */
843    public void doKeyguardTimeout(Bundle options) {
844        mHandler.removeMessages(KEYGUARD_TIMEOUT);
845        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
846        mHandler.sendMessage(msg);
847    }
848
849    /**
850     * Given the state of the keyguard, is the input restricted?
851     * Input is restricted when the keyguard is showing, or when the keyguard
852     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
853     */
854    public boolean isInputRestricted() {
855        return mShowing || mNeedToReshowWhenReenabled || !mUpdateMonitor.isDeviceProvisioned();
856    }
857
858    /**
859     * Enable the keyguard if the settings are appropriate.
860     */
861    private void doKeyguardLocked(Bundle options) {
862        // if another app is disabling us, don't show
863        if (!mExternallyEnabled) {
864            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
865
866            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
867            // for an occasional ugly flicker in this situation:
868            // 1) receive a call with the screen on (no keyguard) or make a call
869            // 2) screen times out
870            // 3) user hits key to turn screen back on
871            // instead, we reenable the keyguard when we know the screen is off and the call
872            // ends (see the broadcast receiver below)
873            // TODO: clean this up when we have better support at the window manager level
874            // for apps that wish to be on top of the keyguard
875            return;
876        }
877
878        // if the keyguard is already showing, don't bother
879        if (mKeyguardViewManager.isShowing()) {
880            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
881            return;
882        }
883
884        // if the setup wizard hasn't run yet, don't show
885        final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim",
886                false);
887        final boolean provisioned = mUpdateMonitor.isDeviceProvisioned();
888        final IccCardConstants.State state = mUpdateMonitor.getSimState();
889        final boolean lockedOrMissing = state.isPinLocked()
890                || ((state == IccCardConstants.State.ABSENT
891                || state == IccCardConstants.State.PERM_DISABLED)
892                && requireSim);
893
894        if (!lockedOrMissing && !provisioned) {
895            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
896                    + " and the sim is not locked or missing");
897            return;
898        }
899
900        if (mUserManager.getUsers(true).size() < 2
901                && mLockPatternUtils.isLockScreenDisabled() && !lockedOrMissing) {
902            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
903            return;
904        }
905
906        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
907        showLocked(options);
908    }
909
910    /**
911     * Dismiss the keyguard through the security layers.
912     */
913    public void handleDismiss() {
914        if (mShowing && !mHidden) {
915            mKeyguardViewManager.dismiss();
916        }
917    }
918
919    public void dismiss() {
920        mHandler.sendEmptyMessage(DISMISS);
921    }
922
923    /**
924     * Send message to keyguard telling it to reset its state.
925     * @param options options about how to show the keyguard
926     * @see #handleReset()
927     */
928    private void resetStateLocked(Bundle options) {
929        if (DEBUG) Log.e(TAG, "resetStateLocked");
930        Message msg = mHandler.obtainMessage(RESET, options);
931        mHandler.sendMessage(msg);
932    }
933
934    /**
935     * Send message to keyguard telling it to verify unlock
936     * @see #handleVerifyUnlock()
937     */
938    private void verifyUnlockLocked() {
939        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
940        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
941    }
942
943
944    /**
945     * Send a message to keyguard telling it the screen just turned on.
946     * @see #onScreenTurnedOff(int)
947     * @see #handleNotifyScreenOff
948     */
949    private void notifyScreenOffLocked() {
950        if (DEBUG) Log.d(TAG, "notifyScreenOffLocked");
951        mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
952    }
953
954    /**
955     * Send a message to keyguard telling it the screen just turned on.
956     * @see #onScreenTurnedOn()
957     * @see #handleNotifyScreenOn
958     */
959    private void notifyScreenOnLocked(IKeyguardShowCallback result) {
960        if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
961        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
962        mHandler.sendMessage(msg);
963    }
964
965    /**
966     * Send message to keyguard telling it to show itself
967     * @see #handleShow()
968     */
969    private void showLocked(Bundle options) {
970        if (DEBUG) Log.d(TAG, "showLocked");
971        // ensure we stay awake until we are finished displaying the keyguard
972        mShowKeyguardWakeLock.acquire();
973        Message msg = mHandler.obtainMessage(SHOW, options);
974        mHandler.sendMessage(msg);
975    }
976
977    /**
978     * Send message to keyguard telling it to hide itself
979     * @see #handleHide()
980     */
981    private void hideLocked() {
982        if (DEBUG) Log.d(TAG, "hideLocked");
983        Message msg = mHandler.obtainMessage(HIDE);
984        mHandler.sendMessage(msg);
985    }
986
987    public boolean isSecure() {
988        return mLockPatternUtils.isSecure()
989            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
990    }
991
992    /**
993     * Update the newUserId. Call while holding WindowManagerService lock.
994     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
995     *
996     * @param newUserId The id of the incoming user.
997     */
998    public void setCurrentUser(int newUserId) {
999        mLockPatternUtils.setCurrentUser(newUserId);
1000    }
1001
1002    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1003        @Override
1004        public void onReceive(Context context, Intent intent) {
1005            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1006                final int sequence = intent.getIntExtra("seq", 0);
1007                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1008                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1009                synchronized (KeyguardViewMediator.this) {
1010                    if (mDelayedShowingSequence == sequence) {
1011                        // Don't play lockscreen SFX if the screen went off due to timeout.
1012                        mSuppressNextLockSound = true;
1013                        doKeyguardLocked(null);
1014                    }
1015                }
1016            }
1017        }
1018    };
1019
1020    public void keyguardDone(boolean authenticated, boolean wakeup) {
1021        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated + ")");
1022        EventLog.writeEvent(70000, 2);
1023        synchronized (this) {
1024            mKeyguardDonePending = false;
1025        }
1026        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0, wakeup ? 1 : 0);
1027        mHandler.sendMessage(msg);
1028    }
1029
1030    /**
1031     * This handler will be associated with the policy thread, which will also
1032     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1033     * this class, can be called by other threads, any action that directly
1034     * interacts with the keyguard ui should be posted to this handler, rather
1035     * than called directly.
1036     */
1037    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1038        @Override
1039        public void handleMessage(Message msg) {
1040            switch (msg.what) {
1041                case SHOW:
1042                    handleShow((Bundle) msg.obj);
1043                    break;
1044                case HIDE:
1045                    handleHide();
1046                    break;
1047                case RESET:
1048                    handleReset((Bundle) msg.obj);
1049                    break;
1050                case VERIFY_UNLOCK:
1051                    handleVerifyUnlock();
1052                    break;
1053                case NOTIFY_SCREEN_OFF:
1054                    handleNotifyScreenOff();
1055                    break;
1056                case NOTIFY_SCREEN_ON:
1057                    handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
1058                    break;
1059                case KEYGUARD_DONE:
1060                    handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
1061                    break;
1062                case KEYGUARD_DONE_DRAWING:
1063                    handleKeyguardDoneDrawing();
1064                    break;
1065                case KEYGUARD_DONE_AUTHENTICATING:
1066                    keyguardDone(true, true);
1067                    break;
1068                case SET_HIDDEN:
1069                    handleSetHidden(msg.arg1 != 0);
1070                    break;
1071                case KEYGUARD_TIMEOUT:
1072                    synchronized (KeyguardViewMediator.this) {
1073                        doKeyguardLocked((Bundle) msg.obj);
1074                    }
1075                    break;
1076                case SHOW_ASSISTANT:
1077                    handleShowAssistant();
1078                    break;
1079                case DISPATCH_EVENT:
1080                    handleDispatchEvent((MotionEvent) msg.obj);
1081                    break;
1082                case LAUNCH_CAMERA:
1083                    handleLaunchCamera();
1084                    break;
1085                case DISMISS:
1086                    handleDismiss();
1087                    break;
1088            }
1089        }
1090    };
1091
1092    /**
1093     * @see #keyguardDone
1094     * @see #KEYGUARD_DONE
1095     */
1096    private void handleKeyguardDone(boolean authenticated, boolean wakeup) {
1097        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1098
1099        if (authenticated) {
1100            mUpdateMonitor.clearFailedUnlockAttempts();
1101        }
1102
1103        if (mExitSecureCallback != null) {
1104            try {
1105                mExitSecureCallback.onKeyguardExitResult(authenticated);
1106            } catch (RemoteException e) {
1107                Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1108            }
1109
1110            mExitSecureCallback = null;
1111
1112            if (authenticated) {
1113                // after succesfully exiting securely, no need to reshow
1114                // the keyguard when they've released the lock
1115                mExternallyEnabled = true;
1116                mNeedToReshowWhenReenabled = false;
1117            }
1118        }
1119
1120        handleHide();
1121        sendUserPresentBroadcast();
1122    }
1123
1124    protected void handleLaunchCamera() {
1125        mKeyguardViewManager.launchCamera();
1126    }
1127
1128    protected void handleDispatchEvent(MotionEvent event) {
1129        mKeyguardViewManager.dispatch(event);
1130    }
1131
1132    private void sendUserPresentBroadcast() {
1133        final UserHandle currentUser = new UserHandle(mLockPatternUtils.getCurrentUser());
1134        mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, currentUser);
1135    }
1136
1137    /**
1138     * @see #keyguardDoneDrawing
1139     * @see #KEYGUARD_DONE_DRAWING
1140     */
1141    private void handleKeyguardDoneDrawing() {
1142        synchronized(this) {
1143            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1144            if (mWaitingUntilKeyguardVisible) {
1145                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1146                mWaitingUntilKeyguardVisible = false;
1147                notifyAll();
1148
1149                // there will usually be two of these sent, one as a timeout, and one
1150                // as a result of the callback, so remove any remaining messages from
1151                // the queue
1152                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1153            }
1154        }
1155    }
1156
1157    private void playSounds(boolean locked) {
1158        // User feedback for keyguard.
1159
1160        if (mSuppressNextLockSound) {
1161            mSuppressNextLockSound = false;
1162            return;
1163        }
1164
1165        final ContentResolver cr = mContext.getContentResolver();
1166        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1167            final int whichSound = locked
1168                ? mLockSoundId
1169                : mUnlockSoundId;
1170            mLockSounds.stop(mLockSoundStreamId);
1171            // Init mAudioManager
1172            if (mAudioManager == null) {
1173                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1174                if (mAudioManager == null) return;
1175                mMasterStreamType = mAudioManager.getMasterStreamType();
1176            }
1177            // If the stream is muted, don't play the sound
1178            if (mAudioManager.isStreamMute(mMasterStreamType)) return;
1179
1180            mLockSoundStreamId = mLockSounds.play(whichSound,
1181                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1182        }
1183    }
1184
1185    private void updateActivityLockScreenState() {
1186        try {
1187            ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mHidden);
1188        } catch (RemoteException e) {
1189        }
1190    }
1191
1192    /**
1193     * Handle message sent by {@link #showLocked}.
1194     * @see #SHOW
1195     */
1196    private void handleShow(Bundle options) {
1197        synchronized (KeyguardViewMediator.this) {
1198            if (!mSystemReady) {
1199                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1200                return;
1201            } else {
1202                if (DEBUG) Log.d(TAG, "handleShow");
1203            }
1204
1205            mKeyguardViewManager.show(options);
1206            mShowing = true;
1207            mKeyguardDonePending = false;
1208            updateActivityLockScreenState();
1209            adjustStatusBarLocked();
1210            userActivity();
1211            try {
1212                ActivityManagerNative.getDefault().closeSystemDialogs("lock");
1213            } catch (RemoteException e) {
1214            }
1215
1216            // Do this at the end to not slow down display of the keyguard.
1217            playSounds(true);
1218
1219            mShowKeyguardWakeLock.release();
1220        }
1221    }
1222
1223    /**
1224     * Handle message sent by {@link #hideLocked()}
1225     * @see #HIDE
1226     */
1227    private void handleHide() {
1228        synchronized (KeyguardViewMediator.this) {
1229            if (DEBUG) Log.d(TAG, "handleHide");
1230
1231            // only play "unlock" noises if not on a call (since the incall UI
1232            // disables the keyguard)
1233            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1234                playSounds(false);
1235            }
1236
1237            mKeyguardViewManager.hide();
1238            mShowing = false;
1239            mKeyguardDonePending = false;
1240            updateActivityLockScreenState();
1241            adjustStatusBarLocked();
1242        }
1243    }
1244
1245    private void adjustStatusBarLocked() {
1246        if (mStatusBarManager == null) {
1247            mStatusBarManager = (StatusBarManager)
1248                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1249        }
1250        if (mStatusBarManager == null) {
1251            Log.w(TAG, "Could not get status bar manager");
1252        } else {
1253            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1254            // windows that appear on top, ever
1255            int flags = StatusBarManager.DISABLE_NONE;
1256            if (mShowing) {
1257                // Permanently disable components not available when keyguard is enabled
1258                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1259                // done in KeyguardHostView.
1260                flags |= StatusBarManager.DISABLE_RECENT;
1261                if (isSecure() || !ENABLE_INSECURE_STATUS_BAR_EXPAND) {
1262                    // showing secure lockscreen; disable expanding.
1263                    flags |= StatusBarManager.DISABLE_EXPAND;
1264                }
1265                if (isSecure()) {
1266                    // showing secure lockscreen; disable ticker.
1267                    flags |= StatusBarManager.DISABLE_NOTIFICATION_TICKER;
1268                }
1269                if (!isAssistantAvailable()) {
1270                    flags |= StatusBarManager.DISABLE_SEARCH;
1271                }
1272            }
1273
1274            if (DEBUG) {
1275                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mHidden=" + mHidden
1276                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1277            }
1278
1279            if (!(mContext instanceof Activity)) {
1280                mStatusBarManager.disable(flags);
1281            }
1282        }
1283    }
1284
1285    /**
1286     * Handle message sent by {@link #resetStateLocked(Bundle)}
1287     * @see #RESET
1288     */
1289    private void handleReset(Bundle options) {
1290        if (options == null) {
1291            options = new Bundle();
1292        }
1293        options.putBoolean(KeyguardViewManager.IS_SWITCHING_USER, mSwitchingUser);
1294        synchronized (KeyguardViewMediator.this) {
1295            if (DEBUG) Log.d(TAG, "handleReset");
1296            mKeyguardViewManager.reset(options);
1297        }
1298    }
1299
1300    /**
1301     * Handle message sent by {@link #verifyUnlock}
1302     * @see #VERIFY_UNLOCK
1303     */
1304    private void handleVerifyUnlock() {
1305        synchronized (KeyguardViewMediator.this) {
1306            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1307            mKeyguardViewManager.verifyUnlock();
1308            mShowing = true;
1309            updateActivityLockScreenState();
1310        }
1311    }
1312
1313    /**
1314     * Handle message sent by {@link #notifyScreenOffLocked()}
1315     * @see #NOTIFY_SCREEN_OFF
1316     */
1317    private void handleNotifyScreenOff() {
1318        synchronized (KeyguardViewMediator.this) {
1319            if (DEBUG) Log.d(TAG, "handleNotifyScreenOff");
1320            mKeyguardViewManager.onScreenTurnedOff();
1321        }
1322    }
1323
1324    /**
1325     * Handle message sent by {@link #notifyScreenOnLocked()}
1326     * @see #NOTIFY_SCREEN_ON
1327     */
1328    private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
1329        synchronized (KeyguardViewMediator.this) {
1330            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
1331            mKeyguardViewManager.onScreenTurnedOn(callback);
1332        }
1333    }
1334
1335    public boolean isDismissable() {
1336        return mKeyguardDonePending || !isSecure();
1337    }
1338
1339    public void showAssistant() {
1340        Message msg = mHandler.obtainMessage(SHOW_ASSISTANT);
1341        mHandler.sendMessage(msg);
1342    }
1343
1344    public void handleShowAssistant() {
1345        mKeyguardViewManager.showAssistant();
1346    }
1347
1348    private boolean isAssistantAvailable() {
1349        return mSearchManager != null
1350                && mSearchManager.getAssistIntent(mContext, false, UserHandle.USER_CURRENT) != null;
1351    }
1352
1353    public static MultiUserAvatarCache getAvatarCache() {
1354        return sMultiUserAvatarCache;
1355    }
1356
1357    public void dispatch(MotionEvent event) {
1358        Message msg = mHandler.obtainMessage(DISPATCH_EVENT, event);
1359        mHandler.sendMessage(msg);
1360    }
1361
1362    public void launchCamera() {
1363        Message msg = mHandler.obtainMessage(LAUNCH_CAMERA);
1364        mHandler.sendMessage(msg);
1365    }
1366
1367    public void onBootCompleted() {
1368        mUpdateMonitor.dispatchBootCompleted();
1369    }
1370}
1371