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