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