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