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 
17 package com.android.systemui.keyguard;
18 
19 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
20 import static android.view.WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER;
21 
22 import static com.android.internal.config.sysui.SystemUiDeviceConfigFlags.NAV_BAR_HANDLE_SHOW_OVER_LOCKSCREEN;
23 import static com.android.internal.jank.InteractionJankMonitor.CUJ_LOCKSCREEN_UNLOCK_ANIMATION;
24 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_USER_REQUEST;
25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
26 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_LOCKOUT;
27 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT;
28 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_TIMEOUT;
29 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_FOR_UNATTENDED_UPDATE;
30 import static com.android.systemui.DejankUtils.whitelistIpcs;
31 
32 import android.animation.Animator;
33 import android.animation.AnimatorListenerAdapter;
34 import android.animation.ValueAnimator;
35 import android.app.ActivityManager;
36 import android.app.ActivityTaskManager;
37 import android.app.AlarmManager;
38 import android.app.PendingIntent;
39 import android.app.StatusBarManager;
40 import android.app.trust.TrustManager;
41 import android.content.BroadcastReceiver;
42 import android.content.ComponentName;
43 import android.content.ContentResolver;
44 import android.content.Context;
45 import android.content.Intent;
46 import android.content.IntentFilter;
47 import android.content.pm.PackageManager.NameNotFoundException;
48 import android.content.pm.UserInfo;
49 import android.hardware.biometrics.BiometricSourceType;
50 import android.media.AudioAttributes;
51 import android.media.AudioManager;
52 import android.media.SoundPool;
53 import android.os.Bundle;
54 import android.os.DeadObjectException;
55 import android.os.Handler;
56 import android.os.IBinder;
57 import android.os.Looper;
58 import android.os.Message;
59 import android.os.PowerManager;
60 import android.os.RemoteException;
61 import android.os.SystemClock;
62 import android.os.SystemProperties;
63 import android.os.Trace;
64 import android.os.UserHandle;
65 import android.os.UserManager;
66 import android.provider.DeviceConfig;
67 import android.provider.Settings;
68 import android.telephony.SubscriptionManager;
69 import android.telephony.TelephonyManager;
70 import android.util.EventLog;
71 import android.util.Log;
72 import android.util.Slog;
73 import android.util.SparseBooleanArray;
74 import android.util.SparseIntArray;
75 import android.view.IRemoteAnimationFinishedCallback;
76 import android.view.IRemoteAnimationRunner;
77 import android.view.RemoteAnimationTarget;
78 import android.view.SyncRtSurfaceTransactionApplier;
79 import android.view.View;
80 import android.view.WindowManager;
81 import android.view.WindowManagerPolicyConstants;
82 import android.view.animation.Animation;
83 import android.view.animation.AnimationUtils;
84 
85 import androidx.annotation.Nullable;
86 
87 import com.android.internal.jank.InteractionJankMonitor;
88 import com.android.internal.jank.InteractionJankMonitor.Configuration;
89 import com.android.internal.policy.IKeyguardDismissCallback;
90 import com.android.internal.policy.IKeyguardDrawnCallback;
91 import com.android.internal.policy.IKeyguardExitCallback;
92 import com.android.internal.policy.IKeyguardStateCallback;
93 import com.android.internal.util.LatencyTracker;
94 import com.android.internal.widget.LockPatternUtils;
95 import com.android.keyguard.KeyguardConstants;
96 import com.android.keyguard.KeyguardDisplayManager;
97 import com.android.keyguard.KeyguardSecurityView;
98 import com.android.keyguard.KeyguardUpdateMonitor;
99 import com.android.keyguard.KeyguardUpdateMonitorCallback;
100 import com.android.keyguard.KeyguardViewController;
101 import com.android.keyguard.ViewMediatorCallback;
102 import com.android.systemui.Dumpable;
103 import com.android.systemui.SystemUI;
104 import com.android.systemui.animation.Interpolators;
105 import com.android.systemui.broadcast.BroadcastDispatcher;
106 import com.android.systemui.classifier.FalsingCollector;
107 import com.android.systemui.dagger.qualifiers.UiBackground;
108 import com.android.systemui.dump.DumpManager;
109 import com.android.systemui.keyguard.dagger.KeyguardModule;
110 import com.android.systemui.navigationbar.NavigationModeController;
111 import com.android.systemui.plugins.statusbar.StatusBarStateController;
112 import com.android.systemui.shared.system.QuickStepContract;
113 import com.android.systemui.statusbar.CommandQueue;
114 import com.android.systemui.statusbar.NotificationShadeDepthController;
115 import com.android.systemui.statusbar.SysuiStatusBarStateController;
116 import com.android.systemui.statusbar.phone.BiometricUnlockController;
117 import com.android.systemui.statusbar.phone.DozeParameters;
118 import com.android.systemui.statusbar.phone.KeyguardBypassController;
119 import com.android.systemui.statusbar.phone.NotificationPanelViewController;
120 import com.android.systemui.statusbar.phone.StatusBar;
121 import com.android.systemui.statusbar.phone.UnlockedScreenOffAnimationController;
122 import com.android.systemui.statusbar.phone.panelstate.PanelExpansionStateManager;
123 import com.android.systemui.statusbar.policy.KeyguardStateController;
124 import com.android.systemui.statusbar.policy.UserSwitcherController;
125 import com.android.systemui.unfold.SysUIUnfoldComponent;
126 import com.android.systemui.unfold.UnfoldLightRevealOverlayAnimation;
127 import com.android.systemui.util.DeviceConfigProxy;
128 
129 import java.io.FileDescriptor;
130 import java.io.PrintWriter;
131 import java.util.ArrayList;
132 import java.util.Optional;
133 import java.util.concurrent.Executor;
134 import java.util.concurrent.atomic.AtomicInteger;
135 
136 import dagger.Lazy;
137 
138 /**
139  * Mediates requests related to the keyguard.  This includes queries about the
140  * state of the keyguard, power management events that effect whether the keyguard
141  * should be shown or reset, callbacks to the phone window manager to notify
142  * it of when the keyguard is showing, and events from the keyguard view itself
143  * stating that the keyguard was succesfully unlocked.
144  *
145  * Note that the keyguard view is shown when the screen is off (as appropriate)
146  * so that once the screen comes on, it will be ready immediately.
147  *
148  * Example queries about the keyguard:
149  * - is {movement, key} one that should wake the keygaurd?
150  * - is the keyguard showing?
151  * - are input events restricted due to the state of the keyguard?
152  *
153  * Callbacks to the phone window manager:
154  * - the keyguard is showing
155  *
156  * Example external events that translate to keyguard view changes:
157  * - screen turned off -> reset the keyguard, and show it so it will be ready
158  *   next time the screen turns on
159  * - keyboard is slid open -> if the keyguard is not secure, hide it
160  *
161  * Events from the keyguard view:
162  * - user succesfully unlocked keyguard -> hide keyguard view, and no longer
163  *   restrict input events.
164  *
165  * Note: in addition to normal power managment events that effect the state of
166  * whether the keyguard should be showing, external apps and services may request
167  * that the keyguard be disabled via {@link #setKeyguardEnabled(boolean)}.  When
168  * false, this will override all other conditions for turning on the keyguard.
169  *
170  * Threading and synchronization:
171  * This class is created by the initialization routine of the {@link WindowManagerPolicyConstants},
172  * and runs on its thread.  The keyguard UI is created from that thread in the
173  * constructor of this class.  The apis may be called from other threads, including the
174  * {@link com.android.server.input.InputManagerService}'s and {@link android.view.WindowManager}'s.
175  * Therefore, methods on this class are synchronized, and any action that is pointed
176  * directly to the keyguard UI is posted to a {@link android.os.Handler} to ensure it is taken on the UI
177  * thread of the keyguard.
178  */
179 public class KeyguardViewMediator extends SystemUI implements Dumpable,
180         StatusBarStateController.StateListener {
181     private static final int KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT = 30000;
182     private static final long KEYGUARD_DONE_PENDING_TIMEOUT_MS = 3000;
183 
184     private static final boolean DEBUG = KeyguardConstants.DEBUG;
185     private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES;
186 
187     private final static String TAG = "KeyguardViewMediator";
188 
189     private static final String DELAYED_KEYGUARD_ACTION =
190         "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_KEYGUARD";
191     private static final String DELAYED_LOCK_PROFILE_ACTION =
192             "com.android.internal.policy.impl.PhoneWindowManager.DELAYED_LOCK";
193 
194     private static final String SYSTEMUI_PERMISSION = "com.android.systemui.permission.SELF";
195 
196     // used for handler messages
197     private static final int SHOW = 1;
198     private static final int HIDE = 2;
199     private static final int RESET = 3;
200     private static final int VERIFY_UNLOCK = 4;
201     private static final int NOTIFY_FINISHED_GOING_TO_SLEEP = 5;
202     private static final int NOTIFY_SCREEN_TURNING_ON = 6;
203     private static final int KEYGUARD_DONE = 7;
204     private static final int KEYGUARD_DONE_DRAWING = 8;
205     private static final int SET_OCCLUDED = 9;
206     private static final int KEYGUARD_TIMEOUT = 10;
207     private static final int DISMISS = 11;
208     private static final int START_KEYGUARD_EXIT_ANIM = 12;
209     private static final int KEYGUARD_DONE_PENDING_TIMEOUT = 13;
210     private static final int NOTIFY_STARTED_WAKING_UP = 14;
211     private static final int NOTIFY_SCREEN_TURNED_ON = 15;
212     private static final int NOTIFY_SCREEN_TURNED_OFF = 16;
213     private static final int NOTIFY_STARTED_GOING_TO_SLEEP = 17;
214     private static final int SYSTEM_READY = 18;
215     private static final int CANCEL_KEYGUARD_EXIT_ANIM = 19;
216 
217     /**
218      * The default amount of time we stay awake (used for all key input)
219      */
220     public static final int AWAKE_INTERVAL_BOUNCER_MS = 10000;
221 
222     /**
223      * How long to wait after the screen turns off due to timeout before
224      * turning on the keyguard (i.e, the user has this much time to turn
225      * the screen back on without having to face the keyguard).
226      */
227     private static final int KEYGUARD_LOCK_AFTER_DELAY_DEFAULT = 5000;
228 
229     /**
230      * How long we'll wait for the {@link ViewMediatorCallback#keyguardDoneDrawing()}
231      * callback before unblocking a call to {@link #setKeyguardEnabled(boolean)}
232      * that is reenabling the keyguard.
233      */
234     private static final int KEYGUARD_DONE_DRAWING_TIMEOUT_MS = 2000;
235 
236     /**
237      * Boolean option for doKeyguardLocked/doKeyguardTimeout which, when set to true, forces the
238      * keyguard to show even if it is disabled for the current user.
239      */
240     public static final String OPTION_FORCE_SHOW = "force_show";
241 
242     /** The stream type that the lock sounds are tied to. */
243     private int mUiSoundsStreamType;
244 
245     private AlarmManager mAlarmManager;
246     private AudioManager mAudioManager;
247     private StatusBarManager mStatusBarManager;
248     private final SysuiStatusBarStateController mStatusBarStateController;
249     private final Executor mUiBgExecutor;
250     private final UnlockedScreenOffAnimationController mUnlockedScreenOffAnimationController;
251     private final Lazy<NotificationShadeDepthController> mNotificationShadeDepthController;
252 
253     private boolean mSystemReady;
254     private boolean mBootCompleted;
255     private boolean mBootSendUserPresent;
256     private boolean mShuttingDown;
257     private boolean mDozing;
258     private boolean mAnimatingScreenOff;
259     private final FalsingCollector mFalsingCollector;
260 
261     /** High level access to the power manager for WakeLocks */
262     private final PowerManager mPM;
263 
264     /** TrustManager for letting it know when we change visibility */
265     private final TrustManager mTrustManager;
266 
267     /** UserSwitcherController for creating guest user on boot complete */
268     private final UserSwitcherController mUserSwitcherController;
269 
270     /**
271      * Used to keep the device awake while to ensure the keyguard finishes opening before
272      * we sleep.
273      */
274     private PowerManager.WakeLock mShowKeyguardWakeLock;
275 
276     private final Lazy<KeyguardViewController> mKeyguardViewControllerLazy;
277 
278     // these are protected by synchronized (this)
279 
280     /**
281      * External apps (like the phone app) can tell us to disable the keygaurd.
282      */
283     private boolean mExternallyEnabled = true;
284 
285     /**
286      * Remember if an external call to {@link #setKeyguardEnabled} with value
287      * false caused us to hide the keyguard, so that we need to reshow it once
288      * the keygaurd is reenabled with another call with value true.
289      */
290     private boolean mNeedToReshowWhenReenabled = false;
291 
292     // cached value of whether we are showing (need to know this to quickly
293     // answer whether the input should be restricted)
294     private boolean mShowing;
295 
296     // AOD is enabled and status bar is in AOD state.
297     private boolean mAodShowing;
298 
299     /** Cached value of #isInputRestricted */
300     private boolean mInputRestricted;
301 
302     // true if the keyguard is hidden by another window
303     private boolean mOccluded = false;
304 
305     /**
306      * Helps remember whether the screen has turned on since the last time
307      * it turned off due to timeout. see {@link #onScreenTurnedOff(int)}
308      */
309     private int mDelayedShowingSequence;
310 
311     /**
312      * Simiar to {@link #mDelayedProfileShowingSequence}, but it is for profile case.
313      */
314     private int mDelayedProfileShowingSequence;
315 
316     /**
317      * If the user has disabled the keyguard, then requests to exit, this is
318      * how we'll ultimately let them know whether it was successful.  We use this
319      * var being non-null as an indicator that there is an in progress request.
320      */
321     private IKeyguardExitCallback mExitSecureCallback;
322     private final DismissCallbackRegistry mDismissCallbackRegistry;
323 
324     // the properties of the keyguard
325 
326     private final KeyguardUpdateMonitor mUpdateMonitor;
327 
328     /**
329      * Last SIM state reported by the telephony system.
330      * Index is the slotId - in case of multiple SIM cards.
331      */
332     private final SparseIntArray mLastSimStates = new SparseIntArray();
333 
334     /**
335      * Indicates if a SIM card had the SIM PIN enabled during the initialization, before
336      * reaching the SIM_STATE_READY state. The flag is reset to false at SIM_STATE_READY.
337      * Index is the slotId - in case of multiple SIM cards.
338      */
339     private final SparseBooleanArray mSimWasLocked = new SparseBooleanArray();
340 
341     private boolean mDeviceInteractive;
342     private boolean mGoingToSleep;
343 
344     // last known state of the cellular connection
345     private String mPhoneState = TelephonyManager.EXTRA_STATE_IDLE;
346 
347     /**
348      * Whether a hide is pending an we are just waiting for #startKeyguardExitAnimation to be
349      * called.
350      * */
351     private boolean mHiding;
352 
353     /**
354      * we send this intent when the keyguard is dismissed.
355      */
356     private static final Intent USER_PRESENT_INTENT = new Intent(Intent.ACTION_USER_PRESENT)
357             .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
358                     | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
359                     | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
360 
361     /**
362      * {@link #setKeyguardEnabled} waits on this condition when it reenables
363      * the keyguard.
364      */
365     private boolean mWaitingUntilKeyguardVisible = false;
366     private final LockPatternUtils mLockPatternUtils;
367     private final BroadcastDispatcher mBroadcastDispatcher;
368     private boolean mKeyguardDonePending = false;
369     private boolean mHideAnimationRun = false;
370     private boolean mHideAnimationRunning = false;
371 
372     private SoundPool mLockSounds;
373     private int mLockSoundId;
374     private int mUnlockSoundId;
375     private int mTrustedSoundId;
376     private int mLockSoundStreamId;
377     /**
378      * The animation used for hiding keyguard. This is used to fetch the animation timings if
379      * WindowManager is not providing us with them.
380      */
381     private Animation mHideAnimation;
382 
383     /**
384      * The volume applied to the lock/unlock sounds.
385      */
386     private float mLockSoundVolume;
387 
388     /**
389      * For managing external displays
390      */
391     private final KeyguardDisplayManager mKeyguardDisplayManager;
392 
393     private final ArrayList<IKeyguardStateCallback> mKeyguardStateCallbacks = new ArrayList<>();
394 
395     /**
396      * When starting going to sleep, we figured out that we need to reset Keyguard state and this
397      * should be committed when finished going to sleep.
398      */
399     private boolean mPendingReset;
400 
401     /**
402      * When starting going to sleep, we figured out that we need to lock Keyguard and this should be
403      * committed when finished going to sleep.
404      */
405     private boolean mPendingLock;
406 
407     /**
408      * When starting to go away, flag a need to show the PIN lock so the keyguard can be brought
409      * back.
410      */
411     private boolean mPendingPinLock = false;
412 
413     /**
414      * Whether a power button gesture (such as double tap for camera) has been detected. This is
415      * delivered directly from {@link KeyguardService}, immediately upon the gesture being detected.
416      * This is used in {@link #onStartedWakingUp} to decide whether to execute the pending lock, or
417      * ignore and reset it because we are actually launching an activity.
418      *
419      * This needs to be delivered directly to us, rather than waiting for
420      * {@link CommandQueue#onCameraLaunchGestureDetected}, because that call is asynchronous and is
421      * often delivered after the call to {@link #onStartedWakingUp}, which results in us locking the
422      * keyguard and then launching the activity behind it.
423      */
424     private boolean mPowerGestureIntercepted = false;
425 
426     /**
427      * Controller for showing individual "work challenge" lock screen windows inside managed profile
428      * tasks when the current user has been unlocked but the profile is still locked.
429      */
430     private WorkLockActivityController mWorkLockController;
431 
432     /**
433      * @see #setPulsing(boolean)
434      */
435     private boolean mPulsing;
436 
437     private boolean mLockLater;
438     private boolean mShowHomeOverLockscreen;
439     private boolean mInGestureNavigationMode;
440 
441     private boolean mWakeAndUnlocking;
442     private IKeyguardDrawnCallback mDrawnCallback;
443     private CharSequence mCustomMessage;
444 
445     /**
446      * Whether the RemoteAnimation on the app/launcher surface behind the keyguard is 'running'.
447      * Note that this does not necessarily mean the surface is currently in motion - we may be
448      * 'animating' it along with the user's finger during a swipe to unlock gesture, a gesture that
449      * can be paused or reversed.
450      */
451     private boolean mSurfaceBehindRemoteAnimationRunning;
452 
453     /**
454      * Whether we've asked to make the app/launcher surface behind the keyguard visible, via a call
455      * to {@link android.app.IActivityTaskManager#keyguardGoingAway(int)}.
456      *
457      * Since that's an IPC, this doesn't necessarily mean the remote animation has started yet.
458      * {@link #mSurfaceBehindRemoteAnimationRunning} will be true if the call completed and the
459      * animation is now running.
460      */
461     private boolean mSurfaceBehindRemoteAnimationRequested = false;
462 
463     /**
464      * Callback to run to end the RemoteAnimation on the app/launcher surface behind the keyguard.
465      */
466     private IRemoteAnimationFinishedCallback mSurfaceBehindRemoteAnimationFinishedCallback;
467 
468     /**
469      * The animation runner to use for the next exit animation.
470      */
471     private IRemoteAnimationRunner mKeyguardExitAnimationRunner;
472 
473     private final DeviceConfig.OnPropertiesChangedListener mOnPropertiesChangedListener =
474             new DeviceConfig.OnPropertiesChangedListener() {
475             @Override
476             public void onPropertiesChanged(DeviceConfig.Properties properties) {
477                 if (properties.getKeyset().contains(NAV_BAR_HANDLE_SHOW_OVER_LOCKSCREEN)) {
478                     mShowHomeOverLockscreen = properties.getBoolean(
479                             NAV_BAR_HANDLE_SHOW_OVER_LOCKSCREEN, true /* defaultValue */);
480                 }
481             }
482     };
483 
484     KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
485 
486         @Override
487         public void onKeyguardVisibilityChanged(boolean showing) {
488             synchronized (KeyguardViewMediator.this) {
489                 if (!showing && mPendingPinLock) {
490                     Log.i(TAG, "PIN lock requested, starting keyguard");
491 
492                     // Bring the keyguard back in order to show the PIN lock
493                     mPendingPinLock = false;
494                     doKeyguardLocked(null);
495                 }
496             }
497         }
498 
499         @Override
500         public void onUserSwitching(int userId) {
501             if (DEBUG) Log.d(TAG, String.format("onUserSwitching %d", userId));
502             // Note that the mLockPatternUtils user has already been updated from setCurrentUser.
503             // We need to force a reset of the views, since lockNow (called by
504             // ActivityManagerService) will not reconstruct the keyguard if it is already showing.
505             synchronized (KeyguardViewMediator.this) {
506                 resetKeyguardDonePendingLocked();
507                 if (mLockPatternUtils.isLockScreenDisabled(userId)) {
508                     // If we switching to a user that has keyguard disabled, dismiss keyguard.
509                     dismiss(null /* callback */, null /* message */);
510                 } else {
511                     resetStateLocked();
512                 }
513                 adjustStatusBarLocked();
514             }
515         }
516 
517         @Override
518         public void onUserSwitchComplete(int userId) {
519             if (DEBUG) Log.d(TAG, String.format("onUserSwitchComplete %d", userId));
520             if (userId != UserHandle.USER_SYSTEM) {
521                 UserInfo info = UserManager.get(mContext).getUserInfo(userId);
522                 // Don't try to dismiss if the user has Pin/Patter/Password set
523                 if (info == null || mLockPatternUtils.isSecure(userId)) {
524                     return;
525                 } else if (info.isGuest() || info.isDemo()) {
526                     // If we just switched to a guest, try to dismiss keyguard.
527                     dismiss(null /* callback */, null /* message */);
528                 }
529             }
530         }
531 
532         @Override
533         public void onUserInfoChanged(int userId) {
534         }
535 
536         @Override
537         public void onClockVisibilityChanged() {
538             adjustStatusBarLocked();
539         }
540 
541         @Override
542         public void onDeviceProvisioned() {
543             sendUserPresentBroadcast();
544             synchronized (KeyguardViewMediator.this) {
545                 // If system user is provisioned, we might want to lock now to avoid showing launcher
546                 if (mustNotUnlockCurrentUser()) {
547                     doKeyguardLocked(null);
548                 }
549             }
550         }
551 
552         @Override
553         public void onSimStateChanged(int subId, int slotId, int simState) {
554 
555             if (DEBUG_SIM_STATES) {
556                 Log.d(TAG, "onSimStateChanged(subId=" + subId + ", slotId=" + slotId
557                         + ",state=" + simState + ")");
558             }
559 
560             int size = mKeyguardStateCallbacks.size();
561             boolean simPinSecure = mUpdateMonitor.isSimPinSecure();
562             for (int i = size - 1; i >= 0; i--) {
563                 try {
564                     mKeyguardStateCallbacks.get(i).onSimSecureStateChanged(simPinSecure);
565                 } catch (RemoteException e) {
566                     Slog.w(TAG, "Failed to call onSimSecureStateChanged", e);
567                     if (e instanceof DeadObjectException) {
568                         mKeyguardStateCallbacks.remove(i);
569                     }
570                 }
571             }
572 
573             boolean lastSimStateWasLocked;
574             synchronized (KeyguardViewMediator.this) {
575                 int lastState = mLastSimStates.get(slotId);
576                 lastSimStateWasLocked = (lastState == TelephonyManager.SIM_STATE_PIN_REQUIRED
577                         || lastState == TelephonyManager.SIM_STATE_PUK_REQUIRED);
578                 mLastSimStates.append(slotId, simState);
579             }
580 
581             switch (simState) {
582                 case TelephonyManager.SIM_STATE_NOT_READY:
583                 case TelephonyManager.SIM_STATE_ABSENT:
584                     // only force lock screen in case of missing sim if user hasn't
585                     // gone through setup wizard
586                     synchronized (KeyguardViewMediator.this) {
587                         if (shouldWaitForProvisioning()) {
588                             if (!mShowing) {
589                                 if (DEBUG_SIM_STATES) Log.d(TAG, "ICC_ABSENT isn't showing,"
590                                         + " we need to show the keyguard since the "
591                                         + "device isn't provisioned yet.");
592                                 doKeyguardLocked(null);
593                             } else {
594                                 resetStateLocked();
595                             }
596                         }
597                         if (simState == TelephonyManager.SIM_STATE_ABSENT) {
598                             // MVNO SIMs can become transiently NOT_READY when switching networks,
599                             // so we should only lock when they are ABSENT.
600                             if (lastSimStateWasLocked) {
601                                 if (DEBUG_SIM_STATES) Log.d(TAG, "SIM moved to ABSENT when the "
602                                         + "previous state was locked. Reset the state.");
603                                 resetStateLocked();
604                             }
605                             mSimWasLocked.append(slotId, false);
606                         }
607                     }
608                     break;
609                 case TelephonyManager.SIM_STATE_PIN_REQUIRED:
610                 case TelephonyManager.SIM_STATE_PUK_REQUIRED:
611                     synchronized (KeyguardViewMediator.this) {
612                         mSimWasLocked.append(slotId, true);
613                         if (!mShowing) {
614                             if (DEBUG_SIM_STATES) Log.d(TAG,
615                                     "INTENT_VALUE_ICC_LOCKED and keygaurd isn't "
616                                     + "showing; need to show keyguard so user can enter sim pin");
617                             doKeyguardLocked(null);
618                         } else {
619                             mPendingPinLock = true;
620                             resetStateLocked();
621                         }
622                     }
623                     break;
624                 case TelephonyManager.SIM_STATE_PERM_DISABLED:
625                     synchronized (KeyguardViewMediator.this) {
626                         if (!mShowing) {
627                             if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED and "
628                                   + "keygaurd isn't showing.");
629                             doKeyguardLocked(null);
630                         } else {
631                             if (DEBUG_SIM_STATES) Log.d(TAG, "PERM_DISABLED, resetStateLocked to"
632                                   + "show permanently disabled message in lockscreen.");
633                             resetStateLocked();
634                         }
635                     }
636                     break;
637                 case TelephonyManager.SIM_STATE_READY:
638                     synchronized (KeyguardViewMediator.this) {
639                         if (DEBUG_SIM_STATES) Log.d(TAG, "READY, reset state? " + mShowing);
640                         if (mShowing && mSimWasLocked.get(slotId, false)) {
641                             if (DEBUG_SIM_STATES) Log.d(TAG, "SIM moved to READY when the "
642                                     + "previously was locked. Reset the state.");
643                             mSimWasLocked.append(slotId, false);
644                             resetStateLocked();
645                         }
646                     }
647                     break;
648                 default:
649                     if (DEBUG_SIM_STATES) Log.v(TAG, "Unspecific state: " + simState);
650                     break;
651             }
652         }
653 
654         @Override
655         public void onBiometricAuthFailed(BiometricSourceType biometricSourceType) {
656             final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
657             if (mLockPatternUtils.isSecure(currentUser)) {
658                 mLockPatternUtils.getDevicePolicyManager().reportFailedBiometricAttempt(
659                         currentUser);
660             }
661         }
662 
663         @Override
664         public void onBiometricAuthenticated(int userId, BiometricSourceType biometricSourceType,
665                 boolean isStrongBiometric) {
666             if (mLockPatternUtils.isSecure(userId)) {
667                 mLockPatternUtils.getDevicePolicyManager().reportSuccessfulBiometricAttempt(
668                         userId);
669             }
670         }
671 
672         @Override
673         public void onTrustChanged(int userId) {
674             if (userId == KeyguardUpdateMonitor.getCurrentUser()) {
675                 synchronized (KeyguardViewMediator.this) {
676                     notifyTrustedChangedLocked(mUpdateMonitor.getUserHasTrust(userId));
677                 }
678             }
679         }
680     };
681 
682     ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
683 
684         @Override
685         public void userActivity() {
686             KeyguardViewMediator.this.userActivity();
687         }
688 
689         @Override
690         public void keyguardDone(boolean strongAuth, int targetUserId) {
691             if (targetUserId != ActivityManager.getCurrentUser()) {
692                 return;
693             }
694             if (DEBUG) Log.d(TAG, "keyguardDone");
695             tryKeyguardDone();
696         }
697 
698         @Override
699         public void keyguardDoneDrawing() {
700             Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardDoneDrawing");
701             mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
702             Trace.endSection();
703         }
704 
705         @Override
706         public void setNeedsInput(boolean needsInput) {
707             mKeyguardViewControllerLazy.get().setNeedsInput(needsInput);
708         }
709 
710         @Override
711         public void keyguardDonePending(boolean strongAuth, int targetUserId) {
712             Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardDonePending");
713             if (DEBUG) Log.d(TAG, "keyguardDonePending");
714             if (targetUserId != ActivityManager.getCurrentUser()) {
715                 Trace.endSection();
716                 return;
717             }
718 
719             mKeyguardDonePending = true;
720             mHideAnimationRun = true;
721             mHideAnimationRunning = true;
722             mKeyguardViewControllerLazy.get()
723                     .startPreHideAnimation(mHideAnimationFinishedRunnable);
724             mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT,
725                     KEYGUARD_DONE_PENDING_TIMEOUT_MS);
726             Trace.endSection();
727         }
728 
729         @Override
730         public void keyguardGone() {
731             Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardGone");
732             if (DEBUG) Log.d(TAG, "keyguardGone");
733             mKeyguardViewControllerLazy.get().setKeyguardGoingAwayState(false);
734             mKeyguardDisplayManager.hide();
735             Trace.endSection();
736         }
737 
738         @Override
739         public void readyForKeyguardDone() {
740             Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#readyForKeyguardDone");
741             if (mKeyguardDonePending) {
742                 mKeyguardDonePending = false;
743                 tryKeyguardDone();
744             }
745             Trace.endSection();
746         }
747 
748         @Override
749         public void resetKeyguard() {
750             resetStateLocked();
751         }
752 
753         @Override
754         public void onCancelClicked() {
755             mKeyguardViewControllerLazy.get().onCancelClicked();
756         }
757 
758         @Override
759         public void onBouncerVisiblityChanged(boolean shown) {
760             synchronized (KeyguardViewMediator.this) {
761                 if (shown) {
762                     mPendingPinLock = false;
763                 }
764                 adjustStatusBarLocked(shown, false);
765             }
766         }
767 
768         @Override
769         public void playTrustedSound() {
770             KeyguardViewMediator.this.playTrustedSound();
771         }
772 
773         @Override
774         public boolean isScreenOn() {
775             return mDeviceInteractive;
776         }
777 
778         @Override
779         public int getBouncerPromptReason() {
780             int currentUser = KeyguardUpdateMonitor.getCurrentUser();
781             boolean trust = mUpdateMonitor.isTrustUsuallyManaged(currentUser);
782             boolean biometrics = mUpdateMonitor.isUnlockingWithBiometricsPossible(currentUser);
783             boolean any = trust || biometrics;
784             KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
785                     mUpdateMonitor.getStrongAuthTracker();
786             int strongAuth = strongAuthTracker.getStrongAuthForUser(currentUser);
787 
788             if (any && !strongAuthTracker.hasUserAuthenticatedSinceBoot()) {
789                 return KeyguardSecurityView.PROMPT_REASON_RESTART;
790             } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_TIMEOUT) != 0) {
791                 return KeyguardSecurityView.PROMPT_REASON_TIMEOUT;
792             } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) != 0) {
793                 return KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN;
794             } else if (trust && (strongAuth & SOME_AUTH_REQUIRED_AFTER_USER_REQUEST) != 0) {
795                 return KeyguardSecurityView.PROMPT_REASON_USER_REQUEST;
796             } else if (any && ((strongAuth & STRONG_AUTH_REQUIRED_AFTER_LOCKOUT) != 0
797                     || mUpdateMonitor.isFingerprintLockedOut())) {
798                 return KeyguardSecurityView.PROMPT_REASON_AFTER_LOCKOUT;
799             } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_FOR_UNATTENDED_UPDATE) != 0) {
800                 return KeyguardSecurityView.PROMPT_REASON_PREPARE_FOR_UPDATE;
801             } else if (any && (strongAuth
802                     & STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT) != 0) {
803                 return KeyguardSecurityView.PROMPT_REASON_NON_STRONG_BIOMETRIC_TIMEOUT;
804             }
805             return KeyguardSecurityView.PROMPT_REASON_NONE;
806         }
807 
808         @Override
809         public CharSequence consumeCustomMessage() {
810             final CharSequence message = mCustomMessage;
811             mCustomMessage = null;
812             return message;
813         }
814     };
815 
816     private DeviceConfigProxy mDeviceConfig;
817     private DozeParameters mDozeParameters;
818 
819     private final Optional<UnfoldLightRevealOverlayAnimation> mUnfoldLightRevealAnimation;
820     private final AtomicInteger mPendingDrawnTasks = new AtomicInteger();
821 
822     private final KeyguardStateController mKeyguardStateController;
823     private final Lazy<KeyguardUnlockAnimationController> mKeyguardUnlockAnimationControllerLazy;
824     private boolean mWallpaperSupportsAmbientMode;
825 
826     /**
827      * Injected constructor. See {@link KeyguardModule}.
828      */
KeyguardViewMediator( Context context, FalsingCollector falsingCollector, LockPatternUtils lockPatternUtils, BroadcastDispatcher broadcastDispatcher, Lazy<KeyguardViewController> statusBarKeyguardViewManagerLazy, DismissCallbackRegistry dismissCallbackRegistry, KeyguardUpdateMonitor keyguardUpdateMonitor, DumpManager dumpManager, @UiBackground Executor uiBgExecutor, PowerManager powerManager, TrustManager trustManager, UserSwitcherController userSwitcherController, DeviceConfigProxy deviceConfig, NavigationModeController navigationModeController, KeyguardDisplayManager keyguardDisplayManager, DozeParameters dozeParameters, Optional<SysUIUnfoldComponent> unfoldComponent, SysuiStatusBarStateController statusBarStateController, KeyguardStateController keyguardStateController, Lazy<KeyguardUnlockAnimationController> keyguardUnlockAnimationControllerLazy, UnlockedScreenOffAnimationController unlockedScreenOffAnimationController, Lazy<NotificationShadeDepthController> notificationShadeDepthController)829     public KeyguardViewMediator(
830             Context context,
831             FalsingCollector falsingCollector,
832             LockPatternUtils lockPatternUtils,
833             BroadcastDispatcher broadcastDispatcher,
834             Lazy<KeyguardViewController> statusBarKeyguardViewManagerLazy,
835             DismissCallbackRegistry dismissCallbackRegistry,
836             KeyguardUpdateMonitor keyguardUpdateMonitor, DumpManager dumpManager,
837             @UiBackground Executor uiBgExecutor, PowerManager powerManager,
838             TrustManager trustManager,
839             UserSwitcherController userSwitcherController,
840             DeviceConfigProxy deviceConfig,
841             NavigationModeController navigationModeController,
842             KeyguardDisplayManager keyguardDisplayManager,
843             DozeParameters dozeParameters,
844             Optional<SysUIUnfoldComponent> unfoldComponent,
845             SysuiStatusBarStateController statusBarStateController,
846             KeyguardStateController keyguardStateController,
847             Lazy<KeyguardUnlockAnimationController> keyguardUnlockAnimationControllerLazy,
848             UnlockedScreenOffAnimationController unlockedScreenOffAnimationController,
849             Lazy<NotificationShadeDepthController> notificationShadeDepthController) {
850         super(context);
851         mFalsingCollector = falsingCollector;
852         mLockPatternUtils = lockPatternUtils;
853         mBroadcastDispatcher = broadcastDispatcher;
854         mKeyguardViewControllerLazy = statusBarKeyguardViewManagerLazy;
855         mDismissCallbackRegistry = dismissCallbackRegistry;
856         mNotificationShadeDepthController = notificationShadeDepthController;
857         mUiBgExecutor = uiBgExecutor;
858         mUpdateMonitor = keyguardUpdateMonitor;
859         mPM = powerManager;
860         mTrustManager = trustManager;
861         mUserSwitcherController = userSwitcherController;
862         mKeyguardDisplayManager = keyguardDisplayManager;
863         dumpManager.registerDumpable(getClass().getName(), this);
864         mDeviceConfig = deviceConfig;
865         mShowHomeOverLockscreen = mDeviceConfig.getBoolean(
866                 DeviceConfig.NAMESPACE_SYSTEMUI,
867                 NAV_BAR_HANDLE_SHOW_OVER_LOCKSCREEN,
868                 /* defaultValue = */ true);
869         mDeviceConfig.addOnPropertiesChangedListener(
870                 DeviceConfig.NAMESPACE_SYSTEMUI,
871                 mHandler::post,
872                 mOnPropertiesChangedListener);
873         mInGestureNavigationMode =
874                 QuickStepContract.isGesturalMode(navigationModeController.addListener(mode -> {
875                     mInGestureNavigationMode = QuickStepContract.isGesturalMode(mode);
876                 }));
877         mDozeParameters = dozeParameters;
878         mUnfoldLightRevealAnimation = unfoldComponent.map(
879                 c -> c.getUnfoldLightRevealOverlayAnimation());
880         mStatusBarStateController = statusBarStateController;
881         statusBarStateController.addCallback(this);
882 
883         mKeyguardStateController = keyguardStateController;
884         mKeyguardUnlockAnimationControllerLazy = keyguardUnlockAnimationControllerLazy;
885         mUnlockedScreenOffAnimationController = unlockedScreenOffAnimationController;
886     }
887 
userActivity()888     public void userActivity() {
889         mPM.userActivity(SystemClock.uptimeMillis(), false);
890     }
891 
mustNotUnlockCurrentUser()892     boolean mustNotUnlockCurrentUser() {
893         return UserManager.isSplitSystemUser()
894                 && KeyguardUpdateMonitor.getCurrentUser() == UserHandle.USER_SYSTEM;
895     }
896 
setupLocked()897     private void setupLocked() {
898         mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
899         mShowKeyguardWakeLock.setReferenceCounted(false);
900 
901         IntentFilter filter = new IntentFilter();
902         filter.addAction(Intent.ACTION_SHUTDOWN);
903         mBroadcastDispatcher.registerReceiver(mBroadcastReceiver, filter);
904 
905         final IntentFilter delayedActionFilter = new IntentFilter();
906         delayedActionFilter.addAction(DELAYED_KEYGUARD_ACTION);
907         delayedActionFilter.addAction(DELAYED_LOCK_PROFILE_ACTION);
908         mContext.registerReceiver(mDelayedLockBroadcastReceiver, delayedActionFilter,
909                 SYSTEMUI_PERMISSION, null /* scheduler */);
910 
911         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
912 
913         KeyguardUpdateMonitor.setCurrentUser(ActivityManager.getCurrentUser());
914 
915         // Assume keyguard is showing (unless it's disabled) until we know for sure, unless Keyguard
916         // is disabled.
917         if (isKeyguardServiceEnabled()) {
918             setShowingLocked(!shouldWaitForProvisioning()
919                     && !mLockPatternUtils.isLockScreenDisabled(
920                             KeyguardUpdateMonitor.getCurrentUser()), true /* forceCallbacks */);
921         } else {
922             // The system's keyguard is disabled or missing.
923             setShowingLocked(false /* showing */, true /* forceCallbacks */);
924         }
925 
926         final ContentResolver cr = mContext.getContentResolver();
927 
928         mDeviceInteractive = mPM.isInteractive();
929 
930         mLockSounds = new SoundPool.Builder()
931                 .setMaxStreams(1)
932                 .setAudioAttributes(
933                         new AudioAttributes.Builder()
934                                 .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
935                                 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
936                                 .build())
937                 .build();
938         String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
939         if (soundPath != null) {
940             mLockSoundId = mLockSounds.load(soundPath, 1);
941         }
942         if (soundPath == null || mLockSoundId == 0) {
943             Log.w(TAG, "failed to load lock sound from " + soundPath);
944         }
945         soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
946         if (soundPath != null) {
947             mUnlockSoundId = mLockSounds.load(soundPath, 1);
948         }
949         if (soundPath == null || mUnlockSoundId == 0) {
950             Log.w(TAG, "failed to load unlock sound from " + soundPath);
951         }
952         soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND);
953         if (soundPath != null) {
954             mTrustedSoundId = mLockSounds.load(soundPath, 1);
955         }
956         if (soundPath == null || mTrustedSoundId == 0) {
957             Log.w(TAG, "failed to load trusted sound from " + soundPath);
958         }
959 
960         int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
961                 com.android.internal.R.integer.config_lockSoundVolumeDb);
962         mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
963 
964         mHideAnimation = AnimationUtils.loadAnimation(mContext,
965                 com.android.internal.R.anim.lock_screen_behind_enter);
966 
967         mWorkLockController = new WorkLockActivityController(mContext);
968     }
969 
970     @Override
start()971     public void start() {
972         synchronized (this) {
973             setupLocked();
974         }
975     }
976 
977     /**
978      * Let us know that the system is ready after startup.
979      */
onSystemReady()980     public void onSystemReady() {
981         mHandler.obtainMessage(SYSTEM_READY).sendToTarget();
982     }
983 
handleSystemReady()984     private void handleSystemReady() {
985         synchronized (this) {
986             if (DEBUG) Log.d(TAG, "onSystemReady");
987             mSystemReady = true;
988             doKeyguardLocked(null);
989             mUpdateMonitor.registerCallback(mUpdateCallback);
990         }
991         // Most services aren't available until the system reaches the ready state, so we
992         // send it here when the device first boots.
993         maybeSendUserPresentBroadcast();
994     }
995 
996     /**
997      * Called to let us know the screen was turned off.
998      * @param offReason either {@link WindowManagerPolicyConstants#OFF_BECAUSE_OF_USER} or
999      * {@link WindowManagerPolicyConstants#OFF_BECAUSE_OF_TIMEOUT}.
1000      */
onStartedGoingToSleep(@indowManagerPolicyConstants.OffReason int offReason)1001     public void onStartedGoingToSleep(@WindowManagerPolicyConstants.OffReason int offReason) {
1002         if (DEBUG) Log.d(TAG, "onStartedGoingToSleep(" + offReason + ")");
1003         synchronized (this) {
1004             mDeviceInteractive = false;
1005             mPowerGestureIntercepted = false;
1006             mGoingToSleep = true;
1007 
1008             // Lock immediately based on setting if secure (user has a pin/pattern/password).
1009             // This also "locks" the device when not secure to provide easy access to the
1010             // camera while preventing unwanted input.
1011             int currentUser = KeyguardUpdateMonitor.getCurrentUser();
1012             final boolean lockImmediately =
1013                     mLockPatternUtils.getPowerButtonInstantlyLocks(currentUser)
1014                             || !mLockPatternUtils.isSecure(currentUser);
1015             long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser());
1016             mLockLater = false;
1017             if (mExitSecureCallback != null) {
1018                 if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
1019                 try {
1020                     mExitSecureCallback.onKeyguardExitResult(false);
1021                 } catch (RemoteException e) {
1022                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1023                 }
1024                 mExitSecureCallback = null;
1025                 if (!mExternallyEnabled) {
1026                     hideLocked();
1027                 }
1028             } else if (mShowing && !mKeyguardStateController.isKeyguardGoingAway()) {
1029                 // If we are going to sleep but the keyguard is showing (and will continue to be
1030                 // showing, not in the process of going away) then reset its state. Otherwise, let
1031                 // this fall through and explicitly re-lock the keyguard.
1032                 mPendingReset = true;
1033             } else if (
1034                     (offReason == WindowManagerPolicyConstants.OFF_BECAUSE_OF_TIMEOUT
1035                             && timeout > 0)
1036                             || (offReason == WindowManagerPolicyConstants.OFF_BECAUSE_OF_USER
1037                             && !lockImmediately)) {
1038                 doKeyguardLaterLocked(timeout);
1039                 mLockLater = true;
1040             } else if (!mLockPatternUtils.isLockScreenDisabled(currentUser)) {
1041                 mPendingLock = true;
1042             }
1043 
1044             if (mPendingLock) {
1045                 playSounds(true);
1046             }
1047         }
1048 
1049         mUpdateMonitor.dispatchStartedGoingToSleep(offReason);
1050 
1051         // Reset keyguard going away state so we can start listening for fingerprint. We
1052         // explicitly DO NOT want to call
1053         // mKeyguardViewControllerLazy.get().setKeyguardGoingAwayState(false)
1054         // here, since that will mess with the device lock state.
1055         mUpdateMonitor.dispatchKeyguardGoingAway(false);
1056 
1057         notifyStartedGoingToSleep();
1058     }
1059 
1060     /**
1061      * Called to let us know the screen finished turning off.
1062      * @param offReason either {@link WindowManagerPolicyConstants#OFF_BECAUSE_OF_USER} or
1063      * {@link WindowManagerPolicyConstants#OFF_BECAUSE_OF_TIMEOUT}.
1064      */
onFinishedGoingToSleep( @indowManagerPolicyConstants.OffReason int offReason, boolean cameraGestureTriggered)1065     public void onFinishedGoingToSleep(
1066             @WindowManagerPolicyConstants.OffReason int offReason, boolean cameraGestureTriggered) {
1067         if (DEBUG) Log.d(TAG, "onFinishedGoingToSleep(" + offReason + ")");
1068         synchronized (this) {
1069             mDeviceInteractive = false;
1070             mGoingToSleep = false;
1071             mWakeAndUnlocking = false;
1072             mAnimatingScreenOff = mDozeParameters.shouldControlUnlockedScreenOff();
1073 
1074             resetKeyguardDonePendingLocked();
1075             mHideAnimationRun = false;
1076 
1077             notifyFinishedGoingToSleep();
1078 
1079             if (cameraGestureTriggered) {
1080 
1081                 // Just to make sure, make sure the device is awake.
1082                 mContext.getSystemService(PowerManager.class).wakeUp(SystemClock.uptimeMillis(),
1083                         PowerManager.WAKE_REASON_CAMERA_LAUNCH,
1084                         "com.android.systemui:CAMERA_GESTURE_PREVENT_LOCK");
1085                 mPendingLock = false;
1086                 mPendingReset = false;
1087             }
1088 
1089             if (mPendingReset) {
1090                 resetStateLocked();
1091                 mPendingReset = false;
1092             }
1093 
1094             maybeHandlePendingLock();
1095 
1096             // We do not have timeout and power button instant lock setting for profile lock.
1097             // So we use the personal setting if there is any. But if there is no device
1098             // we need to make sure we lock it immediately when the screen is off.
1099             if (!mLockLater && !cameraGestureTriggered) {
1100                 doKeyguardForChildProfilesLocked();
1101             }
1102 
1103         }
1104         mUpdateMonitor.dispatchFinishedGoingToSleep(offReason);
1105     }
1106 
1107     /**
1108      * Locks the keyguard if {@link #mPendingLock} is true, unless we're playing the screen off
1109      * animation.
1110      *
1111      * If we are, we will lock the keyguard either when the screen off animation ends, or in
1112      * {@link #onStartedWakingUp} if the animation is cancelled.
1113      */
maybeHandlePendingLock()1114     public void maybeHandlePendingLock() {
1115         if (mPendingLock && !mUnlockedScreenOffAnimationController.isScreenOffAnimationPlaying()) {
1116             doKeyguardLocked(null);
1117             mPendingLock = false;
1118         }
1119     }
1120 
isKeyguardServiceEnabled()1121     private boolean isKeyguardServiceEnabled() {
1122         try {
1123             return mContext.getPackageManager().getServiceInfo(
1124                     new ComponentName(mContext, KeyguardService.class), 0).isEnabled();
1125         } catch (NameNotFoundException e) {
1126             return true;
1127         }
1128     }
1129 
getLockTimeout(int userId)1130     private long getLockTimeout(int userId) {
1131         // if the screen turned off because of timeout or the user hit the power button
1132         // and we don't need to lock immediately, set an alarm
1133         // to enable it a little bit later (i.e, give the user a chance
1134         // to turn the screen back on within a certain window without
1135         // having to unlock the screen)
1136         final ContentResolver cr = mContext.getContentResolver();
1137 
1138         // From SecuritySettings
1139         final long lockAfterTimeout = Settings.Secure.getInt(cr,
1140                 Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
1141                 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
1142 
1143         // From DevicePolicyAdmin
1144         final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
1145                 .getMaximumTimeToLock(null, userId);
1146 
1147         long timeout;
1148 
1149         if (policyTimeout <= 0) {
1150             timeout = lockAfterTimeout;
1151         } else {
1152             // From DisplaySettings
1153             long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
1154                     KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
1155 
1156             // policy in effect. Make sure we don't go beyond policy limit.
1157             displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
1158             timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
1159             timeout = Math.max(timeout, 0);
1160         }
1161         return timeout;
1162     }
1163 
doKeyguardLaterLocked()1164     private void doKeyguardLaterLocked() {
1165         long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser());
1166         if (timeout == 0) {
1167             doKeyguardLocked(null);
1168         } else {
1169             doKeyguardLaterLocked(timeout);
1170         }
1171     }
1172 
doKeyguardLaterLocked(long timeout)1173     private void doKeyguardLaterLocked(long timeout) {
1174         // Lock in the future
1175         long when = SystemClock.elapsedRealtime() + timeout;
1176         Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
1177         intent.putExtra("seq", mDelayedShowingSequence);
1178         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1179         PendingIntent sender = PendingIntent.getBroadcast(mContext,
1180                 0, intent, PendingIntent.FLAG_CANCEL_CURRENT |  PendingIntent.FLAG_IMMUTABLE);
1181         mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
1182         if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
1183                          + mDelayedShowingSequence);
1184         doKeyguardLaterForChildProfilesLocked();
1185     }
1186 
doKeyguardLaterForChildProfilesLocked()1187     private void doKeyguardLaterForChildProfilesLocked() {
1188         UserManager um = UserManager.get(mContext);
1189         for (int profileId : um.getEnabledProfileIds(UserHandle.myUserId())) {
1190             if (mLockPatternUtils.isSeparateProfileChallengeEnabled(profileId)) {
1191                 long userTimeout = getLockTimeout(profileId);
1192                 if (userTimeout == 0) {
1193                     doKeyguardForChildProfilesLocked();
1194                 } else {
1195                     long userWhen = SystemClock.elapsedRealtime() + userTimeout;
1196                     Intent lockIntent = new Intent(DELAYED_LOCK_PROFILE_ACTION);
1197                     lockIntent.putExtra("seq", mDelayedProfileShowingSequence);
1198                     lockIntent.putExtra(Intent.EXTRA_USER_ID, profileId);
1199                     lockIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1200                     PendingIntent lockSender = PendingIntent.getBroadcast(
1201                             mContext, 0, lockIntent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_MUTABLE_UNAUDITED);
1202                     mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1203                             userWhen, lockSender);
1204                 }
1205             }
1206         }
1207     }
1208 
doKeyguardForChildProfilesLocked()1209     private void doKeyguardForChildProfilesLocked() {
1210         UserManager um = UserManager.get(mContext);
1211         for (int profileId : um.getEnabledProfileIds(UserHandle.myUserId())) {
1212             if (mLockPatternUtils.isSeparateProfileChallengeEnabled(profileId)) {
1213                 lockProfile(profileId);
1214             }
1215         }
1216     }
1217 
cancelDoKeyguardLaterLocked()1218     private void cancelDoKeyguardLaterLocked() {
1219         mDelayedShowingSequence++;
1220     }
1221 
cancelDoKeyguardForChildProfilesLocked()1222     private void cancelDoKeyguardForChildProfilesLocked() {
1223         mDelayedProfileShowingSequence++;
1224     }
1225 
1226     /**
1227      * Let's us know when the device is waking up.
1228      */
onStartedWakingUp(boolean cameraGestureTriggered)1229     public void onStartedWakingUp(boolean cameraGestureTriggered) {
1230         Trace.beginSection("KeyguardViewMediator#onStartedWakingUp");
1231 
1232         // TODO: Rename all screen off/on references to interactive/sleeping
1233         synchronized (this) {
1234             mDeviceInteractive = true;
1235             if (mPendingLock && !cameraGestureTriggered) {
1236                 doKeyguardLocked(null);
1237             }
1238             mAnimatingScreenOff = false;
1239             cancelDoKeyguardLaterLocked();
1240             cancelDoKeyguardForChildProfilesLocked();
1241             if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence);
1242             notifyStartedWakingUp();
1243         }
1244         mUpdateMonitor.dispatchStartedWakingUp();
1245         maybeSendUserPresentBroadcast();
1246         Trace.endSection();
1247     }
1248 
onScreenTurningOn(IKeyguardDrawnCallback callback)1249     public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
1250         Trace.beginSection("KeyguardViewMediator#onScreenTurningOn");
1251         notifyScreenOn(callback);
1252         Trace.endSection();
1253     }
1254 
onScreenTurnedOn()1255     public void onScreenTurnedOn() {
1256         Trace.beginSection("KeyguardViewMediator#onScreenTurnedOn");
1257         notifyScreenTurnedOn();
1258         mUpdateMonitor.dispatchScreenTurnedOn();
1259         Trace.endSection();
1260     }
1261 
onScreenTurnedOff()1262     public void onScreenTurnedOff() {
1263         notifyScreenTurnedOff();
1264         mUpdateMonitor.dispatchScreenTurnedOff();
1265     }
1266 
maybeSendUserPresentBroadcast()1267     private void maybeSendUserPresentBroadcast() {
1268         if (mSystemReady && mLockPatternUtils.isLockScreenDisabled(
1269                 KeyguardUpdateMonitor.getCurrentUser())) {
1270             // Lock screen is disabled because the user has set the preference to "None".
1271             // In this case, send out ACTION_USER_PRESENT here instead of in
1272             // handleKeyguardDone()
1273             sendUserPresentBroadcast();
1274         } else if (mSystemReady && shouldWaitForProvisioning()) {
1275             // Skipping the lockscreen because we're not yet provisioned, but we still need to
1276             // notify the StrongAuthTracker that it's now safe to run trust agents, in case the
1277             // user sets a credential later.
1278             getLockPatternUtils().userPresent(KeyguardUpdateMonitor.getCurrentUser());
1279         }
1280     }
1281 
1282     /**
1283      * A dream started.  We should lock after the usual screen-off lock timeout but only
1284      * if there is a secure lock pattern.
1285      */
onDreamingStarted()1286     public void onDreamingStarted() {
1287         mUpdateMonitor.dispatchDreamingStarted();
1288         synchronized (this) {
1289             if (mDeviceInteractive
1290                     && mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) {
1291                 doKeyguardLaterLocked();
1292             }
1293         }
1294     }
1295 
1296     /**
1297      * A dream stopped.
1298      */
onDreamingStopped()1299     public void onDreamingStopped() {
1300         mUpdateMonitor.dispatchDreamingStopped();
1301         synchronized (this) {
1302             if (mDeviceInteractive) {
1303                 cancelDoKeyguardLaterLocked();
1304             }
1305         }
1306     }
1307 
1308     /**
1309      * Same semantics as {@link WindowManagerPolicyConstants#enableKeyguard}; provide
1310      * a way for external stuff to override normal keyguard behavior.  For instance
1311      * the phone app disables the keyguard when it receives incoming calls.
1312      */
setKeyguardEnabled(boolean enabled)1313     public void setKeyguardEnabled(boolean enabled) {
1314         synchronized (this) {
1315             if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
1316 
1317             mExternallyEnabled = enabled;
1318 
1319             if (!enabled && mShowing) {
1320                 if (mExitSecureCallback != null) {
1321                     if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
1322                     // we're in the process of handling a request to verify the user
1323                     // can get past the keyguard. ignore extraneous requests to disable / reenable
1324                     return;
1325                 }
1326 
1327                 // hiding keyguard that is showing, remember to reshow later
1328                 if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
1329                         + "disabling status bar expansion");
1330                 mNeedToReshowWhenReenabled = true;
1331                 updateInputRestrictedLocked();
1332                 hideLocked();
1333             } else if (enabled && mNeedToReshowWhenReenabled) {
1334                 // reenabled after previously hidden, reshow
1335                 if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
1336                         + "status bar expansion");
1337                 mNeedToReshowWhenReenabled = false;
1338                 updateInputRestrictedLocked();
1339 
1340                 if (mExitSecureCallback != null) {
1341                     if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
1342                     try {
1343                         mExitSecureCallback.onKeyguardExitResult(false);
1344                     } catch (RemoteException e) {
1345                         Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1346                     }
1347                     mExitSecureCallback = null;
1348                     resetStateLocked();
1349                 } else {
1350                     showLocked(null);
1351 
1352                     // block until we know the keygaurd is done drawing (and post a message
1353                     // to unblock us after a timeout so we don't risk blocking too long
1354                     // and causing an ANR).
1355                     mWaitingUntilKeyguardVisible = true;
1356                     mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
1357                     if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
1358                     while (mWaitingUntilKeyguardVisible) {
1359                         try {
1360                             wait();
1361                         } catch (InterruptedException e) {
1362                             Thread.currentThread().interrupt();
1363                         }
1364                     }
1365                     if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
1366                 }
1367             }
1368         }
1369     }
1370 
1371     /**
1372      * @see android.app.KeyguardManager#exitKeyguardSecurely
1373      */
verifyUnlock(IKeyguardExitCallback callback)1374     public void verifyUnlock(IKeyguardExitCallback callback) {
1375         Trace.beginSection("KeyguardViewMediator#verifyUnlock");
1376         synchronized (this) {
1377             if (DEBUG) Log.d(TAG, "verifyUnlock");
1378             if (shouldWaitForProvisioning()) {
1379                 // don't allow this api when the device isn't provisioned
1380                 if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
1381                 try {
1382                     callback.onKeyguardExitResult(false);
1383                 } catch (RemoteException e) {
1384                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1385                 }
1386             } else if (mExternallyEnabled) {
1387                 // this only applies when the user has externally disabled the
1388                 // keyguard.  this is unexpected and means the user is not
1389                 // using the api properly.
1390                 Log.w(TAG, "verifyUnlock called when not externally disabled");
1391                 try {
1392                     callback.onKeyguardExitResult(false);
1393                 } catch (RemoteException e) {
1394                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1395                 }
1396             } else if (mExitSecureCallback != null) {
1397                 // already in progress with someone else
1398                 try {
1399                     callback.onKeyguardExitResult(false);
1400                 } catch (RemoteException e) {
1401                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1402                 }
1403             } else if (!isSecure()) {
1404 
1405                 // Keyguard is not secure, no need to do anything, and we don't need to reshow
1406                 // the Keyguard after the client releases the Keyguard lock.
1407                 mExternallyEnabled = true;
1408                 mNeedToReshowWhenReenabled = false;
1409                 updateInputRestricted();
1410                 try {
1411                     callback.onKeyguardExitResult(true);
1412                 } catch (RemoteException e) {
1413                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1414                 }
1415             } else {
1416 
1417                 // Since we prevent apps from hiding the Keyguard if we are secure, this should be
1418                 // a no-op as well.
1419                 try {
1420                     callback.onKeyguardExitResult(false);
1421                 } catch (RemoteException e) {
1422                     Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1423                 }
1424             }
1425         }
1426         Trace.endSection();
1427     }
1428 
1429     /**
1430      * Is the keyguard currently showing and not being force hidden?
1431      */
isShowingAndNotOccluded()1432     public boolean isShowingAndNotOccluded() {
1433         return mShowing && !mOccluded;
1434     }
1435 
1436     /**
1437      * Notify us when the keyguard is occluded by another window
1438      */
setOccluded(boolean isOccluded, boolean animate)1439     public void setOccluded(boolean isOccluded, boolean animate) {
1440         Trace.beginSection("KeyguardViewMediator#setOccluded");
1441         if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
1442         mHandler.removeMessages(SET_OCCLUDED);
1443         Message msg = mHandler.obtainMessage(SET_OCCLUDED, isOccluded ? 1 : 0, animate ? 1 : 0);
1444         mHandler.sendMessage(msg);
1445         Trace.endSection();
1446     }
1447 
isHiding()1448     public boolean isHiding() {
1449         return mHiding;
1450     }
1451 
isAnimatingScreenOff()1452     public boolean isAnimatingScreenOff() {
1453         return mAnimatingScreenOff;
1454     }
1455 
1456     /**
1457      * Handles SET_OCCLUDED message sent by setOccluded()
1458      */
handleSetOccluded(boolean isOccluded, boolean animate)1459     private void handleSetOccluded(boolean isOccluded, boolean animate) {
1460         Trace.beginSection("KeyguardViewMediator#handleSetOccluded");
1461         synchronized (KeyguardViewMediator.this) {
1462             if (mHiding && isOccluded) {
1463                 // We're in the process of going away but WindowManager wants to show a
1464                 // SHOW_WHEN_LOCKED activity instead.
1465                 // TODO(bc-unlock): Migrate to remote animation.
1466                 startKeyguardExitAnimation(0, 0);
1467             }
1468 
1469             if (mOccluded != isOccluded) {
1470                 mOccluded = isOccluded;
1471                 mUpdateMonitor.setKeyguardOccluded(isOccluded);
1472                 mKeyguardViewControllerLazy.get().setOccluded(isOccluded, animate
1473                         && mDeviceInteractive);
1474                 adjustStatusBarLocked();
1475             }
1476         }
1477         Trace.endSection();
1478     }
1479 
1480     /**
1481      * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
1482      * This must be safe to call from any thread and with any window manager locks held.
1483      */
doKeyguardTimeout(Bundle options)1484     public void doKeyguardTimeout(Bundle options) {
1485         mHandler.removeMessages(KEYGUARD_TIMEOUT);
1486         Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
1487         // Treat these messages with priority - A call to timeout means the device should lock
1488         // as soon as possible and not wait for other messages on the thread to process first.
1489         mHandler.sendMessageAtFrontOfQueue(msg);
1490     }
1491 
1492     /**
1493      * Given the state of the keyguard, is the input restricted?
1494      * Input is restricted when the keyguard is showing, or when the keyguard
1495      * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
1496      */
isInputRestricted()1497     public boolean isInputRestricted() {
1498         return mShowing || mNeedToReshowWhenReenabled;
1499     }
1500 
updateInputRestricted()1501     private void updateInputRestricted() {
1502         synchronized (this) {
1503             updateInputRestrictedLocked();
1504         }
1505     }
1506 
updateInputRestrictedLocked()1507     private void updateInputRestrictedLocked() {
1508         boolean inputRestricted = isInputRestricted();
1509         if (mInputRestricted != inputRestricted) {
1510             mInputRestricted = inputRestricted;
1511             int size = mKeyguardStateCallbacks.size();
1512             for (int i = size - 1; i >= 0; i--) {
1513                 final IKeyguardStateCallback callback = mKeyguardStateCallbacks.get(i);
1514                 try {
1515                     callback.onInputRestrictedStateChanged(inputRestricted);
1516                 } catch (RemoteException e) {
1517                     Slog.w(TAG, "Failed to call onDeviceProvisioned", e);
1518                     if (e instanceof DeadObjectException) {
1519                         mKeyguardStateCallbacks.remove(callback);
1520                     }
1521                 }
1522             }
1523         }
1524     }
1525 
1526     /**
1527      * Enable the keyguard if the settings are appropriate.
1528      */
doKeyguardLocked(Bundle options)1529     private void doKeyguardLocked(Bundle options) {
1530         if (KeyguardUpdateMonitor.CORE_APPS_ONLY) {
1531             // Don't show keyguard during half-booted cryptkeeper stage.
1532             if (DEBUG) Log.d(TAG, "doKeyguard: not showing because booting to cryptkeeper");
1533             return;
1534         }
1535 
1536         // if another app is disabling us, don't show
1537         if (!mExternallyEnabled) {
1538             if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
1539 
1540             mNeedToReshowWhenReenabled = true;
1541             return;
1542         }
1543 
1544         // if the keyguard is already showing, don't bother. check flags in both files
1545         // to account for the hiding animation which results in a delay and discrepancy
1546         // between flags
1547         if (mShowing && mKeyguardViewControllerLazy.get().isShowing()) {
1548             if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
1549             resetStateLocked();
1550             return;
1551         }
1552 
1553         // In split system user mode, we never unlock system user.
1554         if (!mustNotUnlockCurrentUser()
1555                 || !mUpdateMonitor.isDeviceProvisioned()) {
1556 
1557             // if the setup wizard hasn't run yet, don't show
1558             final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
1559             final boolean absent = SubscriptionManager.isValidSubscriptionId(
1560                     mUpdateMonitor.getNextSubIdForState(TelephonyManager.SIM_STATE_ABSENT));
1561             final boolean disabled = SubscriptionManager.isValidSubscriptionId(
1562                     mUpdateMonitor.getNextSubIdForState(TelephonyManager.SIM_STATE_PERM_DISABLED));
1563             final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure()
1564                     || ((absent || disabled) && requireSim);
1565 
1566             if (!lockedOrMissing && shouldWaitForProvisioning()) {
1567                 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
1568                         + " and the sim is not locked or missing");
1569                 return;
1570             }
1571 
1572             boolean forceShow = options != null && options.getBoolean(OPTION_FORCE_SHOW, false);
1573             if (mLockPatternUtils.isLockScreenDisabled(KeyguardUpdateMonitor.getCurrentUser())
1574                     && !lockedOrMissing && !forceShow) {
1575                 if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
1576                 return;
1577             }
1578 
1579             if (mLockPatternUtils.checkVoldPassword(KeyguardUpdateMonitor.getCurrentUser())) {
1580                 if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
1581                 // Without this, settings is not enabled until the lock screen first appears
1582                 setShowingLocked(false);
1583                 hideLocked();
1584                 return;
1585             }
1586         }
1587 
1588         if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
1589         showLocked(options);
1590     }
1591 
lockProfile(int userId)1592     private void lockProfile(int userId) {
1593         mTrustManager.setDeviceLockedForUser(userId, true);
1594     }
1595 
shouldWaitForProvisioning()1596     private boolean shouldWaitForProvisioning() {
1597         return !mUpdateMonitor.isDeviceProvisioned() && !isSecure();
1598     }
1599 
1600     /**
1601      * Dismiss the keyguard through the security layers.
1602      * @param callback Callback to be informed about the result
1603      * @param message Message that should be displayed on the bouncer.
1604      */
handleDismiss(IKeyguardDismissCallback callback, CharSequence message)1605     private void handleDismiss(IKeyguardDismissCallback callback, CharSequence message) {
1606         if (mShowing) {
1607             if (callback != null) {
1608                 mDismissCallbackRegistry.addCallback(callback);
1609             }
1610             mCustomMessage = message;
1611             mKeyguardViewControllerLazy.get().dismissAndCollapse();
1612         } else if (callback != null) {
1613             new DismissCallbackWrapper(callback).notifyDismissError();
1614         }
1615     }
1616 
dismiss(IKeyguardDismissCallback callback, CharSequence message)1617     public void dismiss(IKeyguardDismissCallback callback, CharSequence message) {
1618         mHandler.obtainMessage(DISMISS, new DismissMessage(callback, message)).sendToTarget();
1619     }
1620 
1621     /**
1622      * Send message to keyguard telling it to reset its state.
1623      * @see #handleReset
1624      */
resetStateLocked()1625     private void resetStateLocked() {
1626         if (DEBUG) Log.e(TAG, "resetStateLocked");
1627         Message msg = mHandler.obtainMessage(RESET);
1628         mHandler.sendMessage(msg);
1629     }
1630 
1631     /**
1632      * Send message to keyguard telling it to verify unlock
1633      * @see #handleVerifyUnlock()
1634      */
verifyUnlockLocked()1635     private void verifyUnlockLocked() {
1636         if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
1637         mHandler.sendEmptyMessage(VERIFY_UNLOCK);
1638     }
1639 
notifyStartedGoingToSleep()1640     private void notifyStartedGoingToSleep() {
1641         if (DEBUG) Log.d(TAG, "notifyStartedGoingToSleep");
1642         mHandler.sendEmptyMessage(NOTIFY_STARTED_GOING_TO_SLEEP);
1643     }
1644 
notifyFinishedGoingToSleep()1645     private void notifyFinishedGoingToSleep() {
1646         if (DEBUG) Log.d(TAG, "notifyFinishedGoingToSleep");
1647         mHandler.sendEmptyMessage(NOTIFY_FINISHED_GOING_TO_SLEEP);
1648     }
1649 
notifyStartedWakingUp()1650     private void notifyStartedWakingUp() {
1651         if (DEBUG) Log.d(TAG, "notifyStartedWakingUp");
1652         mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP);
1653     }
1654 
notifyScreenOn(IKeyguardDrawnCallback callback)1655     private void notifyScreenOn(IKeyguardDrawnCallback callback) {
1656         if (DEBUG) Log.d(TAG, "notifyScreenOn");
1657         Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNING_ON, callback);
1658         mHandler.sendMessage(msg);
1659     }
1660 
notifyScreenTurnedOn()1661     private void notifyScreenTurnedOn() {
1662         if (DEBUG) Log.d(TAG, "notifyScreenTurnedOn");
1663         Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_ON);
1664         mHandler.sendMessage(msg);
1665     }
1666 
notifyScreenTurnedOff()1667     private void notifyScreenTurnedOff() {
1668         if (DEBUG) Log.d(TAG, "notifyScreenTurnedOff");
1669         Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_OFF);
1670         mHandler.sendMessage(msg);
1671     }
1672 
1673     /**
1674      * Send message to keyguard telling it to show itself
1675      * @see #handleShow
1676      */
showLocked(Bundle options)1677     private void showLocked(Bundle options) {
1678         Trace.beginSection("KeyguardViewMediator#showLocked acquiring mShowKeyguardWakeLock");
1679         if (DEBUG) Log.d(TAG, "showLocked");
1680         // ensure we stay awake until we are finished displaying the keyguard
1681         mShowKeyguardWakeLock.acquire();
1682         Message msg = mHandler.obtainMessage(SHOW, options);
1683         // Treat these messages with priority - This call can originate from #doKeyguardTimeout,
1684         // meaning the device should lock as soon as possible and not wait for other messages on
1685         // the thread to process first.
1686         mHandler.sendMessageAtFrontOfQueue(msg);
1687         Trace.endSection();
1688     }
1689 
1690     /**
1691      * Send message to keyguard telling it to hide itself
1692      * @see #handleHide()
1693      */
hideLocked()1694     private void hideLocked() {
1695         Trace.beginSection("KeyguardViewMediator#hideLocked");
1696         if (DEBUG) Log.d(TAG, "hideLocked");
1697         Message msg = mHandler.obtainMessage(HIDE);
1698         mHandler.sendMessage(msg);
1699         Trace.endSection();
1700     }
1701 
1702     /**
1703      * Hide the keyguard and let {@code runner} handle the animation.
1704      *
1705      * This method should typically be called after {@link ViewMediatorCallback#keyguardDonePending}
1706      * was called, when we are ready to hide the keyguard. It will do nothing if we were not
1707      * expecting the keyguard to go away when called.
1708      */
hideWithAnimation(IRemoteAnimationRunner runner)1709     public void hideWithAnimation(IRemoteAnimationRunner runner) {
1710         if (!mKeyguardDonePending) {
1711             return;
1712         }
1713 
1714         mKeyguardExitAnimationRunner = runner;
1715         mViewMediatorCallback.readyForKeyguardDone();
1716     }
1717 
1718     /**
1719      * Disable notification shade background blurs until the keyguard is dismissed.
1720      * (Used during app launch animations)
1721      */
setBlursDisabledForAppLaunch(boolean disabled)1722     public void setBlursDisabledForAppLaunch(boolean disabled) {
1723         mNotificationShadeDepthController.get().setBlursDisabledForAppLaunch(disabled);
1724     }
1725 
isSecure()1726     public boolean isSecure() {
1727         return isSecure(KeyguardUpdateMonitor.getCurrentUser());
1728     }
1729 
isSecure(int userId)1730     public boolean isSecure(int userId) {
1731         return mLockPatternUtils.isSecure(userId)
1732                 || mUpdateMonitor.isSimPinSecure();
1733     }
1734 
1735     /**
1736      * Whether any of the SIMs on the device are secured with a PIN. If so, the keyguard should not
1737      * be dismissable until the PIN is entered, even if the device itself has no lock set.
1738      */
isAnySimPinSecure()1739     public boolean isAnySimPinSecure() {
1740         for (int i = 0; i < mLastSimStates.size(); i++) {
1741             final int key = mLastSimStates.keyAt(i);
1742             if (KeyguardUpdateMonitor.isSimPinSecure(mLastSimStates.get(key))) {
1743                 return true;
1744             }
1745         }
1746 
1747         return false;
1748     }
1749 
setSwitchingUser(boolean switching)1750     public void setSwitchingUser(boolean switching) {
1751         mUpdateMonitor.setSwitchingUser(switching);
1752     }
1753 
1754     /**
1755      * Update the newUserId. Call while holding WindowManagerService lock.
1756      * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
1757      *
1758      * @param newUserId The id of the incoming user.
1759      */
setCurrentUser(int newUserId)1760     public void setCurrentUser(int newUserId) {
1761         KeyguardUpdateMonitor.setCurrentUser(newUserId);
1762         synchronized (this) {
1763             notifyTrustedChangedLocked(mUpdateMonitor.getUserHasTrust(newUserId));
1764         }
1765     }
1766 
1767     /**
1768      * This broadcast receiver should be registered with the SystemUI permission.
1769      */
1770     private final BroadcastReceiver mDelayedLockBroadcastReceiver = new BroadcastReceiver() {
1771         @Override
1772         public void onReceive(Context context, Intent intent) {
1773             if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1774                 final int sequence = intent.getIntExtra("seq", 0);
1775                 if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1776                         + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1777                 synchronized (KeyguardViewMediator.this) {
1778                     if (mDelayedShowingSequence == sequence) {
1779                         doKeyguardLocked(null);
1780                     }
1781                 }
1782             } else if (DELAYED_LOCK_PROFILE_ACTION.equals(intent.getAction())) {
1783                 final int sequence = intent.getIntExtra("seq", 0);
1784                 int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
1785                 if (userId != 0) {
1786                     synchronized (KeyguardViewMediator.this) {
1787                         if (mDelayedProfileShowingSequence == sequence) {
1788                             lockProfile(userId);
1789                         }
1790                     }
1791                 }
1792             }
1793         }
1794     };
1795 
1796     private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1797         @Override
1798         public void onReceive(Context context, Intent intent) {
1799             if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
1800                 synchronized (KeyguardViewMediator.this){
1801                     mShuttingDown = true;
1802                 }
1803             }
1804         }
1805     };
1806 
keyguardDone()1807     public void keyguardDone() {
1808         Trace.beginSection("KeyguardViewMediator#keyguardDone");
1809         if (DEBUG) Log.d(TAG, "keyguardDone()");
1810         userActivity();
1811         EventLog.writeEvent(70000, 2);
1812         Message msg = mHandler.obtainMessage(KEYGUARD_DONE);
1813         mHandler.sendMessage(msg);
1814         Trace.endSection();
1815     }
1816 
1817     /**
1818      * This handler will be associated with the policy thread, which will also
1819      * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1820      * this class, can be called by other threads, any action that directly
1821      * interacts with the keyguard ui should be posted to this handler, rather
1822      * than called directly.
1823      */
1824     private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1825         @Override
1826         public void handleMessage(Message msg) {
1827             switch (msg.what) {
1828                 case SHOW:
1829                     handleShow((Bundle) msg.obj);
1830                     break;
1831                 case HIDE:
1832                     handleHide();
1833                     break;
1834                 case RESET:
1835                     handleReset();
1836                     break;
1837                 case VERIFY_UNLOCK:
1838                     Trace.beginSection("KeyguardViewMediator#handleMessage VERIFY_UNLOCK");
1839                     handleVerifyUnlock();
1840                     Trace.endSection();
1841                     break;
1842                 case NOTIFY_STARTED_GOING_TO_SLEEP:
1843                     handleNotifyStartedGoingToSleep();
1844                     break;
1845                 case NOTIFY_FINISHED_GOING_TO_SLEEP:
1846                     handleNotifyFinishedGoingToSleep();
1847                     break;
1848                 case NOTIFY_SCREEN_TURNING_ON:
1849                     Trace.beginSection(
1850                             "KeyguardViewMediator#handleMessage NOTIFY_SCREEN_TURNING_ON");
1851                     handleNotifyScreenTurningOn((IKeyguardDrawnCallback) msg.obj);
1852                     Trace.endSection();
1853                     break;
1854                 case NOTIFY_SCREEN_TURNED_ON:
1855                     Trace.beginSection(
1856                             "KeyguardViewMediator#handleMessage NOTIFY_SCREEN_TURNED_ON");
1857                     handleNotifyScreenTurnedOn();
1858                     Trace.endSection();
1859                     break;
1860                 case NOTIFY_SCREEN_TURNED_OFF:
1861                     handleNotifyScreenTurnedOff();
1862                     break;
1863                 case NOTIFY_STARTED_WAKING_UP:
1864                     Trace.beginSection(
1865                             "KeyguardViewMediator#handleMessage NOTIFY_STARTED_WAKING_UP");
1866                     handleNotifyStartedWakingUp();
1867                     Trace.endSection();
1868                     break;
1869                 case KEYGUARD_DONE:
1870                     Trace.beginSection("KeyguardViewMediator#handleMessage KEYGUARD_DONE");
1871                     handleKeyguardDone();
1872                     Trace.endSection();
1873                     break;
1874                 case KEYGUARD_DONE_DRAWING:
1875                     Trace.beginSection("KeyguardViewMediator#handleMessage KEYGUARD_DONE_DRAWING");
1876                     handleKeyguardDoneDrawing();
1877                     Trace.endSection();
1878                     break;
1879                 case SET_OCCLUDED:
1880                     Trace.beginSection("KeyguardViewMediator#handleMessage SET_OCCLUDED");
1881                     handleSetOccluded(msg.arg1 != 0, msg.arg2 != 0);
1882                     Trace.endSection();
1883                     break;
1884                 case KEYGUARD_TIMEOUT:
1885                     synchronized (KeyguardViewMediator.this) {
1886                         doKeyguardLocked((Bundle) msg.obj);
1887                         notifyDefaultDisplayCallbacks(mShowing);
1888                     }
1889                     break;
1890                 case DISMISS:
1891                     final DismissMessage message = (DismissMessage) msg.obj;
1892                     handleDismiss(message.getCallback(), message.getMessage());
1893                     break;
1894                 case START_KEYGUARD_EXIT_ANIM:
1895                     Trace.beginSection(
1896                             "KeyguardViewMediator#handleMessage START_KEYGUARD_EXIT_ANIM");
1897                     StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
1898                     handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration,
1899                             params.mApps, params.mWallpapers, params.mNonApps,
1900                             params.mFinishedCallback);
1901                     mFalsingCollector.onSuccessfulUnlock();
1902                     Trace.endSection();
1903                     break;
1904                 case CANCEL_KEYGUARD_EXIT_ANIM:
1905                     Trace.beginSection(
1906                             "KeyguardViewMediator#handleMessage CANCEL_KEYGUARD_EXIT_ANIM");
1907                     handleCancelKeyguardExitAnimation();
1908                     Trace.endSection();
1909                     break;
1910                 case KEYGUARD_DONE_PENDING_TIMEOUT:
1911                     Trace.beginSection("KeyguardViewMediator#handleMessage"
1912                             + " KEYGUARD_DONE_PENDING_TIMEOUT");
1913                     Log.w(TAG, "Timeout while waiting for activity drawn!");
1914                     Trace.endSection();
1915                     break;
1916                 case SYSTEM_READY:
1917                     handleSystemReady();
1918                     break;
1919             }
1920         }
1921     };
1922 
tryKeyguardDone()1923     private void tryKeyguardDone() {
1924         if (DEBUG) {
1925             Log.d(TAG, "tryKeyguardDone: pending - " + mKeyguardDonePending + ", animRan - "
1926                     + mHideAnimationRun + " animRunning - " + mHideAnimationRunning);
1927         }
1928         if (!mKeyguardDonePending && mHideAnimationRun && !mHideAnimationRunning) {
1929             handleKeyguardDone();
1930         } else if (!mHideAnimationRun) {
1931             if (DEBUG) Log.d(TAG, "tryKeyguardDone: starting pre-hide animation");
1932             mHideAnimationRun = true;
1933             mHideAnimationRunning = true;
1934             mKeyguardViewControllerLazy.get()
1935                     .startPreHideAnimation(mHideAnimationFinishedRunnable);
1936         }
1937     }
1938 
1939     /**
1940      * @see #keyguardDone
1941      * @see #KEYGUARD_DONE
1942      */
handleKeyguardDone()1943     private void handleKeyguardDone() {
1944         Trace.beginSection("KeyguardViewMediator#handleKeyguardDone");
1945         final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
1946         mUiBgExecutor.execute(() -> {
1947             if (mLockPatternUtils.isSecure(currentUser)) {
1948                 mLockPatternUtils.getDevicePolicyManager().reportKeyguardDismissed(currentUser);
1949             }
1950         });
1951         if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1952         synchronized (this) {
1953             resetKeyguardDonePendingLocked();
1954         }
1955 
1956 
1957         if (mGoingToSleep) {
1958             mUpdateMonitor.clearBiometricRecognized();
1959             Log.i(TAG, "Device is going to sleep, aborting keyguardDone");
1960             return;
1961         }
1962         if (mExitSecureCallback != null) {
1963             try {
1964                 mExitSecureCallback.onKeyguardExitResult(true /* authenciated */);
1965             } catch (RemoteException e) {
1966                 Slog.w(TAG, "Failed to call onKeyguardExitResult()", e);
1967             }
1968 
1969             mExitSecureCallback = null;
1970 
1971             // after succesfully exiting securely, no need to reshow
1972             // the keyguard when they've released the lock
1973             mExternallyEnabled = true;
1974             mNeedToReshowWhenReenabled = false;
1975             updateInputRestricted();
1976         }
1977 
1978         handleHide();
1979         mUpdateMonitor.clearBiometricRecognized();
1980         Trace.endSection();
1981     }
1982 
sendUserPresentBroadcast()1983     private void sendUserPresentBroadcast() {
1984         synchronized (this) {
1985             if (mBootCompleted) {
1986                 int currentUserId = KeyguardUpdateMonitor.getCurrentUser();
1987                 final UserHandle currentUser = new UserHandle(currentUserId);
1988                 final UserManager um = (UserManager) mContext.getSystemService(
1989                         Context.USER_SERVICE);
1990                 mUiBgExecutor.execute(() -> {
1991                     for (int profileId : um.getProfileIdsWithDisabled(currentUser.getIdentifier())) {
1992                         mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, UserHandle.of(profileId));
1993                     }
1994                     getLockPatternUtils().userPresent(currentUserId);
1995                 });
1996             } else {
1997                 mBootSendUserPresent = true;
1998             }
1999         }
2000     }
2001 
2002     /**
2003      * @see #keyguardDone
2004      * @see #KEYGUARD_DONE_DRAWING
2005      */
handleKeyguardDoneDrawing()2006     private void handleKeyguardDoneDrawing() {
2007         Trace.beginSection("KeyguardViewMediator#handleKeyguardDoneDrawing");
2008         synchronized(this) {
2009             if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
2010             if (mWaitingUntilKeyguardVisible) {
2011                 if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
2012                 mWaitingUntilKeyguardVisible = false;
2013                 notifyAll();
2014 
2015                 // there will usually be two of these sent, one as a timeout, and one
2016                 // as a result of the callback, so remove any remaining messages from
2017                 // the queue
2018                 mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
2019             }
2020         }
2021         Trace.endSection();
2022     }
2023 
playSounds(boolean locked)2024     private void playSounds(boolean locked) {
2025         playSound(locked ? mLockSoundId : mUnlockSoundId);
2026     }
2027 
playSound(int soundId)2028     private void playSound(int soundId) {
2029         if (soundId == 0) return;
2030         final ContentResolver cr = mContext.getContentResolver();
2031         if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
2032 
2033             mLockSounds.stop(mLockSoundStreamId);
2034             // Init mAudioManager
2035             if (mAudioManager == null) {
2036                 mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
2037                 if (mAudioManager == null) return;
2038                 mUiSoundsStreamType = mAudioManager.getUiSoundsStreamType();
2039             }
2040 
2041             mUiBgExecutor.execute(() -> {
2042                 // If the stream is muted, don't play the sound
2043                 if (mAudioManager.isStreamMute(mUiSoundsStreamType)) return;
2044 
2045                 int id = mLockSounds.play(soundId,
2046                         mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
2047                 synchronized (this) {
2048                     mLockSoundStreamId = id;
2049                 }
2050             });
2051 
2052         }
2053     }
2054 
playTrustedSound()2055     private void playTrustedSound() {
2056         playSound(mTrustedSoundId);
2057     }
2058 
updateActivityLockScreenState(boolean showing, boolean aodShowing)2059     private void updateActivityLockScreenState(boolean showing, boolean aodShowing) {
2060         mUiBgExecutor.execute(() -> {
2061             if (DEBUG) {
2062                 Log.d(TAG, "updateActivityLockScreenState(" + showing + ", " + aodShowing + ")");
2063             }
2064             try {
2065                 ActivityTaskManager.getService().setLockScreenShown(showing, aodShowing);
2066             } catch (RemoteException e) {
2067             }
2068         });
2069     }
2070 
2071     /**
2072      * Handle message sent by {@link #showLocked}.
2073      * @see #SHOW
2074      */
handleShow(Bundle options)2075     private void handleShow(Bundle options) {
2076         Trace.beginSection("KeyguardViewMediator#handleShow");
2077         final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
2078         if (mLockPatternUtils.isSecure(currentUser)) {
2079             mLockPatternUtils.getDevicePolicyManager().reportKeyguardSecured(currentUser);
2080         }
2081         synchronized (KeyguardViewMediator.this) {
2082             if (!mSystemReady) {
2083                 if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
2084                 return;
2085             } else {
2086                 if (DEBUG) Log.d(TAG, "handleShow");
2087             }
2088 
2089             mHiding = false;
2090             mKeyguardExitAnimationRunner = null;
2091             mWakeAndUnlocking = false;
2092             mPendingLock = false;
2093             setShowingLocked(true);
2094             mKeyguardViewControllerLazy.get().show(options);
2095             resetKeyguardDonePendingLocked();
2096             mHideAnimationRun = false;
2097             adjustStatusBarLocked();
2098             userActivity();
2099             mUpdateMonitor.setKeyguardGoingAway(false);
2100             mKeyguardViewControllerLazy.get().setKeyguardGoingAwayState(false);
2101             mShowKeyguardWakeLock.release();
2102         }
2103         mKeyguardDisplayManager.show();
2104 
2105         // schedule 4hr idle timeout after which non-strong biometrics (i.e. weak or convenience
2106         // biometric) can't be used to unlock device until unlocking with strong biometric or
2107         // primary auth (i.e. PIN/pattern/password)
2108         mLockPatternUtils.scheduleNonStrongBiometricIdleTimeout(
2109                 KeyguardUpdateMonitor.getCurrentUser());
2110 
2111         Trace.endSection();
2112     }
2113 
2114     private final Runnable mKeyguardGoingAwayRunnable = new Runnable() {
2115         @Override
2116         public void run() {
2117             Trace.beginSection("KeyguardViewMediator.mKeyGuardGoingAwayRunnable");
2118             if (DEBUG) Log.d(TAG, "keyguardGoingAway");
2119             mKeyguardViewControllerLazy.get().keyguardGoingAway();
2120 
2121             int flags = 0;
2122             if (mKeyguardViewControllerLazy.get().shouldDisableWindowAnimationsForUnlock()
2123                     || mWakeAndUnlocking && !mWallpaperSupportsAmbientMode) {
2124                 flags |= WindowManagerPolicyConstants
2125                         .KEYGUARD_GOING_AWAY_FLAG_NO_WINDOW_ANIMATIONS;
2126             }
2127             if (mKeyguardViewControllerLazy.get().isGoingToNotificationShade()
2128                     || mWakeAndUnlocking && mWallpaperSupportsAmbientMode) {
2129                 // When the wallpaper supports ambient mode, the scrim isn't fully opaque during
2130                 // wake and unlock and we should fade in the app on top of the wallpaper
2131                 flags |= WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_TO_SHADE;
2132             }
2133             if (mKeyguardViewControllerLazy.get().isUnlockWithWallpaper()) {
2134                 flags |= KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER;
2135             }
2136             if (mKeyguardViewControllerLazy.get().shouldSubtleWindowAnimationsForUnlock()) {
2137                 flags |= WindowManagerPolicyConstants
2138                         .KEYGUARD_GOING_AWAY_FLAG_SUBTLE_WINDOW_ANIMATIONS;
2139             }
2140 
2141             mUpdateMonitor.setKeyguardGoingAway(true);
2142             mKeyguardViewControllerLazy.get().setKeyguardGoingAwayState(true);
2143 
2144             // Don't actually hide the Keyguard at the moment, wait for window
2145             // manager until it tells us it's safe to do so with
2146             // startKeyguardExitAnimation.
2147             // Posting to mUiOffloadThread to ensure that calls to ActivityTaskManager will be in
2148             // order.
2149             final int keyguardFlag = flags;
2150             mUiBgExecutor.execute(() -> {
2151                 try {
2152                     ActivityTaskManager.getService().keyguardGoingAway(keyguardFlag);
2153                 } catch (RemoteException e) {
2154                     Log.e(TAG, "Error while calling WindowManager", e);
2155                 }
2156             });
2157             Trace.endSection();
2158         }
2159     };
2160 
2161     private final Runnable mHideAnimationFinishedRunnable = () -> {
2162         Log.e(TAG, "mHideAnimationFinishedRunnable#run");
2163         mHideAnimationRunning = false;
2164         tryKeyguardDone();
2165     };
2166 
2167     /**
2168      * Handle message sent by {@link #hideLocked()}
2169      * @see #HIDE
2170      */
handleHide()2171     private void handleHide() {
2172         Trace.beginSection("KeyguardViewMediator#handleHide");
2173 
2174         // It's possible that the device was unlocked in a dream state. It's time to wake up.
2175         if (mAodShowing) {
2176             PowerManager pm = mContext.getSystemService(PowerManager.class);
2177             pm.wakeUp(SystemClock.uptimeMillis(), PowerManager.WAKE_REASON_GESTURE,
2178                     "com.android.systemui:BOUNCER_DOZING");
2179         }
2180 
2181         synchronized (KeyguardViewMediator.this) {
2182             if (DEBUG) Log.d(TAG, "handleHide");
2183 
2184             if (mustNotUnlockCurrentUser()) {
2185                 // In split system user mode, we never unlock system user. The end user has to
2186                 // switch to another user.
2187                 // TODO: We should stop it early by disabling the swipe up flow. Right now swipe up
2188                 // still completes and makes the screen blank.
2189                 if (DEBUG) Log.d(TAG, "Split system user, quit unlocking.");
2190                 mKeyguardExitAnimationRunner = null;
2191                 return;
2192             }
2193             mHiding = true;
2194 
2195             if (mShowing && !mOccluded) {
2196                 mKeyguardGoingAwayRunnable.run();
2197             } else {
2198                 // TODO(bc-unlock): Fill parameters
2199                 handleStartKeyguardExitAnimation(
2200                         SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
2201                         mHideAnimation.getDuration(), null /* apps */,  null /* wallpapers */,
2202                         null /* nonApps */, null /* finishedCallback */);
2203             }
2204         }
2205         Trace.endSection();
2206     }
2207 
handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration, RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers, RemoteAnimationTarget[] nonApps, IRemoteAnimationFinishedCallback finishedCallback)2208     private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration,
2209             RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers,
2210             RemoteAnimationTarget[] nonApps, IRemoteAnimationFinishedCallback finishedCallback) {
2211         Trace.beginSection("KeyguardViewMediator#handleStartKeyguardExitAnimation");
2212         if (DEBUG) Log.d(TAG, "handleStartKeyguardExitAnimation startTime=" + startTime
2213                 + " fadeoutDuration=" + fadeoutDuration);
2214         synchronized (KeyguardViewMediator.this) {
2215 
2216             // Tell ActivityManager that we canceled the keyguard animation if
2217             // handleStartKeyguardExitAnimation was called but we're not hiding the keyguard, unless
2218             // we're animating the surface behind the keyguard and will be hiding the keyguard
2219             // shortly.
2220             if (!mHiding
2221                     && !mSurfaceBehindRemoteAnimationRequested
2222                     && !mKeyguardStateController.isFlingingToDismissKeyguardDuringSwipeGesture()) {
2223                 if (finishedCallback != null) {
2224                     // There will not execute animation, send a finish callback to ensure the remote
2225                     // animation won't hanging there.
2226                     try {
2227                         finishedCallback.onAnimationFinished();
2228                     } catch (RemoteException e) {
2229                         Slog.w(TAG, "Failed to call onAnimationFinished", e);
2230                     }
2231                 }
2232                 setShowingLocked(mShowing, true /* force */);
2233                 return;
2234             }
2235             mHiding = false;
2236             IRemoteAnimationRunner runner = mKeyguardExitAnimationRunner;
2237             mKeyguardExitAnimationRunner = null;
2238 
2239             if (mWakeAndUnlocking && mDrawnCallback != null) {
2240 
2241                 // Hack level over 9000: To speed up wake-and-unlock sequence, force it to report
2242                 // the next draw from here so we don't have to wait for window manager to signal
2243                 // this to our ViewRootImpl.
2244                 mKeyguardViewControllerLazy.get().getViewRootImpl().setReportNextDraw();
2245                 notifyDrawn(mDrawnCallback);
2246                 mDrawnCallback = null;
2247             }
2248 
2249             LatencyTracker.getInstance(mContext)
2250                     .onActionEnd(LatencyTracker.ACTION_LOCKSCREEN_UNLOCK);
2251 
2252             if (KeyguardService.sEnableRemoteKeyguardGoingAwayAnimation && runner != null
2253                     && finishedCallback != null) {
2254                 // Wrap finishedCallback to clean up the keyguard state once the animation is done.
2255                 IRemoteAnimationFinishedCallback callback =
2256                         new IRemoteAnimationFinishedCallback() {
2257                             @Override
2258                             public void onAnimationFinished() throws RemoteException {
2259                                 try {
2260                                     finishedCallback.onAnimationFinished();
2261                                 } catch (RemoteException e) {
2262                                     Slog.w(TAG, "Failed to call onAnimationFinished", e);
2263                                 }
2264                                 onKeyguardExitFinished();
2265                                 mKeyguardViewControllerLazy.get().hide(0 /* startTime */,
2266                                         0 /* fadeoutDuration */);
2267                                 InteractionJankMonitor.getInstance()
2268                                         .end(CUJ_LOCKSCREEN_UNLOCK_ANIMATION);
2269                             }
2270 
2271                             @Override
2272                             public IBinder asBinder() {
2273                                 return finishedCallback.asBinder();
2274                             }
2275                         };
2276                 try {
2277                     InteractionJankMonitor.getInstance().begin(
2278                             createInteractionJankMonitorConf("RunRemoteAnimation"));
2279                     runner.onAnimationStart(WindowManager.TRANSIT_KEYGUARD_GOING_AWAY, apps,
2280                             wallpapers, nonApps, callback);
2281                 } catch (RemoteException e) {
2282                     Slog.w(TAG, "Failed to call onAnimationStart", e);
2283                 }
2284 
2285             // When remaining on the shade, there's no need to do a fancy remote animation,
2286             // it will dismiss the panel in that case.
2287             } else if (KeyguardService.sEnableRemoteKeyguardGoingAwayAnimation
2288                     && !mStatusBarStateController.leaveOpenOnKeyguardHide()
2289                     && apps != null && apps.length > 0) {
2290                 mSurfaceBehindRemoteAnimationFinishedCallback = finishedCallback;
2291                 mSurfaceBehindRemoteAnimationRunning = true;
2292 
2293                 InteractionJankMonitor.getInstance().begin(
2294                         createInteractionJankMonitorConf("DismissPanel"));
2295 
2296                 // Pass the surface and metadata to the unlock animation controller.
2297                 mKeyguardUnlockAnimationControllerLazy.get().notifyStartKeyguardExitAnimation(
2298                         apps[0], startTime, mSurfaceBehindRemoteAnimationRequested);
2299             } else {
2300                 InteractionJankMonitor.getInstance().begin(
2301                         createInteractionJankMonitorConf("RemoteAnimationDisabled"));
2302 
2303                 mKeyguardViewControllerLazy.get().hide(startTime, fadeoutDuration);
2304 
2305                 // TODO(bc-animation): When remote animation is enabled for keyguard exit animation,
2306                 // apps, wallpapers and finishedCallback are set to non-null. nonApps is not yet
2307                 // supported, so it's always null.
2308                 mContext.getMainExecutor().execute(() -> {
2309                     if (finishedCallback == null) {
2310                         InteractionJankMonitor.getInstance().end(CUJ_LOCKSCREEN_UNLOCK_ANIMATION);
2311                         return;
2312                     }
2313 
2314                     // TODO(bc-unlock): Sample animation, just to apply alpha animation on the app.
2315                     final SyncRtSurfaceTransactionApplier applier =
2316                             new SyncRtSurfaceTransactionApplier(
2317                                     mKeyguardViewControllerLazy.get().getViewRootImpl().getView());
2318                     final RemoteAnimationTarget primary = apps[0];
2319                     ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
2320                     anim.setDuration(400 /* duration */);
2321                     anim.setInterpolator(Interpolators.LINEAR);
2322                     anim.addUpdateListener((ValueAnimator animation) -> {
2323                         SyncRtSurfaceTransactionApplier.SurfaceParams params =
2324                                 new SyncRtSurfaceTransactionApplier.SurfaceParams.Builder(
2325                                         primary.leash)
2326                                         .withAlpha(animation.getAnimatedFraction())
2327                                         .build();
2328                         applier.scheduleApply(params);
2329                     });
2330                     anim.addListener(new AnimatorListenerAdapter() {
2331                         @Override
2332                         public void onAnimationEnd(Animator animation) {
2333                             try {
2334                                 finishedCallback.onAnimationFinished();
2335                             } catch (RemoteException e) {
2336                                 Slog.e(TAG, "RemoteException");
2337                             } finally {
2338                                 InteractionJankMonitor.getInstance()
2339                                         .end(CUJ_LOCKSCREEN_UNLOCK_ANIMATION);
2340                             }
2341                         }
2342 
2343                         @Override
2344                         public void onAnimationCancel(Animator animation) {
2345                             try {
2346                                 finishedCallback.onAnimationFinished();
2347                             } catch (RemoteException e) {
2348                                 Slog.e(TAG, "RemoteException");
2349                             } finally {
2350                                 InteractionJankMonitor.getInstance()
2351                                         .cancel(CUJ_LOCKSCREEN_UNLOCK_ANIMATION);
2352                             }
2353                         }
2354                     });
2355                     anim.start();
2356                 });
2357 
2358                 onKeyguardExitFinished();
2359             }
2360         }
2361 
2362         Trace.endSection();
2363     }
2364 
onKeyguardExitFinished()2365     private void onKeyguardExitFinished() {
2366         // only play "unlock" noises if not on a call (since the incall UI
2367         // disables the keyguard)
2368         if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
2369             playSounds(false);
2370         }
2371 
2372         setShowingLocked(false);
2373         mWakeAndUnlocking = false;
2374         mDismissCallbackRegistry.notifyDismissSucceeded();
2375         resetKeyguardDonePendingLocked();
2376         mHideAnimationRun = false;
2377         adjustStatusBarLocked();
2378         sendUserPresentBroadcast();
2379     }
2380 
createInteractionJankMonitorConf(String tag)2381     private Configuration.Builder createInteractionJankMonitorConf(String tag) {
2382         return Configuration.Builder.withView(CUJ_LOCKSCREEN_UNLOCK_ANIMATION,
2383                 mKeyguardViewControllerLazy.get().getViewRootImpl().getView())
2384                 .setTag(tag);
2385     }
2386 
2387     /**
2388      * Whether we're currently animating between the keyguard and the app/launcher surface behind
2389      * it, or will be shortly (which happens if we started a fling to dismiss the keyguard).
2390      */
isAnimatingBetweenKeyguardAndSurfaceBehindOrWillBe()2391     public boolean isAnimatingBetweenKeyguardAndSurfaceBehindOrWillBe() {
2392         return mSurfaceBehindRemoteAnimationRunning
2393                 || mKeyguardStateController.isFlingingToDismissKeyguard();
2394     }
2395 
2396     /**
2397      * Called if the keyguard exit animation has been cancelled and we should dismiss to the
2398      * keyguard.
2399      *
2400      * This can happen due to the system cancelling the RemoteAnimation (due to a timeout, a new
2401      * app transition before finishing the current RemoteAnimation).
2402      */
handleCancelKeyguardExitAnimation()2403     private void handleCancelKeyguardExitAnimation() {
2404         showSurfaceBehindKeyguard();
2405         onKeyguardExitRemoteAnimationFinished(true /* cancelled */);
2406     }
2407 
2408     /**
2409      * Called when we're done running the keyguard exit animation.
2410      *
2411      * This will call {@link #mSurfaceBehindRemoteAnimationFinishedCallback} to let WM know that
2412      * we're done with the RemoteAnimation, actually hide the keyguard, and clean up state related
2413      * to the keyguard exit animation.
2414      *
2415      * @param cancelled {@code true} if the animation was cancelled before it finishes.
2416      */
onKeyguardExitRemoteAnimationFinished(boolean cancelled)2417     public void onKeyguardExitRemoteAnimationFinished(boolean cancelled) {
2418         if (!mSurfaceBehindRemoteAnimationRunning && !mSurfaceBehindRemoteAnimationRequested) {
2419             return;
2420         }
2421 
2422         // Block the panel from expanding, in case we were doing a swipe to dismiss gesture.
2423         mKeyguardViewControllerLazy.get().blockPanelExpansionFromCurrentTouch();
2424         final boolean wasShowing = mShowing;
2425         onKeyguardExitFinished();
2426 
2427         if (mKeyguardStateController.isDismissingFromSwipe() || wasShowing) {
2428             mKeyguardUnlockAnimationControllerLazy.get().hideKeyguardViewAfterRemoteAnimation();
2429         }
2430 
2431         finishSurfaceBehindRemoteAnimation(cancelled);
2432         mSurfaceBehindRemoteAnimationRequested = false;
2433         mKeyguardUnlockAnimationControllerLazy.get().notifyFinishedKeyguardExitAnimation();
2434         InteractionJankMonitor.getInstance().end(CUJ_LOCKSCREEN_UNLOCK_ANIMATION);
2435     }
2436 
2437     /**
2438      * Tells the ActivityTaskManager that the keyguard is planning to go away, so that it makes the
2439      * surface behind the keyguard visible and calls {@link #handleStartKeyguardExitAnimation} with
2440      * the parameters needed to animate the surface.
2441      */
showSurfaceBehindKeyguard()2442     public void showSurfaceBehindKeyguard() {
2443         mSurfaceBehindRemoteAnimationRequested = true;
2444 
2445         try {
2446             ActivityTaskManager.getService().keyguardGoingAway(
2447                     WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_NO_WINDOW_ANIMATIONS
2448                             | WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER);
2449         } catch (RemoteException e) {
2450             mSurfaceBehindRemoteAnimationRequested = false;
2451             e.printStackTrace();
2452         }
2453     }
2454 
2455     /** Hides the surface behind the keyguard by re-showing the keyguard/activity lock screen. */
hideSurfaceBehindKeyguard()2456     public void hideSurfaceBehindKeyguard() {
2457         mSurfaceBehindRemoteAnimationRequested = false;
2458 
2459         if (mShowing) {
2460             setShowingLocked(true, true);
2461         }
2462     }
2463 
2464     /**
2465      * Whether we have requested to show the surface behind the keyguard, even if it's not yet
2466      * visible due to IPC delay.
2467      */
requestedShowSurfaceBehindKeyguard()2468     public boolean requestedShowSurfaceBehindKeyguard() {
2469         return mSurfaceBehindRemoteAnimationRequested;
2470     }
2471 
2472     /** If it's running, finishes the RemoteAnimation on the surface behind the keyguard. */
finishSurfaceBehindRemoteAnimation(boolean cancelled)2473     public void finishSurfaceBehindRemoteAnimation(boolean cancelled) {
2474         mSurfaceBehindRemoteAnimationRunning = false;
2475 
2476         if (mSurfaceBehindRemoteAnimationFinishedCallback != null) {
2477             try {
2478                 mSurfaceBehindRemoteAnimationFinishedCallback.onAnimationFinished();
2479                 mSurfaceBehindRemoteAnimationFinishedCallback = null;
2480             } catch (RemoteException e) {
2481                 e.printStackTrace();
2482             }
2483         }
2484     }
2485 
adjustStatusBarLocked()2486     private void adjustStatusBarLocked() {
2487         adjustStatusBarLocked(false /* forceHideHomeRecentsButtons */,
2488                 false /* forceClearFlags */);
2489     }
2490 
adjustStatusBarLocked(boolean forceHideHomeRecentsButtons, boolean forceClearFlags)2491     private void adjustStatusBarLocked(boolean forceHideHomeRecentsButtons,
2492             boolean forceClearFlags) {
2493         if (mStatusBarManager == null) {
2494             mStatusBarManager = (StatusBarManager)
2495                     mContext.getSystemService(Context.STATUS_BAR_SERVICE);
2496         }
2497 
2498         if (mStatusBarManager == null) {
2499             Log.w(TAG, "Could not get status bar manager");
2500         } else {
2501             // Disable aspects of the system/status/navigation bars that must not be re-enabled by
2502             // windows that appear on top, ever
2503             int flags = StatusBarManager.DISABLE_NONE;
2504 
2505             // TODO (b/155663717) After restart, status bar will not properly hide home button
2506             //  unless disable is called to show un-hide it once first
2507             if (forceClearFlags) {
2508                 mStatusBarManager.disable(flags);
2509             }
2510 
2511             if (forceHideHomeRecentsButtons || isShowingAndNotOccluded()) {
2512                 if (!mShowHomeOverLockscreen || !mInGestureNavigationMode) {
2513                     flags |= StatusBarManager.DISABLE_HOME;
2514                 }
2515                 flags |= StatusBarManager.DISABLE_RECENT;
2516             }
2517 
2518             if (DEBUG) {
2519                 Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
2520                         + " isSecure=" + isSecure() + " force=" + forceHideHomeRecentsButtons
2521                         +  " --> flags=0x" + Integer.toHexString(flags));
2522             }
2523 
2524             mStatusBarManager.disable(flags);
2525         }
2526     }
2527 
2528     /**
2529      * Handle message sent by {@link #resetStateLocked}
2530      * @see #RESET
2531      */
handleReset()2532     private void handleReset() {
2533         synchronized (KeyguardViewMediator.this) {
2534             if (DEBUG) Log.d(TAG, "handleReset");
2535             mKeyguardViewControllerLazy.get().reset(true /* hideBouncerWhenShowing */);
2536         }
2537     }
2538 
2539     /**
2540      * Handle message sent by {@link #verifyUnlock}
2541      * @see #VERIFY_UNLOCK
2542      */
handleVerifyUnlock()2543     private void handleVerifyUnlock() {
2544         Trace.beginSection("KeyguardViewMediator#handleVerifyUnlock");
2545         synchronized (KeyguardViewMediator.this) {
2546             if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
2547             setShowingLocked(true);
2548             mKeyguardViewControllerLazy.get().dismissAndCollapse();
2549         }
2550         Trace.endSection();
2551     }
2552 
handleNotifyStartedGoingToSleep()2553     private void handleNotifyStartedGoingToSleep() {
2554         synchronized (KeyguardViewMediator.this) {
2555             if (DEBUG) Log.d(TAG, "handleNotifyStartedGoingToSleep");
2556             mKeyguardViewControllerLazy.get().onStartedGoingToSleep();
2557         }
2558     }
2559 
2560     /**
2561      * Handle message sent by {@link #notifyFinishedGoingToSleep()}
2562      * @see #NOTIFY_FINISHED_GOING_TO_SLEEP
2563      */
handleNotifyFinishedGoingToSleep()2564     private void handleNotifyFinishedGoingToSleep() {
2565         synchronized (KeyguardViewMediator.this) {
2566             if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep");
2567             mKeyguardViewControllerLazy.get().onFinishedGoingToSleep();
2568         }
2569     }
2570 
handleNotifyStartedWakingUp()2571     private void handleNotifyStartedWakingUp() {
2572         Trace.beginSection("KeyguardViewMediator#handleMotifyStartedWakingUp");
2573         synchronized (KeyguardViewMediator.this) {
2574             if (DEBUG) Log.d(TAG, "handleNotifyWakingUp");
2575             mKeyguardViewControllerLazy.get().onStartedWakingUp();
2576         }
2577         Trace.endSection();
2578     }
2579 
handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback)2580     private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) {
2581         Trace.beginSection("KeyguardViewMediator#handleNotifyScreenTurningOn");
2582         synchronized (KeyguardViewMediator.this) {
2583             if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn");
2584 
2585             if (mUnfoldLightRevealAnimation.isPresent()) {
2586                 mPendingDrawnTasks.set(2); // unfold overlay and keyguard drawn
2587 
2588                 mUnfoldLightRevealAnimation.get()
2589                         .onScreenTurningOn(() -> {
2590                             if (mPendingDrawnTasks.decrementAndGet() == 0) {
2591                                 try {
2592                                     callback.onDrawn();
2593                                 } catch (RemoteException e) {
2594                                     Slog.w(TAG, "Exception calling onDrawn():", e);
2595                                 }
2596                             }
2597                         });
2598             } else {
2599                 mPendingDrawnTasks.set(1); // only keyguard drawn
2600             }
2601 
2602             mKeyguardViewControllerLazy.get().onScreenTurningOn();
2603             if (callback != null) {
2604                 if (mWakeAndUnlocking) {
2605                     mDrawnCallback = callback;
2606                 } else {
2607                     notifyDrawn(callback);
2608                 }
2609             }
2610         }
2611         Trace.endSection();
2612     }
2613 
handleNotifyScreenTurnedOn()2614     private void handleNotifyScreenTurnedOn() {
2615         Trace.beginSection("KeyguardViewMediator#handleNotifyScreenTurnedOn");
2616         synchronized (this) {
2617             if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOn");
2618             mKeyguardViewControllerLazy.get().onScreenTurnedOn();
2619         }
2620         Trace.endSection();
2621     }
2622 
handleNotifyScreenTurnedOff()2623     private void handleNotifyScreenTurnedOff() {
2624         synchronized (this) {
2625             if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOff");
2626             mDrawnCallback = null;
2627         }
2628     }
2629 
notifyDrawn(final IKeyguardDrawnCallback callback)2630     private void notifyDrawn(final IKeyguardDrawnCallback callback) {
2631         Trace.beginSection("KeyguardViewMediator#notifyDrawn");
2632         if (mPendingDrawnTasks.decrementAndGet() == 0) {
2633             try {
2634                 callback.onDrawn();
2635             } catch (RemoteException e) {
2636                 Slog.w(TAG, "Exception calling onDrawn():", e);
2637             }
2638         }
2639         Trace.endSection();
2640     }
2641 
resetKeyguardDonePendingLocked()2642     private void resetKeyguardDonePendingLocked() {
2643         mKeyguardDonePending = false;
2644         mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT);
2645     }
2646 
2647     @Override
onBootCompleted()2648     public void onBootCompleted() {
2649         synchronized (this) {
2650             if (mContext.getResources().getBoolean(
2651                     com.android.internal.R.bool.config_guestUserAutoCreated)) {
2652                 // TODO(b/191067027): Move post-boot guest creation to system_server
2653                 mUserSwitcherController.schedulePostBootGuestCreation();
2654             }
2655             mBootCompleted = true;
2656             adjustStatusBarLocked(false, true);
2657             if (mBootSendUserPresent) {
2658                 sendUserPresentBroadcast();
2659             }
2660         }
2661     }
2662 
onWakeAndUnlocking()2663     public void onWakeAndUnlocking() {
2664         Trace.beginSection("KeyguardViewMediator#onWakeAndUnlocking");
2665         mWakeAndUnlocking = true;
2666         keyguardDone();
2667         Trace.endSection();
2668     }
2669 
2670     /**
2671      * Registers the StatusBar to which the Keyguard View is mounted.
2672      *
2673      * @param statusBar
2674      * @param panelView
2675      * @param biometricUnlockController
2676      * @param notificationContainer
2677      * @param bypassController
2678      * @return the View Controller for the Keyguard View this class is mediating.
2679      */
registerStatusBar(StatusBar statusBar, NotificationPanelViewController panelView, @Nullable PanelExpansionStateManager panelExpansionStateManager, BiometricUnlockController biometricUnlockController, View notificationContainer, KeyguardBypassController bypassController)2680     public KeyguardViewController registerStatusBar(StatusBar statusBar,
2681             NotificationPanelViewController panelView,
2682             @Nullable PanelExpansionStateManager panelExpansionStateManager,
2683             BiometricUnlockController biometricUnlockController,
2684             View notificationContainer, KeyguardBypassController bypassController) {
2685         mKeyguardViewControllerLazy.get().registerStatusBar(
2686                 statusBar,
2687                 panelView,
2688                 panelExpansionStateManager,
2689                 biometricUnlockController,
2690                 notificationContainer,
2691                 bypassController);
2692         return mKeyguardViewControllerLazy.get();
2693     }
2694 
2695     /**
2696      * Notifies to System UI that the activity behind has now been drawn and it's safe to remove
2697      * the wallpaper and keyguard flag, and WindowManager has started running keyguard exit
2698      * animation.
2699      *
2700      * @param startTime the start time of the animation in uptime milliseconds. Deprecated.
2701      * @param fadeoutDuration the duration of the exit animation, in milliseconds Deprecated.
2702      * @deprecated Will be migrate to remote animation soon.
2703      */
2704     @Deprecated
startKeyguardExitAnimation(long startTime, long fadeoutDuration)2705     public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
2706         startKeyguardExitAnimation(0, startTime, fadeoutDuration, null, null, null, null);
2707     }
2708 
2709     /**
2710      * Notifies to System UI that the activity behind has now been drawn and it's safe to remove
2711      * the wallpaper and keyguard flag, and System UI should start running keyguard exit animation.
2712      *
2713      * @param apps The list of apps to animate.
2714      * @param wallpapers The list of wallpapers to animate.
2715      * @param nonApps The list of non-app windows such as Bubbles to animate.
2716      * @param finishedCallback The callback to invoke when the animation is finished.
2717      */
startKeyguardExitAnimation(@indowManager.TransitionOldType int transit, RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers, RemoteAnimationTarget[] nonApps, IRemoteAnimationFinishedCallback finishedCallback)2718     public void startKeyguardExitAnimation(@WindowManager.TransitionOldType int transit,
2719             RemoteAnimationTarget[] apps,
2720             RemoteAnimationTarget[] wallpapers, RemoteAnimationTarget[] nonApps,
2721             IRemoteAnimationFinishedCallback finishedCallback) {
2722         startKeyguardExitAnimation(transit, 0, 0, apps, wallpapers, nonApps, finishedCallback);
2723     }
2724 
2725     /**
2726      * Notifies to System UI that the activity behind has now been drawn and it's safe to remove
2727      * the wallpaper and keyguard flag, and start running keyguard exit animation.
2728      *
2729      * @param startTime the start time of the animation in uptime milliseconds. Deprecated.
2730      * @param fadeoutDuration the duration of the exit animation, in milliseconds Deprecated.
2731      * @param apps The list of apps to animate.
2732      * @param wallpapers The list of wallpapers to animate.
2733      * @param nonApps The list of non-app windows such as Bubbles to animate.
2734      * @param finishedCallback The callback to invoke when the animation is finished.
2735      */
startKeyguardExitAnimation(@indowManager.TransitionOldType int transit, long startTime, long fadeoutDuration, RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers, RemoteAnimationTarget[] nonApps, IRemoteAnimationFinishedCallback finishedCallback)2736     private void startKeyguardExitAnimation(@WindowManager.TransitionOldType int transit,
2737             long startTime, long fadeoutDuration,
2738             RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers,
2739             RemoteAnimationTarget[] nonApps, IRemoteAnimationFinishedCallback finishedCallback) {
2740         Trace.beginSection("KeyguardViewMediator#startKeyguardExitAnimation");
2741         Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
2742                 new StartKeyguardExitAnimParams(transit, startTime, fadeoutDuration, apps,
2743                         wallpapers, nonApps, finishedCallback));
2744         mHandler.sendMessage(msg);
2745         Trace.endSection();
2746     }
2747 
2748     /**
2749      * Cancel the keyguard exit animation, usually because we were swiping to unlock but WM starts
2750      * a new remote animation before finishing the keyguard exit animation.
2751      *
2752      * This will dismiss the keyguard.
2753      */
cancelKeyguardExitAnimation()2754     public void cancelKeyguardExitAnimation() {
2755         Trace.beginSection("KeyguardViewMediator#cancelKeyguardExitAnimation");
2756         Message msg = mHandler.obtainMessage(CANCEL_KEYGUARD_EXIT_ANIM);
2757         mHandler.sendMessage(msg);
2758         Trace.endSection();
2759     }
2760 
onShortPowerPressedGoHome()2761     public void onShortPowerPressedGoHome() {
2762         // do nothing
2763     }
2764 
getViewMediatorCallback()2765     public ViewMediatorCallback getViewMediatorCallback() {
2766         return mViewMediatorCallback;
2767     }
2768 
getLockPatternUtils()2769     public LockPatternUtils getLockPatternUtils() {
2770         return mLockPatternUtils;
2771     }
2772 
2773     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)2774     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2775         pw.print("  mSystemReady: "); pw.println(mSystemReady);
2776         pw.print("  mBootCompleted: "); pw.println(mBootCompleted);
2777         pw.print("  mBootSendUserPresent: "); pw.println(mBootSendUserPresent);
2778         pw.print("  mExternallyEnabled: "); pw.println(mExternallyEnabled);
2779         pw.print("  mShuttingDown: "); pw.println(mShuttingDown);
2780         pw.print("  mNeedToReshowWhenReenabled: "); pw.println(mNeedToReshowWhenReenabled);
2781         pw.print("  mShowing: "); pw.println(mShowing);
2782         pw.print("  mInputRestricted: "); pw.println(mInputRestricted);
2783         pw.print("  mOccluded: "); pw.println(mOccluded);
2784         pw.print("  mDelayedShowingSequence: "); pw.println(mDelayedShowingSequence);
2785         pw.print("  mExitSecureCallback: "); pw.println(mExitSecureCallback);
2786         pw.print("  mDeviceInteractive: "); pw.println(mDeviceInteractive);
2787         pw.print("  mGoingToSleep: "); pw.println(mGoingToSleep);
2788         pw.print("  mHiding: "); pw.println(mHiding);
2789         pw.print("  mDozing: "); pw.println(mDozing);
2790         pw.print("  mAodShowing: "); pw.println(mAodShowing);
2791         pw.print("  mWaitingUntilKeyguardVisible: "); pw.println(mWaitingUntilKeyguardVisible);
2792         pw.print("  mKeyguardDonePending: "); pw.println(mKeyguardDonePending);
2793         pw.print("  mHideAnimationRun: "); pw.println(mHideAnimationRun);
2794         pw.print("  mPendingReset: "); pw.println(mPendingReset);
2795         pw.print("  mPendingLock: "); pw.println(mPendingLock);
2796         pw.print("  mPendingDrawnTasks: "); pw.println(mPendingDrawnTasks.get());
2797         pw.print("  mWakeAndUnlocking: "); pw.println(mWakeAndUnlocking);
2798         pw.print("  mDrawnCallback: "); pw.println(mDrawnCallback);
2799     }
2800 
2801     /**
2802      * @param dozing true when AOD - or ambient mode - is showing.
2803      */
setDozing(boolean dozing)2804     public void setDozing(boolean dozing) {
2805         if (dozing == mDozing) {
2806             return;
2807         }
2808         mDozing = dozing;
2809         if (!dozing) {
2810             mAnimatingScreenOff = false;
2811         }
2812 
2813         // Don't hide the keyguard due to a doze change if there's a lock pending, because we're
2814         // just going to show it again.
2815         // If the device is not capable of controlling the screen off animation, SysUI needs to
2816         // update lock screen state in ATMS here, otherwise ATMS tries to resume activities when
2817         // enabling doze state.
2818         if (mShowing || !mPendingLock || !mDozeParameters.canControlUnlockedScreenOff()) {
2819             setShowingLocked(mShowing);
2820         }
2821     }
2822 
2823     @Override
onDozeAmountChanged(float linear, float interpolated)2824     public void onDozeAmountChanged(float linear, float interpolated) {
2825         // If we were animating the screen off, and we've completed the doze animation (doze amount
2826         // is 1f), then show the activity lock screen.
2827         if (mAnimatingScreenOff && mDozing && linear == 1f) {
2828             mAnimatingScreenOff = false;
2829             setShowingLocked(mShowing, true);
2830         }
2831     }
2832 
2833     /**
2834      * @param pulsing true when device temporarily wakes up to display an incoming notification.
2835      */
setPulsing(boolean pulsing)2836     public void setPulsing(boolean pulsing) {
2837         mPulsing = pulsing;
2838     }
2839 
2840     /**
2841      * Set if the wallpaper supports ambient mode. This is used to trigger the right animation.
2842      * In case it does support it, we have to fade in the incoming app, otherwise we'll reveal it
2843      * with the light reveal scrim.
2844      */
setWallpaperSupportsAmbientMode(boolean supportsAmbientMode)2845     public void setWallpaperSupportsAmbientMode(boolean supportsAmbientMode) {
2846         mWallpaperSupportsAmbientMode = supportsAmbientMode;
2847     }
2848 
2849     private static class StartKeyguardExitAnimParams {
2850 
2851         @WindowManager.TransitionOldType int mTransit;
2852         long startTime;
2853         long fadeoutDuration;
2854         RemoteAnimationTarget[] mApps;
2855         RemoteAnimationTarget[] mWallpapers;
2856         RemoteAnimationTarget[] mNonApps;
2857         IRemoteAnimationFinishedCallback mFinishedCallback;
2858 
StartKeyguardExitAnimParams(@indowManager.TransitionOldType int transit, long startTime, long fadeoutDuration, RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers, RemoteAnimationTarget[] nonApps, IRemoteAnimationFinishedCallback finishedCallback)2859         private StartKeyguardExitAnimParams(@WindowManager.TransitionOldType int transit,
2860                 long startTime, long fadeoutDuration,
2861                 RemoteAnimationTarget[] apps, RemoteAnimationTarget[] wallpapers,
2862                 RemoteAnimationTarget[] nonApps,
2863                 IRemoteAnimationFinishedCallback finishedCallback) {
2864             this.mTransit = transit;
2865             this.startTime = startTime;
2866             this.fadeoutDuration = fadeoutDuration;
2867             this.mApps = apps;
2868             this.mWallpapers = wallpapers;
2869             this.mNonApps = nonApps;
2870             this.mFinishedCallback = finishedCallback;
2871         }
2872     }
2873 
setShowingLocked(boolean showing)2874     void setShowingLocked(boolean showing) {
2875         setShowingLocked(showing, false /* forceCallbacks */);
2876     }
2877 
setShowingLocked(boolean showing, boolean forceCallbacks)2878     private void setShowingLocked(boolean showing, boolean forceCallbacks) {
2879         final boolean aodShowing = mDozing && !mWakeAndUnlocking;
2880         final boolean notifyDefaultDisplayCallbacks = showing != mShowing
2881                 || aodShowing != mAodShowing || forceCallbacks;
2882         mShowing = showing;
2883         mAodShowing = aodShowing;
2884         if (notifyDefaultDisplayCallbacks) {
2885             notifyDefaultDisplayCallbacks(showing);
2886             updateActivityLockScreenState(showing, aodShowing);
2887         }
2888     }
2889 
notifyDefaultDisplayCallbacks(boolean showing)2890     private void notifyDefaultDisplayCallbacks(boolean showing) {
2891         // TODO(b/140053364)
2892         whitelistIpcs(() -> {
2893             int size = mKeyguardStateCallbacks.size();
2894             for (int i = size - 1; i >= 0; i--) {
2895                 IKeyguardStateCallback callback = mKeyguardStateCallbacks.get(i);
2896                 try {
2897                     callback.onShowingStateChanged(showing, KeyguardUpdateMonitor.getCurrentUser());
2898                 } catch (RemoteException e) {
2899                     Slog.w(TAG, "Failed to call onShowingStateChanged", e);
2900                     if (e instanceof DeadObjectException) {
2901                         mKeyguardStateCallbacks.remove(callback);
2902                     }
2903                 }
2904             }
2905         });
2906         updateInputRestrictedLocked();
2907         mUiBgExecutor.execute(() -> {
2908             mTrustManager.reportKeyguardShowingChanged();
2909         });
2910     }
2911 
notifyTrustedChangedLocked(boolean trusted)2912     private void notifyTrustedChangedLocked(boolean trusted) {
2913         int size = mKeyguardStateCallbacks.size();
2914         for (int i = size - 1; i >= 0; i--) {
2915             try {
2916                 mKeyguardStateCallbacks.get(i).onTrustedChanged(trusted);
2917             } catch (RemoteException e) {
2918                 Slog.w(TAG, "Failed to call notifyTrustedChangedLocked", e);
2919                 if (e instanceof DeadObjectException) {
2920                     mKeyguardStateCallbacks.remove(i);
2921                 }
2922             }
2923         }
2924     }
2925 
addStateMonitorCallback(IKeyguardStateCallback callback)2926     public void addStateMonitorCallback(IKeyguardStateCallback callback) {
2927         synchronized (this) {
2928             mKeyguardStateCallbacks.add(callback);
2929             try {
2930                 callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure());
2931                 callback.onShowingStateChanged(mShowing, KeyguardUpdateMonitor.getCurrentUser());
2932                 callback.onInputRestrictedStateChanged(mInputRestricted);
2933                 callback.onTrustedChanged(mUpdateMonitor.getUserHasTrust(
2934                         KeyguardUpdateMonitor.getCurrentUser()));
2935             } catch (RemoteException e) {
2936                 Slog.w(TAG, "Failed to call to IKeyguardStateCallback", e);
2937             }
2938         }
2939     }
2940 
2941     private static class DismissMessage {
2942         private final CharSequence mMessage;
2943         private final IKeyguardDismissCallback mCallback;
2944 
DismissMessage(IKeyguardDismissCallback callback, CharSequence message)2945         DismissMessage(IKeyguardDismissCallback callback, CharSequence message) {
2946             mCallback = callback;
2947             mMessage = message;
2948         }
2949 
getCallback()2950         public IKeyguardDismissCallback getCallback() {
2951             return mCallback;
2952         }
2953 
getMessage()2954         public CharSequence getMessage() {
2955             return mMessage;
2956         }
2957     }
2958 }
2959