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