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