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