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