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