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