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