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