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