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