KeyguardViewMediator.java revision 338c6ed5d028d0597247f23de91aadb45087bf82
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            if (strongAuth) {
564                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
565            }
566        }
567
568        @Override
569        public void keyguardDoneDrawing() {
570            Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardDoneDrawing");
571            mHandler.sendEmptyMessage(KEYGUARD_DONE_DRAWING);
572            Trace.endSection();
573        }
574
575        @Override
576        public void setNeedsInput(boolean needsInput) {
577            mStatusBarKeyguardViewManager.setNeedsInput(needsInput);
578        }
579
580        @Override
581        public void keyguardDonePending(boolean strongAuth, int targetUserId) {
582            Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardDonePending");
583            if (targetUserId != ActivityManager.getCurrentUser()) {
584                Trace.endSection();
585                return;
586            }
587
588            mKeyguardDonePending = true;
589            mHideAnimationRun = true;
590            mHideAnimationRunning = true;
591            mStatusBarKeyguardViewManager.startPreHideAnimation(mHideAnimationFinishedRunnable);
592            mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_PENDING_TIMEOUT,
593                    KEYGUARD_DONE_PENDING_TIMEOUT_MS);
594            if (strongAuth) {
595                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
596            }
597            Trace.endSection();
598        }
599
600        @Override
601        public void keyguardGone() {
602            Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#keyguardGone");
603            mKeyguardDisplayManager.hide();
604            Trace.endSection();
605        }
606
607        @Override
608        public void readyForKeyguardDone() {
609            Trace.beginSection("KeyguardViewMediator.mViewMediatorCallback#readyForKeyguardDone");
610            if (mKeyguardDonePending) {
611                mKeyguardDonePending = false;
612                tryKeyguardDone();
613            }
614            Trace.endSection();
615        }
616
617        @Override
618        public void resetKeyguard() {
619            resetStateLocked();
620        }
621
622        @Override
623        public void playTrustedSound() {
624            KeyguardViewMediator.this.playTrustedSound();
625        }
626
627        @Override
628        public boolean isScreenOn() {
629            return mDeviceInteractive;
630        }
631
632        @Override
633        public int getBouncerPromptReason() {
634            int currentUser = ActivityManager.getCurrentUser();
635            boolean trust = mTrustManager.isTrustUsuallyManaged(currentUser);
636            boolean fingerprint = mUpdateMonitor.isUnlockWithFingerprintPossible(currentUser);
637            boolean any = trust || fingerprint;
638            KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
639                    mUpdateMonitor.getStrongAuthTracker();
640            int strongAuth = strongAuthTracker.getStrongAuthForUser(currentUser);
641
642            if (any && !strongAuthTracker.hasUserAuthenticatedSinceBoot()) {
643                return KeyguardSecurityView.PROMPT_REASON_RESTART;
644            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_TIMEOUT) != 0) {
645                return KeyguardSecurityView.PROMPT_REASON_TIMEOUT;
646            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) != 0) {
647                return KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN;
648            } else if (trust && (strongAuth & SOME_AUTH_REQUIRED_AFTER_USER_REQUEST) != 0) {
649                return KeyguardSecurityView.PROMPT_REASON_USER_REQUEST;
650            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_LOCKOUT) != 0) {
651                return KeyguardSecurityView.PROMPT_REASON_AFTER_LOCKOUT;
652            }
653            return KeyguardSecurityView.PROMPT_REASON_NONE;
654        }
655    };
656
657    public void userActivity() {
658        mPM.userActivity(SystemClock.uptimeMillis(), false);
659    }
660
661    boolean mustNotUnlockCurrentUser() {
662        return UserManager.isSplitSystemUser()
663                && KeyguardUpdateMonitor.getCurrentUser() == UserHandle.USER_SYSTEM;
664    }
665
666    private void setupLocked() {
667        mPM = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
668        mTrustManager = (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
669
670        mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
671        mShowKeyguardWakeLock.setReferenceCounted(false);
672
673        IntentFilter filter = new IntentFilter();
674        filter.addAction(DELAYED_KEYGUARD_ACTION);
675        filter.addAction(DELAYED_LOCK_PROFILE_ACTION);
676        filter.addAction(Intent.ACTION_SHUTDOWN);
677        mContext.registerReceiver(mBroadcastReceiver, filter);
678
679        mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
680
681        mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
682
683        mUpdateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
684
685        mLockPatternUtils = new LockPatternUtils(mContext);
686        KeyguardUpdateMonitor.setCurrentUser(ActivityManager.getCurrentUser());
687
688        // Assume keyguard is showing (unless it's disabled) until we know for sure, unless Keyguard
689        // is disabled.
690        if (mContext.getResources().getBoolean(
691                com.android.keyguard.R.bool.config_enableKeyguardService)) {
692            setShowingLocked(!shouldWaitForProvisioning()
693                    && !mLockPatternUtils.isLockScreenDisabled(
694                            KeyguardUpdateMonitor.getCurrentUser()), true /* forceCallbacks */);
695        }
696
697        mStatusBarKeyguardViewManager =
698                SystemUIFactory.getInstance().createStatusBarKeyguardViewManager(mContext,
699                        mViewMediatorCallback, mLockPatternUtils);
700        final ContentResolver cr = mContext.getContentResolver();
701
702        mDeviceInteractive = mPM.isInteractive();
703
704        mLockSounds = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);
705        String soundPath = Settings.Global.getString(cr, Settings.Global.LOCK_SOUND);
706        if (soundPath != null) {
707            mLockSoundId = mLockSounds.load(soundPath, 1);
708        }
709        if (soundPath == null || mLockSoundId == 0) {
710            Log.w(TAG, "failed to load lock sound from " + soundPath);
711        }
712        soundPath = Settings.Global.getString(cr, Settings.Global.UNLOCK_SOUND);
713        if (soundPath != null) {
714            mUnlockSoundId = mLockSounds.load(soundPath, 1);
715        }
716        if (soundPath == null || mUnlockSoundId == 0) {
717            Log.w(TAG, "failed to load unlock sound from " + soundPath);
718        }
719        soundPath = Settings.Global.getString(cr, Settings.Global.TRUSTED_SOUND);
720        if (soundPath != null) {
721            mTrustedSoundId = mLockSounds.load(soundPath, 1);
722        }
723        if (soundPath == null || mTrustedSoundId == 0) {
724            Log.w(TAG, "failed to load trusted sound from " + soundPath);
725        }
726
727        int lockSoundDefaultAttenuation = mContext.getResources().getInteger(
728                com.android.internal.R.integer.config_lockSoundVolumeDb);
729        mLockSoundVolume = (float)Math.pow(10, (float)lockSoundDefaultAttenuation/20);
730
731        mHideAnimation = AnimationUtils.loadAnimation(mContext,
732                com.android.internal.R.anim.lock_screen_behind_enter);
733
734        mWorkLockController = new WorkLockActivityController(mContext);
735    }
736
737    @Override
738    public void start() {
739        synchronized (this) {
740            setupLocked();
741        }
742        putComponent(KeyguardViewMediator.class, this);
743    }
744
745    /**
746     * Let us know that the system is ready after startup.
747     */
748    public void onSystemReady() {
749        synchronized (this) {
750            if (DEBUG) Log.d(TAG, "onSystemReady");
751            mSystemReady = true;
752            doKeyguardLocked(null);
753            mUpdateMonitor.registerCallback(mUpdateCallback);
754        }
755        // Most services aren't available until the system reaches the ready state, so we
756        // send it here when the device first boots.
757        maybeSendUserPresentBroadcast();
758    }
759
760    /**
761     * Called to let us know the screen was turned off.
762     * @param why either {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_USER} or
763     *   {@link android.view.WindowManagerPolicy#OFF_BECAUSE_OF_TIMEOUT}.
764     */
765    public void onStartedGoingToSleep(int why) {
766        if (DEBUG) Log.d(TAG, "onStartedGoingToSleep(" + why + ")");
767        synchronized (this) {
768            mDeviceInteractive = false;
769            mGoingToSleep = true;
770
771            // Lock immediately based on setting if secure (user has a pin/pattern/password).
772            // This also "locks" the device when not secure to provide easy access to the
773            // camera while preventing unwanted input.
774            int currentUser = KeyguardUpdateMonitor.getCurrentUser();
775            final boolean lockImmediately =
776                    mLockPatternUtils.getPowerButtonInstantlyLocks(currentUser)
777                            || !mLockPatternUtils.isSecure(currentUser);
778            long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser());
779            mLockLater = false;
780            if (mExitSecureCallback != null) {
781                if (DEBUG) Log.d(TAG, "pending exit secure callback cancelled");
782                try {
783                    mExitSecureCallback.onKeyguardExitResult(false);
784                } catch (RemoteException e) {
785                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
786                }
787                mExitSecureCallback = null;
788                if (!mExternallyEnabled) {
789                    hideLocked();
790                }
791            } else if (mShowing) {
792                mPendingReset = true;
793            } else if ((why == WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT && timeout > 0)
794                    || (why == WindowManagerPolicy.OFF_BECAUSE_OF_USER && !lockImmediately)) {
795                doKeyguardLaterLocked(timeout);
796                mLockLater = true;
797            } else if (!mLockPatternUtils.isLockScreenDisabled(currentUser)) {
798                mPendingLock = true;
799            }
800
801            if (mPendingLock) {
802                playSounds(true);
803            }
804        }
805        KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedGoingToSleep(why);
806        notifyStartedGoingToSleep();
807    }
808
809    public void onFinishedGoingToSleep(int why, boolean cameraGestureTriggered) {
810        if (DEBUG) Log.d(TAG, "onFinishedGoingToSleep(" + why + ")");
811        synchronized (this) {
812            mDeviceInteractive = false;
813            mGoingToSleep = false;
814            mWakeAndUnlocking = false;
815
816            resetKeyguardDonePendingLocked();
817            mHideAnimationRun = false;
818
819            notifyFinishedGoingToSleep();
820
821            if (cameraGestureTriggered) {
822                Log.i(TAG, "Camera gesture was triggered, preventing Keyguard locking.");
823
824                // Just to make sure, make sure the device is awake.
825                mContext.getSystemService(PowerManager.class).wakeUp(SystemClock.uptimeMillis(),
826                        "com.android.systemui:CAMERA_GESTURE_PREVENT_LOCK");
827                mPendingLock = false;
828                mPendingReset = false;
829            }
830
831            if (mPendingReset) {
832                resetStateLocked();
833                mPendingReset = false;
834            }
835
836            if (mPendingLock) {
837                doKeyguardLocked(null);
838                mPendingLock = false;
839            }
840
841            // We do not have timeout and power button instant lock setting for profile lock.
842            // So we use the personal setting if there is any. But if there is no device
843            // we need to make sure we lock it immediately when the screen is off.
844            if (!mLockLater && !cameraGestureTriggered) {
845                doKeyguardForChildProfilesLocked();
846            }
847
848        }
849        KeyguardUpdateMonitor.getInstance(mContext).dispatchFinishedGoingToSleep(why);
850    }
851
852    private long getLockTimeout(int userId) {
853        // if the screen turned off because of timeout or the user hit the power button
854        // and we don't need to lock immediately, set an alarm
855        // to enable it a little bit later (i.e, give the user a chance
856        // to turn the screen back on within a certain window without
857        // having to unlock the screen)
858        final ContentResolver cr = mContext.getContentResolver();
859
860        // From SecuritySettings
861        final long lockAfterTimeout = Settings.Secure.getInt(cr,
862                Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
863                KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);
864
865        // From DevicePolicyAdmin
866        final long policyTimeout = mLockPatternUtils.getDevicePolicyManager()
867                .getMaximumTimeToLockForUserAndProfiles(userId);
868
869        long timeout;
870
871        if (policyTimeout <= 0) {
872            timeout = lockAfterTimeout;
873        } else {
874            // From DisplaySettings
875            long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,
876                    KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);
877
878            // policy in effect. Make sure we don't go beyond policy limit.
879            displayTimeout = Math.max(displayTimeout, 0); // ignore negative values
880            timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);
881            timeout = Math.max(timeout, 0);
882        }
883        return timeout;
884    }
885
886    private void doKeyguardLaterLocked() {
887        long timeout = getLockTimeout(KeyguardUpdateMonitor.getCurrentUser());
888        if (timeout == 0) {
889            doKeyguardLocked(null);
890        } else {
891            doKeyguardLaterLocked(timeout);
892        }
893    }
894
895    private void doKeyguardLaterLocked(long timeout) {
896        // Lock in the future
897        long when = SystemClock.elapsedRealtime() + timeout;
898        Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);
899        intent.putExtra("seq", mDelayedShowingSequence);
900        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
901        PendingIntent sender = PendingIntent.getBroadcast(mContext,
902                0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
903        mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender);
904        if (DEBUG) Log.d(TAG, "setting alarm to turn off keyguard, seq = "
905                         + mDelayedShowingSequence);
906        doKeyguardLaterForChildProfilesLocked();
907    }
908
909    private void doKeyguardLaterForChildProfilesLocked() {
910        UserManager um = UserManager.get(mContext);
911        for (int profileId : um.getEnabledProfileIds(UserHandle.myUserId())) {
912            if (mLockPatternUtils.isSeparateProfileChallengeEnabled(profileId)) {
913                long userTimeout = getLockTimeout(profileId);
914                if (userTimeout == 0) {
915                    doKeyguardForChildProfilesLocked();
916                } else {
917                    long userWhen = SystemClock.elapsedRealtime() + userTimeout;
918                    Intent lockIntent = new Intent(DELAYED_LOCK_PROFILE_ACTION);
919                    lockIntent.putExtra("seq", mDelayedProfileShowingSequence);
920                    lockIntent.putExtra(Intent.EXTRA_USER_ID, profileId);
921                    lockIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
922                    PendingIntent lockSender = PendingIntent.getBroadcast(
923                            mContext, 0, lockIntent, PendingIntent.FLAG_CANCEL_CURRENT);
924                    mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
925                            userWhen, lockSender);
926                }
927            }
928        }
929    }
930
931    private void doKeyguardForChildProfilesLocked() {
932        UserManager um = UserManager.get(mContext);
933        for (int profileId : um.getEnabledProfileIds(UserHandle.myUserId())) {
934            if (mLockPatternUtils.isSeparateProfileChallengeEnabled(profileId)) {
935                lockProfile(profileId);
936            }
937        }
938    }
939
940    private void cancelDoKeyguardLaterLocked() {
941        mDelayedShowingSequence++;
942    }
943
944    private void cancelDoKeyguardForChildProfilesLocked() {
945        mDelayedProfileShowingSequence++;
946    }
947
948    /**
949     * Let's us know when the device is waking up.
950     */
951    public void onStartedWakingUp() {
952        Trace.beginSection("KeyguardViewMediator#onStartedWakingUp");
953
954        // TODO: Rename all screen off/on references to interactive/sleeping
955        synchronized (this) {
956            mDeviceInteractive = true;
957            cancelDoKeyguardLaterLocked();
958            cancelDoKeyguardForChildProfilesLocked();
959            if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence);
960            notifyStartedWakingUp();
961        }
962        KeyguardUpdateMonitor.getInstance(mContext).dispatchStartedWakingUp();
963        maybeSendUserPresentBroadcast();
964        Trace.endSection();
965    }
966
967    public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
968        Trace.beginSection("KeyguardViewMediator#onScreenTurningOn");
969        notifyScreenOn(callback);
970        Trace.endSection();
971    }
972
973    public void onScreenTurnedOn() {
974        Trace.beginSection("KeyguardViewMediator#onScreenTurnedOn");
975        notifyScreenTurnedOn();
976        mUpdateMonitor.dispatchScreenTurnedOn();
977        Trace.endSection();
978    }
979
980    public void onScreenTurnedOff() {
981        notifyScreenTurnedOff();
982        mUpdateMonitor.dispatchScreenTurnedOff();
983    }
984
985    private void maybeSendUserPresentBroadcast() {
986        if (mSystemReady && mLockPatternUtils.isLockScreenDisabled(
987                KeyguardUpdateMonitor.getCurrentUser())) {
988            // Lock screen is disabled because the user has set the preference to "None".
989            // In this case, send out ACTION_USER_PRESENT here instead of in
990            // handleKeyguardDone()
991            sendUserPresentBroadcast();
992        } else if (mSystemReady && shouldWaitForProvisioning()) {
993            // Skipping the lockscreen because we're not yet provisioned, but we still need to
994            // notify the StrongAuthTracker that it's now safe to run trust agents, in case the
995            // user sets a credential later.
996            getLockPatternUtils().userPresent(KeyguardUpdateMonitor.getCurrentUser());
997        }
998    }
999
1000    /**
1001     * A dream started.  We should lock after the usual screen-off lock timeout but only
1002     * if there is a secure lock pattern.
1003     */
1004    public void onDreamingStarted() {
1005        KeyguardUpdateMonitor.getInstance(mContext).dispatchDreamingStarted();
1006        synchronized (this) {
1007            if (mDeviceInteractive
1008                    && mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser())) {
1009                doKeyguardLaterLocked();
1010            }
1011        }
1012    }
1013
1014    /**
1015     * A dream stopped.
1016     */
1017    public void onDreamingStopped() {
1018        KeyguardUpdateMonitor.getInstance(mContext).dispatchDreamingStopped();
1019        synchronized (this) {
1020            if (mDeviceInteractive) {
1021                cancelDoKeyguardLaterLocked();
1022            }
1023        }
1024    }
1025
1026    /**
1027     * Same semantics as {@link android.view.WindowManagerPolicy#enableKeyguard}; provide
1028     * a way for external stuff to override normal keyguard behavior.  For instance
1029     * the phone app disables the keyguard when it receives incoming calls.
1030     */
1031    public void setKeyguardEnabled(boolean enabled) {
1032        synchronized (this) {
1033            if (DEBUG) Log.d(TAG, "setKeyguardEnabled(" + enabled + ")");
1034
1035            mExternallyEnabled = enabled;
1036
1037            if (!enabled && mShowing) {
1038                if (mExitSecureCallback != null) {
1039                    if (DEBUG) Log.d(TAG, "in process of verifyUnlock request, ignoring");
1040                    // we're in the process of handling a request to verify the user
1041                    // can get past the keyguard. ignore extraneous requests to disable / reenable
1042                    return;
1043                }
1044
1045                // hiding keyguard that is showing, remember to reshow later
1046                if (DEBUG) Log.d(TAG, "remembering to reshow, hiding keyguard, "
1047                        + "disabling status bar expansion");
1048                mNeedToReshowWhenReenabled = true;
1049                updateInputRestrictedLocked();
1050                hideLocked();
1051            } else if (enabled && mNeedToReshowWhenReenabled) {
1052                // reenabled after previously hidden, reshow
1053                if (DEBUG) Log.d(TAG, "previously hidden, reshowing, reenabling "
1054                        + "status bar expansion");
1055                mNeedToReshowWhenReenabled = false;
1056                updateInputRestrictedLocked();
1057
1058                if (mExitSecureCallback != null) {
1059                    if (DEBUG) Log.d(TAG, "onKeyguardExitResult(false), resetting");
1060                    try {
1061                        mExitSecureCallback.onKeyguardExitResult(false);
1062                    } catch (RemoteException e) {
1063                        Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1064                    }
1065                    mExitSecureCallback = null;
1066                    resetStateLocked();
1067                } else {
1068                    showLocked(null);
1069
1070                    // block until we know the keygaurd is done drawing (and post a message
1071                    // to unblock us after a timeout so we don't risk blocking too long
1072                    // and causing an ANR).
1073                    mWaitingUntilKeyguardVisible = true;
1074                    mHandler.sendEmptyMessageDelayed(KEYGUARD_DONE_DRAWING, KEYGUARD_DONE_DRAWING_TIMEOUT_MS);
1075                    if (DEBUG) Log.d(TAG, "waiting until mWaitingUntilKeyguardVisible is false");
1076                    while (mWaitingUntilKeyguardVisible) {
1077                        try {
1078                            wait();
1079                        } catch (InterruptedException e) {
1080                            Thread.currentThread().interrupt();
1081                        }
1082                    }
1083                    if (DEBUG) Log.d(TAG, "done waiting for mWaitingUntilKeyguardVisible");
1084                }
1085            }
1086        }
1087    }
1088
1089    /**
1090     * @see android.app.KeyguardManager#exitKeyguardSecurely
1091     */
1092    public void verifyUnlock(IKeyguardExitCallback callback) {
1093        Trace.beginSection("KeyguardViewMediator#verifyUnlock");
1094        synchronized (this) {
1095            if (DEBUG) Log.d(TAG, "verifyUnlock");
1096            if (shouldWaitForProvisioning()) {
1097                // don't allow this api when the device isn't provisioned
1098                if (DEBUG) Log.d(TAG, "ignoring because device isn't provisioned");
1099                try {
1100                    callback.onKeyguardExitResult(false);
1101                } catch (RemoteException e) {
1102                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1103                }
1104            } else if (mExternallyEnabled) {
1105                // this only applies when the user has externally disabled the
1106                // keyguard.  this is unexpected and means the user is not
1107                // using the api properly.
1108                Log.w(TAG, "verifyUnlock called when not externally disabled");
1109                try {
1110                    callback.onKeyguardExitResult(false);
1111                } catch (RemoteException e) {
1112                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1113                }
1114            } else if (mExitSecureCallback != null) {
1115                // already in progress with someone else
1116                try {
1117                    callback.onKeyguardExitResult(false);
1118                } catch (RemoteException e) {
1119                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1120                }
1121            } else if (!isSecure()) {
1122
1123                // Keyguard is not secure, no need to do anything, and we don't need to reshow
1124                // the Keyguard after the client releases the Keyguard lock.
1125                mExternallyEnabled = true;
1126                mNeedToReshowWhenReenabled = false;
1127                updateInputRestricted();
1128                try {
1129                    callback.onKeyguardExitResult(true);
1130                } catch (RemoteException e) {
1131                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1132                }
1133            } else {
1134
1135                // Since we prevent apps from hiding the Keyguard if we are secure, this should be
1136                // a no-op as well.
1137                try {
1138                    callback.onKeyguardExitResult(false);
1139                } catch (RemoteException e) {
1140                    Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
1141                }
1142            }
1143        }
1144        Trace.endSection();
1145    }
1146
1147    /**
1148     * Is the keyguard currently showing and not being force hidden?
1149     */
1150    public boolean isShowingAndNotOccluded() {
1151        return mShowing && !mOccluded;
1152    }
1153
1154    /**
1155     * Notify us when the keyguard is occluded by another window
1156     */
1157    public void setOccluded(boolean isOccluded, boolean animate) {
1158        Trace.beginSection("KeyguardViewMediator#setOccluded");
1159        if (DEBUG) Log.d(TAG, "setOccluded " + isOccluded);
1160        mHandler.removeMessages(SET_OCCLUDED);
1161        Message msg = mHandler.obtainMessage(SET_OCCLUDED, isOccluded ? 1 : 0, animate ? 1 : 0);
1162        mHandler.sendMessage(msg);
1163        Trace.endSection();
1164    }
1165
1166    /**
1167     * Handles SET_OCCLUDED message sent by setOccluded()
1168     */
1169    private void handleSetOccluded(boolean isOccluded, boolean animate) {
1170        Trace.beginSection("KeyguardViewMediator#handleSetOccluded");
1171        synchronized (KeyguardViewMediator.this) {
1172            if (mHiding && isOccluded) {
1173                // We're in the process of going away but WindowManager wants to show a
1174                // SHOW_WHEN_LOCKED activity instead.
1175                startKeyguardExitAnimation(0, 0);
1176            }
1177
1178            if (mOccluded != isOccluded) {
1179                mOccluded = isOccluded;
1180                mUpdateMonitor.setKeyguardOccluded(isOccluded);
1181                mStatusBarKeyguardViewManager.setOccluded(isOccluded, animate
1182                        && mDeviceInteractive);
1183                adjustStatusBarLocked();
1184            }
1185        }
1186        Trace.endSection();
1187    }
1188
1189    /**
1190     * Used by PhoneWindowManager to enable the keyguard due to a user activity timeout.
1191     * This must be safe to call from any thread and with any window manager locks held.
1192     */
1193    public void doKeyguardTimeout(Bundle options) {
1194        mHandler.removeMessages(KEYGUARD_TIMEOUT);
1195        Message msg = mHandler.obtainMessage(KEYGUARD_TIMEOUT, options);
1196        mHandler.sendMessage(msg);
1197    }
1198
1199    /**
1200     * Given the state of the keyguard, is the input restricted?
1201     * Input is restricted when the keyguard is showing, or when the keyguard
1202     * was suppressed by an app that disabled the keyguard or we haven't been provisioned yet.
1203     */
1204    public boolean isInputRestricted() {
1205        return mShowing || mNeedToReshowWhenReenabled;
1206    }
1207
1208    private void updateInputRestricted() {
1209        synchronized (this) {
1210            updateInputRestrictedLocked();
1211        }
1212    }
1213
1214    private void updateInputRestrictedLocked() {
1215        boolean inputRestricted = isInputRestricted();
1216        if (mInputRestricted != inputRestricted) {
1217            mInputRestricted = inputRestricted;
1218            int size = mKeyguardStateCallbacks.size();
1219            for (int i = size - 1; i >= 0; i--) {
1220                final IKeyguardStateCallback callback = mKeyguardStateCallbacks.get(i);
1221                try {
1222                    callback.onInputRestrictedStateChanged(inputRestricted);
1223                } catch (RemoteException e) {
1224                    Slog.w(TAG, "Failed to call onDeviceProvisioned", e);
1225                    if (e instanceof DeadObjectException) {
1226                        mKeyguardStateCallbacks.remove(callback);
1227                    }
1228                }
1229            }
1230        }
1231    }
1232
1233    /**
1234     * Enable the keyguard if the settings are appropriate.
1235     */
1236    private void doKeyguardLocked(Bundle options) {
1237        // if another app is disabling us, don't show
1238        if (!mExternallyEnabled) {
1239            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because externally disabled");
1240
1241            // note: we *should* set mNeedToReshowWhenReenabled=true here, but that makes
1242            // for an occasional ugly flicker in this situation:
1243            // 1) receive a call with the screen on (no keyguard) or make a call
1244            // 2) screen times out
1245            // 3) user hits key to turn screen back on
1246            // instead, we reenable the keyguard when we know the screen is off and the call
1247            // ends (see the broadcast receiver below)
1248            // TODO: clean this up when we have better support at the window manager level
1249            // for apps that wish to be on top of the keyguard
1250            return;
1251        }
1252
1253        // if the keyguard is already showing, don't bother
1254        if (mStatusBarKeyguardViewManager.isShowing()) {
1255            if (DEBUG) Log.d(TAG, "doKeyguard: not showing because it is already showing");
1256            resetStateLocked();
1257            return;
1258        }
1259
1260        // In split system user mode, we never unlock system user.
1261        if (!mustNotUnlockCurrentUser()
1262                || !mUpdateMonitor.isDeviceProvisioned()) {
1263
1264            // if the setup wizard hasn't run yet, don't show
1265            final boolean requireSim = !SystemProperties.getBoolean("keyguard.no_require_sim", false);
1266            final boolean absent = SubscriptionManager.isValidSubscriptionId(
1267                    mUpdateMonitor.getNextSubIdForState(ABSENT));
1268            final boolean disabled = SubscriptionManager.isValidSubscriptionId(
1269                    mUpdateMonitor.getNextSubIdForState(IccCardConstants.State.PERM_DISABLED));
1270            final boolean lockedOrMissing = mUpdateMonitor.isSimPinSecure()
1271                    || ((absent || disabled) && requireSim);
1272
1273            if (!lockedOrMissing && shouldWaitForProvisioning()) {
1274                if (DEBUG) Log.d(TAG, "doKeyguard: not showing because device isn't provisioned"
1275                        + " and the sim is not locked or missing");
1276                return;
1277            }
1278
1279            boolean forceShow = options != null && options.getBoolean(OPTION_FORCE_SHOW, false);
1280            if (mLockPatternUtils.isLockScreenDisabled(KeyguardUpdateMonitor.getCurrentUser())
1281                    && !lockedOrMissing && !forceShow) {
1282                if (DEBUG) Log.d(TAG, "doKeyguard: not showing because lockscreen is off");
1283                return;
1284            }
1285
1286            if (mLockPatternUtils.checkVoldPassword(KeyguardUpdateMonitor.getCurrentUser())) {
1287                if (DEBUG) Log.d(TAG, "Not showing lock screen since just decrypted");
1288                // Without this, settings is not enabled until the lock screen first appears
1289                setShowingLocked(false);
1290                hideLocked();
1291                mUpdateMonitor.reportSuccessfulStrongAuthUnlockAttempt();
1292                return;
1293            }
1294        }
1295
1296        if (DEBUG) Log.d(TAG, "doKeyguard: showing the lock screen");
1297        showLocked(options);
1298    }
1299
1300    private void lockProfile(int userId) {
1301        mTrustManager.setDeviceLockedForUser(userId, true);
1302    }
1303
1304    private boolean shouldWaitForProvisioning() {
1305        return !mUpdateMonitor.isDeviceProvisioned() && !isSecure();
1306    }
1307
1308    /**
1309     * Dismiss the keyguard through the security layers.
1310     * @param callback Callback to be informed about the result
1311     */
1312    private void handleDismiss(IKeyguardDismissCallback callback) {
1313        if (mShowing) {
1314            if (callback != null) {
1315                mDismissCallbackRegistry.addCallback(callback);
1316            }
1317            mStatusBarKeyguardViewManager.dismissAndCollapse();
1318        } else if (callback != null) {
1319            new DismissCallbackWrapper(callback).notifyDismissError();
1320        }
1321    }
1322
1323    public void dismiss(IKeyguardDismissCallback callback) {
1324        mHandler.obtainMessage(DISMISS, callback).sendToTarget();
1325    }
1326
1327    /**
1328     * Send message to keyguard telling it to reset its state.
1329     * @see #handleReset
1330     */
1331    private void resetStateLocked() {
1332        if (DEBUG) Log.e(TAG, "resetStateLocked");
1333        Message msg = mHandler.obtainMessage(RESET);
1334        mHandler.sendMessage(msg);
1335    }
1336
1337    /**
1338     * Send message to keyguard telling it to verify unlock
1339     * @see #handleVerifyUnlock()
1340     */
1341    private void verifyUnlockLocked() {
1342        if (DEBUG) Log.d(TAG, "verifyUnlockLocked");
1343        mHandler.sendEmptyMessage(VERIFY_UNLOCK);
1344    }
1345
1346    private void notifyStartedGoingToSleep() {
1347        if (DEBUG) Log.d(TAG, "notifyStartedGoingToSleep");
1348        mHandler.sendEmptyMessage(NOTIFY_STARTED_GOING_TO_SLEEP);
1349    }
1350
1351    private void notifyFinishedGoingToSleep() {
1352        if (DEBUG) Log.d(TAG, "notifyFinishedGoingToSleep");
1353        mHandler.sendEmptyMessage(NOTIFY_FINISHED_GOING_TO_SLEEP);
1354    }
1355
1356    private void notifyStartedWakingUp() {
1357        if (DEBUG) Log.d(TAG, "notifyStartedWakingUp");
1358        mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP);
1359    }
1360
1361    private void notifyScreenOn(IKeyguardDrawnCallback callback) {
1362        if (DEBUG) Log.d(TAG, "notifyScreenOn");
1363        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNING_ON, callback);
1364        mHandler.sendMessage(msg);
1365    }
1366
1367    private void notifyScreenTurnedOn() {
1368        if (DEBUG) Log.d(TAG, "notifyScreenTurnedOn");
1369        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_ON);
1370        mHandler.sendMessage(msg);
1371    }
1372
1373    private void notifyScreenTurnedOff() {
1374        if (DEBUG) Log.d(TAG, "notifyScreenTurnedOff");
1375        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNED_OFF);
1376        mHandler.sendMessage(msg);
1377    }
1378
1379    /**
1380     * Send message to keyguard telling it to show itself
1381     * @see #handleShow
1382     */
1383    private void showLocked(Bundle options) {
1384        Trace.beginSection("KeyguardViewMediator#showLocked aqcuiring mShowKeyguardWakeLock");
1385        if (DEBUG) Log.d(TAG, "showLocked");
1386        // ensure we stay awake until we are finished displaying the keyguard
1387        mShowKeyguardWakeLock.acquire();
1388        Message msg = mHandler.obtainMessage(SHOW, options);
1389        mHandler.sendMessage(msg);
1390        Trace.endSection();
1391    }
1392
1393    /**
1394     * Send message to keyguard telling it to hide itself
1395     * @see #handleHide()
1396     */
1397    private void hideLocked() {
1398        Trace.beginSection("KeyguardViewMediator#hideLocked");
1399        if (DEBUG) Log.d(TAG, "hideLocked");
1400        Message msg = mHandler.obtainMessage(HIDE);
1401        mHandler.sendMessage(msg);
1402        Trace.endSection();
1403    }
1404
1405    public boolean isSecure() {
1406        return isSecure(KeyguardUpdateMonitor.getCurrentUser());
1407    }
1408
1409    public boolean isSecure(int userId) {
1410        return mLockPatternUtils.isSecure(userId)
1411                || KeyguardUpdateMonitor.getInstance(mContext).isSimPinSecure();
1412    }
1413
1414    public void setSwitchingUser(boolean switching) {
1415        Trace.beginSection("KeyguardViewMediator#setSwitchingUser");
1416        mHandler.removeMessages(SET_SWITCHING_USER);
1417        Message msg = mHandler.obtainMessage(SET_SWITCHING_USER, switching ? 1 : 0, 0);
1418        mHandler.sendMessage(msg);
1419        Trace.endSection();
1420    }
1421
1422    /**
1423     * Update the newUserId. Call while holding WindowManagerService lock.
1424     * NOTE: Should only be called by KeyguardViewMediator in response to the user id changing.
1425     *
1426     * @param newUserId The id of the incoming user.
1427     */
1428    public void setCurrentUser(int newUserId) {
1429        KeyguardUpdateMonitor.setCurrentUser(newUserId);
1430        synchronized (this) {
1431            notifyTrustedChangedLocked(mUpdateMonitor.getUserHasTrust(newUserId));
1432        }
1433    }
1434
1435    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1436        @Override
1437        public void onReceive(Context context, Intent intent) {
1438            if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {
1439                final int sequence = intent.getIntExtra("seq", 0);
1440                if (DEBUG) Log.d(TAG, "received DELAYED_KEYGUARD_ACTION with seq = "
1441                        + sequence + ", mDelayedShowingSequence = " + mDelayedShowingSequence);
1442                synchronized (KeyguardViewMediator.this) {
1443                    if (mDelayedShowingSequence == sequence) {
1444                        doKeyguardLocked(null);
1445                    }
1446                }
1447            } else if (DELAYED_LOCK_PROFILE_ACTION.equals(intent.getAction())) {
1448                final int sequence = intent.getIntExtra("seq", 0);
1449                int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, 0);
1450                if (userId != 0) {
1451                    synchronized (KeyguardViewMediator.this) {
1452                        if (mDelayedProfileShowingSequence == sequence) {
1453                            lockProfile(userId);
1454                        }
1455                    }
1456                }
1457            } else if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
1458                synchronized (KeyguardViewMediator.this){
1459                    mShuttingDown = true;
1460                }
1461            }
1462        }
1463    };
1464
1465    public void keyguardDone() {
1466        Trace.beginSection("KeyguardViewMediator#keyguardDone");
1467        if (DEBUG) Log.d(TAG, "keyguardDone()");
1468        userActivity();
1469        EventLog.writeEvent(70000, 2);
1470        Message msg = mHandler.obtainMessage(KEYGUARD_DONE);
1471        mHandler.sendMessage(msg);
1472        Trace.endSection();
1473    }
1474
1475    /**
1476     * This handler will be associated with the policy thread, which will also
1477     * be the UI thread of the keyguard.  Since the apis of the policy, and therefore
1478     * this class, can be called by other threads, any action that directly
1479     * interacts with the keyguard ui should be posted to this handler, rather
1480     * than called directly.
1481     */
1482    private Handler mHandler = new Handler(Looper.myLooper(), null, true /*async*/) {
1483        @Override
1484        public void handleMessage(Message msg) {
1485            switch (msg.what) {
1486                case SHOW:
1487                    handleShow((Bundle) msg.obj);
1488                    break;
1489                case HIDE:
1490                    handleHide();
1491                    break;
1492                case RESET:
1493                    handleReset();
1494                    break;
1495                case VERIFY_UNLOCK:
1496                    Trace.beginSection("KeyguardViewMediator#handleMessage VERIFY_UNLOCK");
1497                    handleVerifyUnlock();
1498                    Trace.endSection();
1499                    break;
1500                case NOTIFY_STARTED_GOING_TO_SLEEP:
1501                    handleNotifyStartedGoingToSleep();
1502                    break;
1503                case NOTIFY_FINISHED_GOING_TO_SLEEP:
1504                    handleNotifyFinishedGoingToSleep();
1505                    break;
1506                case NOTIFY_SCREEN_TURNING_ON:
1507                    Trace.beginSection("KeyguardViewMediator#handleMessage NOTIFY_SCREEN_TURNING_ON");
1508                    handleNotifyScreenTurningOn((IKeyguardDrawnCallback) msg.obj);
1509                    Trace.endSection();
1510                    break;
1511                case NOTIFY_SCREEN_TURNED_ON:
1512                    Trace.beginSection("KeyguardViewMediator#handleMessage NOTIFY_SCREEN_TURNED_ON");
1513                    handleNotifyScreenTurnedOn();
1514                    Trace.endSection();
1515                    break;
1516                case NOTIFY_SCREEN_TURNED_OFF:
1517                    handleNotifyScreenTurnedOff();
1518                    break;
1519                case NOTIFY_STARTED_WAKING_UP:
1520                    Trace.beginSection("KeyguardViewMediator#handleMessage NOTIFY_STARTED_WAKING_UP");
1521                    handleNotifyStartedWakingUp();
1522                    Trace.endSection();
1523                    break;
1524                case KEYGUARD_DONE:
1525                    Trace.beginSection("KeyguardViewMediator#handleMessage KEYGUARD_DONE");
1526                    handleKeyguardDone();
1527                    Trace.endSection();
1528                    break;
1529                case KEYGUARD_DONE_DRAWING:
1530                    Trace.beginSection("KeyguardViewMediator#handleMessage KEYGUARD_DONE_DRAWING");
1531                    handleKeyguardDoneDrawing();
1532                    Trace.endSection();
1533                    break;
1534                case SET_OCCLUDED:
1535                    Trace.beginSection("KeyguardViewMediator#handleMessage SET_OCCLUDED");
1536                    handleSetOccluded(msg.arg1 != 0, msg.arg2 != 0);
1537                    Trace.endSection();
1538                    break;
1539                case KEYGUARD_TIMEOUT:
1540                    synchronized (KeyguardViewMediator.this) {
1541                        doKeyguardLocked((Bundle) msg.obj);
1542                    }
1543                    break;
1544                case DISMISS:
1545                    handleDismiss((IKeyguardDismissCallback) msg.obj);
1546                    break;
1547                case START_KEYGUARD_EXIT_ANIM:
1548                    Trace.beginSection("KeyguardViewMediator#handleMessage START_KEYGUARD_EXIT_ANIM");
1549                    StartKeyguardExitAnimParams params = (StartKeyguardExitAnimParams) msg.obj;
1550                    handleStartKeyguardExitAnimation(params.startTime, params.fadeoutDuration);
1551                    FalsingManager.getInstance(mContext).onSucccessfulUnlock();
1552                    Trace.endSection();
1553                    break;
1554                case KEYGUARD_DONE_PENDING_TIMEOUT:
1555                    Trace.beginSection("KeyguardViewMediator#handleMessage KEYGUARD_DONE_PENDING_TIMEOUT");
1556                    Log.w(TAG, "Timeout while waiting for activity drawn!");
1557                    Trace.endSection();
1558                    break;
1559                case SET_SWITCHING_USER:
1560                    Trace.beginSection("KeyguardViewMediator#handleMessage SET_SWITCHING_USER");
1561                    KeyguardUpdateMonitor.getInstance(mContext).setSwitchingUser(msg.arg1 != 0);
1562                    Trace.endSection();
1563                    break;
1564            }
1565        }
1566    };
1567
1568    private void tryKeyguardDone() {
1569        if (!mKeyguardDonePending && mHideAnimationRun && !mHideAnimationRunning) {
1570            handleKeyguardDone();
1571        } else if (!mHideAnimationRun) {
1572            mHideAnimationRun = true;
1573            mHideAnimationRunning = true;
1574            mStatusBarKeyguardViewManager.startPreHideAnimation(mHideAnimationFinishedRunnable);
1575        }
1576    }
1577
1578    /**
1579     * @see #keyguardDone
1580     * @see #KEYGUARD_DONE
1581     */
1582    private void handleKeyguardDone() {
1583        Trace.beginSection("KeyguardViewMediator#handleKeyguardDone");
1584        final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
1585        mUiOffloadThread.submit(() -> {
1586            if (mLockPatternUtils.isSecure(currentUser)) {
1587                mLockPatternUtils.getDevicePolicyManager().reportKeyguardDismissed(currentUser);
1588            }
1589        });
1590        if (DEBUG) Log.d(TAG, "handleKeyguardDone");
1591        synchronized (this) {
1592            resetKeyguardDonePendingLocked();
1593        }
1594
1595        mUpdateMonitor.clearFailedUnlockAttempts();
1596        mUpdateMonitor.clearFingerprintRecognized();
1597
1598        if (mGoingToSleep) {
1599            Log.i(TAG, "Device is going to sleep, aborting keyguardDone");
1600            return;
1601        }
1602        if (mExitSecureCallback != null) {
1603            try {
1604                mExitSecureCallback.onKeyguardExitResult(true /* authenciated */);
1605            } catch (RemoteException e) {
1606                Slog.w(TAG, "Failed to call onKeyguardExitResult()", e);
1607            }
1608
1609            mExitSecureCallback = null;
1610
1611            // after succesfully exiting securely, no need to reshow
1612            // the keyguard when they've released the lock
1613            mExternallyEnabled = true;
1614            mNeedToReshowWhenReenabled = false;
1615            updateInputRestricted();
1616        }
1617
1618        handleHide();
1619        Trace.endSection();
1620    }
1621
1622    private void sendUserPresentBroadcast() {
1623        synchronized (this) {
1624            if (mBootCompleted) {
1625                int currentUserId = KeyguardUpdateMonitor.getCurrentUser();
1626                final UserHandle currentUser = new UserHandle(currentUserId);
1627                final UserManager um = (UserManager) mContext.getSystemService(
1628                        Context.USER_SERVICE);
1629                mUiOffloadThread.submit(() -> {
1630                    for (int profileId : um.getProfileIdsWithDisabled(currentUser.getIdentifier())) {
1631                        mContext.sendBroadcastAsUser(USER_PRESENT_INTENT, UserHandle.of(profileId));
1632                    }
1633                    getLockPatternUtils().userPresent(currentUserId);
1634                });
1635            } else {
1636                mBootSendUserPresent = true;
1637            }
1638        }
1639    }
1640
1641    /**
1642     * @see #keyguardDone
1643     * @see #KEYGUARD_DONE_DRAWING
1644     */
1645    private void handleKeyguardDoneDrawing() {
1646        Trace.beginSection("KeyguardViewMediator#handleKeyguardDoneDrawing");
1647        synchronized(this) {
1648            if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing");
1649            if (mWaitingUntilKeyguardVisible) {
1650                if (DEBUG) Log.d(TAG, "handleKeyguardDoneDrawing: notifying mWaitingUntilKeyguardVisible");
1651                mWaitingUntilKeyguardVisible = false;
1652                notifyAll();
1653
1654                // there will usually be two of these sent, one as a timeout, and one
1655                // as a result of the callback, so remove any remaining messages from
1656                // the queue
1657                mHandler.removeMessages(KEYGUARD_DONE_DRAWING);
1658            }
1659        }
1660        Trace.endSection();
1661    }
1662
1663    private void playSounds(boolean locked) {
1664        playSound(locked ? mLockSoundId : mUnlockSoundId);
1665    }
1666
1667    private void playSound(int soundId) {
1668        if (soundId == 0) return;
1669        final ContentResolver cr = mContext.getContentResolver();
1670        if (Settings.System.getInt(cr, Settings.System.LOCKSCREEN_SOUNDS_ENABLED, 1) == 1) {
1671
1672            mLockSounds.stop(mLockSoundStreamId);
1673            // Init mAudioManager
1674            if (mAudioManager == null) {
1675                mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
1676                if (mAudioManager == null) return;
1677                mUiSoundsStreamType = mAudioManager.getUiSoundsStreamType();
1678            }
1679
1680            mUiOffloadThread.submit(() -> {
1681                // If the stream is muted, don't play the sound
1682                if (mAudioManager.isStreamMute(mUiSoundsStreamType)) return;
1683
1684                int id = mLockSounds.play(soundId,
1685                        mLockSoundVolume, mLockSoundVolume, 1/*priortiy*/, 0/*loop*/, 1.0f/*rate*/);
1686                synchronized (this) {
1687                    mLockSoundStreamId = id;
1688                }
1689            });
1690
1691        }
1692    }
1693
1694    private void playTrustedSound() {
1695        playSound(mTrustedSoundId);
1696    }
1697
1698    private void updateActivityLockScreenState(boolean showing) {
1699        mUiOffloadThread.submit(() -> {
1700            try {
1701                ActivityManager.getService().setLockScreenShown(showing);
1702            } catch (RemoteException e) {
1703            }
1704        });
1705    }
1706
1707    /**
1708     * Handle message sent by {@link #showLocked}.
1709     * @see #SHOW
1710     */
1711    private void handleShow(Bundle options) {
1712        Trace.beginSection("KeyguardViewMediator#handleShow");
1713        final int currentUser = KeyguardUpdateMonitor.getCurrentUser();
1714        if (mLockPatternUtils.isSecure(currentUser)) {
1715            mLockPatternUtils.getDevicePolicyManager().reportKeyguardSecured(currentUser);
1716        }
1717        synchronized (KeyguardViewMediator.this) {
1718            if (!mSystemReady) {
1719                if (DEBUG) Log.d(TAG, "ignoring handleShow because system is not ready.");
1720                return;
1721            } else {
1722                if (DEBUG) Log.d(TAG, "handleShow");
1723            }
1724
1725            setShowingLocked(true);
1726            mStatusBarKeyguardViewManager.show(options);
1727            mHiding = false;
1728            mWakeAndUnlocking = false;
1729            resetKeyguardDonePendingLocked();
1730            mHideAnimationRun = false;
1731            adjustStatusBarLocked();
1732            userActivity();
1733            mShowKeyguardWakeLock.release();
1734        }
1735        mKeyguardDisplayManager.show();
1736        Trace.endSection();
1737    }
1738
1739    private final Runnable mKeyguardGoingAwayRunnable = new Runnable() {
1740        @Override
1741        public void run() {
1742            Trace.beginSection("KeyguardViewMediator.mKeyGuardGoingAwayRunnable");
1743            if (DEBUG) Log.d(TAG, "keyguardGoingAway");
1744            try {
1745                mStatusBarKeyguardViewManager.keyguardGoingAway();
1746
1747                int flags = 0;
1748                if (mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock()
1749                        || mWakeAndUnlocking) {
1750                    flags |= WindowManagerPolicy.KEYGUARD_GOING_AWAY_FLAG_NO_WINDOW_ANIMATIONS;
1751                }
1752                if (mStatusBarKeyguardViewManager.isGoingToNotificationShade()) {
1753                    flags |= WindowManagerPolicy.KEYGUARD_GOING_AWAY_FLAG_TO_SHADE;
1754                }
1755                if (mStatusBarKeyguardViewManager.isUnlockWithWallpaper()) {
1756                    flags |= WindowManagerPolicy.KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER;
1757                }
1758
1759                mUpdateMonitor.setKeyguardGoingAway(true /* goingAway */);
1760                // Don't actually hide the Keyguard at the moment, wait for window
1761                // manager until it tells us it's safe to do so with
1762                // startKeyguardExitAnimation.
1763                ActivityManager.getService().keyguardGoingAway(flags);
1764            } catch (RemoteException e) {
1765                Log.e(TAG, "Error while calling WindowManager", e);
1766            }
1767            Trace.endSection();
1768        }
1769    };
1770
1771    private final Runnable mHideAnimationFinishedRunnable = () -> {
1772        mHideAnimationRunning = false;
1773        tryKeyguardDone();
1774    };
1775
1776    /**
1777     * Handle message sent by {@link #hideLocked()}
1778     * @see #HIDE
1779     */
1780    private void handleHide() {
1781        Trace.beginSection("KeyguardViewMediator#handleHide");
1782        synchronized (KeyguardViewMediator.this) {
1783            if (DEBUG) Log.d(TAG, "handleHide");
1784
1785            if (mustNotUnlockCurrentUser()) {
1786                // In split system user mode, we never unlock system user. The end user has to
1787                // switch to another user.
1788                // TODO: We should stop it early by disabling the swipe up flow. Right now swipe up
1789                // still completes and makes the screen blank.
1790                if (DEBUG) Log.d(TAG, "Split system user, quit unlocking.");
1791                return;
1792            }
1793            mHiding = true;
1794
1795            if (mShowing && !mOccluded) {
1796                mKeyguardGoingAwayRunnable.run();
1797            } else {
1798                handleStartKeyguardExitAnimation(
1799                        SystemClock.uptimeMillis() + mHideAnimation.getStartOffset(),
1800                        mHideAnimation.getDuration());
1801            }
1802        }
1803        Trace.endSection();
1804    }
1805
1806    private void handleStartKeyguardExitAnimation(long startTime, long fadeoutDuration) {
1807        Trace.beginSection("KeyguardViewMediator#handleStartKeyguardExitAnimation");
1808        if (DEBUG) Log.d(TAG, "handleStartKeyguardExitAnimation startTime=" + startTime
1809                + " fadeoutDuration=" + fadeoutDuration);
1810        synchronized (KeyguardViewMediator.this) {
1811
1812            if (!mHiding) {
1813                return;
1814            }
1815            mHiding = false;
1816
1817            if (mWakeAndUnlocking && mDrawnCallback != null) {
1818
1819                // Hack level over 9000: To speed up wake-and-unlock sequence, force it to report
1820                // the next draw from here so we don't have to wait for window manager to signal
1821                // this to our ViewRootImpl.
1822                mStatusBarKeyguardViewManager.getViewRootImpl().setReportNextDraw();
1823                notifyDrawn(mDrawnCallback);
1824                mDrawnCallback = null;
1825            }
1826
1827            // only play "unlock" noises if not on a call (since the incall UI
1828            // disables the keyguard)
1829            if (TelephonyManager.EXTRA_STATE_IDLE.equals(mPhoneState)) {
1830                playSounds(false);
1831            }
1832
1833            mWakeAndUnlocking = false;
1834            setShowingLocked(false);
1835            mDismissCallbackRegistry.notifyDismissSucceeded();
1836            mStatusBarKeyguardViewManager.hide(startTime, fadeoutDuration);
1837            resetKeyguardDonePendingLocked();
1838            mHideAnimationRun = false;
1839            adjustStatusBarLocked();
1840            sendUserPresentBroadcast();
1841            mUpdateMonitor.setKeyguardGoingAway(false /* goingAway */);
1842        }
1843        Trace.endSection();
1844    }
1845
1846    private void adjustStatusBarLocked() {
1847        if (mStatusBarManager == null) {
1848            mStatusBarManager = (StatusBarManager)
1849                    mContext.getSystemService(Context.STATUS_BAR_SERVICE);
1850        }
1851        if (mStatusBarManager == null) {
1852            Log.w(TAG, "Could not get status bar manager");
1853        } else {
1854            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
1855            // windows that appear on top, ever
1856            int flags = StatusBarManager.DISABLE_NONE;
1857            if (mShowing) {
1858                // Permanently disable components not available when keyguard is enabled
1859                // (like recents). Temporary enable/disable (e.g. the "back" button) are
1860                // done in KeyguardHostView.
1861                flags |= StatusBarManager.DISABLE_RECENT;
1862            }
1863            if (isShowingAndNotOccluded()) {
1864                flags |= StatusBarManager.DISABLE_HOME;
1865            }
1866
1867            if (DEBUG) {
1868                Log.d(TAG, "adjustStatusBarLocked: mShowing=" + mShowing + " mOccluded=" + mOccluded
1869                        + " isSecure=" + isSecure() + " --> flags=0x" + Integer.toHexString(flags));
1870            }
1871
1872            mStatusBarManager.disable(flags);
1873        }
1874    }
1875
1876    /**
1877     * Handle message sent by {@link #resetStateLocked}
1878     * @see #RESET
1879     */
1880    private void handleReset() {
1881        synchronized (KeyguardViewMediator.this) {
1882            if (DEBUG) Log.d(TAG, "handleReset");
1883            mStatusBarKeyguardViewManager.reset(true /* hideBouncerWhenShowing */);
1884        }
1885    }
1886
1887    /**
1888     * Handle message sent by {@link #verifyUnlock}
1889     * @see #VERIFY_UNLOCK
1890     */
1891    private void handleVerifyUnlock() {
1892        Trace.beginSection("KeyguardViewMediator#handleVerifyUnlock");
1893        synchronized (KeyguardViewMediator.this) {
1894            if (DEBUG) Log.d(TAG, "handleVerifyUnlock");
1895            setShowingLocked(true);
1896            mStatusBarKeyguardViewManager.dismissAndCollapse();
1897        }
1898        Trace.endSection();
1899    }
1900
1901    private void handleNotifyStartedGoingToSleep() {
1902        synchronized (KeyguardViewMediator.this) {
1903            if (DEBUG) Log.d(TAG, "handleNotifyStartedGoingToSleep");
1904            mStatusBarKeyguardViewManager.onStartedGoingToSleep();
1905        }
1906    }
1907
1908    /**
1909     * Handle message sent by {@link #notifyFinishedGoingToSleep()}
1910     * @see #NOTIFY_FINISHED_GOING_TO_SLEEP
1911     */
1912    private void handleNotifyFinishedGoingToSleep() {
1913        synchronized (KeyguardViewMediator.this) {
1914            if (DEBUG) Log.d(TAG, "handleNotifyFinishedGoingToSleep");
1915            mStatusBarKeyguardViewManager.onFinishedGoingToSleep();
1916        }
1917    }
1918
1919    private void handleNotifyStartedWakingUp() {
1920        Trace.beginSection("KeyguardViewMediator#handleMotifyStartedWakingUp");
1921        synchronized (KeyguardViewMediator.this) {
1922            if (DEBUG) Log.d(TAG, "handleNotifyWakingUp");
1923            mStatusBarKeyguardViewManager.onStartedWakingUp();
1924        }
1925        Trace.endSection();
1926    }
1927
1928    private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) {
1929        Trace.beginSection("KeyguardViewMediator#handleNotifyScreenTurningOn");
1930        synchronized (KeyguardViewMediator.this) {
1931            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn");
1932            mStatusBarKeyguardViewManager.onScreenTurningOn();
1933            if (callback != null) {
1934                if (mWakeAndUnlocking) {
1935                    mDrawnCallback = callback;
1936                } else {
1937                    notifyDrawn(callback);
1938                }
1939            }
1940        }
1941        Trace.endSection();
1942    }
1943
1944    private void handleNotifyScreenTurnedOn() {
1945        Trace.beginSection("KeyguardViewMediator#handleNotifyScreenTurnedOn");
1946        if (LatencyTracker.isEnabled(mContext)) {
1947            LatencyTracker.getInstance(mContext).onActionEnd(LatencyTracker.ACTION_TURN_ON_SCREEN);
1948        }
1949        synchronized (this) {
1950            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOn");
1951            mStatusBarKeyguardViewManager.onScreenTurnedOn();
1952        }
1953        Trace.endSection();
1954    }
1955
1956    private void handleNotifyScreenTurnedOff() {
1957        synchronized (this) {
1958            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurnedOff");
1959            mStatusBarKeyguardViewManager.onScreenTurnedOff();
1960            mDrawnCallback = null;
1961        }
1962    }
1963
1964    private void notifyDrawn(final IKeyguardDrawnCallback callback) {
1965        Trace.beginSection("KeyguardViewMediator#notifyDrawn");
1966        try {
1967            callback.onDrawn();
1968        } catch (RemoteException e) {
1969            Slog.w(TAG, "Exception calling onDrawn():", e);
1970        }
1971        Trace.endSection();
1972    }
1973
1974    private void resetKeyguardDonePendingLocked() {
1975        mKeyguardDonePending = false;
1976        mHandler.removeMessages(KEYGUARD_DONE_PENDING_TIMEOUT);
1977    }
1978
1979    @Override
1980    public void onBootCompleted() {
1981        mUpdateMonitor.dispatchBootCompleted();
1982        synchronized (this) {
1983            mBootCompleted = true;
1984            if (mBootSendUserPresent) {
1985                sendUserPresentBroadcast();
1986            }
1987        }
1988    }
1989
1990    public void onWakeAndUnlocking() {
1991        Trace.beginSection("KeyguardViewMediator#onWakeAndUnlocking");
1992        mWakeAndUnlocking = true;
1993        keyguardDone();
1994        Trace.endSection();
1995    }
1996
1997    public StatusBarKeyguardViewManager registerStatusBar(StatusBar statusBar,
1998            ViewGroup container,
1999            ScrimController scrimController,
2000            FingerprintUnlockController fingerprintUnlockController) {
2001        mStatusBarKeyguardViewManager.registerStatusBar(statusBar, container,
2002                scrimController, fingerprintUnlockController,
2003                mDismissCallbackRegistry);
2004        return mStatusBarKeyguardViewManager;
2005    }
2006
2007    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
2008        Trace.beginSection("KeyguardViewMediator#startKeyguardExitAnimation");
2009        Message msg = mHandler.obtainMessage(START_KEYGUARD_EXIT_ANIM,
2010                new StartKeyguardExitAnimParams(startTime, fadeoutDuration));
2011        mHandler.sendMessage(msg);
2012        Trace.endSection();
2013    }
2014
2015    public void onShortPowerPressedGoHome() {
2016        // do nothing
2017    }
2018
2019    public ViewMediatorCallback getViewMediatorCallback() {
2020        return mViewMediatorCallback;
2021    }
2022
2023    public LockPatternUtils getLockPatternUtils() {
2024        return mLockPatternUtils;
2025    }
2026
2027    @Override
2028    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2029        pw.print("  mSystemReady: "); pw.println(mSystemReady);
2030        pw.print("  mBootCompleted: "); pw.println(mBootCompleted);
2031        pw.print("  mBootSendUserPresent: "); pw.println(mBootSendUserPresent);
2032        pw.print("  mExternallyEnabled: "); pw.println(mExternallyEnabled);
2033        pw.print("  mShuttingDown: "); pw.println(mShuttingDown);
2034        pw.print("  mNeedToReshowWhenReenabled: "); pw.println(mNeedToReshowWhenReenabled);
2035        pw.print("  mShowing: "); pw.println(mShowing);
2036        pw.print("  mInputRestricted: "); pw.println(mInputRestricted);
2037        pw.print("  mOccluded: "); pw.println(mOccluded);
2038        pw.print("  mDelayedShowingSequence: "); pw.println(mDelayedShowingSequence);
2039        pw.print("  mExitSecureCallback: "); pw.println(mExitSecureCallback);
2040        pw.print("  mDeviceInteractive: "); pw.println(mDeviceInteractive);
2041        pw.print("  mGoingToSleep: "); pw.println(mGoingToSleep);
2042        pw.print("  mHiding: "); pw.println(mHiding);
2043        pw.print("  mWaitingUntilKeyguardVisible: "); pw.println(mWaitingUntilKeyguardVisible);
2044        pw.print("  mKeyguardDonePending: "); pw.println(mKeyguardDonePending);
2045        pw.print("  mHideAnimationRun: "); pw.println(mHideAnimationRun);
2046        pw.print("  mPendingReset: "); pw.println(mPendingReset);
2047        pw.print("  mPendingLock: "); pw.println(mPendingLock);
2048        pw.print("  mWakeAndUnlocking: "); pw.println(mWakeAndUnlocking);
2049        pw.print("  mDrawnCallback: "); pw.println(mDrawnCallback);
2050    }
2051
2052    private static class StartKeyguardExitAnimParams {
2053
2054        long startTime;
2055        long fadeoutDuration;
2056
2057        private StartKeyguardExitAnimParams(long startTime, long fadeoutDuration) {
2058            this.startTime = startTime;
2059            this.fadeoutDuration = fadeoutDuration;
2060        }
2061    }
2062
2063    private void setShowingLocked(boolean showing) {
2064        setShowingLocked(showing, false /* forceCallbacks */);
2065    }
2066
2067    private void setShowingLocked(boolean showing, boolean forceCallbacks) {
2068        if (showing != mShowing || forceCallbacks) {
2069            mShowing = showing;
2070            int size = mKeyguardStateCallbacks.size();
2071            for (int i = size - 1; i >= 0; i--) {
2072                IKeyguardStateCallback callback = mKeyguardStateCallbacks.get(i);
2073                try {
2074                    callback.onShowingStateChanged(showing);
2075                } catch (RemoteException e) {
2076                    Slog.w(TAG, "Failed to call onShowingStateChanged", e);
2077                    if (e instanceof DeadObjectException) {
2078                        mKeyguardStateCallbacks.remove(callback);
2079                    }
2080                }
2081            }
2082            updateInputRestrictedLocked();
2083            mUiOffloadThread.submit(() -> {
2084                mTrustManager.reportKeyguardShowingChanged();
2085            });
2086            updateActivityLockScreenState(showing);
2087        }
2088    }
2089
2090    private void notifyTrustedChangedLocked(boolean trusted) {
2091        int size = mKeyguardStateCallbacks.size();
2092        for (int i = size - 1; i >= 0; i--) {
2093            try {
2094                mKeyguardStateCallbacks.get(i).onTrustedChanged(trusted);
2095            } catch (RemoteException e) {
2096                Slog.w(TAG, "Failed to call notifyTrustedChangedLocked", e);
2097                if (e instanceof DeadObjectException) {
2098                    mKeyguardStateCallbacks.remove(i);
2099                }
2100            }
2101        }
2102    }
2103
2104    private void notifyHasLockscreenWallpaperChanged(boolean hasLockscreenWallpaper) {
2105        int size = mKeyguardStateCallbacks.size();
2106        for (int i = size - 1; i >= 0; i--) {
2107            try {
2108                mKeyguardStateCallbacks.get(i).onHasLockscreenWallpaperChanged(
2109                        hasLockscreenWallpaper);
2110            } catch (RemoteException e) {
2111                Slog.w(TAG, "Failed to call onHasLockscreenWallpaperChanged", e);
2112                if (e instanceof DeadObjectException) {
2113                    mKeyguardStateCallbacks.remove(i);
2114                }
2115            }
2116        }
2117    }
2118
2119    public void addStateMonitorCallback(IKeyguardStateCallback callback) {
2120        synchronized (this) {
2121            mKeyguardStateCallbacks.add(callback);
2122            try {
2123                callback.onSimSecureStateChanged(mUpdateMonitor.isSimPinSecure());
2124                callback.onShowingStateChanged(mShowing);
2125                callback.onInputRestrictedStateChanged(mInputRestricted);
2126                callback.onTrustedChanged(mUpdateMonitor.getUserHasTrust(
2127                        KeyguardUpdateMonitor.getCurrentUser()));
2128                callback.onHasLockscreenWallpaperChanged(mUpdateMonitor.hasLockscreenWallpaper());
2129            } catch (RemoteException e) {
2130                Slog.w(TAG, "Failed to call to IKeyguardStateCallback", e);
2131            }
2132        }
2133    }
2134}
2135