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