KeyguardViewMediator.java revision 3dc575f1358112b232bd74bcd0d102401ef7549e
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        doKeyguardForChildProfilesLocked();
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 (policyTimeout <= 0) {
785            timeout = lockAfterTimeout;
786        } else {
787            // From DisplaySettings
788            long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
789                    KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
790
791            // policy in effect. Make sure we don't go beyond policy limit.
792            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
793            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
794        }
795        return timeout;
796    }
797
798    private void doKeyguardLaterLocked() {
799        long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser());
800        if (timeout == 0) {
801            doKeyguardLocked(null);
802        } else {
803            doKeyguardLaterLocked(timeout);
804        }
805    }
806
807    private void doKeyguardLaterLocked(long timeout) {
808        // Lock in the future
809        long when = SystemClock.elapsedRealtime() + timeout;
810        Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
811        intent.putExtra("seq", mDelayedShowingSequence);
812        PendingIntent sender = PendingIntent.getBroadcast(mContext,
813                0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
814        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
815        if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
816                         + mDelayedShowingSequence);
817        doKeyguardLaterForChildProfilesLocked();
818    }
819
820    private void doKeyguardLaterForChildProfilesLocked() {
821        UserManager um = UserManager.get(mContext);
822        List<UserInfo> profiles = um.getEnabledProfiles(UserHandle.myUserId());
823        for (UserInfo info : profiles) {
824            if (mLockPatternUtils.isSeparateProfileChallengeEnabled(info.id)) {
825                long userTimeout = getLockTimeout(info.id);
826                long userWhen = SystemClock.elapsedRealtime() + userTimeout;
827                Intent lockIntent = new Intent(DELAYED_LOCK_PROFILE_ACTION);
828                lockIntent.putExtra(Intent.EXTRA_USER_ID, info.id);
829                PendingIntent lockSender = PendingIntent.getBroadcast(
830                        mContext, 0, lockIntent, PendingIntent.FLAG_CANCEL_CURRENT);
831                mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, userWhen, lockSender);
832            }
833        }
834    }
835
836    private void doKeyguardForChildProfilesLocked() {
837        UserManager um = UserManager.get(mContext);
838        List<UserInfo> profiles = um.getEnabledProfiles(UserHandle.myUserId());
839        for (UserInfo info : profiles) {
840            if (mLockPatternUtils.isSeparateProfileChallengeEnabled(info.id)) {
841                lockProfile(info.id);
842            }
843        }
844    }
845
846    private void cancelDoKeyguardLaterLocked() {
847        mDelayedShowingSequence++;
848    }
849
850    /**
851     * Let's us know when the device is waking up.
852     */
853    public void onStartedWakingUp() {
854
855        // TODO: Rename all screen off/on references to interactive/sleeping
856        synchronized (this) {
857            mDeviceInteractive = true;
858            cancelDoKeyguardLaterLocked();
859            if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence);
860            notifyStartedWakingUp();
861        }
862        KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedWakingUp();
863        maybeSendUserPresentBroadcast();
864    }
865
866    public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
867        notifyScreenOn(callback);
868    }
869
870    public void onScreenTurnedOn() {
871        notifyScreenTurnedOn();
872        mUpdateMonitor.dispatchScreenTurnedOn();
873    }
874
875    public void onScreenTurnedOff() {
876        notifyScreenTurnedOff();
877        mUpdateMonitor.dispatchScreenTurnedOff();
878    }
879
880    private void maybeSendUserPresentBroadcast() {
881        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled(
882                KeyguardUpdateMonitor.getCurrentUser())) {
883            // Lock screen is disabled because the user has set the preference to "None".
884            // In this case, send out ACTION_USER_PRESENT here instead of in
885            // handleKeyguardDone()
886            sendUserPresentBroadcast();
887        }
888    }
889
890    /**
891     * A dream started.  We should lock after the usual screen-off lock timeout but only
892     * if there is a secure lock pattern.
893     */
894    public void onDreamingStarted() {
895        synchronized (this) {
896            if (mDeviceInteractive
897                    && mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) {
898                doKeyguardLaterLocked();
899            }
900        }
901    }
902
903    /**
904     * A dream stopped.
905     */
906    public void onDreamingStopped() {
907        synchronized (this) {
908            if (mDeviceInteractive) {
909                cancelDoKeyguardLaterLocked();
910            }
911        }
912    }
913
914    /**
915     * Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide
916     * a way for external stuff to override normal keyguard behavior.  For instance
917     * the phone app disables the keyguard when it receives incoming calls.
918     */
919    public void setKeyguardEnabled(boolean enabled) {
920        synchronized (this) {
921            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
922
923            mExternallyEnabled = enabled;
924
925            if (!enabled && mShowing) {
926                if (mExitSecureCallback != null) {
927                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
928                    // we're in the process of handling a request to verify the user
929                    // can get past the keyguard. ignore extraneous requests to disable / reenable
930                    return;
931                }
932
933                // hiding keyguard that is showing, remember to reshow later
934                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
935                        + "disabling status bar expansion");
936                mNeedToReshowWhenReenabled = true;
937                updateInputRestrictedLocked();
938                hideLocked();
939            } else if (enabled && mNeedToReshowWhenReenabled) {
940                // reenabled after previously hidden, reshow
941                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
942                        + "status bar expansion");
943                mNeedToReshowWhenReenabled = false;
944                updateInputRestrictedLocked();
945
946                if (mExitSecureCallback != null) {
947                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
948                    try {
949                        mExitSecureCallback.onKeyguardExitResult(false);
950                    } catch (RemoteException e) {
951                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
952                    }
953                    mExitSecureCallback = null;
954                    resetStateLocked();
955                } else {
956                    showLocked(null);
957
958                    // block until we know the keygaurd is done drawing (and post a message
959                    // to unblock us after a timeout so we don't risk blocking too long
960                    // and causing an ANR).
961                    mWaitingUntilKeyguardVisible = true;
962                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
963                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
964                    while (mWaitingUntilKeyguardVisible) {
965                        try {
966                            wait();
967                        } catch (InterruptedException e) {
968                            Thread.currentThread().interrupt();
969                        }
970                    }
971                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
972                }
973            }
974        }
975    }
976
977    /**
978     * @see android.app.KeyguardManager#exitKeyguardSecurely
979     */
980    public void verifyUnlock(IKeyguardExitCallback callback) {
981        synchronized (this) {
982            if (DEBUG) Log.d(TAG, "verifyUnlock");
983            if (shouldWaitForProvisioning()) {
984                // don't allow this api when the device isn't provisioned
985                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
986                try {
987                    callback.onKeyguardExitResult(false);
988                } catch (RemoteException e) {
989                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
990                }
991            } else if (mExternallyEnabled) {
992                // this only applies when the user has externally disabled the
993                // keyguard.  this is unexpected and means the user is not
994                // using the api properly.
995                Log.w(TAG, "verifyUnlock called when not externally disabled");
996                try {
997                    callback.onKeyguardExitResult(false);
998                } catch (RemoteException e) {
999                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1000                }
1001            } else if (mExitSecureCallback != null) {
1002                // already in progress with someone else
1003                try {
1004                    callback.onKeyguardExitResult(false);
1005                } catch (RemoteException e) {
1006                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1007                }
1008            } else if (!isSecure()) {
1009
1010                // Keyguard is not secure, no need to do anything, and we don't need to reshow
1011                // the Keyguard after the client releases the Keyguard lock.
1012                mExternallyEnabled = true;
1013                mNeedToReshowWhenReenabled = false;
1014                updateInputRestricted();
1015                try {
1016                    callback.onKeyguardExitResult(true);
1017                } catch (RemoteException e) {
1018                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1019                }
1020            } else {
1021
1022                // Since we prevent apps from hiding the Keyguard if we are secure, this should be
1023                // a no-op as well.
1024                try {
1025                    callback.onKeyguardExitResult(false);
1026                } catch (RemoteException e) {
1027                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1028                }
1029            }
1030        }
1031    }
1032
1033    /**
1034     * Is the keyguard currently showing and not being force hidden?
1035     */
1036    public boolean isShowingAndNotOccluded() {
1037        return mShowing && !mOccluded;
1038    }
1039
1040    /**
1041     * Notify us when the keyguard is occluded by another window
1042     */
1043    public void setOccluded(boolean isOccluded) {
1044        if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
1045        mHandler.removeMessages(SET_OCCLUDED);
1046        Message msg = mHandler.obtainMessage(SET_OCCLUDED, (isOccluded ? 1 : 0), 0);
1047        mHandler.sendMessage(msg);
1048    }
1049
1050    /**
1051     * Handles SET_OCCLUDED message sent by setOccluded()
1052     */
1053    private void handleSetOccluded(boolean isOccluded) {
1054        synchronized (KeyguardViewMediator.this) {
1055            if (mHiding && isOccluded) {
1056                // We're in the process of going away but WindowManager wants to show a
1057                // SHOW_WHEN_LOCKED activity instead.
1058                startKeyguardExitAnimation(0, 0);
1059            }
1060
1061            if (mOccluded != isOccluded) {
1062                mOccluded = isOccluded;
1063                mStatusBarKeyguardViewManager.setOccluded(isOccluded);
1064                updateActivityLockScreenState();
1065                adjustStatusBarLocked();
1066            }
1067        }
1068    }
1069
1070    /**
1071     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
1072     * This must be safe to call from any thread and with any window manager locks held.
1073     */
1074    public void doKeyguardTimeout(Bundle options) {
1075        mHandler.removeMessages(KEYGUARD_TIMEOUT);
1076        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
1077        mHandler.sendMessage(msg);
1078    }
1079
1080    /**
1081     * Given the state of the keyguard, is the input restricted?
1082     * Input is restricted when the keyguard is showing, or when the keyguard
1083     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
1084     */
1085    public boolean isInputRestricted() {
1086        return mShowing || mNeedToReshowWhenReenabled;
1087    }
1088
1089    private void updateInputRestricted() {
1090        synchronized (this) {
1091            updateInputRestrictedLocked();
1092        }
1093    }
1094    private void updateInputRestrictedLocked() {
1095        boolean inputRestricted = isInputRestricted();
1096        if (mInputRestricted != inputRestricted) {
1097            mInputRestricted = inputRestricted;
1098            int size = mKeyguardStateCallbacks.size();
1099            for (int i = size - 1; i >= 0; i--) {
1100                try {
1101                    mKeyguardStateCallbacks.get(i).onInputRestrictedStateChanged(inputRestricted);
1102                } catch (RemoteException e) {
1103                    Slog.w(TAG, "Failed to call onDeviceProvisioned", e);
1104                    if (e instanceof DeadObjectException) {
1105                        mKeyguardStateCallbacks.remove(i);
1106                    }
1107                }
1108            }
1109        }
1110    }
1111
1112    /**
1113     * Enable the keyguard if the settings are appropriate.
1114     */
1115    private void doKeyguardLocked(Bundle options) {
1116        // if another app is disabling us, don't show
1117        if (!mExternallyEnabled) {
1118            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
1119
1120            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
1121            // for an occasional ugly flicker in this situation:
1122            // 1) receive a call with the screen on (no keyguard) or make a call
1123            // 2) screen times out
1124            // 3) user hits key to turn screen back on
1125            // instead, we reenable the keyguard when we know the screen is off and the call
1126            // ends (see the broadcast receiver below)
1127            // TODO: clean this up when we have better support at the window manager level
1128            // for apps that wish to be on top of the keyguard
1129            return;
1130        }
1131
1132        // if the keyguard is already showing, don't bother
1133        if (mStatusBarKeyguardViewManager.isShowing()) {
1134            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
1135            resetStateLocked();
1136            return;
1137        }
1138
1139        // In split system user mode, we never unlock system user.
1140        if (!UserManager.isSplitSystemUser()
1141                || KeyguardUpdateMonitor.getCurrentUser() != UserHandle.USER_SYSTEM
1142                || !mUpdateMonitor.isDeviceProvisioned()) {
1143
1144            // if the setup wizard hasn't run yet, don't show
1145            final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
1146            final boolean absent = SubscriptionManager.isValidSubscriptionId(
1147                    mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.ABSENT));
1148            final boolean disabled = SubscriptionManager.isValidSubscriptionId(
1149                    mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED));
1150            final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure()
1151                    || ((absent || disabled) && requireSim);
1152
1153            if (!lockedOrMissing && shouldWaitForProvisioning()) {
1154                if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
1155                        + " and the sim is not locked or missing");
1156                return;
1157            }
1158
1159            if (mLockPatternUtils.isLockScreenDisabled(KeyguardUpdateMonitor.getCurrentUser())
1160                    && !lockedOrMissing) {
1161                if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
1162                return;
1163            }
1164
1165            if (mLockPatternUtils.checkVoldPassword(KeyguardUpdateMonitor.getCurrentUser())) {
1166                if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
1167                // Without this, settings is not enabled until the lock screen first appears
1168                setShowingLocked(false);
1169                hideLocked();
1170                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
1171                return;
1172            }
1173        }
1174
1175        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
1176        showLocked(options);
1177    }
1178
1179    private void lockProfile(int userId) {
1180        mTrustManager.setDeviceLockedForUser(userId, true);
1181    }
1182
1183    private boolean shouldWaitForProvisioning() {
1184        return !mUpdateMonitor.isDeviceProvisioned() && !isSecure();
1185    }
1186
1187    /**
1188     * Dismiss the keyguard through the security layers.
1189     */
1190    public void handleDismiss() {
1191        if (mShowing && !mOccluded) {
1192            mStatusBarKeyguardViewManager.dismiss();
1193        }
1194    }
1195
1196    public void dismiss() {
1197        mHandler.sendEmptyMessage(DISMISS);
1198    }
1199
1200    /**
1201     * Send message to keyguard telling it to reset its state.
1202     * @see #handleReset
1203     */
1204    private void resetStateLocked() {
1205        if (DEBUG) Log.e(TAG, "resetStateLocked");
1206        Message msg = mHandler.obtainMessage(RESET);
1207        mHandler.sendMessage(msg);
1208    }
1209
1210    /**
1211     * Send message to keyguard telling it to verify unlock
1212     * @see #handleVerifyUnlock()
1213     */
1214    private void verifyUnlockLocked() {
1215        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
1216        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
1217    }
1218
1219    private void notifyStartedGoingToSleep() {
1220        if (DEBUG) Log.d(TAG, "notifyStartedGoingToSleep");
1221        mHandler.sendEmptyMessage(NOTIFY_STARTED_GOING_TO_SLEEP);
1222    }
1223
1224    private void notifyFinishedGoingToSleep() {
1225        if (DEBUG) Log.d(TAG, "notifyFinishedGoingToSleep");
1226        mHandler.sendEmptyMessage(NOTIFY_FINISHED_GOING_TO_SLEEP);
1227    }
1228
1229    private void notifyStartedWakingUp() {
1230        if (DEBUG) Log.d(TAG, "notifyStartedWakingUp");
1231        mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP);
1232    }
1233
1234    private void notifyScreenOn(IKeyguardDrawnCallback callback) {
1235        if (DEBUG) Log.d(TAG, "notifyScreenOn");
1236        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNING_ON, callback);
1237        mHandler.sendMessage(msg);
1238    }
1239
1240    private void notifyScreenTurnedOn() {
1241        if (DEBUG) Log.d(TAG, "notifyScreenTurnedOn");
1242        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_ON);
1243        mHandler.sendMessage(msg);
1244    }
1245
1246    private void notifyScreenTurnedOff() {
1247        if (DEBUG) Log.d(TAG, "notifyScreenTurnedOff");
1248        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_OFF);
1249        mHandler.sendMessage(msg);
1250    }
1251
1252    /**
1253     * Send message to keyguard telling it to show itself
1254     * @see #handleShow
1255     */
1256    private void showLocked(Bundle options) {
1257        if (DEBUG) Log.d(TAG, "showLocked");
1258        // ensure we stay awake until we are finished displaying the keyguard
1259        mShowKeyguardWakeLock.acquire();
1260        Message msg = mHandler.obtainMessage(SHOW, options);
1261        mHandler.sendMessage(msg);
1262    }
1263
1264    /**
1265     * Send message to keyguard telling it to hide itself
1266     * @see #handleHide()
1267     */
1268    private void hideLocked() {
1269        if (DEBUG) Log.d(TAG, "hideLocked");
1270        Message msg = mHandler.obtainMessage(HIDE);
1271        mHandler.sendMessage(msg);
1272    }
1273
1274    public boolean isSecure() {
1275        return mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())
1276            || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
1277    }
1278
1279    /**
1280     * Update the newUserId. Call while holding WindowManagerService lock.
1281     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
1282     *
1283     * @param newUserId The id of the incoming user.
1284     */
1285    public void setCurrentUser(int newUserId) {
1286        KeyguardUpdateMonitor.setCurrentUser(newUserId);
1287    }
1288
1289    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1290        @Override
1291        public void onReceive(Context context, Intent intent) {
1292            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1293                final int sequence = intent.getIntExtra("seq", 0);
1294                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1295                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1296                synchronized (KeyguardViewMediator.this) {
1297                    if (mDelayedShowingSequence == sequence) {
1298                        doKeyguardLocked(null);
1299                    }
1300                }
1301            } else if (DELAYED_LOCK_PROFILE_ACTION.equals(intent.getAction())) {
1302                int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
1303                if (userId != 0) {
1304                    synchronized (KeyguardViewMediator.this) {
1305                        lockProfile(userId);
1306                    }
1307                }
1308            }
1309        }
1310    };
1311
1312    public void keyguardDone(boolean authenticated) {
1313        if (DEBUG) Log.d(TAG, "keyguardDone(" + authenticated +")");
1314        EventLog.writeEvent(70000, 2);
1315        Message msg = mHandler.obtainMessage(KEYGUARD_DONE, authenticated ? 1 : 0);
1316        mHandler.sendMessage(msg);
1317    }
1318
1319    /**
1320     * This handler will be associated with the policy thread, which will also
1321     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1322     * this class, can be called by other threads, any action that directly
1323     * interacts with the keyguard ui should be posted to this handler, rather
1324     * than called directly.
1325     */
1326    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1327        @Override
1328        public void handleMessage(Message msg) {
1329            switch (msg.what) {
1330                case SHOW:
1331                    handleShow((Bundle) msg.obj);
1332                    break;
1333                case HIDE:
1334                    handleHide();
1335                    break;
1336                case RESET:
1337                    handleReset();
1338                    break;
1339                case VERIFY_UNLOCK:
1340                    handleVerifyUnlock();
1341                    break;
1342                case NOTIFY_STARTED_GOING_TO_SLEEP:
1343                    handleNotifyStartedGoingToSleep();
1344                    break;
1345                case NOTIFY_FINISHED_GOING_TO_SLEEP:
1346                    handleNotifyFinishedGoingToSleep();
1347                    break;
1348                case NOTIFY_SCREEN_TURNING_ON:
1349                    handleNotifyScreenTurningOn((IKeyguardDrawnCallback) msg.obj);
1350                    break;
1351                case NOTIFY_SCREEN_TURNED_ON:
1352                    handleNotifyScreenTurnedOn();
1353                    break;
1354                case NOTIFY_SCREEN_TURNED_OFF:
1355                    handleNotifyScreenTurnedOff();
1356                    break;
1357                case NOTIFY_STARTED_WAKING_UP:
1358                    handleNotifyStartedWakingUp();
1359                    break;
1360                case KEYGUARD_DONE:
1361                    handleKeyguardDone(msg.arg1 != 0);
1362                    break;
1363                case KEYGUARD_DONE_DRAWING:
1364                    handleKeyguardDoneDrawing();
1365                    break;
1366                case SET_OCCLUDED:
1367                    handleSetOccluded(msg.arg1 != 0);
1368                    break;
1369                case KEYGUARD_TIMEOUT:
1370                    synchronized (KeyguardViewMediator.this) {
1371                        doKeyguardLocked((Bundle) msg.obj);
1372                    }
1373                    break;
1374                case DISMISS:
1375                    handleDismiss();
1376                    break;
1377                case START_KEYGUARD_EXIT_ANIM:
1378                    StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
1379                    handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration);
1380                    FalsingManager.getInstance(mContext).onSucccessfulUnlock();
1381                    break;
1382                case KEYGUARD_DONE_PENDING_TIMEOUT:
1383                    Log.w(TAG, "Timeout while waiting for activity drawn!");
1384                    // Fall through.
1385                case ON_ACTIVITY_DRAWN:
1386                    handleOnActivityDrawn();
1387                    break;
1388            }
1389        }
1390    };
1391
1392    /**
1393     * @see #keyguardDone
1394     * @see #KEYGUARD_DONE
1395     */
1396    private void handleKeyguardDone(boolean authenticated) {
1397        final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
1398        if (mLockPatternUtils.isSecure(currentUser)) {
1399            mLockPatternUtils.getDevicePolicyManager().reportKeyguardDismissed(currentUser);
1400        }
1401        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1402        synchronized (this) {
1403            resetKeyguardDonePendingLocked();
1404        }
1405
1406        if (authenticated) {
1407            mUpdateMonitor.clearFailedUnlockAttempts();
1408        }
1409        mUpdateMonitor.clearFingerprintRecognized();
1410
1411        if (mGoingToSleep) {
1412            Log.i(TAG, "Device is going to sleep, aborting keyguardDone");
1413            return;
1414        }
1415        if (mExitSecureCallback != null) {
1416            try {
1417                mExitSecureCallback.onKeyguardExitResult(authenticated);
1418            } catch (RemoteException e) {
1419                Slog.w(TAG, "Failed to call onKeyguardExitResult(" + authenticated + ")", e);
1420            }
1421
1422            mExitSecureCallback = null;
1423
1424            if (authenticated) {
1425                // after succesfully exiting securely, no need to reshow
1426                // the keyguard when they've released the lock
1427                mExternallyEnabled = true;
1428                mNeedToReshowWhenReenabled = false;
1429                updateInputRestricted();
1430            }
1431        }
1432
1433        handleHide();
1434    }
1435
1436    private void sendUserPresentBroadcast() {
1437        synchronized (this) {
1438            if (mBootCompleted) {
1439                final UserHandle currentUser = new UserHandle(KeyguardUpdateMonitor.getCurrentUser());
1440                final UserManager um = (UserManager) mContext.getSystemService(
1441                        Context.USER_SERVICE);
1442                List <UserInfo> userHandles = um.getProfiles(currentUser.getIdentifier());
1443                for (UserInfo ui : userHandles) {
1444                    mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, ui.getUserHandle());
1445                }
1446            } else {
1447                mBootSendUserPresent = true;
1448            }
1449        }
1450    }
1451
1452    /**
1453     * @see #keyguardDone
1454     * @see #KEYGUARD_DONE_DRAWING
1455     */
1456    private void handleKeyguardDoneDrawing() {
1457        synchronized(this) {
1458            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1459            if (mWaitingUntilKeyguardVisible) {
1460                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1461                mWaitingUntilKeyguardVisible = false;
1462                notifyAll();
1463
1464                // there will usually be two of these sent, one as a timeout, and one
1465                // as a result of the callback, so remove any remaining messages from
1466                // the queue
1467                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1468            }
1469        }
1470    }
1471
1472    private void playSounds(boolean locked) {
1473        playSound(locked ? mLockSoundId : mUnlockSoundId);
1474    }
1475
1476    private void playSound(int soundId) {
1477        if (soundId == 0) return;
1478        final ContentResolver cr = mContext.getContentResolver();
1479        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1480
1481            mLockSounds.stop(mLockSoundStreamId);
1482            // Init mAudioManager
1483            if (mAudioManager == null) {
1484                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1485                if (mAudioManager == null) return;
1486                mUiSoundsStreamType = mAudioManager.getUiSoundsStreamType();
1487            }
1488            // If the stream is muted, don't play the sound
1489            if (mAudioManager.isStreamMute(mUiSoundsStreamType)) return;
1490
1491            mLockSoundStreamId = mLockSounds.play(soundId,
1492                    mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1493        }
1494    }
1495
1496    private void playTrustedSound() {
1497        playSound(mTrustedSoundId);
1498    }
1499
1500    private void updateActivityLockScreenState() {
1501        try {
1502            ActivityManagerNative.getDefault().setLockScreenShown(mShowing && !mOccluded);
1503        } catch (RemoteException e) {
1504        }
1505    }
1506
1507    /**
1508     * Handle message sent by {@link #showLocked}.
1509     * @see #SHOW
1510     */
1511    private void handleShow(Bundle options) {
1512        final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
1513        if (mLockPatternUtils.isSecure(currentUser)) {
1514            mLockPatternUtils.getDevicePolicyManager().reportKeyguardSecured(currentUser);
1515        }
1516        synchronized (KeyguardViewMediator.this) {
1517            if (!mSystemReady) {
1518                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1519                return;
1520            } else {
1521                if (DEBUG) Log.d(TAG, "handleShow");
1522            }
1523
1524            setShowingLocked(true);
1525            mStatusBarKeyguardViewManager.show(options);
1526            mHiding = false;
1527            mWakeAndUnlocking = false;
1528            resetKeyguardDonePendingLocked();
1529            mHideAnimationRun = false;
1530            updateActivityLockScreenState();
1531            adjustStatusBarLocked();
1532            userActivity();
1533
1534            mShowKeyguardWakeLock.release();
1535        }
1536        mKeyguardDisplayManager.show();
1537    }
1538
1539    private final Runnable mKeyguardGoingAwayRunnable = new Runnable() {
1540        @Override
1541        public void run() {
1542            try {
1543                mStatusBarKeyguardViewManager.keyguardGoingAway();
1544
1545                // Don't actually hide the Keyguard at the moment, wait for window
1546                // manager until it tells us it's safe to do so with
1547                // startKeyguardExitAnimation.
1548                ActivityManagerNative.getDefault().keyguardGoingAway(
1549                        mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock()
1550                                || mWakeAndUnlocking,
1551                        mStatusBarKeyguardViewManager.isGoingToNotificationShade());
1552            } catch (RemoteException e) {
1553                Log.e(TAG, "Error while calling WindowManager", e);
1554            }
1555        }
1556    };
1557
1558    /**
1559     * Handle message sent by {@link #hideLocked()}
1560     * @see #HIDE
1561     */
1562    private void handleHide() {
1563        synchronized (KeyguardViewMediator.this) {
1564            if (DEBUG) Log.d(TAG, "handleHide");
1565
1566            if (UserManager.isSplitSystemUser()
1567                    && KeyguardUpdateMonitor.getCurrentUser() == UserHandle.USER_SYSTEM) {
1568                // In split system user mode, we never unlock system user. The end user has to
1569                // switch to another user.
1570                // TODO: We should stop it early by disabling the swipe up flow. Right now swipe up
1571                // still completes and makes the screen blank.
1572                if (DEBUG) Log.d(TAG, "Split system user, quit unlocking.");
1573                return;
1574            }
1575            mHiding = true;
1576            if (mShowing && !mOccluded) {
1577                if (!mHideAnimationRun) {
1578                    mStatusBarKeyguardViewManager.startPreHideAnimation(mKeyguardGoingAwayRunnable);
1579                } else {
1580                    mKeyguardGoingAwayRunnable.run();
1581                }
1582            } else {
1583
1584                // Don't try to rely on WindowManager - if Keyguard wasn't showing, window
1585                // manager won't start the exit animation.
1586                handleStartKeyguardExitAnimation(
1587                        SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
1588                        mHideAnimation.getDuration());
1589            }
1590        }
1591    }
1592
1593    private void handleOnActivityDrawn() {
1594        if (DEBUG) Log.d(TAG, "handleOnActivityDrawn: mKeyguardDonePending=" + mKeyguardDonePending);
1595        if (mKeyguardDonePending) {
1596            mStatusBarKeyguardViewManager.onActivityDrawn();
1597        }
1598    }
1599
1600    private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1601        synchronized (KeyguardViewMediator.this) {
1602
1603            if (!mHiding) {
1604                return;
1605            }
1606            mHiding = false;
1607
1608            if (mWakeAndUnlocking && mDrawnCallback != null) {
1609
1610                // Hack level over 9000: To speed up wake-and-unlock sequence, force it to report
1611                // the next draw from here so we don't have to wait for window manager to signal
1612                // this to our ViewRootImpl.
1613                mStatusBarKeyguardViewManager.getViewRootImpl().setReportNextDraw();
1614                notifyDrawn(mDrawnCallback);
1615            }
1616
1617            // only play "unlock" noises if not on a call (since the incall UI
1618            // disables the keyguard)
1619            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1620                playSounds(false);
1621            }
1622
1623            setShowingLocked(false);
1624            mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
1625            resetKeyguardDonePendingLocked();
1626            mHideAnimationRun = false;
1627            updateActivityLockScreenState();
1628            adjustStatusBarLocked();
1629            sendUserPresentBroadcast();
1630        }
1631    }
1632
1633    private void adjustStatusBarLocked() {
1634        if (mStatusBarManager == null) {
1635            mStatusBarManager = (StatusBarManager)
1636                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1637        }
1638        if (mStatusBarManager == null) {
1639            Log.w(TAG, "Could not get status bar manager");
1640        } else {
1641            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1642            // windows that appear on top, ever
1643            int flags = StatusBarManager.DISABLE_NONE;
1644            if (mShowing) {
1645                // Permanently disable components not available when keyguard is enabled
1646                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1647                // done in KeyguardHostView.
1648                flags |= StatusBarManager.DISABLE_RECENT;
1649                flags |= StatusBarManager.DISABLE_SEARCH;
1650            }
1651            if (isShowingAndNotOccluded()) {
1652                flags |= StatusBarManager.DISABLE_HOME;
1653            }
1654
1655            if (DEBUG) {
1656                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
1657                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1658            }
1659
1660            if (!(mContext instanceof Activity)) {
1661                mStatusBarManager.disable(flags);
1662            }
1663        }
1664    }
1665
1666    /**
1667     * Handle message sent by {@link #resetStateLocked}
1668     * @see #RESET
1669     */
1670    private void handleReset() {
1671        synchronized (KeyguardViewMediator.this) {
1672            if (DEBUG) Log.d(TAG, "handleReset");
1673            mStatusBarKeyguardViewManager.reset();
1674        }
1675    }
1676
1677    /**
1678     * Handle message sent by {@link #verifyUnlock}
1679     * @see #VERIFY_UNLOCK
1680     */
1681    private void handleVerifyUnlock() {
1682        synchronized (KeyguardViewMediator.this) {
1683            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1684            setShowingLocked(true);
1685            mStatusBarKeyguardViewManager.verifyUnlock();
1686            updateActivityLockScreenState();
1687        }
1688    }
1689
1690    private void handleNotifyStartedGoingToSleep() {
1691        synchronized (KeyguardViewMediator.this) {
1692            if (DEBUG) Log.d(TAG, "handleNotifyStartedGoingToSleep");
1693            mStatusBarKeyguardViewManager.onStartedGoingToSleep();
1694        }
1695    }
1696
1697    /**
1698     * Handle message sent by {@link #notifyFinishedGoingToSleep()}
1699     * @see #NOTIFY_FINISHED_GOING_TO_SLEEP
1700     */
1701    private void handleNotifyFinishedGoingToSleep() {
1702        synchronized (KeyguardViewMediator.this) {
1703            if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep");
1704            mStatusBarKeyguardViewManager.onFinishedGoingToSleep();
1705        }
1706    }
1707
1708    private void handleNotifyStartedWakingUp() {
1709        synchronized (KeyguardViewMediator.this) {
1710            if (DEBUG) Log.d(TAG, "handleNotifyWakingUp");
1711            mStatusBarKeyguardViewManager.onStartedWakingUp();
1712        }
1713    }
1714
1715    private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) {
1716        synchronized (KeyguardViewMediator.this) {
1717            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn");
1718            mStatusBarKeyguardViewManager.onScreenTurningOn();
1719            if (callback != null) {
1720                if (mWakeAndUnlocking) {
1721                    mDrawnCallback = callback;
1722                } else {
1723                    notifyDrawn(callback);
1724                }
1725            }
1726        }
1727    }
1728
1729    private void handleNotifyScreenTurnedOn() {
1730        synchronized (this) {
1731            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOn");
1732            mStatusBarKeyguardViewManager.onScreenTurnedOn();
1733        }
1734    }
1735
1736    private void handleNotifyScreenTurnedOff() {
1737        synchronized (this) {
1738            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOff");
1739            mStatusBarKeyguardViewManager.onScreenTurnedOff();
1740            mWakeAndUnlocking = false;
1741        }
1742    }
1743
1744    private void notifyDrawn(final IKeyguardDrawnCallback callback) {
1745        try {
1746            callback.onDrawn();
1747        } catch (RemoteException e) {
1748            Slog.w(TAG, "Exception calling onDrawn():", e);
1749        }
1750    }
1751
1752    private void resetKeyguardDonePendingLocked() {
1753        mKeyguardDonePending = false;
1754        mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT);
1755    }
1756
1757    @Override
1758    public void onBootCompleted() {
1759        mUpdateMonitor.dispatchBootCompleted();
1760        synchronized (this) {
1761            mBootCompleted = true;
1762            if (mBootSendUserPresent) {
1763                sendUserPresentBroadcast();
1764            }
1765        }
1766    }
1767
1768    public void onWakeAndUnlocking() {
1769        mWakeAndUnlocking = true;
1770        keyguardDone(true /* authenticated */);
1771    }
1772
1773    public StatusBarKeyguardViewManager registerStatusBar(PhoneStatusBar phoneStatusBar,
1774            ViewGroup container, StatusBarWindowManager statusBarWindowManager,
1775            ScrimController scrimController,
1776            FingerprintUnlockController fingerprintUnlockController) {
1777        mStatusBarKeyguardViewManager.registerStatusBar(phoneStatusBar, container,
1778                statusBarWindowManager, scrimController, fingerprintUnlockController);
1779        return mStatusBarKeyguardViewManager;
1780    }
1781
1782    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1783        Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
1784                new StartKeyguardExitAnimParams(startTime, fadeoutDuration));
1785        mHandler.sendMessage(msg);
1786    }
1787
1788    public void onActivityDrawn() {
1789        mHandler.sendEmptyMessage(ON_ACTIVITY_DRAWN);
1790    }
1791
1792    public ViewMediatorCallback getViewMediatorCallback() {
1793        return mViewMediatorCallback;
1794    }
1795
1796    public LockPatternUtils getLockPatternUtils() {
1797        return mLockPatternUtils;
1798    }
1799
1800    @Override
1801    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1802        pw.print("  mSystemReady: "); pw.println(mSystemReady);
1803        pw.print("  mBootCompleted: "); pw.println(mBootCompleted);
1804        pw.print("  mBootSendUserPresent: "); pw.println(mBootSendUserPresent);
1805        pw.print("  mExternallyEnabled: "); pw.println(mExternallyEnabled);
1806        pw.print("  mNeedToReshowWhenReenabled: "); pw.println(mNeedToReshowWhenReenabled);
1807        pw.print("  mShowing: "); pw.println(mShowing);
1808        pw.print("  mInputRestricted: "); pw.println(mInputRestricted);
1809        pw.print("  mOccluded: "); pw.println(mOccluded);
1810        pw.print("  mDelayedShowingSequence: "); pw.println(mDelayedShowingSequence);
1811        pw.print("  mExitSecureCallback: "); pw.println(mExitSecureCallback);
1812        pw.print("  mDeviceInteractive: "); pw.println(mDeviceInteractive);
1813        pw.print("  mGoingToSleep: "); pw.println(mGoingToSleep);
1814        pw.print("  mHiding: "); pw.println(mHiding);
1815        pw.print("  mWaitingUntilKeyguardVisible: "); pw.println(mWaitingUntilKeyguardVisible);
1816        pw.print("  mKeyguardDonePending: "); pw.println(mKeyguardDonePending);
1817        pw.print("  mHideAnimationRun: "); pw.println(mHideAnimationRun);
1818        pw.print("  mPendingReset: "); pw.println(mPendingReset);
1819        pw.print("  mPendingLock: "); pw.println(mPendingLock);
1820        pw.print("  mWakeAndUnlocking: "); pw.println(mWakeAndUnlocking);
1821        pw.print("  mDrawnCallback: "); pw.println(mDrawnCallback);
1822    }
1823
1824    private static class StartKeyguardExitAnimParams {
1825
1826        long startTime;
1827        long fadeoutDuration;
1828
1829        private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) {
1830            this.startTime = startTime;
1831            this.fadeoutDuration = fadeoutDuration;
1832        }
1833    }
1834
1835    private void setShowingLocked(boolean showing) {
1836        if (showing != mShowing) {
1837            mShowing = showing;
1838            int size = mKeyguardStateCallbacks.size();
1839            for (int i = size - 1; i >= 0; i--) {
1840                try {
1841                    mKeyguardStateCallbacks.get(i).onShowingStateChanged(showing);
1842                } catch (RemoteException e) {
1843                    Slog.w(TAG, "Failed to call onShowingStateChanged", e);
1844                    if (e instanceof DeadObjectException) {
1845                        mKeyguardStateCallbacks.remove(i);
1846                    }
1847                }
1848            }
1849            updateInputRestrictedLocked();
1850            mTrustManager.reportKeyguardShowingChanged();
1851        }
1852    }
1853
1854    public void addStateMonitorCallback(IKeyguardStateCallback callback) {
1855        synchronized (this) {
1856            mKeyguardStateCallbacks.add(callback);
1857            try {
1858                callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure());
1859                callback.onShowingStateChanged(mShowing);
1860                callback.onInputRestrictedStateChanged(mInputRestricted);
1861            } catch (RemoteException e) {
1862                Slog.w(TAG, "Failed to call onShowingStateChanged or onSimSecureStateChanged or onInputRestrictedStateChanged", e);
1863            }
1864        }
1865    }
1866}
1867