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