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