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