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