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