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