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