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