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