KeyguardViewMediator.java revision eb437d4dffb310857e19bb619778dc5b6b7febff
1/*
2 * Copyright (C) 2014 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.systemui.keyguard;
18
19import android.annotation.UserIdInt;
20import android.app.Activity;
21import android.app.ActivityManager;
22import android.app.ActivityManagerNative;
23import android.app.AlarmManager;
24import android.app.PendingIntent;
25import android.app.SearchManager;
26import android.app.StatusBarManager;
27import android.app.trust.TrustManager;
28import android.content.BroadcastReceiver;
29import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.UserInfo;
34import android.media.AudioManager;
35import android.media.SoundPool;
36import android.os.Bundle;
37import android.os.DeadObjectException;
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.os.storage.StorageManager;
48import android.provider.Settings;
49import android.telephony.SubscriptionManager;
50import android.telephony.TelephonyManager;
51import android.util.EventLog;
52import android.util.Log;
53import android.util.Slog;
54import android.view.IWindowManager;
55import android.view.ViewGroup;
56import android.view.WindowManagerGlobal;
57import android.view.WindowManagerPolicy;
58import android.view.animation.Animation;
59import android.view.animation.AnimationUtils;
60
61import com.android.internal.policy.IKeyguardDrawnCallback;
62import com.android.internal.policy.IKeyguardExitCallback;
63import com.android.internal.policy.IKeyguardStateCallback;
64import com.android.internal.telephony.IccCardConstants;
65import com.android.internal.widget.LockPatternUtils;
66import com.android.keyguard.KeyguardConstants;
67import com.android.keyguard.KeyguardDisplayManager;
68import com.android.keyguard.KeyguardSecurityView;
69import com.android.keyguard.KeyguardUpdateMonitor;
70import com.android.keyguard.KeyguardUpdateMonitorCallback;
71import com.android.keyguard.ViewMediatorCallback;
72import com.android.systemui.SystemUI;
73import com.android.systemui.SystemUIFactory;
74import com.android.systemui.classifier.FalsingManager;
75import com.android.systemui.statusbar.phone.FingerprintUnlockController;
76import com.android.systemui.statusbar.phone.PhoneStatusBar;
77import com.android.systemui.statusbar.phone.ScrimController;
78import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
79import com.android.systemui.statusbar.phone.StatusBarWindowManager;
80
81import java.io.FileDescriptor;
82import java.io.PrintWriter;
83import java.util.ArrayList;
84import java.util.List;
85
86import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
87import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_USER_REQUEST;
88import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_WRONG_CREDENTIAL;
89import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
90import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
91
92/**
93 * Mediates requests related to the keyguard.  This includes queries about the
94 * state of the keyguard, power management events that effect whether the keyguard
95 * should be shown or reset, callbacks to the phone window manager to notify
96 * it of when the keyguard is showing, and events from the keyguard view itself
97 * stating that the keyguard was succesfully unlocked.
98 *
99 * Note that the keyguard view is shown when the screen is off (as appropriate)
100 * so that once the screen comes on, it will be ready immediately.
101 *
102 * Example queries about the keyguard:
103 * - is {movement, key} one that should wake the keygaurd?
104 * - is the keyguard showing?
105 * - are input events restricted due to the state of the keyguard?
106 *
107 * Callbacks to the phone window manager:
108 * - the keyguard is showing
109 *
110 * Example external events that translate to keyguard view changes:
111 * - screen turned off -> reset the keyguard, and show it so it will be ready
112 *   next time the screen turns on
113 * - keyboard is slid open -> if the keyguard is not secure, hide it
114 *
115 * Events from the keyguard view:
116 * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
117 *   restrict input events.
118 *
119 * Note: in addition to normal power managment events that effect the state of
120 * whether the keyguard should be showing, external apps and services may request
121 * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}.  When
122 * false, this will override all other conditions for turning on the keyguard.
123 *
124 * Threading and synchronization:
125 * This class is created by the initialization routine of the {@link android.view.WindowManagerPolicy},
126 * and runs on its thread.  The keyguard UI is created from that thread in the
127 * constructor of this class.  The apis may be called from other threads, including the
128 * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s.
129 * Therefore, methods on this class are synchronized, and any action that is pointed
130 * directly to the keyguard UI is posted to a {@link android.os.Handler} to ensure it is taken on the UI
131 * thread of the keyguard.
132 */
133public class KeyguardViewMediator extends SystemUI {
134    private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
135    private static final long KEYGUARD_DONE_PENDING_TIMEOUT_MS = 3000;
136
137    private static final boolean DEBUG = KeyguardConstants.DEBUG;
138    private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES;
139    private final static boolean DBG_WAKE = false;
140
141    private final static String TAG = "KeyguardViewMediator";
142
143    private static final String DELAYED_KEYGUARD_ACTION =
144        "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
145    private static final String DELAYED_LOCK_PROFILE_ACTION =
146            "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_LOCK";
147
148    // used for handler messages
149    private static final int SHOW = 2;
150    private static final int HIDE = 3;
151    private static final int RESET = 4;
152    private static final int VERIFY_UNLOCK = 5;
153    private static final int NOTIFY_FINISHED_GOING_TO_SLEEP = 6;
154    private static final int NOTIFY_SCREEN_TURNING_ON = 7;
155    private static final int KEYGUARD_DONE = 9;
156    private static final int KEYGUARD_DONE_DRAWING = 10;
157    private static final int KEYGUARD_DONE_AUTHENTICATING = 11;
158    private static final int SET_OCCLUDED = 12;
159    private static final int KEYGUARD_TIMEOUT = 13;
160    private static final int DISMISS = 17;
161    private static final int START_KEYGUARD_EXIT_ANIM = 18;
162    private static final int ON_ACTIVITY_DRAWN = 19;
163    private static final int KEYGUARD_DONE_PENDING_TIMEOUT = 20;
164    private static final int NOTIFY_STARTED_WAKING_UP = 21;
165    private static final int NOTIFY_SCREEN_TURNED_ON = 22;
166    private static final int NOTIFY_SCREEN_TURNED_OFF = 23;
167    private static final int NOTIFY_STARTED_GOING_TO_SLEEP = 24;
168
169    /**
170     * The default amount of time we stay awake (used for all key input)
171     */
172    public static final int AWAKE_INTERVAL_DEFAULT_MS = 10000;
173
174    /**
175     * How long to wait after the screen turns off due to timeout before
176     * turning on the keyguard (i.e, the user has this much time to turn
177     * the screen back on without having to face the keyguard).
178     */
179    private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000;
180
181    /**
182     * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()}
183     * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)}
184     * that is reenabling the keyguard.
185     */
186    private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
187
188    /**
189     * Secure setting whether analytics are collected on the keyguard.
190     */
191    private static final String KEYGUARD_ANALYTICS_SETTING = "keyguard_analytics";
192
193    /** The stream type that the lock sounds are tied to. */
194    private int mUiSoundsStreamType;
195
196    private AlarmManager mAlarmManager;
197    private AudioManager mAudioManager;
198    private StatusBarManager mStatusBarManager;
199    private boolean mSwitchingUser;
200
201    private boolean mSystemReady;
202    private boolean mBootCompleted;
203    private boolean mBootSendUserPresent;
204
205    /** High level access to the power manager for WakeLocks */
206    private PowerManager mPM;
207
208    /** High level access to the window manager for dismissing keyguard animation */
209    private IWindowManager mWM;
210
211
212    /** TrustManager for letting it know when we change visibility */
213    private TrustManager mTrustManager;
214
215    /** SearchManager for determining whether or not search assistant is available */
216    private SearchManager mSearchManager;
217
218    /**
219     * Used to keep the device awake while to ensure the keyguard finishes opening before
220     * we sleep.
221     */
222    private PowerManager.WakeLock mShowKeyguardWakeLock;
223
224    private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
225
226    // these are protected by synchronized (this)
227
228    /**
229     * External apps (like the phone app) can tell us to disable the keygaurd.
230     */
231    private boolean mExternallyEnabled = true;
232
233    /**
234     * Remember if an external call to {@link #setKeyguardEnabled} with value
235     * false caused us to hide the keyguard, so that we need to reshow it once
236     * the keygaurd is reenabled with another call with value true.
237     */
238    private boolean mNeedToReshowWhenReenabled = false;
239
240    // cached value of whether we are showing (need to know this to quickly
241    // answer whether the input should be restricted)
242    private boolean mShowing;
243
244    /** Cached value of #isInputRestricted */
245    private boolean mInputRestricted;
246
247    // true if the keyguard is hidden by another window
248    private boolean mOccluded = false;
249
250    /**
251     * Helps remember whether the screen has turned on since the last time
252     * it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
253     */
254    private int mDelayedShowingSequence;
255
256    /**
257     * Simiar to {@link #mDelayedProfileShowingSequence}, but it is for profile case.
258     */
259    private int mDelayedProfileShowingSequence;
260
261    /**
262     * If the user has disabled the keyguard, then requests to exit, this is
263     * how we'll ultimately let them know whether it was successful.  We use this
264     * var being non-null as an indicator that there is an in progress request.
265     */
266    private IKeyguardExitCallback mExitSecureCallback;
267
268    // the properties of the keyguard
269
270    private KeyguardUpdateMonitor mUpdateMonitor;
271
272    private boolean mDeviceInteractive;
273    private boolean mGoingToSleep;
274
275    // last known state of the cellular connection
276    private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE;
277
278    /**
279     * Whether a hide is pending an we are just waiting for #startKeyguardExitAnimation to be
280     * called.
281     * */
282    private boolean mHiding;
283
284    /**
285     * we send this intent when the keyguard is dismissed.
286     */
287    private static final Intent USER_PRESENT_INTENT = new Intent(Intent.ACTION_USER_PRESENT)
288            .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
289                    | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
290
291    /**
292     * {@link #setKeyguardEnabled} waits on this condition when it reenables
293     * the keyguard.
294     */
295    private boolean mWaitingUntilKeyguardVisible = false;
296    private LockPatternUtils mLockPatternUtils;
297    private boolean mKeyguardDonePending = false;
298    private boolean mHideAnimationRun = false;
299
300    private SoundPool mLockSounds;
301    private int mLockSoundId;
302    private int mUnlockSoundId;
303    private int mTrustedSoundId;
304    private int mLockSoundStreamId;
305
306    /**
307     * The animation used for hiding keyguard. This is used to fetch the animation timings if
308     * WindowManager is not providing us with them.
309     */
310    private Animation mHideAnimation;
311
312    /**
313     * The volume applied to the lock/unlock sounds.
314     */
315    private float mLockSoundVolume;
316
317    /**
318     * For managing external displays
319     */
320    private KeyguardDisplayManager mKeyguardDisplayManager;
321
322    private final ArrayList<IKeyguardStateCallback> mKeyguardStateCallbacks = new ArrayList<>();
323
324    /**
325     * When starting going to sleep, we figured out that we need to reset Keyguard state and this
326     * should be committed when finished going to sleep.
327     */
328    private boolean mPendingReset;
329
330    /**
331     * When starting going to sleep, we figured out that we need to lock Keyguard and this should be
332     * committed when finished going to sleep.
333     */
334    private boolean mPendingLock;
335
336    private boolean mLockLater;
337
338    private boolean mWakeAndUnlocking;
339    private IKeyguardDrawnCallback mDrawnCallback;
340
341    private boolean mIsPerUserLock;
342
343    KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
344
345        @Override
346        public void onUserSwitching(int userId) {
347            // Note that the mLockPatternUtils user has already been updated from setCurrentUser.
348            // We need to force a reset of the views, since lockNow (called by
349            // ActivityManagerService) will not reconstruct the keyguard if it is already showing.
350            synchronized (KeyguardViewMediator.this) {
351                mSwitchingUser = true;
352                resetKeyguardDonePendingLocked();
353                resetStateLocked();
354                adjustStatusBarLocked();
355            }
356        }
357
358        @Override
359        public void onUserSwitchComplete(int userId) {
360            mSwitchingUser = false;
361            if (userId != UserHandle.USER_SYSTEM) {
362                UserInfo info = UserManager.get(mContext).getUserInfo(userId);
363                if (info != null && info.isGuest()) {
364                    // If we just switched to a guest, try to dismiss keyguard.
365                    dismiss();
366                }
367            }
368        }
369
370        @Override
371        public void onUserInfoChanged(int userId) {
372        }
373
374        @Override
375        public void onPhoneStateChanged(int phoneState) {
376            synchronized (KeyguardViewMediator.this) {
377                if (TelephonyManager.CALL_STATE_IDLE == phoneState  // call ending
378                        && !mDeviceInteractive                           // screen off
379                        && mExternallyEnabled) {                // not disabled by any app
380
381                    // note: this is a way to gracefully reenable the keyguard when the call
382                    // ends and the screen is off without always reenabling the keyguard
383                    // each time the screen turns off while in call (and having an occasional ugly
384                    // flicker while turning back on the screen and disabling the keyguard again).
385                    if (DEBUG) Log.d(TAG, "screen is off and call ended, let's make sure the "
386                            + "keyguard is showing");
387                    doKeyguardLocked(null);
388                }
389            }
390        }
391
392        @Override
393        public void onClockVisibilityChanged() {
394            adjustStatusBarLocked();
395        }
396
397        @Override
398        public void onDeviceProvisioned() {
399            sendUserPresentBroadcast();
400            synchronized (KeyguardViewMediator.this) {
401                // If system user is provisioned, we might want to lock now to avoid showing launcher
402                if (mustNotUnlockCurrentUser()) {
403                    doKeyguardLocked(null);
404                }
405            }
406        }
407
408        @Override
409        public void onSimStateChanged(int subId, int slotId, IccCardConstants.State simState) {
410
411            if (DEBUG_SIM_STATES) {
412                Log.d(TAG, "onSimStateChanged(subId=" + subId + ", slotId=" + slotId
413                        + ",state=" + simState + ")");
414            }
415
416            int size = mKeyguardStateCallbacks.size();
417            boolean simPinSecure = mUpdateMonitor.isSimPinSecure();
418            for (int i = size - 1; i >= 0; i--) {
419                try {
420                    mKeyguardStateCallbacks.get(i).onSimSecureStateChanged(simPinSecure);
421                } catch (RemoteException e) {
422                    Slog.w(TAG, "Failed to call onSimSecureStateChanged", e);
423                    if (e instanceof DeadObjectException) {
424                        mKeyguardStateCallbacks.remove(i);
425                    }
426                }
427            }
428
429            switch (simState) {
430                case NOT_READY:
431                case ABSENT:
432                    // only force lock screen in case of missing sim if user hasn't
433                    // gone through setup wizard
434                    synchronized (this) {
435                        if (shouldWaitForProvisioning()) {
436                            if (!mShowing) {
437                                if (DEBUG_SIM_STATES) Log.d(TAG, "ICC_ABSENT isn't showing,"
438                                        + " we need to show the keyguard since the "
439                                        + "device isn't provisioned yet.");
440                                doKeyguardLocked(null);
441                            } else {
442                                resetStateLocked();
443                            }
444                        }
445                    }
446                    break;
447                case PIN_REQUIRED:
448                case PUK_REQUIRED:
449                    synchronized (this) {
450                        if (!mShowing) {
451                            if (DEBUG_SIM_STATES) Log.d(TAG,
452                                    "INTENT_VALUE_ICC_LOCKED and keygaurd isn't "
453                                    + "showing; need to show keyguard so user can enter sim pin");
454                            doKeyguardLocked(null);
455                        } else {
456                            resetStateLocked();
457                        }
458                    }
459                    break;
460                case PERM_DISABLED:
461                    synchronized (this) {
462                        if (!mShowing) {
463                            if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED and "
464                                  + "keygaurd isn't showing.");
465                            doKeyguardLocked(null);
466                        } else {
467                            if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED, resetStateLocked to"
468                                  + "show permanently disabled message in lockscreen.");
469                            resetStateLocked();
470                        }
471                    }
472                    break;
473                case READY:
474                    synchronized (this) {
475                        if (mShowing) {
476                            resetStateLocked();
477                        }
478                    }
479                    break;
480                default:
481                    if (DEBUG_SIM_STATES) Log.v(TAG, "Ignoring state: " + simState);
482                    break;
483            }
484        }
485
486        @Override
487        public void onFingerprintAuthFailed() {
488            final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
489            if (mLockPatternUtils.isSecure(currentUser)) {
490                mLockPatternUtils.getDevicePolicyManager().reportFailedFingerprintAttempt(
491                        currentUser);
492            }
493        }
494
495        @Override
496        public void onFingerprintAuthenticated(int userId) {
497            if (mLockPatternUtils.isSecure(userId)) {
498                mLockPatternUtils.getDevicePolicyManager().reportSuccessfulFingerprintAttempt(
499                        userId);
500            }
501        }
502    };
503
504    ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
505
506        @Override
507        public void userActivity() {
508            KeyguardViewMediator.this.userActivity();
509        }
510
511        @Override
512        public void keyguardDone(boolean strongAuth) {
513            if (!mKeyguardDonePending) {
514                KeyguardViewMediator.this.keyguardDone(true /* authenticated */);
515            }
516            if (strongAuth) {
517                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
518            }
519        }
520
521        @Override
522        public void keyguardDoneDrawing() {
523            mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
524        }
525
526        @Override
527        public void setNeedsInput(boolean needsInput) {
528            mStatusBarKeyguardViewManager.setNeedsInput(needsInput);
529        }
530
531        @Override
532        public void keyguardDonePending(boolean strongAuth) {
533            mKeyguardDonePending = true;
534            mHideAnimationRun = true;
535            mStatusBarKeyguardViewManager.startPreHideAnimation(null /* finishRunnable */);
536            mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT,
537                    KEYGUARD_DONE_PENDING_TIMEOUT_MS);
538            if (strongAuth) {
539                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
540            }
541        }
542
543        @Override
544        public void keyguardGone() {
545            mKeyguardDisplayManager.hide();
546        }
547
548        @Override
549        public void readyForKeyguardDone() {
550            if (mKeyguardDonePending) {
551                // Somebody has called keyguardDonePending before, which means that we are
552                // authenticated
553                KeyguardViewMediator.this.keyguardDone(true /* authenticated */);
554            }
555        }
556
557        @Override
558        public void resetKeyguard() {
559            resetStateLocked();
560        }
561
562        @Override
563        public void playTrustedSound() {
564            KeyguardViewMediator.this.playTrustedSound();
565        }
566
567        @Override
568        public boolean isInputRestricted() {
569            return KeyguardViewMediator.this.isInputRestricted();
570        }
571
572        @Override
573        public boolean isScreenOn() {
574            return mDeviceInteractive;
575        }
576
577        @Override
578        public int getBouncerPromptReason() {
579            int currentUser = ActivityManager.getCurrentUser();
580            boolean trust = mTrustManager.isTrustUsuallyManaged(currentUser);
581            boolean fingerprint = mUpdateMonitor.isUnlockWithFingerprintPossible(currentUser);
582            boolean any = trust || fingerprint;
583            KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
584                    mUpdateMonitor.getStrongAuthTracker();
585            int strongAuth = strongAuthTracker.getStrongAuthForUser(currentUser);
586
587            if (any && !strongAuthTracker.hasUserAuthenticatedSinceBoot()) {
588                return KeyguardSecurityView.PROMPT_REASON_RESTART;
589            } else if (fingerprint && mUpdateMonitor.hasFingerprintUnlockTimedOut(currentUser)) {
590                return KeyguardSecurityView.PROMPT_REASON_TIMEOUT;
591            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) != 0) {
592                return KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN;
593            } else if (trust && (strongAuth & SOME_AUTH_REQUIRED_AFTER_USER_REQUEST) != 0) {
594                return KeyguardSecurityView.PROMPT_REASON_USER_REQUEST;
595            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_LOCKOUT) != 0) {
596                return KeyguardSecurityView.PROMPT_REASON_AFTER_LOCKOUT;
597            } else if (trust && (strongAuth & SOME_AUTH_REQUIRED_AFTER_WRONG_CREDENTIAL) != 0) {
598                return KeyguardSecurityView.PROMPT_REASON_WRONG_CREDENTIAL;
599            }
600
601            return KeyguardSecurityView.PROMPT_REASON_NONE;
602        }
603    };
604
605    public void userActivity() {
606        mPM.userActivity(SystemClock.uptimeMillis(), false);
607    }
608
609    boolean mustNotUnlockCurrentUser() {
610        return (UserManager.isSplitSystemUser() || UserManager.isDeviceInDemoMode(mContext))
611                && KeyguardUpdateMonitor.getCurrentUser() == UserHandle.USER_SYSTEM;
612    }
613
614    private void setupLocked() {
615        mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
616        mWM = WindowManagerGlobal.getWindowManagerService();
617        mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
618
619        mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
620        mShowKeyguardWakeLock.setReferenceCounted(false);
621
622        mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
623        mContext.registerReceiver(
624                mBroadcastReceiver, new IntentFilter(DELAYED_LOCK_PROFILE_ACTION));
625
626        mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
627
628        mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
629
630        mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
631
632        mLockPatternUtils = new LockPatternUtils(mContext);
633        KeyguardUpdateMonitor.setCurrentUser(ActivityManager.getCurrentUser());
634
635        // Assume keyguard is showing (unless it's disabled) until we know for sure...
636        setShowingLocked(!shouldWaitForProvisioning() && !mLockPatternUtils.isLockScreenDisabled(
637                KeyguardUpdateMonitor.getCurrentUser()));
638        updateInputRestrictedLocked();
639        mTrustManager.reportKeyguardShowingChanged();
640
641        mStatusBarKeyguardViewManager =
642                SystemUIFactory.getInstance().createStatusBarKeyguardViewManager(mContext,
643                        mViewMediatorCallback, mLockPatternUtils);
644        final ContentResolver cr = mContext.getContentResolver();
645
646        mDeviceInteractive = mPM.isInteractive();
647
648        mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
649        String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
650        if (soundPath != null) {
651            mLockSoundId = mLockSounds.load(soundPath, 1);
652        }
653        if (soundPath == null || mLockSoundId == 0) {
654            Log.w(TAG, "failed to load lock sound from " + soundPath);
655        }
656        soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
657        if (soundPath != null) {
658            mUnlockSoundId = mLockSounds.load(soundPath, 1);
659        }
660        if (soundPath == null || mUnlockSoundId == 0) {
661            Log.w(TAG, "failed to load unlock sound from " + soundPath);
662        }
663        soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND);
664        if (soundPath != null) {
665            mTrustedSoundId = mLockSounds.load(soundPath, 1);
666        }
667        if (soundPath == null || mTrustedSoundId == 0) {
668            Log.w(TAG, "failed to load trusted sound from " + soundPath);
669        }
670
671        int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
672                com.android.internal.R.integer.config_lockSoundVolumeDb);
673        mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
674
675        mHideAnimation = AnimationUtils.loadAnimation(mContext,
676                com.android.internal.R.anim.lock_screen_behind_enter);
677    }
678
679    @Override
680    public void start() {
681        synchronized (this) {
682            setupLocked();
683        }
684        putComponent(KeyguardViewMediator.class, this);
685    }
686
687    /**
688     * Let us know that the system is ready after startup.
689     */
690    public void onSystemReady() {
691        mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
692        synchronized (this) {
693            if (DEBUG) Log.d(TAG, "onSystemReady");
694            mSystemReady = true;
695            doKeyguardLocked(null);
696            mUpdateMonitor.registerCallback(mUpdateCallback);
697        }
698        mIsPerUserLock = StorageManager.isFileEncryptedNativeOrEmulated();
699        // Most services aren't available until the system reaches the ready state, so we
700        // send it here when the device first boots.
701        maybeSendUserPresentBroadcast();
702    }
703
704    /**
705     * Called to let us know the screen was turned off.
706     * @param why either {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_USER} or
707     *   {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.
708     */
709    public void onStartedGoingToSleep(int why) {
710        if (DEBUG) Log.d(TAG, "onStartedGoingToSleep(" + why + ")");
711        synchronized (this) {
712            mDeviceInteractive = false;
713            mGoingToSleep = true;
714
715            // Lock immediately based on setting if secure (user has a pin/pattern/password).
716            // This also "locks" the device when not secure to provide easy access to the
717            // camera while preventing unwanted input.
718            int currentUser = KeyguardUpdateMonitor.getCurrentUser();
719            final boolean lockImmediately =
720                    mLockPatternUtils.getPowerButtonInstantlyLocks(currentUser)
721                            || !mLockPatternUtils.isSecure(currentUser);
722            long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser());
723            mLockLater = false;
724            if (mExitSecureCallback != null) {
725                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
726                try {
727                    mExitSecureCallback.onKeyguardExitResult(false);
728                } catch (RemoteException e) {
729                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
730                }
731                mExitSecureCallback = null;
732                if (!mExternallyEnabled) {
733                    hideLocked();
734                }
735            } else if (mShowing) {
736                mPendingReset = true;
737            } else if ((why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT && timeout > 0)
738                    || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
739                doKeyguardLaterLocked(timeout);
740                mLockLater = true;
741            } else if (!mLockPatternUtils.isLockScreenDisabled(currentUser)) {
742                mPendingLock = true;
743            }
744
745            if (mPendingLock) {
746                playSounds(true);
747            }
748        }
749        KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedGoingToSleep(why);
750        notifyStartedGoingToSleep();
751    }
752
753    public void onFinishedGoingToSleep(int why, boolean cameraGestureTriggered) {
754        if (DEBUG) Log.d(TAG, "onFinishedGoingToSleep(" + why + ")");
755        synchronized (this) {
756            mDeviceInteractive = false;
757            mGoingToSleep = false;
758
759            resetKeyguardDonePendingLocked();
760            mHideAnimationRun = false;
761
762            notifyFinishedGoingToSleep();
763
764            if (cameraGestureTriggered) {
765                Log.i(TAG, "Camera gesture was triggered, preventing Keyguard locking.");
766
767                // Just to make sure, make sure the device is awake.
768                mContext.getSystemService(PowerManager.class).wakeUp(SystemClock.uptimeMillis(),
769                        "com.android.systemui:CAMERA_GESTURE_PREVENT_LOCK");
770                mPendingLock = false;
771                mPendingReset = false;
772            }
773
774            if (mPendingReset) {
775                resetStateLocked();
776                mPendingReset = false;
777            }
778
779            if (mPendingLock) {
780                doKeyguardLocked(null);
781                mPendingLock = false;
782            }
783
784            // We do not have timeout and power button instant lock setting for profile lock.
785            // So we use the personal setting if there is any. But if there is no device
786            // we need to make sure we lock it immediately when the screen is off.
787            if (!mLockLater && !cameraGestureTriggered) {
788                doKeyguardForChildProfilesLocked();
789            }
790
791        }
792        KeyguardUpdateMonitor.getInstance(mContext).dispatchFinishedGoingToSleep(why);
793    }
794
795    private long getLockTimeout(int userId) {
796        // if the screen turned off because of timeout or the user hit the power button
797        // and we don't need to lock immediately, set an alarm
798        // to enable it a little bit later (i.e, give the user a chance
799        // to turn the screen back on within a certain window without
800        // having to unlock the screen)
801        final ContentResolver cr = mContext.getContentResolver();
802
803        // From SecuritySettings
804        final long lockAfterTimeout = Settings.Secure.getInt(cr,
805                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
806                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
807
808        // From DevicePolicyAdmin
809        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
810                .getMaximumTimeToLockForUserAndProfiles(userId);
811
812        long timeout;
813
814        if (policyTimeout <= 0) {
815            timeout = lockAfterTimeout;
816        } else {
817            // From DisplaySettings
818            long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
819                    KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
820
821            // policy in effect. Make sure we don't go beyond policy limit.
822            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
823            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
824            timeout = Math.max(timeout, 0);
825        }
826        return timeout;
827    }
828
829    private void doKeyguardLaterLocked() {
830        long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser());
831        if (timeout == 0) {
832            doKeyguardLocked(null);
833        } else {
834            doKeyguardLaterLocked(timeout);
835        }
836    }
837
838    private void doKeyguardLaterLocked(long timeout) {
839        // Lock in the future
840        long when = SystemClock.elapsedRealtime() + timeout;
841        Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
842        intent.putExtra("seq", mDelayedShowingSequence);
843        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
844        PendingIntent sender = PendingIntent.getBroadcast(mContext,
845                0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
846        mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
847        if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
848                         + mDelayedShowingSequence);
849        doKeyguardLaterForChildProfilesLocked();
850    }
851
852    private void doKeyguardLaterForChildProfilesLocked() {
853        UserManager um = UserManager.get(mContext);
854        for (int profileId : um.getEnabledProfileIds(UserHandle.myUserId())) {
855            if (mLockPatternUtils.isSeparateProfileChallengeEnabled(profileId)) {
856                long userTimeout = getLockTimeout(profileId);
857                if (userTimeout == 0) {
858                    doKeyguardForChildProfilesLocked();
859                } else {
860                    long userWhen = SystemClock.elapsedRealtime() + userTimeout;
861                    Intent lockIntent = new Intent(DELAYED_LOCK_PROFILE_ACTION);
862                    lockIntent.putExtra("seq", mDelayedProfileShowingSequence);
863                    lockIntent.putExtra(Intent.EXTRA_USER_ID, profileId);
864                    lockIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
865                    PendingIntent lockSender = PendingIntent.getBroadcast(
866                            mContext, 0, lockIntent, PendingIntent.FLAG_CANCEL_CURRENT);
867                    mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
868                            userWhen, lockSender);
869                }
870            }
871        }
872    }
873
874    private void doKeyguardForChildProfilesLocked() {
875        UserManager um = UserManager.get(mContext);
876        for (int profileId : um.getEnabledProfileIds(UserHandle.myUserId())) {
877            if (mLockPatternUtils.isSeparateProfileChallengeEnabled(profileId)) {
878                lockProfile(profileId);
879            }
880        }
881    }
882
883    private void cancelDoKeyguardLaterLocked() {
884        mDelayedShowingSequence++;
885    }
886
887    private void cancelDoKeyguardForChildProfilesLocked() {
888        mDelayedProfileShowingSequence++;
889    }
890
891    /**
892     * Let's us know when the device is waking up.
893     */
894    public void onStartedWakingUp() {
895
896        // TODO: Rename all screen off/on references to interactive/sleeping
897        synchronized (this) {
898            mDeviceInteractive = true;
899            cancelDoKeyguardLaterLocked();
900            cancelDoKeyguardForChildProfilesLocked();
901            if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence);
902            notifyStartedWakingUp();
903        }
904        KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedWakingUp();
905        maybeSendUserPresentBroadcast();
906    }
907
908    public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
909        notifyScreenOn(callback);
910    }
911
912    public void onScreenTurnedOn() {
913        notifyScreenTurnedOn();
914        mUpdateMonitor.dispatchScreenTurnedOn();
915    }
916
917    public void onScreenTurnedOff() {
918        notifyScreenTurnedOff();
919        mUpdateMonitor.dispatchScreenTurnedOff();
920    }
921
922    private void maybeSendUserPresentBroadcast() {
923        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled(
924                KeyguardUpdateMonitor.getCurrentUser())) {
925            // Lock screen is disabled because the user has set the preference to "None".
926            // In this case, send out ACTION_USER_PRESENT here instead of in
927            // handleKeyguardDone()
928            sendUserPresentBroadcast();
929        }
930    }
931
932    /**
933     * A dream started.  We should lock after the usual screen-off lock timeout but only
934     * if there is a secure lock pattern.
935     */
936    public void onDreamingStarted() {
937        synchronized (this) {
938            if (mDeviceInteractive
939                    && mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) {
940                doKeyguardLaterLocked();
941            }
942        }
943    }
944
945    /**
946     * A dream stopped.
947     */
948    public void onDreamingStopped() {
949        synchronized (this) {
950            if (mDeviceInteractive) {
951                cancelDoKeyguardLaterLocked();
952            }
953        }
954    }
955
956    /**
957     * Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide
958     * a way for external stuff to override normal keyguard behavior.  For instance
959     * the phone app disables the keyguard when it receives incoming calls.
960     */
961    public void setKeyguardEnabled(boolean enabled) {
962        synchronized (this) {
963            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
964
965            mExternallyEnabled = enabled;
966
967            if (!enabled && mShowing) {
968                if (mExitSecureCallback != null) {
969                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
970                    // we're in the process of handling a request to verify the user
971                    // can get past the keyguard. ignore extraneous requests to disable / reenable
972                    return;
973                }
974
975                // hiding keyguard that is showing, remember to reshow later
976                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
977                        + "disabling status bar expansion");
978                mNeedToReshowWhenReenabled = true;
979                updateInputRestrictedLocked();
980                hideLocked();
981            } else if (enabled && mNeedToReshowWhenReenabled) {
982                // reenabled after previously hidden, reshow
983                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
984                        + "status bar expansion");
985                mNeedToReshowWhenReenabled = false;
986                updateInputRestrictedLocked();
987
988                if (mExitSecureCallback != null) {
989                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
990                    try {
991                        mExitSecureCallback.onKeyguardExitResult(false);
992                    } catch (RemoteException e) {
993                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
994                    }
995                    mExitSecureCallback = null;
996                    resetStateLocked();
997                } else {
998                    showLocked(null);
999
1000                    // block until we know the keygaurd is done drawing (and post a message
1001                    // to unblock us after a timeout so we don't risk blocking too long
1002                    // and causing an ANR).
1003                    mWaitingUntilKeyguardVisible = true;
1004                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
1005                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
1006                    while (mWaitingUntilKeyguardVisible) {
1007                        try {
1008                            wait();
1009                        } catch (InterruptedException e) {
1010                            Thread.currentThread().interrupt();
1011                        }
1012                    }
1013                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
1014                }
1015            }
1016        }
1017    }
1018
1019    /**
1020     * @see android.app.KeyguardManager#exitKeyguardSecurely
1021     */
1022    public void verifyUnlock(IKeyguardExitCallback callback) {
1023        synchronized (this) {
1024            if (DEBUG) Log.d(TAG, "verifyUnlock");
1025            if (shouldWaitForProvisioning()) {
1026                // don't allow this api when the device isn't provisioned
1027                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
1028                try {
1029                    callback.onKeyguardExitResult(false);
1030                } catch (RemoteException e) {
1031                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1032                }
1033            } else if (mExternallyEnabled) {
1034                // this only applies when the user has externally disabled the
1035                // keyguard.  this is unexpected and means the user is not
1036                // using the api properly.
1037                Log.w(TAG, "verifyUnlock called when not externally disabled");
1038                try {
1039                    callback.onKeyguardExitResult(false);
1040                } catch (RemoteException e) {
1041                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1042                }
1043            } else if (mExitSecureCallback != null) {
1044                // already in progress with someone else
1045                try {
1046                    callback.onKeyguardExitResult(false);
1047                } catch (RemoteException e) {
1048                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1049                }
1050            } else if (!isSecure()) {
1051
1052                // Keyguard is not secure, no need to do anything, and we don't need to reshow
1053                // the Keyguard after the client releases the Keyguard lock.
1054                mExternallyEnabled = true;
1055                mNeedToReshowWhenReenabled = false;
1056                updateInputRestricted();
1057                try {
1058                    callback.onKeyguardExitResult(true);
1059                } catch (RemoteException e) {
1060                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1061                }
1062            } else {
1063
1064                // Since we prevent apps from hiding the Keyguard if we are secure, this should be
1065                // a no-op as well.
1066                try {
1067                    callback.onKeyguardExitResult(false);
1068                } catch (RemoteException e) {
1069                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1070                }
1071            }
1072        }
1073    }
1074
1075    /**
1076     * Is the keyguard currently showing and not being force hidden?
1077     */
1078    public boolean isShowingAndNotOccluded() {
1079        return mShowing && !mOccluded;
1080    }
1081
1082    /**
1083     * Notify us when the keyguard is occluded by another window
1084     */
1085    public void setOccluded(boolean isOccluded) {
1086        if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
1087        mHandler.removeMessages(SET_OCCLUDED);
1088        Message msg = mHandler.obtainMessage(SET_OCCLUDED, (isOccluded ? 1 : 0), 0);
1089        mHandler.sendMessage(msg);
1090    }
1091
1092    /**
1093     * Handles SET_OCCLUDED message sent by setOccluded()
1094     */
1095    private void handleSetOccluded(boolean isOccluded) {
1096        synchronized (KeyguardViewMediator.this) {
1097            if (mHiding && isOccluded) {
1098                // We're in the process of going away but WindowManager wants to show a
1099                // SHOW_WHEN_LOCKED activity instead.
1100                startKeyguardExitAnimation(0, 0);
1101            }
1102
1103            if (mOccluded != isOccluded) {
1104                mOccluded = isOccluded;
1105                mStatusBarKeyguardViewManager.setOccluded(isOccluded);
1106                updateActivityLockScreenState();
1107                adjustStatusBarLocked();
1108            }
1109        }
1110    }
1111
1112    /**
1113     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
1114     * This must be safe to call from any thread and with any window manager locks held.
1115     */
1116    public void doKeyguardTimeout(Bundle options) {
1117        mHandler.removeMessages(KEYGUARD_TIMEOUT);
1118        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
1119        mHandler.sendMessage(msg);
1120    }
1121
1122    /**
1123     * Given the state of the keyguard, is the input restricted?
1124     * Input is restricted when the keyguard is showing, or when the keyguard
1125     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
1126     */
1127    public boolean isInputRestricted() {
1128        return mShowing || mNeedToReshowWhenReenabled;
1129    }
1130
1131    private void updateInputRestricted() {
1132        synchronized (this) {
1133            updateInputRestrictedLocked();
1134        }
1135    }
1136    private void updateInputRestrictedLocked() {
1137        boolean inputRestricted = isInputRestricted();
1138        if (mInputRestricted != inputRestricted) {
1139            mInputRestricted = inputRestricted;
1140            int size = mKeyguardStateCallbacks.size();
1141            for (int i = size - 1; i >= 0; i--) {
1142                try {
1143                    mKeyguardStateCallbacks.get(i).onInputRestrictedStateChanged(inputRestricted);
1144                } catch (RemoteException e) {
1145                    Slog.w(TAG, "Failed to call onDeviceProvisioned", e);
1146                    if (e instanceof DeadObjectException) {
1147                        mKeyguardStateCallbacks.remove(i);
1148                    }
1149                }
1150            }
1151        }
1152    }
1153
1154    /**
1155     * Enable the keyguard if the settings are appropriate.
1156     */
1157    private void doKeyguardLocked(Bundle options) {
1158        // if another app is disabling us, don't show
1159        if (!mExternallyEnabled) {
1160            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
1161
1162            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
1163            // for an occasional ugly flicker in this situation:
1164            // 1) receive a call with the screen on (no keyguard) or make a call
1165            // 2) screen times out
1166            // 3) user hits key to turn screen back on
1167            // instead, we reenable the keyguard when we know the screen is off and the call
1168            // ends (see the broadcast receiver below)
1169            // TODO: clean this up when we have better support at the window manager level
1170            // for apps that wish to be on top of the keyguard
1171            return;
1172        }
1173
1174        // if the keyguard is already showing, don't bother
1175        if (mStatusBarKeyguardViewManager.isShowing()) {
1176            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
1177            resetStateLocked();
1178            return;
1179        }
1180
1181        // In split system user mode, we never unlock system user.
1182        if (!mustNotUnlockCurrentUser()
1183                || !mUpdateMonitor.isDeviceProvisioned()) {
1184
1185            // if the setup wizard hasn't run yet, don't show
1186            final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
1187            final boolean absent = SubscriptionManager.isValidSubscriptionId(
1188                    mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.ABSENT));
1189            final boolean disabled = SubscriptionManager.isValidSubscriptionId(
1190                    mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED));
1191            final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure()
1192                    || ((absent || disabled) && requireSim);
1193
1194            if (!lockedOrMissing && shouldWaitForProvisioning()) {
1195                if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
1196                        + " and the sim is not locked or missing");
1197                return;
1198            }
1199
1200            if (mLockPatternUtils.isLockScreenDisabled(KeyguardUpdateMonitor.getCurrentUser())
1201                    && !lockedOrMissing) {
1202                if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
1203                return;
1204            }
1205
1206            if (mLockPatternUtils.checkVoldPassword(KeyguardUpdateMonitor.getCurrentUser())) {
1207                if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
1208                // Without this, settings is not enabled until the lock screen first appears
1209                setShowingLocked(false);
1210                hideLocked();
1211                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
1212                return;
1213            }
1214        }
1215
1216        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
1217        showLocked(options);
1218    }
1219
1220    private void lockProfile(int userId) {
1221        mTrustManager.setDeviceLockedForUser(userId, true);
1222    }
1223
1224    private boolean shouldWaitForProvisioning() {
1225        return !mUpdateMonitor.isDeviceProvisioned() && !isSecure();
1226    }
1227
1228    /**
1229     * Dismiss the keyguard through the security layers.
1230     */
1231    public void handleDismiss() {
1232        if (mShowing && !mOccluded) {
1233            mStatusBarKeyguardViewManager.dismiss();
1234        }
1235    }
1236
1237    public void dismiss() {
1238        mHandler.sendEmptyMessage(DISMISS);
1239    }
1240
1241    /**
1242     * Send message to keyguard telling it to reset its state.
1243     * @see #handleReset
1244     */
1245    private void resetStateLocked() {
1246        if (DEBUG) Log.e(TAG, "resetStateLocked");
1247        Message msg = mHandler.obtainMessage(RESET);
1248        mHandler.sendMessage(msg);
1249    }
1250
1251    /**
1252     * Send message to keyguard telling it to verify unlock
1253     * @see #handleVerifyUnlock()
1254     */
1255    private void verifyUnlockLocked() {
1256        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
1257        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
1258    }
1259
1260    private void notifyStartedGoingToSleep() {
1261        if (DEBUG) Log.d(TAG, "notifyStartedGoingToSleep");
1262        mHandler.sendEmptyMessage(NOTIFY_STARTED_GOING_TO_SLEEP);
1263    }
1264
1265    private void notifyFinishedGoingToSleep() {
1266        if (DEBUG) Log.d(TAG, "notifyFinishedGoingToSleep");
1267        mHandler.sendEmptyMessage(NOTIFY_FINISHED_GOING_TO_SLEEP);
1268    }
1269
1270    private void notifyStartedWakingUp() {
1271        if (DEBUG) Log.d(TAG, "notifyStartedWakingUp");
1272        mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP);
1273    }
1274
1275    private void notifyScreenOn(IKeyguardDrawnCallback callback) {
1276        if (DEBUG) Log.d(TAG, "notifyScreenOn");
1277        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNING_ON, callback);
1278        mHandler.sendMessage(msg);
1279    }
1280
1281    private void notifyScreenTurnedOn() {
1282        if (DEBUG) Log.d(TAG, "notifyScreenTurnedOn");
1283        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_ON);
1284        mHandler.sendMessage(msg);
1285    }
1286
1287    private void notifyScreenTurnedOff() {
1288        if (DEBUG) Log.d(TAG, "notifyScreenTurnedOff");
1289        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_OFF);
1290        mHandler.sendMessage(msg);
1291    }
1292
1293    /**
1294     * Send message to keyguard telling it to show itself
1295     * @see #handleShow
1296     */
1297    private void showLocked(Bundle options) {
1298        if (DEBUG) Log.d(TAG, "showLocked");
1299        // ensure we stay awake until we are finished displaying the keyguard
1300        mShowKeyguardWakeLock.acquire();
1301        Message msg = mHandler.obtainMessage(SHOW, options);
1302        mHandler.sendMessage(msg);
1303    }
1304
1305    /**
1306     * Send message to keyguard telling it to hide itself
1307     * @see #handleHide()
1308     */
1309    private void hideLocked() {
1310        if (DEBUG) Log.d(TAG, "hideLocked");
1311        Message msg = mHandler.obtainMessage(HIDE);
1312        mHandler.sendMessage(msg);
1313    }
1314
1315    public boolean isSecure() {
1316        return mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())
1317            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
1318    }
1319
1320    /**
1321     * Update the newUserId. Call while holding WindowManagerService lock.
1322     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
1323     *
1324     * @param newUserId The id of the incoming user.
1325     */
1326    public void setCurrentUser(int newUserId) {
1327        KeyguardUpdateMonitor.setCurrentUser(newUserId);
1328    }
1329
1330    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1331        @Override
1332        public void onReceive(Context context, Intent intent) {
1333            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1334                final int sequence = intent.getIntExtra("seq", 0);
1335                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1336                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1337                synchronized (KeyguardViewMediator.this) {
1338                    if (mDelayedShowingSequence == sequence) {
1339                        doKeyguardLocked(null);
1340                    }
1341                }
1342            } else if (DELAYED_LOCK_PROFILE_ACTION.equals(intent.getAction())) {
1343                final int sequence = intent.getIntExtra("seq", 0);
1344                int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
1345                if (userId != 0) {
1346                    synchronized (KeyguardViewMediator.this) {
1347                        if (mDelayedProfileShowingSequence == sequence) {
1348                            lockProfile(userId);
1349                        }
1350                    }
1351                }
1352            }
1353        }
1354    };
1355
1356    public void keyguardDone(boolean authenticated) {
1357        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated +")");
1358        EventLog.writeEvent(70000, 2);
1359        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0);
1360        mHandler.sendMessage(msg);
1361    }
1362
1363    /**
1364     * This handler will be associated with the policy thread, which will also
1365     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1366     * this class, can be called by other threads, any action that directly
1367     * interacts with the keyguard ui should be posted to this handler, rather
1368     * than called directly.
1369     */
1370    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1371        @Override
1372        public void handleMessage(Message msg) {
1373            switch (msg.what) {
1374                case SHOW:
1375                    handleShow((Bundle) msg.obj);
1376                    break;
1377                case HIDE:
1378                    handleHide();
1379                    break;
1380                case RESET:
1381                    handleReset();
1382                    break;
1383                case VERIFY_UNLOCK:
1384                    handleVerifyUnlock();
1385                    break;
1386                case NOTIFY_STARTED_GOING_TO_SLEEP:
1387                    handleNotifyStartedGoingToSleep();
1388                    break;
1389                case NOTIFY_FINISHED_GOING_TO_SLEEP:
1390                    handleNotifyFinishedGoingToSleep();
1391                    break;
1392                case NOTIFY_SCREEN_TURNING_ON:
1393                    handleNotifyScreenTurningOn((IKeyguardDrawnCallback) msg.obj);
1394                    break;
1395                case NOTIFY_SCREEN_TURNED_ON:
1396                    handleNotifyScreenTurnedOn();
1397                    break;
1398                case NOTIFY_SCREEN_TURNED_OFF:
1399                    handleNotifyScreenTurnedOff();
1400                    break;
1401                case NOTIFY_STARTED_WAKING_UP:
1402                    handleNotifyStartedWakingUp();
1403                    break;
1404                case KEYGUARD_DONE:
1405                    handleKeyguardDone(msg.arg1 != 0);
1406                    break;
1407                case KEYGUARD_DONE_DRAWING:
1408                    handleKeyguardDoneDrawing();
1409                    break;
1410                case SET_OCCLUDED:
1411                    handleSetOccluded(msg.arg1 != 0);
1412                    break;
1413                case KEYGUARD_TIMEOUT:
1414                    synchronized (KeyguardViewMediator.this) {
1415                        doKeyguardLocked((Bundle) msg.obj);
1416                    }
1417                    break;
1418                case DISMISS:
1419                    handleDismiss();
1420                    break;
1421                case START_KEYGUARD_EXIT_ANIM:
1422                    StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
1423                    handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration);
1424                    FalsingManager.getInstance(mContext).onSucccessfulUnlock();
1425                    break;
1426                case KEYGUARD_DONE_PENDING_TIMEOUT:
1427                    Log.w(TAG, "Timeout while waiting for activity drawn!");
1428                    // Fall through.
1429                case ON_ACTIVITY_DRAWN:
1430                    handleOnActivityDrawn();
1431                    break;
1432            }
1433        }
1434    };
1435
1436    /**
1437     * @see #keyguardDone
1438     * @see #KEYGUARD_DONE
1439     */
1440    private void handleKeyguardDone(boolean authenticated) {
1441        final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
1442        if (mLockPatternUtils.isSecure(currentUser)) {
1443            mLockPatternUtils.getDevicePolicyManager().reportKeyguardDismissed(currentUser);
1444        }
1445        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1446        synchronized (this) {
1447            resetKeyguardDonePendingLocked();
1448        }
1449
1450        if (authenticated) {
1451            mUpdateMonitor.clearFailedUnlockAttempts();
1452        }
1453        mUpdateMonitor.clearFingerprintRecognized();
1454
1455        if (mGoingToSleep) {
1456            Log.i(TAG, "Device is going to sleep, aborting keyguardDone");
1457            return;
1458        }
1459        if (mExitSecureCallback != null) {
1460            try {
1461                mExitSecureCallback.onKeyguardExitResult(authenticated);
1462            } catch (RemoteException e) {
1463                Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1464            }
1465
1466            mExitSecureCallback = null;
1467
1468            if (authenticated) {
1469                // after succesfully exiting securely, no need to reshow
1470                // the keyguard when they've released the lock
1471                mExternallyEnabled = true;
1472                mNeedToReshowWhenReenabled = false;
1473                updateInputRestricted();
1474            }
1475        }
1476
1477        handleHide();
1478    }
1479
1480    private void sendUserPresentBroadcast() {
1481        synchronized (this) {
1482            if (mBootCompleted) {
1483                int currentUserId = KeyguardUpdateMonitor.getCurrentUser();
1484                final UserHandle currentUser = new UserHandle(currentUserId);
1485                final UserManager um = (UserManager) mContext.getSystemService(
1486                        Context.USER_SERVICE);
1487                for (int profileId : um.getProfileIdsWithDisabled(currentUser.getIdentifier())) {
1488                    mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, UserHandle.of(profileId));
1489                }
1490                getLockPatternUtils().userPresent(currentUserId);
1491            } else {
1492                mBootSendUserPresent = true;
1493            }
1494        }
1495    }
1496
1497    /**
1498     * @see #keyguardDone
1499     * @see #KEYGUARD_DONE_DRAWING
1500     */
1501    private void handleKeyguardDoneDrawing() {
1502        synchronized(this) {
1503            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1504            if (mWaitingUntilKeyguardVisible) {
1505                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1506                mWaitingUntilKeyguardVisible = false;
1507                notifyAll();
1508
1509                // there will usually be two of these sent, one as a timeout, and one
1510                // as a result of the callback, so remove any remaining messages from
1511                // the queue
1512                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1513            }
1514        }
1515    }
1516
1517    private void playSounds(boolean locked) {
1518        playSound(locked ? mLockSoundId : mUnlockSoundId);
1519    }
1520
1521    private void playSound(int soundId) {
1522        if (soundId == 0) return;
1523        final ContentResolver cr = mContext.getContentResolver();
1524        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1525
1526            mLockSounds.stop(mLockSoundStreamId);
1527            // Init mAudioManager
1528            if (mAudioManager == null) {
1529                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1530                if (mAudioManager == null) return;
1531                mUiSoundsStreamType = mAudioManager.getUiSoundsStreamType();
1532            }
1533            // If the stream is muted, don't play the sound
1534            if (mAudioManager.isStreamMute(mUiSoundsStreamType)) return;
1535
1536            mLockSoundStreamId = mLockSounds.play(soundId,
1537                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1538        }
1539    }
1540
1541    private void playTrustedSound() {
1542        playSound(mTrustedSoundId);
1543    }
1544
1545    private void updateActivityLockScreenState() {
1546        try {
1547            ActivityManagerNative.getDefault().setLockScreenShown(mShowing, mOccluded);
1548        } catch (RemoteException e) {
1549        }
1550    }
1551
1552    /**
1553     * Handle message sent by {@link #showLocked}.
1554     * @see #SHOW
1555     */
1556    private void handleShow(Bundle options) {
1557        final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
1558        if (mLockPatternUtils.isSecure(currentUser)) {
1559            mLockPatternUtils.getDevicePolicyManager().reportKeyguardSecured(currentUser);
1560        }
1561        synchronized (KeyguardViewMediator.this) {
1562            if (!mSystemReady) {
1563                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1564                return;
1565            } else {
1566                if (DEBUG) Log.d(TAG, "handleShow");
1567            }
1568
1569            setShowingLocked(true);
1570            mStatusBarKeyguardViewManager.show(options);
1571            mHiding = false;
1572            mWakeAndUnlocking = false;
1573            resetKeyguardDonePendingLocked();
1574            mHideAnimationRun = false;
1575            updateActivityLockScreenState();
1576            adjustStatusBarLocked();
1577            userActivity();
1578
1579            mShowKeyguardWakeLock.release();
1580        }
1581        mKeyguardDisplayManager.show();
1582    }
1583
1584    private final Runnable mKeyguardGoingAwayRunnable = new Runnable() {
1585        @Override
1586        public void run() {
1587            try {
1588                mStatusBarKeyguardViewManager.keyguardGoingAway();
1589
1590                int flags = 0;
1591                if (mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock()
1592                        || mWakeAndUnlocking) {
1593                    flags |= WindowManagerPolicy.KEYGUARD_GOING_AWAY_FLAG_NO_WINDOW_ANIMATIONS;
1594                }
1595                if (mStatusBarKeyguardViewManager.isGoingToNotificationShade()) {
1596                    flags |= WindowManagerPolicy.KEYGUARD_GOING_AWAY_FLAG_TO_SHADE;
1597                }
1598                if (mStatusBarKeyguardViewManager.isUnlockWithWallpaper()) {
1599                    flags |= WindowManagerPolicy.KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER;
1600                }
1601
1602                // Don't actually hide the Keyguard at the moment, wait for window
1603                // manager until it tells us it's safe to do so with
1604                // startKeyguardExitAnimation.
1605                ActivityManagerNative.getDefault().keyguardGoingAway(flags);
1606            } catch (RemoteException e) {
1607                Log.e(TAG, "Error while calling WindowManager", e);
1608            }
1609        }
1610    };
1611
1612    /**
1613     * Handle message sent by {@link #hideLocked()}
1614     * @see #HIDE
1615     */
1616    private void handleHide() {
1617        synchronized (KeyguardViewMediator.this) {
1618            if (DEBUG) Log.d(TAG, "handleHide");
1619
1620            if (mustNotUnlockCurrentUser()) {
1621                // In split system user mode, we never unlock system user. The end user has to
1622                // switch to another user.
1623                // TODO: We should stop it early by disabling the swipe up flow. Right now swipe up
1624                // still completes and makes the screen blank.
1625                if (DEBUG) Log.d(TAG, "Split system user, quit unlocking.");
1626                return;
1627            }
1628            mHiding = true;
1629            if (mShowing && !mOccluded) {
1630                if (!mHideAnimationRun) {
1631                    mStatusBarKeyguardViewManager.startPreHideAnimation(mKeyguardGoingAwayRunnable);
1632                } else {
1633                    mKeyguardGoingAwayRunnable.run();
1634                }
1635            } else {
1636
1637                // Don't try to rely on WindowManager - if Keyguard wasn't showing, window
1638                // manager won't start the exit animation.
1639                handleStartKeyguardExitAnimation(
1640                        SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
1641                        mHideAnimation.getDuration());
1642            }
1643        }
1644    }
1645
1646    private void handleOnActivityDrawn() {
1647        if (DEBUG) Log.d(TAG, "handleOnActivityDrawn: mKeyguardDonePending=" + mKeyguardDonePending);
1648        if (mKeyguardDonePending) {
1649            mStatusBarKeyguardViewManager.onActivityDrawn();
1650        }
1651    }
1652
1653    private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1654        synchronized (KeyguardViewMediator.this) {
1655
1656            if (!mHiding) {
1657                return;
1658            }
1659            mHiding = false;
1660
1661            if (mWakeAndUnlocking && mDrawnCallback != null) {
1662
1663                // Hack level over 9000: To speed up wake-and-unlock sequence, force it to report
1664                // the next draw from here so we don't have to wait for window manager to signal
1665                // this to our ViewRootImpl.
1666                mStatusBarKeyguardViewManager.getViewRootImpl().setReportNextDraw();
1667                notifyDrawn(mDrawnCallback);
1668            }
1669
1670            // only play "unlock" noises if not on a call (since the incall UI
1671            // disables the keyguard)
1672            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1673                playSounds(false);
1674            }
1675
1676            setShowingLocked(false);
1677            mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
1678            resetKeyguardDonePendingLocked();
1679            mHideAnimationRun = false;
1680            updateActivityLockScreenState();
1681            adjustStatusBarLocked();
1682            sendUserPresentBroadcast();
1683        }
1684    }
1685
1686    private void adjustStatusBarLocked() {
1687        if (mStatusBarManager == null) {
1688            mStatusBarManager = (StatusBarManager)
1689                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1690        }
1691        if (mStatusBarManager == null) {
1692            Log.w(TAG, "Could not get status bar manager");
1693        } else {
1694            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1695            // windows that appear on top, ever
1696            int flags = StatusBarManager.DISABLE_NONE;
1697            if (mShowing) {
1698                // Permanently disable components not available when keyguard is enabled
1699                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1700                // done in KeyguardHostView.
1701                flags |= StatusBarManager.DISABLE_RECENT;
1702                flags |= StatusBarManager.DISABLE_SEARCH;
1703            }
1704            if (isShowingAndNotOccluded()) {
1705                flags |= StatusBarManager.DISABLE_HOME;
1706            }
1707
1708            if (DEBUG) {
1709                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
1710                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1711            }
1712
1713            if (!(mContext instanceof Activity)) {
1714                mStatusBarManager.disable(flags);
1715            }
1716        }
1717    }
1718
1719    /**
1720     * Handle message sent by {@link #resetStateLocked}
1721     * @see #RESET
1722     */
1723    private void handleReset() {
1724        synchronized (KeyguardViewMediator.this) {
1725            if (DEBUG) Log.d(TAG, "handleReset");
1726            mStatusBarKeyguardViewManager.reset();
1727        }
1728    }
1729
1730    /**
1731     * Handle message sent by {@link #verifyUnlock}
1732     * @see #VERIFY_UNLOCK
1733     */
1734    private void handleVerifyUnlock() {
1735        synchronized (KeyguardViewMediator.this) {
1736            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1737            setShowingLocked(true);
1738            mStatusBarKeyguardViewManager.verifyUnlock();
1739            updateActivityLockScreenState();
1740        }
1741    }
1742
1743    private void handleNotifyStartedGoingToSleep() {
1744        synchronized (KeyguardViewMediator.this) {
1745            if (DEBUG) Log.d(TAG, "handleNotifyStartedGoingToSleep");
1746            mStatusBarKeyguardViewManager.onStartedGoingToSleep();
1747        }
1748    }
1749
1750    /**
1751     * Handle message sent by {@link #notifyFinishedGoingToSleep()}
1752     * @see #NOTIFY_FINISHED_GOING_TO_SLEEP
1753     */
1754    private void handleNotifyFinishedGoingToSleep() {
1755        synchronized (KeyguardViewMediator.this) {
1756            if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep");
1757            mStatusBarKeyguardViewManager.onFinishedGoingToSleep();
1758        }
1759    }
1760
1761    private void handleNotifyStartedWakingUp() {
1762        synchronized (KeyguardViewMediator.this) {
1763            if (DEBUG) Log.d(TAG, "handleNotifyWakingUp");
1764            mStatusBarKeyguardViewManager.onStartedWakingUp();
1765        }
1766    }
1767
1768    private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) {
1769        synchronized (KeyguardViewMediator.this) {
1770            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn");
1771            mStatusBarKeyguardViewManager.onScreenTurningOn();
1772            if (callback != null) {
1773                if (mWakeAndUnlocking) {
1774                    mDrawnCallback = callback;
1775                } else {
1776                    notifyDrawn(callback);
1777                }
1778            }
1779        }
1780    }
1781
1782    private void handleNotifyScreenTurnedOn() {
1783        synchronized (this) {
1784            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOn");
1785            mStatusBarKeyguardViewManager.onScreenTurnedOn();
1786        }
1787    }
1788
1789    private void handleNotifyScreenTurnedOff() {
1790        synchronized (this) {
1791            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOff");
1792            mStatusBarKeyguardViewManager.onScreenTurnedOff();
1793            mWakeAndUnlocking = false;
1794        }
1795    }
1796
1797    private void notifyDrawn(final IKeyguardDrawnCallback callback) {
1798        try {
1799            callback.onDrawn();
1800        } catch (RemoteException e) {
1801            Slog.w(TAG, "Exception calling onDrawn():", e);
1802        }
1803    }
1804
1805    private void resetKeyguardDonePendingLocked() {
1806        mKeyguardDonePending = false;
1807        mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT);
1808    }
1809
1810    @Override
1811    public void onBootCompleted() {
1812        mUpdateMonitor.dispatchBootCompleted();
1813        synchronized (this) {
1814            mBootCompleted = true;
1815            if (mBootSendUserPresent) {
1816                sendUserPresentBroadcast();
1817            }
1818        }
1819    }
1820
1821    public void onWakeAndUnlocking() {
1822        mWakeAndUnlocking = true;
1823        keyguardDone(true /* authenticated */);
1824    }
1825
1826    public StatusBarKeyguardViewManager registerStatusBar(PhoneStatusBar phoneStatusBar,
1827            ViewGroup container, StatusBarWindowManager statusBarWindowManager,
1828            ScrimController scrimController,
1829            FingerprintUnlockController fingerprintUnlockController) {
1830        mStatusBarKeyguardViewManager.registerStatusBar(phoneStatusBar, container,
1831                statusBarWindowManager, scrimController, fingerprintUnlockController);
1832        return mStatusBarKeyguardViewManager;
1833    }
1834
1835    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1836        Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
1837                new StartKeyguardExitAnimParams(startTime, fadeoutDuration));
1838        mHandler.sendMessage(msg);
1839    }
1840
1841    public void onActivityDrawn() {
1842        mHandler.sendEmptyMessage(ON_ACTIVITY_DRAWN);
1843    }
1844
1845    public ViewMediatorCallback getViewMediatorCallback() {
1846        return mViewMediatorCallback;
1847    }
1848
1849    public LockPatternUtils getLockPatternUtils() {
1850        return mLockPatternUtils;
1851    }
1852
1853    @Override
1854    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1855        pw.print("  mSystemReady: "); pw.println(mSystemReady);
1856        pw.print("  mBootCompleted: "); pw.println(mBootCompleted);
1857        pw.print("  mBootSendUserPresent: "); pw.println(mBootSendUserPresent);
1858        pw.print("  mExternallyEnabled: "); pw.println(mExternallyEnabled);
1859        pw.print("  mNeedToReshowWhenReenabled: "); pw.println(mNeedToReshowWhenReenabled);
1860        pw.print("  mShowing: "); pw.println(mShowing);
1861        pw.print("  mInputRestricted: "); pw.println(mInputRestricted);
1862        pw.print("  mOccluded: "); pw.println(mOccluded);
1863        pw.print("  mDelayedShowingSequence: "); pw.println(mDelayedShowingSequence);
1864        pw.print("  mExitSecureCallback: "); pw.println(mExitSecureCallback);
1865        pw.print("  mDeviceInteractive: "); pw.println(mDeviceInteractive);
1866        pw.print("  mGoingToSleep: "); pw.println(mGoingToSleep);
1867        pw.print("  mHiding: "); pw.println(mHiding);
1868        pw.print("  mWaitingUntilKeyguardVisible: "); pw.println(mWaitingUntilKeyguardVisible);
1869        pw.print("  mKeyguardDonePending: "); pw.println(mKeyguardDonePending);
1870        pw.print("  mHideAnimationRun: "); pw.println(mHideAnimationRun);
1871        pw.print("  mPendingReset: "); pw.println(mPendingReset);
1872        pw.print("  mPendingLock: "); pw.println(mPendingLock);
1873        pw.print("  mWakeAndUnlocking: "); pw.println(mWakeAndUnlocking);
1874        pw.print("  mDrawnCallback: "); pw.println(mDrawnCallback);
1875    }
1876
1877    private static class StartKeyguardExitAnimParams {
1878
1879        long startTime;
1880        long fadeoutDuration;
1881
1882        private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) {
1883            this.startTime = startTime;
1884            this.fadeoutDuration = fadeoutDuration;
1885        }
1886    }
1887
1888    private void setShowingLocked(boolean showing) {
1889        if (showing != mShowing) {
1890            mShowing = showing;
1891            int size = mKeyguardStateCallbacks.size();
1892            for (int i = size - 1; i >= 0; i--) {
1893                try {
1894                    mKeyguardStateCallbacks.get(i).onShowingStateChanged(showing);
1895                } catch (RemoteException e) {
1896                    Slog.w(TAG, "Failed to call onShowingStateChanged", e);
1897                    if (e instanceof DeadObjectException) {
1898                        mKeyguardStateCallbacks.remove(i);
1899                    }
1900                }
1901            }
1902            updateInputRestrictedLocked();
1903            mTrustManager.reportKeyguardShowingChanged();
1904        }
1905    }
1906
1907    public void addStateMonitorCallback(IKeyguardStateCallback callback) {
1908        synchronized (this) {
1909            mKeyguardStateCallbacks.add(callback);
1910            try {
1911                callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure());
1912                callback.onShowingStateChanged(mShowing);
1913                callback.onInputRestrictedStateChanged(mInputRestricted);
1914            } catch (RemoteException e) {
1915                Slog.w(TAG, "Failed to call onShowingStateChanged or onSimSecureStateChanged or onInputRestrictedStateChanged", e);
1916            }
1917        }
1918    }
1919}
1920