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