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