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