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