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