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