PhoneWindowManager.java revision e097d341a46a8c40c7e9e1e7e028088b7725b243
1/*
2 * Copyright (C) 2006 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.server.policy;
18
19import android.app.ActivityManager;
20import android.app.ActivityManagerInternal;
21import android.app.ActivityManagerInternal.SleepToken;
22import android.app.ActivityManagerNative;
23import android.app.AppOpsManager;
24import android.app.IUiModeManager;
25import android.app.ProgressDialog;
26import android.app.SearchManager;
27import android.app.StatusBarManager;
28import android.app.UiModeManager;
29import android.content.ActivityNotFoundException;
30import android.content.BroadcastReceiver;
31import android.content.ComponentName;
32import android.content.ContentResolver;
33import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
37import android.content.pm.ActivityInfo;
38import android.content.pm.PackageManager;
39import android.content.pm.ResolveInfo;
40import android.content.res.CompatibilityInfo;
41import android.content.res.Configuration;
42import android.content.res.Resources;
43import android.content.res.TypedArray;
44import android.database.ContentObserver;
45import android.graphics.PixelFormat;
46import android.graphics.Rect;
47import android.hardware.hdmi.HdmiControlManager;
48import android.hardware.hdmi.HdmiPlaybackClient;
49import android.hardware.hdmi.HdmiPlaybackClient.OneTouchPlayCallback;
50import android.media.AudioAttributes;
51import android.media.AudioManager;
52import android.media.AudioSystem;
53import android.media.IAudioService;
54import android.media.Ringtone;
55import android.media.RingtoneManager;
56import android.media.session.MediaSessionLegacyHelper;
57import android.os.Binder;
58import android.os.Bundle;
59import android.os.Debug;
60import android.os.FactoryTest;
61import android.os.Handler;
62import android.os.IBinder;
63import android.os.IDeviceIdleController;
64import android.os.Looper;
65import android.os.Message;
66import android.os.Messenger;
67import android.os.PowerManager;
68import android.os.PowerManagerInternal;
69import android.os.Process;
70import android.os.RemoteException;
71import android.os.ServiceManager;
72import android.os.SystemClock;
73import android.os.SystemProperties;
74import android.os.UEventObserver;
75import android.os.UserHandle;
76import android.os.Vibrator;
77import android.provider.MediaStore;
78import android.provider.Settings;
79import android.service.dreams.DreamManagerInternal;
80import android.service.dreams.DreamService;
81import android.service.dreams.IDreamManager;
82import android.speech.RecognizerIntent;
83import android.telecom.TelecomManager;
84import android.util.DisplayMetrics;
85import android.util.EventLog;
86import android.util.Log;
87import android.util.Slog;
88import android.util.SparseArray;
89import android.view.Display;
90import android.view.Gravity;
91import android.view.HapticFeedbackConstants;
92import android.view.IApplicationToken;
93import android.view.IWindowManager;
94import android.view.InputChannel;
95import android.view.InputDevice;
96import android.view.InputEvent;
97import android.view.InputEventReceiver;
98import android.view.KeyCharacterMap;
99import android.view.KeyCharacterMap.FallbackAction;
100import android.view.KeyEvent;
101import android.view.MotionEvent;
102
103import com.android.internal.logging.MetricsLogger;
104import com.android.internal.policy.PhoneWindow;
105import android.view.Surface;
106import android.view.View;
107import android.view.ViewConfiguration;
108import android.view.WindowManager;
109import android.view.WindowManagerGlobal;
110import android.view.WindowManagerInternal;
111import android.view.WindowManagerPolicy;
112import android.view.accessibility.AccessibilityEvent;
113import android.view.accessibility.AccessibilityManager;
114import android.view.animation.Animation;
115import android.view.animation.AnimationSet;
116import android.view.animation.AnimationUtils;
117import com.android.internal.R;
118import com.android.internal.statusbar.IStatusBarService;
119import com.android.internal.util.ScreenShapeHelper;
120import com.android.internal.widget.PointerLocationView;
121import com.android.server.LocalServices;
122import com.android.server.policy.keyguard.KeyguardServiceDelegate;
123import com.android.server.policy.keyguard.KeyguardServiceDelegate.DrawnListener;
124
125import java.io.File;
126import java.io.FileReader;
127import java.io.IOException;
128import java.io.PrintWriter;
129import java.util.Arrays;
130import java.util.HashSet;
131import java.util.List;
132
133import static android.view.WindowManager.LayoutParams.*;
134import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_ABSENT;
135import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN;
136import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_CLOSED;
137import static android.view.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_COVER_ABSENT;
138import static android.view.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_UNCOVERED;
139import static android.view.WindowManagerPolicy.WindowManagerFuncs.CAMERA_LENS_COVERED;
140
141/**
142 * WindowManagerPolicy implementation for the Android phone UI.  This
143 * introduces a new method suffix, Lp, for an internal lock of the
144 * PhoneWindowManager.  This is used to protect some internal state, and
145 * can be acquired with either the Lw and Li lock held, so has the restrictions
146 * of both of those when held.
147 */
148public class PhoneWindowManager implements WindowManagerPolicy {
149    static final String TAG = "WindowManager";
150    static final boolean DEBUG = false;
151    static final boolean localLOGV = false;
152    static final boolean DEBUG_INPUT = false;
153    static final boolean DEBUG_KEYGUARD = false;
154    static final boolean DEBUG_LAYOUT = false;
155    static final boolean DEBUG_STARTING_WINDOW = false;
156    static final boolean DEBUG_WAKEUP = false;
157    static final boolean SHOW_STARTING_ANIMATIONS = true;
158    static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
159
160    // Whether to allow dock apps with METADATA_DOCK_HOME to temporarily take over the Home key.
161    // No longer recommended for desk docks; still useful in car docks.
162    static final boolean ENABLE_CAR_DOCK_HOME_CAPTURE = true;
163    static final boolean ENABLE_DESK_DOCK_HOME_CAPTURE = false;
164
165    static final int SHORT_PRESS_POWER_NOTHING = 0;
166    static final int SHORT_PRESS_POWER_GO_TO_SLEEP = 1;
167    static final int SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP = 2;
168    static final int SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP_AND_GO_HOME = 3;
169    static final int SHORT_PRESS_POWER_GO_HOME = 4;
170
171    static final int LONG_PRESS_POWER_NOTHING = 0;
172    static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
173    static final int LONG_PRESS_POWER_SHUT_OFF = 2;
174    static final int LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM = 3;
175
176    static final int MULTI_PRESS_POWER_NOTHING = 0;
177    static final int MULTI_PRESS_POWER_THEATER_MODE = 1;
178    static final int MULTI_PRESS_POWER_BRIGHTNESS_BOOST = 2;
179
180    // These need to match the documentation/constant in
181    // core/res/res/values/config.xml
182    static final int LONG_PRESS_HOME_NOTHING = 0;
183    static final int LONG_PRESS_HOME_RECENT_SYSTEM_UI = 1;
184    static final int LONG_PRESS_HOME_ASSIST = 2;
185
186    static final int DOUBLE_TAP_HOME_NOTHING = 0;
187    static final int DOUBLE_TAP_HOME_RECENT_SYSTEM_UI = 1;
188
189    static final int SHORT_PRESS_SLEEP_GO_TO_SLEEP = 0;
190    static final int SHORT_PRESS_SLEEP_GO_TO_SLEEP_AND_GO_HOME = 1;
191
192    static final int APPLICATION_MEDIA_SUBLAYER = -2;
193    static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
194    static final int APPLICATION_PANEL_SUBLAYER = 1;
195    static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
196    static final int APPLICATION_ABOVE_SUB_PANEL_SUBLAYER = 3;
197
198    static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
199    static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
200    static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
201    static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
202    static public final String SYSTEM_DIALOG_REASON_ASSIST = "assist";
203
204    /**
205     * These are the system UI flags that, when changing, can cause the layout
206     * of the screen to change.
207     */
208    static final int SYSTEM_UI_CHANGING_LAYOUT =
209              View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
210            | View.SYSTEM_UI_FLAG_FULLSCREEN
211            | View.STATUS_BAR_TRANSLUCENT
212            | View.NAVIGATION_BAR_TRANSLUCENT
213            | View.SYSTEM_UI_TRANSPARENT;
214
215    private static final AudioAttributes VIBRATION_ATTRIBUTES = new AudioAttributes.Builder()
216            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
217            .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
218            .build();
219
220    // The panic gesture may become active only after the keyguard is dismissed and the immersive
221    // app shows again. If that doesn't happen for 30s we drop the gesture.
222    private static final long PANIC_GESTURE_EXPIRATION = 30000;
223
224    /**
225     * Keyguard stuff
226     */
227    private WindowState mKeyguardScrim;
228    private boolean mKeyguardHidden;
229    private boolean mKeyguardDrawnOnce;
230
231    /* Table of Application Launch keys.  Maps from key codes to intent categories.
232     *
233     * These are special keys that are used to launch particular kinds of applications,
234     * such as a web browser.  HID defines nearly a hundred of them in the Consumer (0x0C)
235     * usage page.  We don't support quite that many yet...
236     */
237    static SparseArray<String> sApplicationLaunchKeyCategories;
238    static {
239        sApplicationLaunchKeyCategories = new SparseArray<String>();
240        sApplicationLaunchKeyCategories.append(
241                KeyEvent.KEYCODE_EXPLORER, Intent.CATEGORY_APP_BROWSER);
242        sApplicationLaunchKeyCategories.append(
243                KeyEvent.KEYCODE_ENVELOPE, Intent.CATEGORY_APP_EMAIL);
244        sApplicationLaunchKeyCategories.append(
245                KeyEvent.KEYCODE_CONTACTS, Intent.CATEGORY_APP_CONTACTS);
246        sApplicationLaunchKeyCategories.append(
247                KeyEvent.KEYCODE_CALENDAR, Intent.CATEGORY_APP_CALENDAR);
248        sApplicationLaunchKeyCategories.append(
249                KeyEvent.KEYCODE_MUSIC, Intent.CATEGORY_APP_MUSIC);
250        sApplicationLaunchKeyCategories.append(
251                KeyEvent.KEYCODE_CALCULATOR, Intent.CATEGORY_APP_CALCULATOR);
252    }
253
254    /** Amount of time (in milliseconds) to wait for windows drawn before powering on. */
255    static final int WAITING_FOR_DRAWN_TIMEOUT = 1000;
256
257    /**
258     * Lock protecting internal state.  Must not call out into window
259     * manager with lock held.  (This lock will be acquired in places
260     * where the window manager is calling in with its own lock held.)
261     */
262    private final Object mLock = new Object();
263
264    Context mContext;
265    IWindowManager mWindowManager;
266    WindowManagerFuncs mWindowManagerFuncs;
267    WindowManagerInternal mWindowManagerInternal;
268    PowerManager mPowerManager;
269    PowerManagerInternal mPowerManagerInternal;
270    ActivityManagerInternal mActivityManagerInternal;
271    DreamManagerInternal mDreamManagerInternal;
272    IStatusBarService mStatusBarService;
273    boolean mPreloadedRecentApps;
274    final Object mServiceAquireLock = new Object();
275    Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
276    SearchManager mSearchManager;
277    AccessibilityManager mAccessibilityManager;
278    BurnInProtectionHelper mBurnInProtectionHelper;
279    AppOpsManager mAppOpsManager;
280
281    // Vibrator pattern for haptic feedback of a long press.
282    long[] mLongPressVibePattern;
283
284    // Vibrator pattern for haptic feedback of virtual key press.
285    long[] mVirtualKeyVibePattern;
286
287    // Vibrator pattern for a short vibration.
288    long[] mKeyboardTapVibePattern;
289
290    // Vibrator pattern for a short vibration when tapping on an hour/minute tick of a Clock.
291    long[] mClockTickVibePattern;
292
293    // Vibrator pattern for a short vibration when tapping on a day/month/year date of a Calendar.
294    long[] mCalendarDateVibePattern;
295
296    // Vibrator pattern for haptic feedback during boot when safe mode is disabled.
297    long[] mSafeModeDisabledVibePattern;
298
299    // Vibrator pattern for haptic feedback during boot when safe mode is enabled.
300    long[] mSafeModeEnabledVibePattern;
301
302    // Vibrator pattern for haptic feedback of a context click.
303    long[] mContextClickVibePattern;
304
305    /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
306    boolean mEnableShiftMenuBugReports = false;
307
308    boolean mSafeMode;
309    WindowState mStatusBar = null;
310    int mStatusBarHeight;
311    WindowState mNavigationBar = null;
312    boolean mHasNavigationBar = false;
313    boolean mCanHideNavigationBar = false;
314    boolean mNavigationBarCanMove = false; // can the navigation bar ever move to the side?
315    boolean mNavigationBarOnBottom = true; // is the navigation bar on the bottom *right now*?
316    int[] mNavigationBarHeightForRotation = new int[4];
317    int[] mNavigationBarWidthForRotation = new int[4];
318
319    boolean mBootMessageNeedsHiding;
320    KeyguardServiceDelegate mKeyguardDelegate;
321    final Runnable mWindowManagerDrawCallback = new Runnable() {
322        @Override
323        public void run() {
324            if (DEBUG_WAKEUP) Slog.i(TAG, "All windows ready for display!");
325            mHandler.sendEmptyMessage(MSG_WINDOW_MANAGER_DRAWN_COMPLETE);
326        }
327    };
328    final DrawnListener mKeyguardDrawnCallback = new DrawnListener() {
329        @Override
330        public void onDrawn() {
331            if (DEBUG_WAKEUP) Slog.d(TAG, "mKeyguardDelegate.ShowListener.onDrawn.");
332            mHandler.sendEmptyMessage(MSG_KEYGUARD_DRAWN_COMPLETE);
333        }
334    };
335
336    GlobalActions mGlobalActions;
337    Handler mHandler;
338    WindowState mLastInputMethodWindow = null;
339    WindowState mLastInputMethodTargetWindow = null;
340
341    // FIXME This state is shared between the input reader and handler thread.
342    // Technically it's broken and buggy but it has been like this for many years
343    // and we have not yet seen any problems.  Someday we'll rewrite this logic
344    // so that only one thread is involved in handling input policy.  Unfortunately
345    // it's on a critical path for power management so we can't just post the work to the
346    // handler thread.  We'll need to resolve this someday by teaching the input dispatcher
347    // to hold wakelocks during dispatch and eliminating the critical path.
348    volatile boolean mPowerKeyHandled;
349    volatile boolean mBeganFromNonInteractive;
350    volatile int mPowerKeyPressCounter;
351    volatile boolean mEndCallKeyHandled;
352
353    boolean mRecentsVisible;
354    int mRecentAppsHeldModifiers;
355    boolean mLanguageSwitchKeyPressed;
356
357    int mLidState = LID_ABSENT;
358    int mCameraLensCoverState = CAMERA_LENS_COVER_ABSENT;
359    boolean mHaveBuiltInKeyboard;
360
361    boolean mSystemReady;
362    boolean mSystemBooted;
363    private boolean mDeferBindKeyguard;
364    boolean mHdmiPlugged;
365    HdmiControl mHdmiControl;
366    IUiModeManager mUiModeManager;
367    int mUiMode;
368    int mDockMode = Intent.EXTRA_DOCK_STATE_UNDOCKED;
369    int mLidOpenRotation;
370    int mCarDockRotation;
371    int mDeskDockRotation;
372    int mUndockedHdmiRotation;
373    int mDemoHdmiRotation;
374    boolean mDemoHdmiRotationLock;
375    int mDemoRotation;
376    boolean mDemoRotationLock;
377
378    boolean mWakeGestureEnabledSetting;
379    MyWakeGestureListener mWakeGestureListener;
380
381    // Default display does not rotate, apps that require non-default orientation will have to
382    // have the orientation emulated.
383    private boolean mForceDefaultOrientation = false;
384
385    int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE;
386    int mUserRotation = Surface.ROTATION_0;
387    boolean mAccelerometerDefault;
388
389    boolean mSupportAutoRotation;
390    int mAllowAllRotations = -1;
391    boolean mCarDockEnablesAccelerometer;
392    boolean mDeskDockEnablesAccelerometer;
393    int mLidKeyboardAccessibility;
394    int mLidNavigationAccessibility;
395    boolean mLidControlsSleep;
396    int mShortPressOnPowerBehavior;
397    int mLongPressOnPowerBehavior;
398    int mDoublePressOnPowerBehavior;
399    int mTriplePressOnPowerBehavior;
400    int mShortPressOnSleepBehavior;
401    boolean mAwake;
402    boolean mScreenOnEarly;
403    boolean mScreenOnFully;
404    ScreenOnListener mScreenOnListener;
405    boolean mKeyguardDrawComplete;
406    boolean mWindowManagerDrawComplete;
407    boolean mOrientationSensorEnabled = false;
408    int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
409    boolean mHasSoftInput = false;
410    boolean mTranslucentDecorEnabled = true;
411    boolean mUseTvRouting;
412
413    int mPointerLocationMode = 0; // guarded by mLock
414
415    // The last window we were told about in focusChanged.
416    WindowState mFocusedWindow;
417    IApplicationToken mFocusedApp;
418
419    PointerLocationView mPointerLocationView;
420
421    // The current size of the screen; really; extends into the overscan area of
422    // the screen and doesn't account for any system elements like the status bar.
423    int mOverscanScreenLeft, mOverscanScreenTop;
424    int mOverscanScreenWidth, mOverscanScreenHeight;
425    // The current visible size of the screen; really; (ir)regardless of whether the status
426    // bar can be hidden but not extending into the overscan area.
427    int mUnrestrictedScreenLeft, mUnrestrictedScreenTop;
428    int mUnrestrictedScreenWidth, mUnrestrictedScreenHeight;
429    // Like mOverscanScreen*, but allowed to move into the overscan region where appropriate.
430    int mRestrictedOverscanScreenLeft, mRestrictedOverscanScreenTop;
431    int mRestrictedOverscanScreenWidth, mRestrictedOverscanScreenHeight;
432    // The current size of the screen; these may be different than (0,0)-(dw,dh)
433    // if the status bar can't be hidden; in that case it effectively carves out
434    // that area of the display from all other windows.
435    int mRestrictedScreenLeft, mRestrictedScreenTop;
436    int mRestrictedScreenWidth, mRestrictedScreenHeight;
437    // During layout, the current screen borders accounting for any currently
438    // visible system UI elements.
439    int mSystemLeft, mSystemTop, mSystemRight, mSystemBottom;
440    // For applications requesting stable content insets, these are them.
441    int mStableLeft, mStableTop, mStableRight, mStableBottom;
442    // For applications requesting stable content insets but have also set the
443    // fullscreen window flag, these are the stable dimensions without the status bar.
444    int mStableFullscreenLeft, mStableFullscreenTop;
445    int mStableFullscreenRight, mStableFullscreenBottom;
446    // During layout, the current screen borders with all outer decoration
447    // (status bar, input method dock) accounted for.
448    int mCurLeft, mCurTop, mCurRight, mCurBottom;
449    // During layout, the frame in which content should be displayed
450    // to the user, accounting for all screen decoration except for any
451    // space they deem as available for other content.  This is usually
452    // the same as mCur*, but may be larger if the screen decor has supplied
453    // content insets.
454    int mContentLeft, mContentTop, mContentRight, mContentBottom;
455    // During layout, the frame in which voice content should be displayed
456    // to the user, accounting for all screen decoration except for any
457    // space they deem as available for other content.
458    int mVoiceContentLeft, mVoiceContentTop, mVoiceContentRight, mVoiceContentBottom;
459    // During layout, the current screen borders along which input method
460    // windows are placed.
461    int mDockLeft, mDockTop, mDockRight, mDockBottom;
462    // During layout, the layer at which the doc window is placed.
463    int mDockLayer;
464    // During layout, this is the layer of the status bar.
465    int mStatusBarLayer;
466    int mLastSystemUiFlags;
467    // Bits that we are in the process of clearing, so we want to prevent
468    // them from being set by applications until everything has been updated
469    // to have them clear.
470    int mResettingSystemUiFlags = 0;
471    // Bits that we are currently always keeping cleared.
472    int mForceClearedSystemUiFlags = 0;
473    // What we last reported to system UI about whether the compatibility
474    // menu needs to be displayed.
475    boolean mLastFocusNeedsMenu = false;
476    // If nonzero, a panic gesture was performed at that time in uptime millis and is still pending.
477    private long mPendingPanicGestureUptime;
478
479    InputConsumer mInputConsumer = null;
480
481    static final Rect mTmpParentFrame = new Rect();
482    static final Rect mTmpDisplayFrame = new Rect();
483    static final Rect mTmpOverscanFrame = new Rect();
484    static final Rect mTmpContentFrame = new Rect();
485    static final Rect mTmpVisibleFrame = new Rect();
486    static final Rect mTmpDecorFrame = new Rect();
487    static final Rect mTmpStableFrame = new Rect();
488    static final Rect mTmpNavigationFrame = new Rect();
489    static final Rect mTmpOutsetFrame = new Rect();
490
491    WindowState mTopFullscreenOpaqueWindowState;
492    WindowState mTopFullscreenOpaqueOrDimmingWindowState;
493    HashSet<IApplicationToken> mAppsToBeHidden = new HashSet<IApplicationToken>();
494    HashSet<IApplicationToken> mAppsThatDismissKeyguard = new HashSet<IApplicationToken>();
495    boolean mTopIsFullscreen;
496    boolean mForceStatusBar;
497    boolean mForceStatusBarFromKeyguard;
498    private boolean mForceStatusBarTransparent;
499    boolean mHideLockScreen;
500    boolean mForcingShowNavBar;
501    int mForcingShowNavBarLayer;
502
503    // States of keyguard dismiss.
504    private static final int DISMISS_KEYGUARD_NONE = 0; // Keyguard not being dismissed.
505    private static final int DISMISS_KEYGUARD_START = 1; // Keyguard needs to be dismissed.
506    private static final int DISMISS_KEYGUARD_CONTINUE = 2; // Keyguard has been dismissed.
507    int mDismissKeyguard = DISMISS_KEYGUARD_NONE;
508
509    /** The window that is currently dismissing the keyguard. Dismissing the keyguard must only
510     * be done once per window. */
511    private WindowState mWinDismissingKeyguard;
512
513    /** When window is currently dismissing the keyguard, dismissing the keyguard must handle
514     * the keygaurd secure state change instantly case, e.g. the use case of inserting a PIN
515     * lock SIM card. This variable is used to record the previous keyguard secure state for
516     * monitoring secure state change on window dismissing keyguard. */
517    private boolean mSecureDismissingKeyguard;
518
519    /** The window that is currently showing "over" the keyguard. If there is an app window
520     * belonging to another app on top of this the keyguard shows. If there is a fullscreen
521     * app window under this, still dismiss the keyguard but don't show the app underneath. Show
522     * the wallpaper. */
523    private WindowState mWinShowWhenLocked;
524
525    boolean mShowingLockscreen;
526    boolean mShowingDream;
527    boolean mDreamingLockscreen;
528    boolean mDreamingSleepTokenNeeded;
529    SleepToken mDreamingSleepToken;
530    SleepToken mScreenOffSleepToken;
531    boolean mKeyguardSecure;
532    boolean mKeyguardSecureIncludingHidden;
533    volatile boolean mKeyguardOccluded;
534    boolean mHomePressed;
535    boolean mHomeConsumed;
536    boolean mHomeDoubleTapPending;
537    Intent mHomeIntent;
538    Intent mCarDockIntent;
539    Intent mDeskDockIntent;
540    boolean mSearchKeyShortcutPending;
541    boolean mConsumeSearchKeyUp;
542    boolean mAssistKeyLongPressed;
543    boolean mPendingMetaAction;
544
545    // support for activating the lock screen while the screen is on
546    boolean mAllowLockscreenWhenOn;
547    int mLockScreenTimeout;
548    boolean mLockScreenTimerActive;
549
550    // Behavior of ENDCALL Button.  (See Settings.System.END_BUTTON_BEHAVIOR.)
551    int mEndcallBehavior;
552
553    // Behavior of POWER button while in-call and screen on.
554    // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.)
555    int mIncallPowerBehavior;
556
557    Display mDisplay;
558
559    private int mDisplayRotation;
560
561    int mLandscapeRotation = 0;  // default landscape rotation
562    int mSeascapeRotation = 0;   // "other" landscape rotation, 180 degrees from mLandscapeRotation
563    int mPortraitRotation = 0;   // default portrait rotation
564    int mUpsideDownRotation = 0; // "other" portrait rotation
565
566    int mOverscanLeft = 0;
567    int mOverscanTop = 0;
568    int mOverscanRight = 0;
569    int mOverscanBottom = 0;
570
571    // What we do when the user long presses on home
572    private int mLongPressOnHomeBehavior;
573
574    // What we do when the user double-taps on home
575    private int mDoubleTapOnHomeBehavior;
576
577    // Allowed theater mode wake actions
578    private boolean mAllowTheaterModeWakeFromKey;
579    private boolean mAllowTheaterModeWakeFromPowerKey;
580    private boolean mAllowTheaterModeWakeFromMotion;
581    private boolean mAllowTheaterModeWakeFromMotionWhenNotDreaming;
582    private boolean mAllowTheaterModeWakeFromCameraLens;
583    private boolean mAllowTheaterModeWakeFromLidSwitch;
584    private boolean mAllowTheaterModeWakeFromWakeGesture;
585
586    // Whether to support long press from power button in non-interactive mode
587    private boolean mSupportLongPressPowerWhenNonInteractive;
588
589    // Whether to go to sleep entering theater mode from power button
590    private boolean mGoToSleepOnButtonPressTheaterMode;
591
592    // Screenshot trigger states
593    // Time to volume and power must be pressed within this interval of each other.
594    private static final long SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS = 150;
595    // Increase the chord delay when taking a screenshot from the keyguard
596    private static final float KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER = 2.5f;
597    private boolean mScreenshotChordEnabled;
598    private boolean mScreenshotChordVolumeDownKeyTriggered;
599    private long mScreenshotChordVolumeDownKeyTime;
600    private boolean mScreenshotChordVolumeDownKeyConsumed;
601    private boolean mScreenshotChordVolumeUpKeyTriggered;
602    private boolean mScreenshotChordPowerKeyTriggered;
603    private long mScreenshotChordPowerKeyTime;
604
605    /* The number of steps between min and max brightness */
606    private static final int BRIGHTNESS_STEPS = 10;
607
608    SettingsObserver mSettingsObserver;
609    ShortcutManager mShortcutManager;
610    PowerManager.WakeLock mBroadcastWakeLock;
611    PowerManager.WakeLock mPowerKeyWakeLock;
612    boolean mHavePendingMediaKeyRepeatWithWakeLock;
613
614    private int mCurrentUserId;
615
616    // Maps global key codes to the components that will handle them.
617    private GlobalKeyManager mGlobalKeyManager;
618
619    // Fallback actions by key code.
620    private final SparseArray<KeyCharacterMap.FallbackAction> mFallbackActions =
621            new SparseArray<KeyCharacterMap.FallbackAction>();
622
623    private final LogDecelerateInterpolator mLogDecelerateInterpolator
624            = new LogDecelerateInterpolator(100, 0);
625
626    private static final int MSG_ENABLE_POINTER_LOCATION = 1;
627    private static final int MSG_DISABLE_POINTER_LOCATION = 2;
628    private static final int MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK = 3;
629    private static final int MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK = 4;
630    private static final int MSG_KEYGUARD_DRAWN_COMPLETE = 5;
631    private static final int MSG_KEYGUARD_DRAWN_TIMEOUT = 6;
632    private static final int MSG_WINDOW_MANAGER_DRAWN_COMPLETE = 7;
633    private static final int MSG_DISPATCH_SHOW_RECENTS = 9;
634    private static final int MSG_DISPATCH_SHOW_GLOBAL_ACTIONS = 10;
635    private static final int MSG_HIDE_BOOT_MESSAGE = 11;
636    private static final int MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK = 12;
637    private static final int MSG_POWER_DELAYED_PRESS = 13;
638    private static final int MSG_POWER_LONG_PRESS = 14;
639    private static final int MSG_UPDATE_DREAMING_SLEEP_TOKEN = 15;
640    private static final int MSG_REQUEST_TRANSIENT_BARS = 16;
641
642    private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS = 0;
643    private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION = 1;
644
645    private class PolicyHandler extends Handler {
646        @Override
647        public void handleMessage(Message msg) {
648            switch (msg.what) {
649                case MSG_ENABLE_POINTER_LOCATION:
650                    enablePointerLocation();
651                    break;
652                case MSG_DISABLE_POINTER_LOCATION:
653                    disablePointerLocation();
654                    break;
655                case MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK:
656                    dispatchMediaKeyWithWakeLock((KeyEvent)msg.obj);
657                    break;
658                case MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK:
659                    dispatchMediaKeyRepeatWithWakeLock((KeyEvent)msg.obj);
660                    break;
661                case MSG_DISPATCH_SHOW_RECENTS:
662                    showRecentApps(false);
663                    break;
664                case MSG_DISPATCH_SHOW_GLOBAL_ACTIONS:
665                    showGlobalActionsInternal();
666                    break;
667                case MSG_KEYGUARD_DRAWN_COMPLETE:
668                    if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mKeyguardDrawComplete");
669                    finishKeyguardDrawn();
670                    break;
671                case MSG_KEYGUARD_DRAWN_TIMEOUT:
672                    Slog.w(TAG, "Keyguard drawn timeout. Setting mKeyguardDrawComplete");
673                    finishKeyguardDrawn();
674                    break;
675                case MSG_WINDOW_MANAGER_DRAWN_COMPLETE:
676                    if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mWindowManagerDrawComplete");
677                    finishWindowsDrawn();
678                    break;
679                case MSG_HIDE_BOOT_MESSAGE:
680                    handleHideBootMessage();
681                    break;
682                case MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK:
683                    launchVoiceAssistWithWakeLock(msg.arg1 != 0);
684                    break;
685                case MSG_POWER_DELAYED_PRESS:
686                    powerPress((Long)msg.obj, msg.arg1 != 0, msg.arg2);
687                    finishPowerKeyPress();
688                    break;
689                case MSG_POWER_LONG_PRESS:
690                    powerLongPress();
691                    break;
692                case MSG_UPDATE_DREAMING_SLEEP_TOKEN:
693                    updateDreamingSleepToken(msg.arg1 != 0);
694                    break;
695                case MSG_REQUEST_TRANSIENT_BARS:
696                    WindowState targetBar = (msg.arg1 == MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS) ?
697                            mStatusBar : mNavigationBar;
698                    if (targetBar != null) {
699                        requestTransientBars(targetBar);
700                    }
701                    break;
702            }
703        }
704    }
705
706    private UEventObserver mHDMIObserver = new UEventObserver() {
707        @Override
708        public void onUEvent(UEventObserver.UEvent event) {
709            setHdmiPlugged("1".equals(event.get("SWITCH_STATE")));
710        }
711    };
712
713    class SettingsObserver extends ContentObserver {
714        SettingsObserver(Handler handler) {
715            super(handler);
716        }
717
718        void observe() {
719            // Observe all users' changes
720            ContentResolver resolver = mContext.getContentResolver();
721            resolver.registerContentObserver(Settings.System.getUriFor(
722                    Settings.System.END_BUTTON_BEHAVIOR), false, this,
723                    UserHandle.USER_ALL);
724            resolver.registerContentObserver(Settings.Secure.getUriFor(
725                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this,
726                    UserHandle.USER_ALL);
727            resolver.registerContentObserver(Settings.Secure.getUriFor(
728                    Settings.Secure.WAKE_GESTURE_ENABLED), false, this,
729                    UserHandle.USER_ALL);
730            resolver.registerContentObserver(Settings.System.getUriFor(
731                    Settings.System.ACCELEROMETER_ROTATION), false, this,
732                    UserHandle.USER_ALL);
733            resolver.registerContentObserver(Settings.System.getUriFor(
734                    Settings.System.USER_ROTATION), false, this,
735                    UserHandle.USER_ALL);
736            resolver.registerContentObserver(Settings.System.getUriFor(
737                    Settings.System.SCREEN_OFF_TIMEOUT), false, this,
738                    UserHandle.USER_ALL);
739            resolver.registerContentObserver(Settings.System.getUriFor(
740                    Settings.System.POINTER_LOCATION), false, this,
741                    UserHandle.USER_ALL);
742            resolver.registerContentObserver(Settings.Secure.getUriFor(
743                    Settings.Secure.DEFAULT_INPUT_METHOD), false, this,
744                    UserHandle.USER_ALL);
745            resolver.registerContentObserver(Settings.Secure.getUriFor(
746                    Settings.Secure.IMMERSIVE_MODE_CONFIRMATIONS), false, this,
747                    UserHandle.USER_ALL);
748            resolver.registerContentObserver(Settings.Global.getUriFor(
749                    Settings.Global.POLICY_CONTROL), false, this,
750                    UserHandle.USER_ALL);
751            updateSettings();
752        }
753
754        @Override public void onChange(boolean selfChange) {
755            updateSettings();
756            updateRotation(false);
757        }
758    }
759
760    class MyWakeGestureListener extends WakeGestureListener {
761        MyWakeGestureListener(Context context, Handler handler) {
762            super(context, handler);
763        }
764
765        @Override
766        public void onWakeUp() {
767            synchronized (mLock) {
768                if (shouldEnableWakeGestureLp()) {
769                    performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
770                    wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromWakeGesture,
771                            "android.policy:GESTURE");
772                }
773            }
774        }
775    }
776
777    class MyOrientationListener extends WindowOrientationListener {
778        private final Runnable mUpdateRotationRunnable = new Runnable() {
779            @Override
780            public void run() {
781                updateRotation(false);
782            }
783        };
784
785        MyOrientationListener(Context context, Handler handler) {
786            super(context, handler);
787        }
788
789        @Override
790        public void onProposedRotationChanged(int rotation) {
791            if (localLOGV) Slog.v(TAG, "onProposedRotationChanged, rotation=" + rotation);
792            mHandler.post(mUpdateRotationRunnable);
793        }
794    }
795    MyOrientationListener mOrientationListener;
796
797    private final StatusBarController mStatusBarController = new StatusBarController();
798
799    private final BarController mNavigationBarController = new BarController("NavigationBar",
800            View.NAVIGATION_BAR_TRANSIENT,
801            View.NAVIGATION_BAR_UNHIDE,
802            View.NAVIGATION_BAR_TRANSLUCENT,
803            StatusBarManager.WINDOW_NAVIGATION_BAR,
804            WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
805
806    private ImmersiveModeConfirmation mImmersiveModeConfirmation;
807
808    private SystemGesturesPointerEventListener mSystemGestures;
809
810    IStatusBarService getStatusBarService() {
811        synchronized (mServiceAquireLock) {
812            if (mStatusBarService == null) {
813                mStatusBarService = IStatusBarService.Stub.asInterface(
814                        ServiceManager.getService("statusbar"));
815            }
816            return mStatusBarService;
817        }
818    }
819
820    /*
821     * We always let the sensor be switched on by default except when
822     * the user has explicitly disabled sensor based rotation or when the
823     * screen is switched off.
824     */
825    boolean needSensorRunningLp() {
826        if (mSupportAutoRotation) {
827            if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
828                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
829                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
830                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
831                // If the application has explicitly requested to follow the
832                // orientation, then we need to turn the sensor on.
833                return true;
834            }
835        }
836        if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) ||
837                (mDeskDockEnablesAccelerometer && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
838                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
839                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK))) {
840            // enable accelerometer if we are docked in a dock that enables accelerometer
841            // orientation management,
842            return true;
843        }
844        if (mUserRotationMode == USER_ROTATION_LOCKED) {
845            // If the setting for using the sensor by default is enabled, then
846            // we will always leave it on.  Note that the user could go to
847            // a window that forces an orientation that does not use the
848            // sensor and in theory we could turn it off... however, when next
849            // turning it on we won't have a good value for the current
850            // orientation for a little bit, which can cause orientation
851            // changes to lag, so we'd like to keep it always on.  (It will
852            // still be turned off when the screen is off.)
853            return false;
854        }
855        return mSupportAutoRotation;
856    }
857
858    /*
859     * Various use cases for invoking this function
860     * screen turning off, should always disable listeners if already enabled
861     * screen turned on and current app has sensor based orientation, enable listeners
862     * if not already enabled
863     * screen turned on and current app does not have sensor orientation, disable listeners if
864     * already enabled
865     * screen turning on and current app has sensor based orientation, enable listeners if needed
866     * screen turning on and current app has nosensor based orientation, do nothing
867     */
868    void updateOrientationListenerLp() {
869        if (!mOrientationListener.canDetectOrientation()) {
870            // If sensor is turned off or nonexistent for some reason
871            return;
872        }
873        // Could have been invoked due to screen turning on or off or
874        // change of the currently visible window's orientation.
875        if (localLOGV) Slog.v(TAG, "mScreenOnEarly=" + mScreenOnEarly
876                + ", mAwake=" + mAwake + ", mCurrentAppOrientation=" + mCurrentAppOrientation
877                + ", mOrientationSensorEnabled=" + mOrientationSensorEnabled
878                + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
879                + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
880        boolean disable = true;
881        // Note: We postpone the rotating of the screen until the keyguard as well as the
882        // window manager have reported a draw complete.
883        if (mScreenOnEarly && mAwake &&
884                mKeyguardDrawComplete && mWindowManagerDrawComplete) {
885            if (needSensorRunningLp()) {
886                disable = false;
887                //enable listener if not already enabled
888                if (!mOrientationSensorEnabled) {
889                    mOrientationListener.enable();
890                    if(localLOGV) Slog.v(TAG, "Enabling listeners");
891                    mOrientationSensorEnabled = true;
892                }
893            }
894        }
895        //check if sensors need to be disabled
896        if (disable && mOrientationSensorEnabled) {
897            mOrientationListener.disable();
898            if(localLOGV) Slog.v(TAG, "Disabling listeners");
899            mOrientationSensorEnabled = false;
900        }
901    }
902
903    private void interceptPowerKeyDown(KeyEvent event, boolean interactive) {
904        // Hold a wake lock until the power key is released.
905        if (!mPowerKeyWakeLock.isHeld()) {
906            mPowerKeyWakeLock.acquire();
907        }
908
909        // Cancel multi-press detection timeout.
910        if (mPowerKeyPressCounter != 0) {
911            mHandler.removeMessages(MSG_POWER_DELAYED_PRESS);
912        }
913
914        // Detect user pressing the power button in panic when an application has
915        // taken over the whole screen.
916        boolean panic = mImmersiveModeConfirmation.onPowerKeyDown(interactive,
917                SystemClock.elapsedRealtime(), isImmersiveMode(mLastSystemUiFlags));
918        if (panic) {
919            mHandler.post(mHiddenNavPanic);
920        }
921
922        // Latch power key state to detect screenshot chord.
923        if (interactive && !mScreenshotChordPowerKeyTriggered
924                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
925            mScreenshotChordPowerKeyTriggered = true;
926            mScreenshotChordPowerKeyTime = event.getDownTime();
927            interceptScreenshotChord();
928        }
929
930        // Stop ringing or end call if configured to do so when power is pressed.
931        TelecomManager telecomManager = getTelecommService();
932        boolean hungUp = false;
933        if (telecomManager != null) {
934            if (telecomManager.isRinging()) {
935                // Pressing Power while there's a ringing incoming
936                // call should silence the ringer.
937                telecomManager.silenceRinger();
938            } else if ((mIncallPowerBehavior
939                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
940                    && telecomManager.isInCall() && interactive) {
941                // Otherwise, if "Power button ends call" is enabled,
942                // the Power button will hang up any current active call.
943                hungUp = telecomManager.endCall();
944            }
945        }
946
947        // If the power key has still not yet been handled, then detect short
948        // press, long press, or multi press and decide what to do.
949        mPowerKeyHandled = hungUp || mScreenshotChordVolumeDownKeyTriggered
950                || mScreenshotChordVolumeUpKeyTriggered;
951        if (!mPowerKeyHandled) {
952            if (interactive) {
953                // When interactive, we're already awake.
954                // Wait for a long press or for the button to be released to decide what to do.
955                if (hasLongPressOnPowerBehavior()) {
956                    Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);
957                    msg.setAsynchronous(true);
958                    mHandler.sendMessageDelayed(msg,
959                            ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
960                }
961            } else {
962                wakeUpFromPowerKey(event.getDownTime());
963
964                if (mSupportLongPressPowerWhenNonInteractive && hasLongPressOnPowerBehavior()) {
965                    Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);
966                    msg.setAsynchronous(true);
967                    mHandler.sendMessageDelayed(msg,
968                            ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
969                    mBeganFromNonInteractive = true;
970                } else {
971                    final int maxCount = getMaxMultiPressPowerCount();
972
973                    if (maxCount <= 1) {
974                        mPowerKeyHandled = true;
975                    } else {
976                        mBeganFromNonInteractive = true;
977                    }
978                }
979            }
980        }
981    }
982
983    private void interceptPowerKeyUp(KeyEvent event, boolean interactive, boolean canceled) {
984        final boolean handled = canceled || mPowerKeyHandled;
985        mScreenshotChordPowerKeyTriggered = false;
986        cancelPendingScreenshotChordAction();
987        cancelPendingPowerKeyAction();
988
989        if (!handled) {
990            // Figure out how to handle the key now that it has been released.
991            mPowerKeyPressCounter += 1;
992
993            final int maxCount = getMaxMultiPressPowerCount();
994            final long eventTime = event.getDownTime();
995            if (mPowerKeyPressCounter < maxCount) {
996                // This could be a multi-press.  Wait a little bit longer to confirm.
997                // Continue holding the wake lock.
998                Message msg = mHandler.obtainMessage(MSG_POWER_DELAYED_PRESS,
999                        interactive ? 1 : 0, mPowerKeyPressCounter, eventTime);
1000                msg.setAsynchronous(true);
1001                mHandler.sendMessageDelayed(msg, ViewConfiguration.getDoubleTapTimeout());
1002                return;
1003            }
1004
1005            // No other actions.  Handle it immediately.
1006            powerPress(eventTime, interactive, mPowerKeyPressCounter);
1007        }
1008
1009        // Done.  Reset our state.
1010        finishPowerKeyPress();
1011    }
1012
1013    private void finishPowerKeyPress() {
1014        mBeganFromNonInteractive = false;
1015        mPowerKeyPressCounter = 0;
1016        if (mPowerKeyWakeLock.isHeld()) {
1017            mPowerKeyWakeLock.release();
1018        }
1019    }
1020
1021    private void cancelPendingPowerKeyAction() {
1022        if (!mPowerKeyHandled) {
1023            mPowerKeyHandled = true;
1024            mHandler.removeMessages(MSG_POWER_LONG_PRESS);
1025        }
1026    }
1027
1028    private void powerPress(long eventTime, boolean interactive, int count) {
1029        if (mScreenOnEarly && !mScreenOnFully) {
1030            Slog.i(TAG, "Suppressed redundant power key press while "
1031                    + "already in the process of turning the screen on.");
1032            return;
1033        }
1034
1035        if (count == 2) {
1036            powerMultiPressAction(eventTime, interactive, mDoublePressOnPowerBehavior);
1037        } else if (count == 3) {
1038            powerMultiPressAction(eventTime, interactive, mTriplePressOnPowerBehavior);
1039        } else if (interactive && !mBeganFromNonInteractive) {
1040            switch (mShortPressOnPowerBehavior) {
1041                case SHORT_PRESS_POWER_NOTHING:
1042                    break;
1043                case SHORT_PRESS_POWER_GO_TO_SLEEP:
1044                    mPowerManager.goToSleep(eventTime,
1045                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
1046                    break;
1047                case SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP:
1048                    mPowerManager.goToSleep(eventTime,
1049                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON,
1050                            PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
1051                    break;
1052                case SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP_AND_GO_HOME:
1053                    mPowerManager.goToSleep(eventTime,
1054                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON,
1055                            PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
1056                    launchHomeFromHotKey();
1057                    break;
1058                case SHORT_PRESS_POWER_GO_HOME:
1059                    launchHomeFromHotKey(true /* awakenFromDreams */, false /*respectKeyguard*/);
1060                    break;
1061            }
1062        }
1063    }
1064
1065    private void powerMultiPressAction(long eventTime, boolean interactive, int behavior) {
1066        switch (behavior) {
1067            case MULTI_PRESS_POWER_NOTHING:
1068                break;
1069            case MULTI_PRESS_POWER_THEATER_MODE:
1070                if (!isUserSetupComplete()) {
1071                    Slog.i(TAG, "Ignoring toggling theater mode - device not setup.");
1072                    break;
1073                }
1074
1075                if (isTheaterModeEnabled()) {
1076                    Slog.i(TAG, "Toggling theater mode off.");
1077                    Settings.Global.putInt(mContext.getContentResolver(),
1078                            Settings.Global.THEATER_MODE_ON, 0);
1079                    if (!interactive) {
1080                        wakeUpFromPowerKey(eventTime);
1081                    }
1082                } else {
1083                    Slog.i(TAG, "Toggling theater mode on.");
1084                    Settings.Global.putInt(mContext.getContentResolver(),
1085                            Settings.Global.THEATER_MODE_ON, 1);
1086
1087                    if (mGoToSleepOnButtonPressTheaterMode && interactive) {
1088                        mPowerManager.goToSleep(eventTime,
1089                                PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
1090                    }
1091                }
1092                break;
1093            case MULTI_PRESS_POWER_BRIGHTNESS_BOOST:
1094                Slog.i(TAG, "Starting brightness boost.");
1095                if (!interactive) {
1096                    wakeUpFromPowerKey(eventTime);
1097                }
1098                mPowerManager.boostScreenBrightness(eventTime);
1099                break;
1100        }
1101    }
1102
1103    private int getMaxMultiPressPowerCount() {
1104        if (mTriplePressOnPowerBehavior != MULTI_PRESS_POWER_NOTHING) {
1105            return 3;
1106        }
1107        if (mDoublePressOnPowerBehavior != MULTI_PRESS_POWER_NOTHING) {
1108            return 2;
1109        }
1110        return 1;
1111    }
1112
1113    private void powerLongPress() {
1114        final int behavior = getResolvedLongPressOnPowerBehavior();
1115        switch (behavior) {
1116        case LONG_PRESS_POWER_NOTHING:
1117            break;
1118        case LONG_PRESS_POWER_GLOBAL_ACTIONS:
1119            mPowerKeyHandled = true;
1120            if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
1121                performAuditoryFeedbackForAccessibilityIfNeed();
1122            }
1123            showGlobalActionsInternal();
1124            break;
1125        case LONG_PRESS_POWER_SHUT_OFF:
1126        case LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM:
1127            mPowerKeyHandled = true;
1128            performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
1129            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
1130            mWindowManagerFuncs.shutdown(behavior == LONG_PRESS_POWER_SHUT_OFF);
1131            break;
1132        }
1133    }
1134
1135    private void sleepPress(long eventTime) {
1136        if (mShortPressOnSleepBehavior == SHORT_PRESS_SLEEP_GO_TO_SLEEP_AND_GO_HOME) {
1137            launchHomeFromHotKey(false /* awakenDreams */, true /*respectKeyguard*/);
1138        }
1139    }
1140
1141    private void sleepRelease(long eventTime) {
1142        switch (mShortPressOnSleepBehavior) {
1143            case SHORT_PRESS_SLEEP_GO_TO_SLEEP:
1144            case SHORT_PRESS_SLEEP_GO_TO_SLEEP_AND_GO_HOME:
1145                Slog.i(TAG, "sleepRelease() calling goToSleep(GO_TO_SLEEP_REASON_SLEEP_BUTTON)");
1146                mPowerManager.goToSleep(eventTime,
1147                       PowerManager.GO_TO_SLEEP_REASON_SLEEP_BUTTON, 0);
1148                break;
1149        }
1150    }
1151
1152    private int getResolvedLongPressOnPowerBehavior() {
1153        if (FactoryTest.isLongPressOnPowerOffEnabled()) {
1154            return LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM;
1155        }
1156        return mLongPressOnPowerBehavior;
1157    }
1158
1159    private boolean hasLongPressOnPowerBehavior() {
1160        return getResolvedLongPressOnPowerBehavior() != LONG_PRESS_POWER_NOTHING;
1161    }
1162
1163    private void interceptScreenshotChord() {
1164        if (mScreenshotChordEnabled
1165                && mScreenshotChordVolumeDownKeyTriggered && mScreenshotChordPowerKeyTriggered
1166                && !mScreenshotChordVolumeUpKeyTriggered) {
1167            final long now = SystemClock.uptimeMillis();
1168            if (now <= mScreenshotChordVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS
1169                    && now <= mScreenshotChordPowerKeyTime
1170                            + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) {
1171                mScreenshotChordVolumeDownKeyConsumed = true;
1172                cancelPendingPowerKeyAction();
1173
1174                mHandler.postDelayed(mScreenshotRunnable, getScreenshotChordLongPressDelay());
1175            }
1176        }
1177    }
1178
1179    private long getScreenshotChordLongPressDelay() {
1180        if (mKeyguardDelegate.isShowing()) {
1181            // Double the time it takes to take a screenshot from the keyguard
1182            return (long) (KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER *
1183                    ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
1184        }
1185        return ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout();
1186    }
1187
1188    private void cancelPendingScreenshotChordAction() {
1189        mHandler.removeCallbacks(mScreenshotRunnable);
1190    }
1191
1192    private final Runnable mEndCallLongPress = new Runnable() {
1193        @Override
1194        public void run() {
1195            mEndCallKeyHandled = true;
1196            if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
1197                performAuditoryFeedbackForAccessibilityIfNeed();
1198            }
1199            showGlobalActionsInternal();
1200        }
1201    };
1202
1203    private final Runnable mScreenshotRunnable = new Runnable() {
1204        @Override
1205        public void run() {
1206            takeScreenshot();
1207        }
1208    };
1209
1210    @Override
1211    public void showGlobalActions() {
1212        mHandler.removeMessages(MSG_DISPATCH_SHOW_GLOBAL_ACTIONS);
1213        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_GLOBAL_ACTIONS);
1214    }
1215
1216    void showGlobalActionsInternal() {
1217        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
1218        if (mGlobalActions == null) {
1219            mGlobalActions = new GlobalActions(mContext, mWindowManagerFuncs);
1220        }
1221        final boolean keyguardShowing = isKeyguardShowingAndNotOccluded();
1222        mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
1223        if (keyguardShowing) {
1224            // since it took two seconds of long press to bring this up,
1225            // poke the wake lock so they have some time to see the dialog.
1226            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
1227        }
1228    }
1229
1230    boolean isDeviceProvisioned() {
1231        return Settings.Global.getInt(
1232                mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1233    }
1234
1235    boolean isUserSetupComplete() {
1236        return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1237                Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_CURRENT) != 0;
1238    }
1239
1240    private void handleShortPressOnHome() {
1241        // Turn on the connected TV and switch HDMI input if we're a HDMI playback device.
1242        getHdmiControl().turnOnTv();
1243
1244        // If there's a dream running then use home to escape the dream
1245        // but don't actually go home.
1246        if (mDreamManagerInternal != null && mDreamManagerInternal.isDreaming()) {
1247            mDreamManagerInternal.stopDream(false /*immediate*/);
1248            return;
1249        }
1250
1251        // Go home!
1252        launchHomeFromHotKey();
1253    }
1254
1255    /**
1256     * Creates an accessor to HDMI control service that performs the operation of
1257     * turning on TV (optional) and switching input to us. If HDMI control service
1258     * is not available or we're not a HDMI playback device, the operation is no-op.
1259     */
1260    private HdmiControl getHdmiControl() {
1261        if (null == mHdmiControl) {
1262            HdmiControlManager manager = (HdmiControlManager) mContext.getSystemService(
1263                        Context.HDMI_CONTROL_SERVICE);
1264            HdmiPlaybackClient client = null;
1265            if (manager != null) {
1266                client = manager.getPlaybackClient();
1267            }
1268            mHdmiControl = new HdmiControl(client);
1269        }
1270        return mHdmiControl;
1271    }
1272
1273    private static class HdmiControl {
1274        private final HdmiPlaybackClient mClient;
1275
1276        private HdmiControl(HdmiPlaybackClient client) {
1277            mClient = client;
1278        }
1279
1280        public void turnOnTv() {
1281            if (mClient == null) {
1282                return;
1283            }
1284            mClient.oneTouchPlay(new OneTouchPlayCallback() {
1285                @Override
1286                public void onComplete(int result) {
1287                    if (result != HdmiControlManager.RESULT_SUCCESS) {
1288                        Log.w(TAG, "One touch play failed: " + result);
1289                    }
1290                }
1291            });
1292        }
1293    }
1294
1295    private void handleLongPressOnHome(int deviceId) {
1296        if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) {
1297            mHomeConsumed = true;
1298            performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
1299
1300            if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
1301                toggleRecentApps();
1302            } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_ASSIST) {
1303                launchAssistAction(null, deviceId);
1304            }
1305        }
1306    }
1307
1308    private void handleDoubleTapOnHome() {
1309        if (mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
1310            mHomeConsumed = true;
1311            toggleRecentApps();
1312        }
1313    }
1314
1315    private final Runnable mHomeDoubleTapTimeoutRunnable = new Runnable() {
1316        @Override
1317        public void run() {
1318            if (mHomeDoubleTapPending) {
1319                mHomeDoubleTapPending = false;
1320                handleShortPressOnHome();
1321            }
1322        }
1323    };
1324
1325    private boolean isRoundWindow() {
1326        return mContext.getResources().getConfiguration().isScreenRound();
1327    }
1328
1329    /** {@inheritDoc} */
1330    @Override
1331    public void init(Context context, IWindowManager windowManager,
1332            WindowManagerFuncs windowManagerFuncs) {
1333        mContext = context;
1334        mWindowManager = windowManager;
1335        mWindowManagerFuncs = windowManagerFuncs;
1336        mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
1337        mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
1338        mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class);
1339        mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1340        mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
1341
1342        // Init display burn-in protection
1343        boolean burnInProtectionEnabled = context.getResources().getBoolean(
1344                com.android.internal.R.bool.config_enableBurnInProtection);
1345        // Allow a system property to override this. Used by developer settings.
1346        boolean burnInProtectionDevMode =
1347                SystemProperties.getBoolean("persist.debug.force_burn_in", false);
1348        if (burnInProtectionEnabled || burnInProtectionDevMode) {
1349            final int minHorizontal;
1350            final int maxHorizontal;
1351            final int minVertical;
1352            final int maxVertical;
1353            final int maxRadius;
1354            if (burnInProtectionDevMode) {
1355                minHorizontal = -8;
1356                maxHorizontal = 8;
1357                minVertical = -8;
1358                maxVertical = -4;
1359                maxRadius = (isRoundWindow()) ? 6 : -1;
1360            } else {
1361                Resources resources = context.getResources();
1362                minHorizontal = resources.getInteger(
1363                        com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset);
1364                maxHorizontal = resources.getInteger(
1365                        com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset);
1366                minVertical = resources.getInteger(
1367                        com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset);
1368                maxVertical = resources.getInteger(
1369                        com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset);
1370                maxRadius = resources.getInteger(
1371                        com.android.internal.R.integer.config_burnInProtectionMaxRadius);
1372            }
1373            mBurnInProtectionHelper = new BurnInProtectionHelper(
1374                    context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius);
1375        }
1376
1377        mHandler = new PolicyHandler();
1378        mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler);
1379        mOrientationListener = new MyOrientationListener(mContext, mHandler);
1380        try {
1381            mOrientationListener.setCurrentRotation(windowManager.getRotation());
1382        } catch (RemoteException ex) { }
1383        mSettingsObserver = new SettingsObserver(mHandler);
1384        mSettingsObserver.observe();
1385        mShortcutManager = new ShortcutManager(context);
1386        mUiMode = context.getResources().getInteger(
1387                com.android.internal.R.integer.config_defaultUiModeType);
1388        mHomeIntent =  new Intent(Intent.ACTION_MAIN, null);
1389        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
1390        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1391                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1392        mCarDockIntent =  new Intent(Intent.ACTION_MAIN, null);
1393        mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
1394        mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1395                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1396        mDeskDockIntent =  new Intent(Intent.ACTION_MAIN, null);
1397        mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
1398        mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1399                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1400
1401        mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1402        mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1403                "PhoneWindowManager.mBroadcastWakeLock");
1404        mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1405                "PhoneWindowManager.mPowerKeyWakeLock");
1406        mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
1407        mSupportAutoRotation = mContext.getResources().getBoolean(
1408                com.android.internal.R.bool.config_supportAutoRotation);
1409        mLidOpenRotation = readRotation(
1410                com.android.internal.R.integer.config_lidOpenRotation);
1411        mCarDockRotation = readRotation(
1412                com.android.internal.R.integer.config_carDockRotation);
1413        mDeskDockRotation = readRotation(
1414                com.android.internal.R.integer.config_deskDockRotation);
1415        mUndockedHdmiRotation = readRotation(
1416                com.android.internal.R.integer.config_undockedHdmiRotation);
1417        mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
1418                com.android.internal.R.bool.config_carDockEnablesAccelerometer);
1419        mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
1420                com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
1421        mLidKeyboardAccessibility = mContext.getResources().getInteger(
1422                com.android.internal.R.integer.config_lidKeyboardAccessibility);
1423        mLidNavigationAccessibility = mContext.getResources().getInteger(
1424                com.android.internal.R.integer.config_lidNavigationAccessibility);
1425        mLidControlsSleep = mContext.getResources().getBoolean(
1426                com.android.internal.R.bool.config_lidControlsSleep);
1427        mTranslucentDecorEnabled = mContext.getResources().getBoolean(
1428                com.android.internal.R.bool.config_enableTranslucentDecor);
1429
1430        mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean(
1431                com.android.internal.R.bool.config_allowTheaterModeWakeFromKey);
1432        mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey
1433                || mContext.getResources().getBoolean(
1434                    com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey);
1435        mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean(
1436                com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion);
1437        mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean(
1438                com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming);
1439        mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean(
1440                com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens);
1441        mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean(
1442                com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch);
1443        mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean(
1444                com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture);
1445
1446        mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean(
1447                com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode);
1448
1449        mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean(
1450                com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive);
1451
1452        mShortPressOnPowerBehavior = mContext.getResources().getInteger(
1453                com.android.internal.R.integer.config_shortPressOnPowerBehavior);
1454        mLongPressOnPowerBehavior = mContext.getResources().getInteger(
1455                com.android.internal.R.integer.config_longPressOnPowerBehavior);
1456        mDoublePressOnPowerBehavior = mContext.getResources().getInteger(
1457                com.android.internal.R.integer.config_doublePressOnPowerBehavior);
1458        mTriplePressOnPowerBehavior = mContext.getResources().getInteger(
1459                com.android.internal.R.integer.config_triplePressOnPowerBehavior);
1460        mShortPressOnSleepBehavior = mContext.getResources().getInteger(
1461                com.android.internal.R.integer.config_shortPressOnSleepBehavior);
1462
1463        mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION;
1464
1465        readConfigurationDependentBehaviors();
1466
1467        mAccessibilityManager = (AccessibilityManager) context.getSystemService(
1468                Context.ACCESSIBILITY_SERVICE);
1469
1470        // register for dock events
1471        IntentFilter filter = new IntentFilter();
1472        filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE);
1473        filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE);
1474        filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE);
1475        filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE);
1476        filter.addAction(Intent.ACTION_DOCK_EVENT);
1477        Intent intent = context.registerReceiver(mDockReceiver, filter);
1478        if (intent != null) {
1479            // Retrieve current sticky dock event broadcast.
1480            mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1481                    Intent.EXTRA_DOCK_STATE_UNDOCKED);
1482        }
1483
1484        // register for dream-related broadcasts
1485        filter = new IntentFilter();
1486        filter.addAction(Intent.ACTION_DREAMING_STARTED);
1487        filter.addAction(Intent.ACTION_DREAMING_STOPPED);
1488        context.registerReceiver(mDreamReceiver, filter);
1489
1490        // register for multiuser-relevant broadcasts
1491        filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
1492        context.registerReceiver(mMultiuserReceiver, filter);
1493
1494        // monitor for system gestures
1495        mSystemGestures = new SystemGesturesPointerEventListener(context,
1496                new SystemGesturesPointerEventListener.Callbacks() {
1497                    @Override
1498                    public void onSwipeFromTop() {
1499                        if (mStatusBar != null) {
1500                            requestTransientBars(mStatusBar);
1501                        }
1502                    }
1503                    @Override
1504                    public void onSwipeFromBottom() {
1505                        if (mNavigationBar != null && mNavigationBarOnBottom) {
1506                            requestTransientBars(mNavigationBar);
1507                        }
1508                    }
1509                    @Override
1510                    public void onSwipeFromRight() {
1511                        if (mNavigationBar != null && !mNavigationBarOnBottom) {
1512                            requestTransientBars(mNavigationBar);
1513                        }
1514                    }
1515                    @Override
1516                    public void onDebug() {
1517                        // no-op
1518                    }
1519                    @Override
1520                    public void onDown() {
1521                        mOrientationListener.onTouchStart();
1522                    }
1523                    @Override
1524                    public void onUpOrCancel() {
1525                        mOrientationListener.onTouchEnd();
1526                    }
1527                    @Override
1528                    public void onMouseHoverAtTop() {
1529                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1530                        Message msg = mHandler.obtainMessage(MSG_REQUEST_TRANSIENT_BARS);
1531                        msg.arg1 = MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS;
1532                        mHandler.sendMessageDelayed(msg, 500);
1533                    }
1534                    @Override
1535                    public void onMouseHoverAtBottom() {
1536                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1537                        Message msg = mHandler.obtainMessage(MSG_REQUEST_TRANSIENT_BARS);
1538                        msg.arg1 = MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION;
1539                        mHandler.sendMessageDelayed(msg, 500);
1540                    }
1541                    @Override
1542                    public void onMouseLeaveFromEdge() {
1543                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1544                    }
1545                });
1546        mImmersiveModeConfirmation = new ImmersiveModeConfirmation(mContext);
1547        mWindowManagerFuncs.registerPointerEventListener(mSystemGestures);
1548
1549        mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
1550        mLongPressVibePattern = getLongIntArray(mContext.getResources(),
1551                com.android.internal.R.array.config_longPressVibePattern);
1552        mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
1553                com.android.internal.R.array.config_virtualKeyVibePattern);
1554        mKeyboardTapVibePattern = getLongIntArray(mContext.getResources(),
1555                com.android.internal.R.array.config_keyboardTapVibePattern);
1556        mClockTickVibePattern = getLongIntArray(mContext.getResources(),
1557                com.android.internal.R.array.config_clockTickVibePattern);
1558        mCalendarDateVibePattern = getLongIntArray(mContext.getResources(),
1559                com.android.internal.R.array.config_calendarDateVibePattern);
1560        mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
1561                com.android.internal.R.array.config_safeModeDisabledVibePattern);
1562        mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
1563                com.android.internal.R.array.config_safeModeEnabledVibePattern);
1564        mContextClickVibePattern = getLongIntArray(mContext.getResources(),
1565                com.android.internal.R.array.config_contextClickVibePattern);
1566
1567        mScreenshotChordEnabled = mContext.getResources().getBoolean(
1568                com.android.internal.R.bool.config_enableScreenshotChord);
1569
1570        mGlobalKeyManager = new GlobalKeyManager(mContext);
1571
1572        // Controls rotation and the like.
1573        initializeHdmiState();
1574
1575        // Match current screen state.
1576        if (!mPowerManager.isInteractive()) {
1577            startedGoingToSleep(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1578            finishedGoingToSleep(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1579        }
1580
1581        mWindowManagerInternal.registerAppTransitionListener(
1582                mStatusBarController.getAppTransitionListener());
1583    }
1584
1585    /**
1586     * Read values from config.xml that may be overridden depending on
1587     * the configuration of the device.
1588     * eg. Disable long press on home goes to recents on sw600dp.
1589     */
1590    private void readConfigurationDependentBehaviors() {
1591        mLongPressOnHomeBehavior = mContext.getResources().getInteger(
1592                com.android.internal.R.integer.config_longPressOnHomeBehavior);
1593        if (mLongPressOnHomeBehavior < LONG_PRESS_HOME_NOTHING ||
1594                mLongPressOnHomeBehavior > LONG_PRESS_HOME_ASSIST) {
1595            mLongPressOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
1596        }
1597
1598        mDoubleTapOnHomeBehavior = mContext.getResources().getInteger(
1599                com.android.internal.R.integer.config_doubleTapOnHomeBehavior);
1600        if (mDoubleTapOnHomeBehavior < DOUBLE_TAP_HOME_NOTHING ||
1601                mDoubleTapOnHomeBehavior > DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
1602            mDoubleTapOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
1603        }
1604    }
1605
1606    @Override
1607    public void setInitialDisplaySize(Display display, int width, int height, int density) {
1608        // This method might be called before the policy has been fully initialized
1609        // or for other displays we don't care about.
1610        if (mContext == null || display.getDisplayId() != Display.DEFAULT_DISPLAY) {
1611            return;
1612        }
1613        mDisplay = display;
1614
1615        final Resources res = mContext.getResources();
1616        int shortSize, longSize;
1617        if (width > height) {
1618            shortSize = height;
1619            longSize = width;
1620            mLandscapeRotation = Surface.ROTATION_0;
1621            mSeascapeRotation = Surface.ROTATION_180;
1622            if (res.getBoolean(com.android.internal.R.bool.config_reverseDefaultRotation)) {
1623                mPortraitRotation = Surface.ROTATION_90;
1624                mUpsideDownRotation = Surface.ROTATION_270;
1625            } else {
1626                mPortraitRotation = Surface.ROTATION_270;
1627                mUpsideDownRotation = Surface.ROTATION_90;
1628            }
1629        } else {
1630            shortSize = width;
1631            longSize = height;
1632            mPortraitRotation = Surface.ROTATION_0;
1633            mUpsideDownRotation = Surface.ROTATION_180;
1634            if (res.getBoolean(com.android.internal.R.bool.config_reverseDefaultRotation)) {
1635                mLandscapeRotation = Surface.ROTATION_270;
1636                mSeascapeRotation = Surface.ROTATION_90;
1637            } else {
1638                mLandscapeRotation = Surface.ROTATION_90;
1639                mSeascapeRotation = Surface.ROTATION_270;
1640            }
1641        }
1642
1643        mStatusBarHeight =
1644                res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
1645
1646        // Height of the navigation bar when presented horizontally at bottom
1647        mNavigationBarHeightForRotation[mPortraitRotation] =
1648        mNavigationBarHeightForRotation[mUpsideDownRotation] =
1649                res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_height);
1650        mNavigationBarHeightForRotation[mLandscapeRotation] =
1651        mNavigationBarHeightForRotation[mSeascapeRotation] = res.getDimensionPixelSize(
1652                com.android.internal.R.dimen.navigation_bar_height_landscape);
1653
1654        // Width of the navigation bar when presented vertically along one side
1655        mNavigationBarWidthForRotation[mPortraitRotation] =
1656        mNavigationBarWidthForRotation[mUpsideDownRotation] =
1657        mNavigationBarWidthForRotation[mLandscapeRotation] =
1658        mNavigationBarWidthForRotation[mSeascapeRotation] =
1659                res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_width);
1660
1661        // SystemUI (status bar) layout policy
1662        int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / density;
1663        int longSizeDp = longSize * DisplayMetrics.DENSITY_DEFAULT / density;
1664
1665        // Allow the navigation bar to move on non-square small devices (phones).
1666        mNavigationBarCanMove = width != height && shortSizeDp < 600;
1667
1668        mHasNavigationBar = res.getBoolean(com.android.internal.R.bool.config_showNavigationBar);
1669        // Allow a system property to override this. Used by the emulator.
1670        // See also hasNavigationBar().
1671        String navBarOverride = SystemProperties.get("qemu.hw.mainkeys");
1672        if ("1".equals(navBarOverride)) {
1673            mHasNavigationBar = false;
1674        } else if ("0".equals(navBarOverride)) {
1675            mHasNavigationBar = true;
1676        }
1677
1678        // For demo purposes, allow the rotation of the HDMI display to be controlled.
1679        // By default, HDMI locks rotation to landscape.
1680        if ("portrait".equals(SystemProperties.get("persist.demo.hdmirotation"))) {
1681            mDemoHdmiRotation = mPortraitRotation;
1682        } else {
1683            mDemoHdmiRotation = mLandscapeRotation;
1684        }
1685        mDemoHdmiRotationLock = SystemProperties.getBoolean("persist.demo.hdmirotationlock", false);
1686
1687        // For demo purposes, allow the rotation of the remote display to be controlled.
1688        // By default, remote display locks rotation to landscape.
1689        if ("portrait".equals(SystemProperties.get("persist.demo.remoterotation"))) {
1690            mDemoRotation = mPortraitRotation;
1691        } else {
1692            mDemoRotation = mLandscapeRotation;
1693        }
1694        mDemoRotationLock = SystemProperties.getBoolean(
1695                "persist.demo.rotationlock", false);
1696
1697        // Only force the default orientation if the screen is xlarge, at least 960dp x 720dp, per
1698        // http://developer.android.com/guide/practices/screens_support.html#range
1699        mForceDefaultOrientation = longSizeDp >= 960 && shortSizeDp >= 720 &&
1700                res.getBoolean(com.android.internal.R.bool.config_forceDefaultOrientation) &&
1701                // For debug purposes the next line turns this feature off with:
1702                // $ adb shell setprop config.override_forced_orient true
1703                // $ adb shell wm size reset
1704                !"true".equals(SystemProperties.get("config.override_forced_orient"));
1705    }
1706
1707    /**
1708     * @return whether the navigation bar can be hidden, e.g. the device has a
1709     *         navigation bar and touch exploration is not enabled
1710     */
1711    private boolean canHideNavigationBar() {
1712        return mHasNavigationBar;
1713    }
1714
1715    @Override
1716    public boolean isDefaultOrientationForced() {
1717        return mForceDefaultOrientation;
1718    }
1719
1720    @Override
1721    public void setDisplayOverscan(Display display, int left, int top, int right, int bottom) {
1722        if (display.getDisplayId() == Display.DEFAULT_DISPLAY) {
1723            mOverscanLeft = left;
1724            mOverscanTop = top;
1725            mOverscanRight = right;
1726            mOverscanBottom = bottom;
1727        }
1728    }
1729
1730    public void updateSettings() {
1731        ContentResolver resolver = mContext.getContentResolver();
1732        boolean updateRotation = false;
1733        synchronized (mLock) {
1734            mEndcallBehavior = Settings.System.getIntForUser(resolver,
1735                    Settings.System.END_BUTTON_BEHAVIOR,
1736                    Settings.System.END_BUTTON_BEHAVIOR_DEFAULT,
1737                    UserHandle.USER_CURRENT);
1738            mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver,
1739                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
1740                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT,
1741                    UserHandle.USER_CURRENT);
1742
1743            // Configure wake gesture.
1744            boolean wakeGestureEnabledSetting = Settings.Secure.getIntForUser(resolver,
1745                    Settings.Secure.WAKE_GESTURE_ENABLED, 0,
1746                    UserHandle.USER_CURRENT) != 0;
1747            if (mWakeGestureEnabledSetting != wakeGestureEnabledSetting) {
1748                mWakeGestureEnabledSetting = wakeGestureEnabledSetting;
1749                updateWakeGestureListenerLp();
1750            }
1751
1752            // Configure rotation lock.
1753            int userRotation = Settings.System.getIntForUser(resolver,
1754                    Settings.System.USER_ROTATION, Surface.ROTATION_0,
1755                    UserHandle.USER_CURRENT);
1756            if (mUserRotation != userRotation) {
1757                mUserRotation = userRotation;
1758                updateRotation = true;
1759            }
1760            int userRotationMode = Settings.System.getIntForUser(resolver,
1761                    Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
1762                            WindowManagerPolicy.USER_ROTATION_FREE :
1763                                    WindowManagerPolicy.USER_ROTATION_LOCKED;
1764            if (mUserRotationMode != userRotationMode) {
1765                mUserRotationMode = userRotationMode;
1766                updateRotation = true;
1767                updateOrientationListenerLp();
1768            }
1769
1770            if (mSystemReady) {
1771                int pointerLocation = Settings.System.getIntForUser(resolver,
1772                        Settings.System.POINTER_LOCATION, 0, UserHandle.USER_CURRENT);
1773                if (mPointerLocationMode != pointerLocation) {
1774                    mPointerLocationMode = pointerLocation;
1775                    mHandler.sendEmptyMessage(pointerLocation != 0 ?
1776                            MSG_ENABLE_POINTER_LOCATION : MSG_DISABLE_POINTER_LOCATION);
1777                }
1778            }
1779            // use screen off timeout setting as the timeout for the lockscreen
1780            mLockScreenTimeout = Settings.System.getIntForUser(resolver,
1781                    Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT);
1782            String imId = Settings.Secure.getStringForUser(resolver,
1783                    Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT);
1784            boolean hasSoftInput = imId != null && imId.length() > 0;
1785            if (mHasSoftInput != hasSoftInput) {
1786                mHasSoftInput = hasSoftInput;
1787                updateRotation = true;
1788            }
1789            if (mImmersiveModeConfirmation != null) {
1790                mImmersiveModeConfirmation.loadSetting(mCurrentUserId);
1791            }
1792        }
1793        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
1794            PolicyControl.reloadFromSetting(mContext);
1795        }
1796        if (updateRotation) {
1797            updateRotation(true);
1798        }
1799    }
1800
1801    private void updateWakeGestureListenerLp() {
1802        if (shouldEnableWakeGestureLp()) {
1803            mWakeGestureListener.requestWakeUpTrigger();
1804        } else {
1805            mWakeGestureListener.cancelWakeUpTrigger();
1806        }
1807    }
1808
1809    private boolean shouldEnableWakeGestureLp() {
1810        return mWakeGestureEnabledSetting && !mAwake
1811                && (!mLidControlsSleep || mLidState != LID_CLOSED)
1812                && mWakeGestureListener.isSupported();
1813    }
1814
1815    private void enablePointerLocation() {
1816        if (mPointerLocationView == null) {
1817            mPointerLocationView = new PointerLocationView(mContext);
1818            mPointerLocationView.setPrintCoords(false);
1819            WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1820                    WindowManager.LayoutParams.MATCH_PARENT,
1821                    WindowManager.LayoutParams.MATCH_PARENT);
1822            lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
1823            lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
1824                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
1825                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1826                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
1827            if (ActivityManager.isHighEndGfx()) {
1828                lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1829                lp.privateFlags |=
1830                        WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED;
1831            }
1832            lp.format = PixelFormat.TRANSLUCENT;
1833            lp.setTitle("PointerLocation");
1834            WindowManager wm = (WindowManager)
1835                    mContext.getSystemService(Context.WINDOW_SERVICE);
1836            lp.inputFeatures |= WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL;
1837            wm.addView(mPointerLocationView, lp);
1838            mWindowManagerFuncs.registerPointerEventListener(mPointerLocationView);
1839        }
1840    }
1841
1842    private void disablePointerLocation() {
1843        if (mPointerLocationView != null) {
1844            mWindowManagerFuncs.unregisterPointerEventListener(mPointerLocationView);
1845            WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
1846            wm.removeView(mPointerLocationView);
1847            mPointerLocationView = null;
1848        }
1849    }
1850
1851    private int readRotation(int resID) {
1852        try {
1853            int rotation = mContext.getResources().getInteger(resID);
1854            switch (rotation) {
1855                case 0:
1856                    return Surface.ROTATION_0;
1857                case 90:
1858                    return Surface.ROTATION_90;
1859                case 180:
1860                    return Surface.ROTATION_180;
1861                case 270:
1862                    return Surface.ROTATION_270;
1863            }
1864        } catch (Resources.NotFoundException e) {
1865            // fall through
1866        }
1867        return -1;
1868    }
1869
1870    /** {@inheritDoc} */
1871    @Override
1872    public int checkAddPermission(WindowManager.LayoutParams attrs, int[] outAppOp) {
1873        int type = attrs.type;
1874
1875        outAppOp[0] = AppOpsManager.OP_NONE;
1876
1877        if (!((type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW)
1878                || (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW)
1879                || (type >= FIRST_SYSTEM_WINDOW && type <= LAST_SYSTEM_WINDOW))) {
1880            return WindowManagerGlobal.ADD_INVALID_TYPE;
1881        }
1882
1883        if (type < FIRST_SYSTEM_WINDOW || type > LAST_SYSTEM_WINDOW) {
1884            // Window manager will make sure these are okay.
1885            return WindowManagerGlobal.ADD_OKAY;
1886        }
1887        String permission = null;
1888        switch (type) {
1889            case TYPE_TOAST:
1890                // XXX right now the app process has complete control over
1891                // this...  should introduce a token to let the system
1892                // monitor/control what they are doing.
1893                outAppOp[0] = AppOpsManager.OP_TOAST_WINDOW;
1894                break;
1895            case TYPE_DREAM:
1896            case TYPE_INPUT_METHOD:
1897            case TYPE_WALLPAPER:
1898            case TYPE_PRIVATE_PRESENTATION:
1899            case TYPE_VOICE_INTERACTION:
1900            case TYPE_ACCESSIBILITY_OVERLAY:
1901                // The window manager will check these.
1902                break;
1903            case TYPE_PHONE:
1904            case TYPE_PRIORITY_PHONE:
1905            case TYPE_SYSTEM_ALERT:
1906            case TYPE_SYSTEM_ERROR:
1907            case TYPE_SYSTEM_OVERLAY:
1908                permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
1909                outAppOp[0] = AppOpsManager.OP_SYSTEM_ALERT_WINDOW;
1910                break;
1911            default:
1912                permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
1913        }
1914        if (permission != null) {
1915            if (permission == android.Manifest.permission.SYSTEM_ALERT_WINDOW) {
1916                final int callingUid = Binder.getCallingUid();
1917                // system processes will be automatically allowed privilege to draw
1918                if (callingUid == Process.SYSTEM_UID) {
1919                    return WindowManagerGlobal.ADD_OKAY;
1920                }
1921
1922                // check if user has enabled this operation. SecurityException will be thrown if
1923                // this app has not been allowed by the user
1924                final int mode = mAppOpsManager.checkOp(outAppOp[0], callingUid,
1925                        attrs.packageName);
1926                switch (mode) {
1927                    case AppOpsManager.MODE_ALLOWED:
1928                    case AppOpsManager.MODE_IGNORED:
1929                        // although we return ADD_OKAY for MODE_IGNORED, the added window will
1930                        // actually be hidden in WindowManagerService
1931                        return WindowManagerGlobal.ADD_OKAY;
1932                    case AppOpsManager.MODE_ERRORED:
1933                        return WindowManagerGlobal.ADD_PERMISSION_DENIED;
1934                    default:
1935                        // in the default mode, we will make a decision here based on
1936                        // checkCallingPermission()
1937                        if (mContext.checkCallingPermission(permission) !=
1938                                PackageManager.PERMISSION_GRANTED) {
1939                            return WindowManagerGlobal.ADD_PERMISSION_DENIED;
1940                        } else {
1941                            return WindowManagerGlobal.ADD_OKAY;
1942                        }
1943                }
1944            }
1945
1946            if (mContext.checkCallingOrSelfPermission(permission)
1947                    != PackageManager.PERMISSION_GRANTED) {
1948                return WindowManagerGlobal.ADD_PERMISSION_DENIED;
1949            }
1950        }
1951        return WindowManagerGlobal.ADD_OKAY;
1952    }
1953
1954    @Override
1955    public boolean checkShowToOwnerOnly(WindowManager.LayoutParams attrs) {
1956
1957        // If this switch statement is modified, modify the comment in the declarations of
1958        // the type in {@link WindowManager.LayoutParams} as well.
1959        switch (attrs.type) {
1960            default:
1961                // These are the windows that by default are shown only to the user that created
1962                // them. If this needs to be overridden, set
1963                // {@link WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS} in
1964                // {@link WindowManager.LayoutParams}. Note that permission
1965                // {@link android.Manifest.permission.INTERNAL_SYSTEM_WINDOW} is required as well.
1966                if ((attrs.privateFlags & PRIVATE_FLAG_SHOW_FOR_ALL_USERS) == 0) {
1967                    return true;
1968                }
1969                break;
1970
1971            // These are the windows that by default are shown to all users. However, to
1972            // protect against spoofing, check permissions below.
1973            case TYPE_APPLICATION_STARTING:
1974            case TYPE_BOOT_PROGRESS:
1975            case TYPE_DISPLAY_OVERLAY:
1976            case TYPE_INPUT_CONSUMER:
1977            case TYPE_KEYGUARD_SCRIM:
1978            case TYPE_KEYGUARD_DIALOG:
1979            case TYPE_MAGNIFICATION_OVERLAY:
1980            case TYPE_NAVIGATION_BAR:
1981            case TYPE_NAVIGATION_BAR_PANEL:
1982            case TYPE_PHONE:
1983            case TYPE_POINTER:
1984            case TYPE_PRIORITY_PHONE:
1985            case TYPE_SEARCH_BAR:
1986            case TYPE_STATUS_BAR:
1987            case TYPE_STATUS_BAR_PANEL:
1988            case TYPE_STATUS_BAR_SUB_PANEL:
1989            case TYPE_SYSTEM_DIALOG:
1990            case TYPE_VOLUME_OVERLAY:
1991            case TYPE_PRIVATE_PRESENTATION:
1992                break;
1993        }
1994
1995        // Check if third party app has set window to system window type.
1996        return mContext.checkCallingOrSelfPermission(
1997                android.Manifest.permission.INTERNAL_SYSTEM_WINDOW)
1998                        != PackageManager.PERMISSION_GRANTED;
1999    }
2000
2001    @Override
2002    public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
2003        switch (attrs.type) {
2004            case TYPE_SYSTEM_OVERLAY:
2005            case TYPE_SECURE_SYSTEM_OVERLAY:
2006                // These types of windows can't receive input events.
2007                attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
2008                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
2009                attrs.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
2010                break;
2011            case TYPE_STATUS_BAR:
2012
2013                // If the Keyguard is in a hidden state (occluded by another window), we force to
2014                // remove the wallpaper and keyguard flag so that any change in-flight after setting
2015                // the keyguard as occluded wouldn't set these flags again.
2016                // See {@link #processKeyguardSetHiddenResultLw}.
2017                if (mKeyguardHidden) {
2018                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
2019                    attrs.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
2020                }
2021                break;
2022        }
2023
2024        if (attrs.type != TYPE_STATUS_BAR) {
2025            // The status bar is the only window allowed to exhibit keyguard behavior.
2026            attrs.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
2027        }
2028
2029        if (ActivityManager.isHighEndGfx()
2030                && (attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0) {
2031            attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
2032                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
2033        }
2034    }
2035
2036    void readLidState() {
2037        mLidState = mWindowManagerFuncs.getLidState();
2038    }
2039
2040    private void readCameraLensCoverState() {
2041        mCameraLensCoverState = mWindowManagerFuncs.getCameraLensCoverState();
2042    }
2043
2044    private boolean isHidden(int accessibilityMode) {
2045        switch (accessibilityMode) {
2046            case 1:
2047                return mLidState == LID_CLOSED;
2048            case 2:
2049                return mLidState == LID_OPEN;
2050            default:
2051                return false;
2052        }
2053    }
2054
2055    /** {@inheritDoc} */
2056    @Override
2057    public void adjustConfigurationLw(Configuration config, int keyboardPresence,
2058            int navigationPresence) {
2059        mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
2060
2061        readConfigurationDependentBehaviors();
2062        readLidState();
2063        applyLidSwitchState();
2064
2065        if (config.keyboard == Configuration.KEYBOARD_NOKEYS
2066                || (keyboardPresence == PRESENCE_INTERNAL
2067                        && isHidden(mLidKeyboardAccessibility))) {
2068            config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
2069            if (!mHasSoftInput) {
2070                config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES;
2071            }
2072        }
2073
2074        if (config.navigation == Configuration.NAVIGATION_NONAV
2075                || (navigationPresence == PRESENCE_INTERNAL
2076                        && isHidden(mLidNavigationAccessibility))) {
2077            config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
2078        }
2079    }
2080
2081    /** {@inheritDoc} */
2082    @Override
2083    public int windowTypeToLayerLw(int type) {
2084        if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
2085            return 2;
2086        }
2087        switch (type) {
2088        case TYPE_PRIVATE_PRESENTATION:
2089            return 2;
2090        case TYPE_WALLPAPER:
2091            // wallpaper is at the bottom, though the window manager may move it.
2092            return 2;
2093        case TYPE_PHONE:
2094            return 3;
2095        case TYPE_SEARCH_BAR:
2096        case TYPE_VOICE_INTERACTION_STARTING:
2097            return 4;
2098        case TYPE_VOICE_INTERACTION:
2099            // voice interaction layer is almost immediately above apps.
2100            return 5;
2101        case TYPE_INPUT_CONSUMER:
2102            return 6;
2103        case TYPE_SYSTEM_DIALOG:
2104            return 7;
2105        case TYPE_TOAST:
2106            // toasts and the plugged-in battery thing
2107            return 8;
2108        case TYPE_PRIORITY_PHONE:
2109            // SIM errors and unlock.  Not sure if this really should be in a high layer.
2110            return 9;
2111        case TYPE_DREAM:
2112            // used for Dreams (screensavers with TYPE_DREAM windows)
2113            return 10;
2114        case TYPE_SYSTEM_ALERT:
2115            // like the ANR / app crashed dialogs
2116            return 11;
2117        case TYPE_INPUT_METHOD:
2118            // on-screen keyboards and other such input method user interfaces go here.
2119            return 12;
2120        case TYPE_INPUT_METHOD_DIALOG:
2121            // on-screen keyboards and other such input method user interfaces go here.
2122            return 13;
2123        case TYPE_KEYGUARD_SCRIM:
2124            // the safety window that shows behind keyguard while keyguard is starting
2125            return 14;
2126        case TYPE_STATUS_BAR_SUB_PANEL:
2127            return 15;
2128        case TYPE_STATUS_BAR:
2129            return 16;
2130        case TYPE_STATUS_BAR_PANEL:
2131            return 17;
2132        case TYPE_KEYGUARD_DIALOG:
2133            return 18;
2134        case TYPE_VOLUME_OVERLAY:
2135            // the on-screen volume indicator and controller shown when the user
2136            // changes the device volume
2137            return 19;
2138        case TYPE_SYSTEM_OVERLAY:
2139            // the on-screen volume indicator and controller shown when the user
2140            // changes the device volume
2141            return 20;
2142        case TYPE_NAVIGATION_BAR:
2143            // the navigation bar, if available, shows atop most things
2144            return 21;
2145        case TYPE_NAVIGATION_BAR_PANEL:
2146            // some panels (e.g. search) need to show on top of the navigation bar
2147            return 22;
2148        case TYPE_SYSTEM_ERROR:
2149            // system-level error dialogs
2150            return 23;
2151        case TYPE_MAGNIFICATION_OVERLAY:
2152            // used to highlight the magnified portion of a display
2153            return 24;
2154        case TYPE_DISPLAY_OVERLAY:
2155            // used to simulate secondary display devices
2156            return 25;
2157        case TYPE_DRAG:
2158            // the drag layer: input for drag-and-drop is associated with this window,
2159            // which sits above all other focusable windows
2160            return 26;
2161        case TYPE_ACCESSIBILITY_OVERLAY:
2162            // overlay put by accessibility services to intercept user interaction
2163            return 27;
2164        case TYPE_SECURE_SYSTEM_OVERLAY:
2165            return 28;
2166        case TYPE_BOOT_PROGRESS:
2167            return 29;
2168        case TYPE_POINTER:
2169            // the (mouse) pointer layer
2170            return 30;
2171        }
2172        Log.e(TAG, "Unknown window type: " + type);
2173        return 2;
2174    }
2175
2176    /** {@inheritDoc} */
2177    @Override
2178    public int subWindowTypeToLayerLw(int type) {
2179        switch (type) {
2180        case TYPE_APPLICATION_PANEL:
2181        case TYPE_APPLICATION_ATTACHED_DIALOG:
2182            return APPLICATION_PANEL_SUBLAYER;
2183        case TYPE_APPLICATION_MEDIA:
2184            return APPLICATION_MEDIA_SUBLAYER;
2185        case TYPE_APPLICATION_MEDIA_OVERLAY:
2186            return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
2187        case TYPE_APPLICATION_SUB_PANEL:
2188            return APPLICATION_SUB_PANEL_SUBLAYER;
2189        case TYPE_APPLICATION_ABOVE_SUB_PANEL:
2190            return APPLICATION_ABOVE_SUB_PANEL_SUBLAYER;
2191        }
2192        Log.e(TAG, "Unknown sub-window type: " + type);
2193        return 0;
2194    }
2195
2196    @Override
2197    public int getMaxWallpaperLayer() {
2198        return windowTypeToLayerLw(TYPE_STATUS_BAR);
2199    }
2200
2201    @Override
2202    public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation) {
2203        if (mHasNavigationBar) {
2204            // For a basic navigation bar, when we are in landscape mode we place
2205            // the navigation bar to the side.
2206            if (mNavigationBarCanMove && fullWidth > fullHeight) {
2207                return fullWidth - mNavigationBarWidthForRotation[rotation];
2208            }
2209        }
2210        return fullWidth;
2211    }
2212
2213    @Override
2214    public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation) {
2215        if (mHasNavigationBar) {
2216            // For a basic navigation bar, when we are in portrait mode we place
2217            // the navigation bar to the bottom.
2218            if (!mNavigationBarCanMove || fullWidth < fullHeight) {
2219                return fullHeight - mNavigationBarHeightForRotation[rotation];
2220            }
2221        }
2222        return fullHeight;
2223    }
2224
2225    @Override
2226    public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation) {
2227        return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation);
2228    }
2229
2230    @Override
2231    public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation) {
2232        // There is a separate status bar at the top of the display.  We don't count that as part
2233        // of the fixed decor, since it can hide; however, for purposes of configurations,
2234        // we do want to exclude it since applications can't generally use that part
2235        // of the screen.
2236        return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation) - mStatusBarHeight;
2237    }
2238
2239    @Override
2240    public boolean isForceHiding(WindowManager.LayoutParams attrs) {
2241        return (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 ||
2242                (isKeyguardHostWindow(attrs) &&
2243                        (mKeyguardDelegate != null && mKeyguardDelegate.isShowing())) ||
2244                (attrs.type == TYPE_KEYGUARD_SCRIM);
2245    }
2246
2247    @Override
2248    public boolean isKeyguardHostWindow(WindowManager.LayoutParams attrs) {
2249        return attrs.type == TYPE_STATUS_BAR;
2250    }
2251
2252    @Override
2253    public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
2254        switch (attrs.type) {
2255            case TYPE_STATUS_BAR:
2256            case TYPE_NAVIGATION_BAR:
2257            case TYPE_WALLPAPER:
2258            case TYPE_DREAM:
2259            case TYPE_KEYGUARD_SCRIM:
2260                return false;
2261            default:
2262                // Hide only windows below the keyguard host window.
2263                return windowTypeToLayerLw(win.getBaseType())
2264                        < windowTypeToLayerLw(TYPE_STATUS_BAR);
2265        }
2266    }
2267
2268    @Override
2269    public WindowState getWinShowWhenLockedLw() {
2270        return mWinShowWhenLocked;
2271    }
2272
2273    /** {@inheritDoc} */
2274    @Override
2275    public View addStartingWindow(IBinder appToken, String packageName, int theme,
2276            CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel, int labelRes,
2277            int icon, int logo, int windowFlags) {
2278        if (!SHOW_STARTING_ANIMATIONS) {
2279            return null;
2280        }
2281        if (packageName == null) {
2282            return null;
2283        }
2284
2285        WindowManager wm = null;
2286        View view = null;
2287
2288        try {
2289            Context context = mContext;
2290            if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow " + packageName
2291                    + ": nonLocalizedLabel=" + nonLocalizedLabel + " theme="
2292                    + Integer.toHexString(theme));
2293            if (theme != context.getThemeResId() || labelRes != 0) {
2294                try {
2295                    context = context.createPackageContext(packageName, 0);
2296                    context.setTheme(theme);
2297                } catch (PackageManager.NameNotFoundException e) {
2298                    // Ignore
2299                }
2300            }
2301
2302            PhoneWindow win = new PhoneWindow(context);
2303            win.setIsStartingWindow(true);
2304            final TypedArray ta = win.getWindowStyle();
2305            if (ta.getBoolean(
2306                        com.android.internal.R.styleable.Window_windowDisablePreview, false)
2307                || ta.getBoolean(
2308                        com.android.internal.R.styleable.Window_windowShowWallpaper,false)) {
2309                return null;
2310            }
2311
2312            Resources r = context.getResources();
2313            win.setTitle(r.getText(labelRes, nonLocalizedLabel));
2314
2315            win.setType(
2316                WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
2317
2318            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
2319                // Assumes it's safe to show starting windows of launched apps while
2320                // the keyguard is being hidden. This is okay because starting windows never show
2321                // secret information.
2322                if (mKeyguardHidden) {
2323                    windowFlags |= FLAG_SHOW_WHEN_LOCKED;
2324                }
2325            }
2326
2327            // Force the window flags: this is a fake window, so it is not really
2328            // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
2329            // flag because we do know that the next window will take input
2330            // focus, so we want to get the IME window up on top of us right away.
2331            win.setFlags(
2332                windowFlags|
2333                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2334                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2335                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
2336                windowFlags|
2337                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2338                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2339                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
2340
2341            win.setDefaultIcon(icon);
2342            win.setDefaultLogo(logo);
2343
2344            win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
2345                    WindowManager.LayoutParams.MATCH_PARENT);
2346
2347            final WindowManager.LayoutParams params = win.getAttributes();
2348            params.token = appToken;
2349            params.packageName = packageName;
2350            params.windowAnimations = win.getWindowStyle().getResourceId(
2351                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2352            params.privateFlags |=
2353                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED;
2354            params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
2355
2356            if (!compatInfo.supportsScreen()) {
2357                params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
2358            }
2359
2360            params.setTitle("Starting " + packageName);
2361
2362            wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
2363            view = win.getDecorView();
2364
2365            if (win.isFloating()) {
2366                // Whoops, there is no way to display an animation/preview
2367                // of such a thing!  After all that work...  let's skip it.
2368                // (Note that we must do this here because it is in
2369                // getDecorView() where the theme is evaluated...  maybe
2370                // we should peek the floating attribute from the theme
2371                // earlier.)
2372                return null;
2373            }
2374
2375            if (DEBUG_STARTING_WINDOW) Slog.d(
2376                TAG, "Adding starting window for " + packageName
2377                + " / " + appToken + ": "
2378                + (view.getParent() != null ? view : null));
2379
2380            wm.addView(view, params);
2381
2382            // Only return the view if it was successfully added to the
2383            // window manager... which we can tell by it having a parent.
2384            return view.getParent() != null ? view : null;
2385        } catch (WindowManager.BadTokenException e) {
2386            // ignore
2387            Log.w(TAG, appToken + " already running, starting window not displayed. " +
2388                    e.getMessage());
2389        } catch (RuntimeException e) {
2390            // don't crash if something else bad happens, for example a
2391            // failure loading resources because we are loading from an app
2392            // on external storage that has been unmounted.
2393            Log.w(TAG, appToken + " failed creating starting window", e);
2394        } finally {
2395            if (view != null && view.getParent() == null) {
2396                Log.w(TAG, "view not successfully added to wm, removing view");
2397                wm.removeViewImmediate(view);
2398            }
2399        }
2400
2401        return null;
2402    }
2403
2404    /** {@inheritDoc} */
2405    @Override
2406    public void removeStartingWindow(IBinder appToken, View window) {
2407        if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Removing starting window for " + appToken + ": "
2408                + window + " Callers=" + Debug.getCallers(4));
2409
2410        if (window != null) {
2411            WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
2412            wm.removeView(window);
2413        }
2414    }
2415
2416    /**
2417     * Preflight adding a window to the system.
2418     *
2419     * Currently enforces that three window types are singletons:
2420     * <ul>
2421     * <li>STATUS_BAR_TYPE</li>
2422     * <li>KEYGUARD_TYPE</li>
2423     * </ul>
2424     *
2425     * @param win The window to be added
2426     * @param attrs Information about the window to be added
2427     *
2428     * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons,
2429     * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
2430     */
2431    @Override
2432    public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
2433        switch (attrs.type) {
2434            case TYPE_STATUS_BAR:
2435                mContext.enforceCallingOrSelfPermission(
2436                        android.Manifest.permission.STATUS_BAR_SERVICE,
2437                        "PhoneWindowManager");
2438                if (mStatusBar != null) {
2439                    if (mStatusBar.isAlive()) {
2440                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2441                    }
2442                }
2443                mStatusBar = win;
2444                mStatusBarController.setWindow(win);
2445                break;
2446            case TYPE_NAVIGATION_BAR:
2447                mContext.enforceCallingOrSelfPermission(
2448                        android.Manifest.permission.STATUS_BAR_SERVICE,
2449                        "PhoneWindowManager");
2450                if (mNavigationBar != null) {
2451                    if (mNavigationBar.isAlive()) {
2452                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2453                    }
2454                }
2455                mNavigationBar = win;
2456                mNavigationBarController.setWindow(win);
2457                if (DEBUG_LAYOUT) Slog.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
2458                break;
2459            case TYPE_NAVIGATION_BAR_PANEL:
2460            case TYPE_STATUS_BAR_PANEL:
2461            case TYPE_STATUS_BAR_SUB_PANEL:
2462            case TYPE_VOICE_INTERACTION_STARTING:
2463                mContext.enforceCallingOrSelfPermission(
2464                        android.Manifest.permission.STATUS_BAR_SERVICE,
2465                        "PhoneWindowManager");
2466                break;
2467            case TYPE_KEYGUARD_SCRIM:
2468                if (mKeyguardScrim != null) {
2469                    return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2470                }
2471                mKeyguardScrim = win;
2472                break;
2473        }
2474        return WindowManagerGlobal.ADD_OKAY;
2475    }
2476
2477    /** {@inheritDoc} */
2478    @Override
2479    public void removeWindowLw(WindowState win) {
2480        if (mStatusBar == win) {
2481            mStatusBar = null;
2482            mStatusBarController.setWindow(null);
2483            mKeyguardDelegate.showScrim();
2484        } else if (mKeyguardScrim == win) {
2485            Log.v(TAG, "Removing keyguard scrim");
2486            mKeyguardScrim = null;
2487        } if (mNavigationBar == win) {
2488            mNavigationBar = null;
2489            mNavigationBarController.setWindow(null);
2490        }
2491    }
2492
2493    static final boolean PRINT_ANIM = false;
2494
2495    /** {@inheritDoc} */
2496    @Override
2497    public int selectAnimationLw(WindowState win, int transit) {
2498        if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
2499              + ": transit=" + transit);
2500        if (win == mStatusBar) {
2501            boolean isKeyguard = (win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
2502            if (transit == TRANSIT_EXIT
2503                    || transit == TRANSIT_HIDE) {
2504                return isKeyguard ? -1 : R.anim.dock_top_exit;
2505            } else if (transit == TRANSIT_ENTER
2506                    || transit == TRANSIT_SHOW) {
2507                return isKeyguard ? -1 : R.anim.dock_top_enter;
2508            }
2509        } else if (win == mNavigationBar) {
2510            if (win.getAttrs().windowAnimations != 0) {
2511                return 0;
2512            }
2513            // This can be on either the bottom or the right.
2514            if (mNavigationBarOnBottom) {
2515                if (transit == TRANSIT_EXIT
2516                        || transit == TRANSIT_HIDE) {
2517                    return R.anim.dock_bottom_exit;
2518                } else if (transit == TRANSIT_ENTER
2519                        || transit == TRANSIT_SHOW) {
2520                    return R.anim.dock_bottom_enter;
2521                }
2522            } else {
2523                if (transit == TRANSIT_EXIT
2524                        || transit == TRANSIT_HIDE) {
2525                    return R.anim.dock_right_exit;
2526                } else if (transit == TRANSIT_ENTER
2527                        || transit == TRANSIT_SHOW) {
2528                    return R.anim.dock_right_enter;
2529                }
2530            }
2531        }
2532
2533        if (transit == TRANSIT_PREVIEW_DONE) {
2534            if (win.hasAppShownWindows()) {
2535                if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
2536                return com.android.internal.R.anim.app_starting_exit;
2537            }
2538        } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
2539                && transit == TRANSIT_ENTER) {
2540            // Special case: we are animating in a dream, while the keyguard
2541            // is shown.  We don't want an animation on the dream, because
2542            // we need it shown immediately with the keyguard animating away
2543            // to reveal it.
2544            return -1;
2545        }
2546
2547        return 0;
2548    }
2549
2550    @Override
2551    public void selectRotationAnimationLw(int anim[]) {
2552        if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
2553                + mTopFullscreenOpaqueWindowState + " rotationAnimation="
2554                + (mTopFullscreenOpaqueWindowState == null ?
2555                        "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
2556        if (mTopFullscreenOpaqueWindowState != null && mTopIsFullscreen) {
2557            switch (mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation) {
2558                case ROTATION_ANIMATION_CROSSFADE:
2559                    anim[0] = R.anim.rotation_animation_xfade_exit;
2560                    anim[1] = R.anim.rotation_animation_enter;
2561                    break;
2562                case ROTATION_ANIMATION_JUMPCUT:
2563                    anim[0] = R.anim.rotation_animation_jump_exit;
2564                    anim[1] = R.anim.rotation_animation_enter;
2565                    break;
2566                case ROTATION_ANIMATION_ROTATE:
2567                default:
2568                    anim[0] = anim[1] = 0;
2569                    break;
2570            }
2571        } else {
2572            anim[0] = anim[1] = 0;
2573        }
2574    }
2575
2576    @Override
2577    public boolean validateRotationAnimationLw(int exitAnimId, int enterAnimId,
2578            boolean forceDefault) {
2579        switch (exitAnimId) {
2580            case R.anim.rotation_animation_xfade_exit:
2581            case R.anim.rotation_animation_jump_exit:
2582                // These are the only cases that matter.
2583                if (forceDefault) {
2584                    return false;
2585                }
2586                int anim[] = new int[2];
2587                selectRotationAnimationLw(anim);
2588                return (exitAnimId == anim[0] && enterAnimId == anim[1]);
2589            default:
2590                return true;
2591        }
2592    }
2593
2594    @Override
2595    public Animation createForceHideEnterAnimation(boolean onWallpaper,
2596            boolean goingToNotificationShade) {
2597        if (goingToNotificationShade) {
2598            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_behind_enter_fade_in);
2599        }
2600
2601        AnimationSet set = (AnimationSet) AnimationUtils.loadAnimation(mContext, onWallpaper ?
2602                    R.anim.lock_screen_behind_enter_wallpaper :
2603                    R.anim.lock_screen_behind_enter);
2604
2605        // TODO: Use XML interpolators when we have log interpolators available in XML.
2606        final List<Animation> animations = set.getAnimations();
2607        for (int i = animations.size() - 1; i >= 0; --i) {
2608            animations.get(i).setInterpolator(mLogDecelerateInterpolator);
2609        }
2610
2611        return set;
2612    }
2613
2614
2615    @Override
2616    public Animation createForceHideWallpaperExitAnimation(boolean goingToNotificationShade) {
2617        if (goingToNotificationShade) {
2618            return null;
2619        } else {
2620            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_wallpaper_exit);
2621        }
2622    }
2623
2624    private static void awakenDreams() {
2625        IDreamManager dreamManager = getDreamManager();
2626        if (dreamManager != null) {
2627            try {
2628                dreamManager.awaken();
2629            } catch (RemoteException e) {
2630                // fine, stay asleep then
2631            }
2632        }
2633    }
2634
2635    static IDreamManager getDreamManager() {
2636        return IDreamManager.Stub.asInterface(
2637                ServiceManager.checkService(DreamService.DREAM_SERVICE));
2638    }
2639
2640    TelecomManager getTelecommService() {
2641        return (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2642    }
2643
2644    static IAudioService getAudioService() {
2645        IAudioService audioService = IAudioService.Stub.asInterface(
2646                ServiceManager.checkService(Context.AUDIO_SERVICE));
2647        if (audioService == null) {
2648            Log.w(TAG, "Unable to find IAudioService interface.");
2649        }
2650        return audioService;
2651    }
2652
2653    boolean keyguardOn() {
2654        return isKeyguardShowingAndNotOccluded() || inKeyguardRestrictedKeyInputMode();
2655    }
2656
2657    private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
2658            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
2659            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
2660        };
2661
2662    /** {@inheritDoc} */
2663    @Override
2664    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
2665        final boolean keyguardOn = keyguardOn();
2666        final int keyCode = event.getKeyCode();
2667        final int repeatCount = event.getRepeatCount();
2668        final int metaState = event.getMetaState();
2669        final int flags = event.getFlags();
2670        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
2671        final boolean canceled = event.isCanceled();
2672
2673        if (DEBUG_INPUT) {
2674            Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
2675                    + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
2676                    + " canceled=" + canceled);
2677        }
2678
2679        // If we think we might have a volume down & power key chord on the way
2680        // but we're not sure, then tell the dispatcher to wait a little while and
2681        // try again later before dispatching.
2682        if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
2683            if (mScreenshotChordVolumeDownKeyTriggered && !mScreenshotChordPowerKeyTriggered) {
2684                final long now = SystemClock.uptimeMillis();
2685                final long timeoutTime = mScreenshotChordVolumeDownKeyTime
2686                        + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
2687                if (now < timeoutTime) {
2688                    return timeoutTime - now;
2689                }
2690            }
2691            if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
2692                    && mScreenshotChordVolumeDownKeyConsumed) {
2693                if (!down) {
2694                    mScreenshotChordVolumeDownKeyConsumed = false;
2695                }
2696                return -1;
2697            }
2698        }
2699
2700        // Cancel any pending meta actions if we see any other keys being pressed between the down
2701        // of the meta key and its corresponding up.
2702        if (mPendingMetaAction && !KeyEvent.isMetaKey(keyCode)) {
2703            mPendingMetaAction = false;
2704        }
2705
2706        // First we always handle the home key here, so applications
2707        // can never break it, although if keyguard is on, we do let
2708        // it handle it, because that gives us the correct 5 second
2709        // timeout.
2710        if (keyCode == KeyEvent.KEYCODE_HOME) {
2711
2712            // If we have released the home key, and didn't do anything else
2713            // while it was pressed, then it is time to go home!
2714            if (!down) {
2715                cancelPreloadRecentApps();
2716
2717                mHomePressed = false;
2718                if (mHomeConsumed) {
2719                    mHomeConsumed = false;
2720                    return -1;
2721                }
2722
2723                if (canceled) {
2724                    Log.i(TAG, "Ignoring HOME; event canceled.");
2725                    return -1;
2726                }
2727
2728                // If an incoming call is ringing, HOME is totally disabled.
2729                // (The user is already on the InCallUI at this point,
2730                // and his ONLY options are to answer or reject the call.)
2731                TelecomManager telecomManager = getTelecommService();
2732                if (telecomManager != null && telecomManager.isRinging()) {
2733                    Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
2734                    return -1;
2735                }
2736
2737                // Delay handling home if a double-tap is possible.
2738                if (mDoubleTapOnHomeBehavior != DOUBLE_TAP_HOME_NOTHING) {
2739                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable); // just in case
2740                    mHomeDoubleTapPending = true;
2741                    mHandler.postDelayed(mHomeDoubleTapTimeoutRunnable,
2742                            ViewConfiguration.getDoubleTapTimeout());
2743                    return -1;
2744                }
2745
2746                handleShortPressOnHome();
2747                return -1;
2748            }
2749
2750            // If a system window has focus, then it doesn't make sense
2751            // right now to interact with applications.
2752            WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
2753            if (attrs != null) {
2754                final int type = attrs.type;
2755                if (type == WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM
2756                        || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
2757                        || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
2758                    // the "app" is keyguard, so give it the key
2759                    return 0;
2760                }
2761                final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
2762                for (int i=0; i<typeCount; i++) {
2763                    if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
2764                        // don't do anything, but also don't pass it to the app
2765                        return -1;
2766                    }
2767                }
2768            }
2769
2770            // Remember that home is pressed and handle special actions.
2771            if (repeatCount == 0) {
2772                mHomePressed = true;
2773                if (mHomeDoubleTapPending) {
2774                    mHomeDoubleTapPending = false;
2775                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable);
2776                    handleDoubleTapOnHome();
2777                } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI
2778                        || mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
2779                    preloadRecentApps();
2780                }
2781            } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
2782                if (!keyguardOn) {
2783                    handleLongPressOnHome(event.getDeviceId());
2784                }
2785            }
2786            return -1;
2787        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
2788            // Hijack modified menu keys for debugging features
2789            final int chordBug = KeyEvent.META_SHIFT_ON;
2790
2791            if (down && repeatCount == 0) {
2792                if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
2793                    Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
2794                    mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
2795                            null, null, null, 0, null, null);
2796                    return -1;
2797                } else if (SHOW_PROCESSES_ON_ALT_MENU &&
2798                        (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
2799                    Intent service = new Intent();
2800                    service.setClassName(mContext, "com.android.server.LoadAverageService");
2801                    ContentResolver res = mContext.getContentResolver();
2802                    boolean shown = Settings.Global.getInt(
2803                            res, Settings.Global.SHOW_PROCESSES, 0) != 0;
2804                    if (!shown) {
2805                        mContext.startService(service);
2806                    } else {
2807                        mContext.stopService(service);
2808                    }
2809                    Settings.Global.putInt(
2810                            res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
2811                    return -1;
2812                }
2813            }
2814        } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
2815            if (down) {
2816                if (repeatCount == 0) {
2817                    mSearchKeyShortcutPending = true;
2818                    mConsumeSearchKeyUp = false;
2819                }
2820            } else {
2821                mSearchKeyShortcutPending = false;
2822                if (mConsumeSearchKeyUp) {
2823                    mConsumeSearchKeyUp = false;
2824                    return -1;
2825                }
2826            }
2827            return 0;
2828        } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
2829            if (!keyguardOn) {
2830                if (down && repeatCount == 0) {
2831                    preloadRecentApps();
2832                } else if (!down) {
2833                    toggleRecentApps();
2834                }
2835            }
2836            return -1;
2837        } else if (keyCode == KeyEvent.KEYCODE_N && event.isMetaPressed()) {
2838            if (down) {
2839                IStatusBarService service = getStatusBarService();
2840                if (service != null) {
2841                    try {
2842                        service.expandNotificationsPanel();
2843                    } catch (RemoteException e) {
2844                        // do nothing.
2845                    }
2846                }
2847            }
2848        } else if (keyCode == KeyEvent.KEYCODE_SLASH && event.isMetaPressed()) {
2849            if (down) {
2850                if (repeatCount == 0) {
2851                    showKeyboardShortcutsMenu();
2852                }
2853            }
2854        } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
2855            if (down) {
2856                if (repeatCount == 0) {
2857                    mAssistKeyLongPressed = false;
2858                } else if (repeatCount == 1) {
2859                    mAssistKeyLongPressed = true;
2860                    if (!keyguardOn) {
2861                         launchAssistLongPressAction();
2862                    }
2863                }
2864            } else {
2865                if (mAssistKeyLongPressed) {
2866                    mAssistKeyLongPressed = false;
2867                } else {
2868                    if (!keyguardOn) {
2869                        launchAssistAction(null, event.getDeviceId());
2870                    }
2871                }
2872            }
2873            return -1;
2874        } else if (keyCode == KeyEvent.KEYCODE_VOICE_ASSIST) {
2875            if (!down) {
2876                Intent voiceIntent;
2877                if (!keyguardOn) {
2878                    voiceIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2879                } else {
2880                    IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
2881                            ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
2882                    if (dic != null) {
2883                        try {
2884                            dic.exitIdle("voice-search");
2885                        } catch (RemoteException e) {
2886                        }
2887                    }
2888                    voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
2889                    voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, true);
2890                }
2891                startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
2892            }
2893        } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
2894            if (down && repeatCount == 0) {
2895                mHandler.post(mScreenshotRunnable);
2896            }
2897            return -1;
2898        } else if (keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP
2899                || keyCode == KeyEvent.KEYCODE_BRIGHTNESS_DOWN) {
2900            if (down) {
2901                int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1;
2902
2903                // Disable autobrightness if it's on
2904                int auto = Settings.System.getIntForUser(
2905                        mContext.getContentResolver(),
2906                        Settings.System.SCREEN_BRIGHTNESS_MODE,
2907                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
2908                        UserHandle.USER_CURRENT_OR_SELF);
2909                if (auto != 0) {
2910                    Settings.System.putIntForUser(mContext.getContentResolver(),
2911                            Settings.System.SCREEN_BRIGHTNESS_MODE,
2912                            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
2913                            UserHandle.USER_CURRENT_OR_SELF);
2914                }
2915
2916                int min = mPowerManager.getMinimumScreenBrightnessSetting();
2917                int max = mPowerManager.getMaximumScreenBrightnessSetting();
2918                int step = (max - min + BRIGHTNESS_STEPS - 1) / BRIGHTNESS_STEPS * direction;
2919                int brightness = Settings.System.getIntForUser(mContext.getContentResolver(),
2920                        Settings.System.SCREEN_BRIGHTNESS,
2921                        mPowerManager.getDefaultScreenBrightnessSetting(),
2922                        UserHandle.USER_CURRENT_OR_SELF);
2923                brightness += step;
2924                // Make sure we don't go beyond the limits.
2925                brightness = Math.min(max, brightness);
2926                brightness = Math.max(min, brightness);
2927
2928                Settings.System.putIntForUser(mContext.getContentResolver(),
2929                        Settings.System.SCREEN_BRIGHTNESS, brightness,
2930                        UserHandle.USER_CURRENT_OR_SELF);
2931                startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG),
2932                        UserHandle.CURRENT_OR_SELF);
2933            }
2934            return -1;
2935        } else if (KeyEvent.isMetaKey(keyCode)) {
2936            if (down) {
2937                mPendingMetaAction = true;
2938            } else if (mPendingMetaAction) {
2939                launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, event.getDeviceId());
2940            }
2941            return -1;
2942        }
2943
2944        // Shortcuts are invoked through Search+key, so intercept those here
2945        // Any printing key that is chorded with Search should be consumed
2946        // even if no shortcut was invoked.  This prevents text from being
2947        // inadvertently inserted when using a keyboard that has built-in macro
2948        // shortcut keys (that emit Search+x) and some of them are not registered.
2949        if (mSearchKeyShortcutPending) {
2950            final KeyCharacterMap kcm = event.getKeyCharacterMap();
2951            if (kcm.isPrintingKey(keyCode)) {
2952                mConsumeSearchKeyUp = true;
2953                mSearchKeyShortcutPending = false;
2954                if (down && repeatCount == 0 && !keyguardOn) {
2955                    Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
2956                    if (shortcutIntent != null) {
2957                        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2958                        try {
2959                            startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
2960                        } catch (ActivityNotFoundException ex) {
2961                            Slog.w(TAG, "Dropping shortcut key combination because "
2962                                    + "the activity to which it is registered was not found: "
2963                                    + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
2964                        }
2965                    } else {
2966                        Slog.i(TAG, "Dropping unregistered shortcut key combination: "
2967                                + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
2968                    }
2969                }
2970                return -1;
2971            }
2972        }
2973
2974        // Invoke shortcuts using Meta.
2975        if (down && repeatCount == 0 && !keyguardOn
2976                && (metaState & KeyEvent.META_META_ON) != 0) {
2977            final KeyCharacterMap kcm = event.getKeyCharacterMap();
2978            if (kcm.isPrintingKey(keyCode)) {
2979                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
2980                        metaState & ~(KeyEvent.META_META_ON
2981                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
2982                if (shortcutIntent != null) {
2983                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2984                    try {
2985                        startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
2986                    } catch (ActivityNotFoundException ex) {
2987                        Slog.w(TAG, "Dropping shortcut key combination because "
2988                                + "the activity to which it is registered was not found: "
2989                                + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
2990                    }
2991                    return -1;
2992                }
2993            }
2994        }
2995
2996        // Handle application launch keys.
2997        if (down && repeatCount == 0 && !keyguardOn) {
2998            String category = sApplicationLaunchKeyCategories.get(keyCode);
2999            if (category != null) {
3000                Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
3001                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3002                try {
3003                    startActivityAsUser(intent, UserHandle.CURRENT);
3004                } catch (ActivityNotFoundException ex) {
3005                    Slog.w(TAG, "Dropping application launch key because "
3006                            + "the activity to which it is registered was not found: "
3007                            + "keyCode=" + keyCode + ", category=" + category, ex);
3008                }
3009                return -1;
3010            }
3011        }
3012
3013        // Display task switcher for ALT-TAB.
3014        if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
3015            if (mRecentAppsHeldModifiers == 0 && !keyguardOn) {
3016                final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
3017                if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)) {
3018                    mRecentAppsHeldModifiers = shiftlessModifiers;
3019                    showRecentApps(true);
3020                    return -1;
3021                }
3022            }
3023        } else if (!down && mRecentAppsHeldModifiers != 0
3024                && (metaState & mRecentAppsHeldModifiers) == 0) {
3025            mRecentAppsHeldModifiers = 0;
3026            hideRecentApps(true, false);
3027        }
3028
3029        // Handle keyboard language switching.
3030        if (down && repeatCount == 0
3031                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3032                        || (keyCode == KeyEvent.KEYCODE_SPACE
3033                                && (metaState & KeyEvent.META_CTRL_MASK) != 0))) {
3034            int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1;
3035            mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction);
3036            return -1;
3037        }
3038        if (mLanguageSwitchKeyPressed && !down
3039                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3040                        || keyCode == KeyEvent.KEYCODE_SPACE)) {
3041            mLanguageSwitchKeyPressed = false;
3042            return -1;
3043        }
3044
3045        if (isValidGlobalKey(keyCode)
3046                && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
3047            return -1;
3048        }
3049
3050        // Reserve all the META modifier combos for system behavior
3051        if ((metaState & KeyEvent.META_META_ON) != 0) {
3052            return -1;
3053        }
3054
3055        // Let the application handle the key.
3056        return 0;
3057    }
3058
3059    /** {@inheritDoc} */
3060    @Override
3061    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
3062        // Note: This method is only called if the initial down was unhandled.
3063        if (DEBUG_INPUT) {
3064            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
3065                    + ", flags=" + event.getFlags()
3066                    + ", keyCode=" + event.getKeyCode()
3067                    + ", scanCode=" + event.getScanCode()
3068                    + ", metaState=" + event.getMetaState()
3069                    + ", repeatCount=" + event.getRepeatCount()
3070                    + ", policyFlags=" + policyFlags);
3071        }
3072
3073        KeyEvent fallbackEvent = null;
3074        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3075            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3076            final int keyCode = event.getKeyCode();
3077            final int metaState = event.getMetaState();
3078            final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
3079                    && event.getRepeatCount() == 0;
3080
3081            // Check for fallback actions specified by the key character map.
3082            final FallbackAction fallbackAction;
3083            if (initialDown) {
3084                fallbackAction = kcm.getFallbackAction(keyCode, metaState);
3085            } else {
3086                fallbackAction = mFallbackActions.get(keyCode);
3087            }
3088
3089            if (fallbackAction != null) {
3090                if (DEBUG_INPUT) {
3091                    Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
3092                            + " metaState=" + Integer.toHexString(fallbackAction.metaState));
3093                }
3094
3095                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
3096                fallbackEvent = KeyEvent.obtain(
3097                        event.getDownTime(), event.getEventTime(),
3098                        event.getAction(), fallbackAction.keyCode,
3099                        event.getRepeatCount(), fallbackAction.metaState,
3100                        event.getDeviceId(), event.getScanCode(),
3101                        flags, event.getSource(), null);
3102
3103                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
3104                    fallbackEvent.recycle();
3105                    fallbackEvent = null;
3106                }
3107
3108                if (initialDown) {
3109                    mFallbackActions.put(keyCode, fallbackAction);
3110                } else if (event.getAction() == KeyEvent.ACTION_UP) {
3111                    mFallbackActions.remove(keyCode);
3112                    fallbackAction.recycle();
3113                }
3114            }
3115        }
3116
3117        if (DEBUG_INPUT) {
3118            if (fallbackEvent == null) {
3119                Slog.d(TAG, "No fallback.");
3120            } else {
3121                Slog.d(TAG, "Performing fallback: " + fallbackEvent);
3122            }
3123        }
3124        return fallbackEvent;
3125    }
3126
3127    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
3128        int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
3129        if ((actions & ACTION_PASS_TO_USER) != 0) {
3130            long delayMillis = interceptKeyBeforeDispatching(
3131                    win, fallbackEvent, policyFlags);
3132            if (delayMillis == 0) {
3133                return true;
3134            }
3135        }
3136        return false;
3137    }
3138
3139    private void launchAssistLongPressAction() {
3140        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3141        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3142
3143        // launch the search activity
3144        Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
3145        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3146        try {
3147            // TODO: This only stops the factory-installed search manager.
3148            // Need to formalize an API to handle others
3149            SearchManager searchManager = getSearchManager();
3150            if (searchManager != null) {
3151                searchManager.stopSearch();
3152            }
3153            startActivityAsUser(intent, UserHandle.CURRENT);
3154        } catch (ActivityNotFoundException e) {
3155            Slog.w(TAG, "No activity to handle assist long press action.", e);
3156        }
3157    }
3158
3159    private void launchAssistAction(String hint, int deviceId) {
3160        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3161        if (!isUserSetupComplete()) {
3162            // Disable opening assist window during setup
3163            return;
3164        }
3165        Bundle args = null;
3166        if (deviceId > Integer.MIN_VALUE) {
3167            args = new Bundle();
3168            args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
3169        }
3170        if ((mContext.getResources().getConfiguration().uiMode
3171                & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
3172            // On TV, use legacy handling until assistants are implemented in the proper way.
3173            ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
3174                    .launchLegacyAssist(hint, UserHandle.myUserId(), args);
3175        } else {
3176            try {
3177                if (hint != null) {
3178                    if (args == null) {
3179                        args = new Bundle();
3180                    }
3181                    args.putBoolean(hint, true);
3182                }
3183                IStatusBarService statusbar = getStatusBarService();
3184                if (statusbar != null) {
3185                    statusbar.startAssist(args);
3186                }
3187            } catch (RemoteException e) {
3188                Slog.e(TAG, "RemoteException when starting assist", e);
3189                // re-acquire status bar service next time it is needed.
3190                mStatusBarService = null;
3191            }
3192        }
3193    }
3194
3195    private void startActivityAsUser(Intent intent, UserHandle handle) {
3196        if (isUserSetupComplete()) {
3197            mContext.startActivityAsUser(intent, handle);
3198        } else {
3199            Slog.i(TAG, "Not starting activity because user setup is in progress: " + intent);
3200        }
3201    }
3202
3203    private SearchManager getSearchManager() {
3204        if (mSearchManager == null) {
3205            mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
3206        }
3207        return mSearchManager;
3208    }
3209
3210    private void preloadRecentApps() {
3211        mPreloadedRecentApps = true;
3212        try {
3213            IStatusBarService statusbar = getStatusBarService();
3214            if (statusbar != null) {
3215                statusbar.preloadRecentApps();
3216            }
3217        } catch (RemoteException e) {
3218            Slog.e(TAG, "RemoteException when preloading recent apps", e);
3219            // re-acquire status bar service next time it is needed.
3220            mStatusBarService = null;
3221        }
3222    }
3223
3224    private void cancelPreloadRecentApps() {
3225        if (mPreloadedRecentApps) {
3226            mPreloadedRecentApps = false;
3227            try {
3228                IStatusBarService statusbar = getStatusBarService();
3229                if (statusbar != null) {
3230                    statusbar.cancelPreloadRecentApps();
3231                }
3232            } catch (RemoteException e) {
3233                Slog.e(TAG, "RemoteException when cancelling recent apps preload", e);
3234                // re-acquire status bar service next time it is needed.
3235                mStatusBarService = null;
3236            }
3237        }
3238    }
3239
3240    private void toggleRecentApps() {
3241        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3242        try {
3243            IStatusBarService statusbar = getStatusBarService();
3244            if (statusbar != null) {
3245                statusbar.toggleRecentApps();
3246            }
3247        } catch (RemoteException e) {
3248            Slog.e(TAG, "RemoteException when toggling recent apps", e);
3249            // re-acquire status bar service next time it is needed.
3250            mStatusBarService = null;
3251        }
3252    }
3253
3254    @Override
3255    public void showRecentApps() {
3256        mHandler.removeMessages(MSG_DISPATCH_SHOW_RECENTS);
3257        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_RECENTS);
3258    }
3259
3260    private void showRecentApps(boolean triggeredFromAltTab) {
3261        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3262        try {
3263            IStatusBarService statusbar = getStatusBarService();
3264            if (statusbar != null) {
3265                statusbar.showRecentApps(triggeredFromAltTab);
3266            }
3267        } catch (RemoteException e) {
3268            Slog.e(TAG, "RemoteException when showing recent apps", e);
3269            // re-acquire status bar service next time it is needed.
3270            mStatusBarService = null;
3271        }
3272    }
3273
3274    private void showKeyboardShortcutsMenu() {
3275        try {
3276            IStatusBarService statusbar = getStatusBarService();
3277            if (statusbar != null) {
3278                statusbar.showKeyboardShortcutsMenu();
3279            }
3280        } catch (RemoteException e) {
3281            Slog.e(TAG, "RemoteException when showing keyboard shortcuts menu", e);
3282        }
3283    }
3284
3285    private void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHome) {
3286        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3287        try {
3288            IStatusBarService statusbar = getStatusBarService();
3289            if (statusbar != null) {
3290                statusbar.hideRecentApps(triggeredFromAltTab, triggeredFromHome);
3291            }
3292        } catch (RemoteException e) {
3293            Slog.e(TAG, "RemoteException when closing recent apps", e);
3294            // re-acquire status bar service next time it is needed.
3295            mStatusBarService = null;
3296        }
3297    }
3298
3299    void launchHomeFromHotKey() {
3300        launchHomeFromHotKey(true /* awakenFromDreams */, true /*respectKeyguard*/);
3301    }
3302
3303    /**
3304     * A home key -> launch home action was detected.  Take the appropriate action
3305     * given the situation with the keyguard.
3306     */
3307    void launchHomeFromHotKey(final boolean awakenFromDreams, final boolean respectKeyguard) {
3308        if (respectKeyguard) {
3309            if (isKeyguardShowingAndNotOccluded()) {
3310                // don't launch home if keyguard showing
3311                return;
3312            }
3313
3314            if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
3315                // when in keyguard restricted mode, must first verify unlock
3316                // before launching home
3317                mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
3318                    @Override
3319                    public void onKeyguardExitResult(boolean success) {
3320                        if (success) {
3321                            try {
3322                                ActivityManagerNative.getDefault().stopAppSwitches();
3323                            } catch (RemoteException e) {
3324                            }
3325                            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3326                            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3327                        }
3328                    }
3329                });
3330                return;
3331            }
3332        }
3333
3334        // no keyguard stuff to worry about, just launch home!
3335        try {
3336            ActivityManagerNative.getDefault().stopAppSwitches();
3337        } catch (RemoteException e) {
3338        }
3339        if (mRecentsVisible) {
3340            // Hide Recents and notify it to launch Home
3341            if (awakenFromDreams) {
3342                awakenDreams();
3343            }
3344            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3345            hideRecentApps(false, true);
3346        } else {
3347            // Otherwise, just launch Home
3348            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3349            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3350        }
3351    }
3352
3353    private final Runnable mClearHideNavigationFlag = new Runnable() {
3354        @Override
3355        public void run() {
3356            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3357                // Clear flags.
3358                mForceClearedSystemUiFlags &=
3359                        ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3360            }
3361            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3362        }
3363    };
3364
3365    /**
3366     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
3367     * to determine when the nav bar should be shown and prevent applications from
3368     * receiving those touches.
3369     */
3370    final class HideNavInputEventReceiver extends InputEventReceiver {
3371        public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
3372            super(inputChannel, looper);
3373        }
3374
3375        @Override
3376        public void onInputEvent(InputEvent event) {
3377            boolean handled = false;
3378            try {
3379                if (event instanceof MotionEvent
3380                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3381                    final MotionEvent motionEvent = (MotionEvent)event;
3382                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
3383                        // When the user taps down, we re-show the nav bar.
3384                        boolean changed = false;
3385                        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3386                            // Any user activity always causes us to show the
3387                            // navigation controls, if they had been hidden.
3388                            // We also clear the low profile and only content
3389                            // flags so that tapping on the screen will atomically
3390                            // restore all currently hidden screen decorations.
3391                            int newVal = mResettingSystemUiFlags |
3392                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3393                                    View.SYSTEM_UI_FLAG_LOW_PROFILE |
3394                                    View.SYSTEM_UI_FLAG_FULLSCREEN;
3395                            if (mResettingSystemUiFlags != newVal) {
3396                                mResettingSystemUiFlags = newVal;
3397                                changed = true;
3398                            }
3399                            // We don't allow the system's nav bar to be hidden
3400                            // again for 1 second, to prevent applications from
3401                            // spamming us and keeping it from being shown.
3402                            newVal = mForceClearedSystemUiFlags |
3403                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3404                            if (mForceClearedSystemUiFlags != newVal) {
3405                                mForceClearedSystemUiFlags = newVal;
3406                                changed = true;
3407                                mHandler.postDelayed(mClearHideNavigationFlag, 1000);
3408                            }
3409                        }
3410                        if (changed) {
3411                            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3412                        }
3413                    }
3414                }
3415            } finally {
3416                finishInputEvent(event, handled);
3417            }
3418        }
3419    }
3420    final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
3421            new InputEventReceiver.Factory() {
3422        @Override
3423        public InputEventReceiver createInputEventReceiver(
3424                InputChannel inputChannel, Looper looper) {
3425            return new HideNavInputEventReceiver(inputChannel, looper);
3426        }
3427    };
3428
3429    @Override
3430    public int adjustSystemUiVisibilityLw(int visibility) {
3431        mStatusBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3432        mNavigationBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3433        mRecentsVisible = (visibility & View.RECENT_APPS_VISIBLE) > 0;
3434
3435        // Reset any bits in mForceClearingStatusBarVisibility that
3436        // are now clear.
3437        mResettingSystemUiFlags &= visibility;
3438        // Clear any bits in the new visibility that are currently being
3439        // force cleared, before reporting it.
3440        return visibility & ~mResettingSystemUiFlags
3441                & ~mForceClearedSystemUiFlags;
3442    }
3443
3444    @Override
3445    public void getInsetHintLw(WindowManager.LayoutParams attrs, int displayRotation,
3446            Rect outContentInsets, Rect outStableInsets, Rect outOutsets) {
3447        final int fl = PolicyControl.getWindowFlags(null, attrs);
3448        final int sysuiVis = PolicyControl.getSystemUiVisibility(null, attrs);
3449        final int systemUiVisibility = (sysuiVis | attrs.subtreeSystemUiVisibility);
3450
3451        final boolean useOutsets = outOutsets != null && shouldUseOutsets(attrs, fl);
3452        if (useOutsets) {
3453            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
3454            if (outset > 0) {
3455                if (displayRotation == Surface.ROTATION_0) {
3456                    outOutsets.bottom += outset;
3457                } else if (displayRotation == Surface.ROTATION_90) {
3458                    outOutsets.right += outset;
3459                } else if (displayRotation == Surface.ROTATION_180) {
3460                    outOutsets.top += outset;
3461                } else if (displayRotation == Surface.ROTATION_270) {
3462                    outOutsets.left += outset;
3463                }
3464            }
3465        }
3466
3467        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3468                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3469            int availRight, availBottom;
3470            if (canHideNavigationBar() &&
3471                    (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
3472                availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3473                availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3474            } else {
3475                availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
3476                availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3477            }
3478            if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3479                if ((fl & FLAG_FULLSCREEN) != 0) {
3480                    outContentInsets.set(mStableFullscreenLeft, mStableFullscreenTop,
3481                            availRight - mStableFullscreenRight,
3482                            availBottom - mStableFullscreenBottom);
3483                } else {
3484                    outContentInsets.set(mStableLeft, mStableTop,
3485                            availRight - mStableRight, availBottom - mStableBottom);
3486                }
3487            } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
3488                outContentInsets.setEmpty();
3489            } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
3490                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
3491                outContentInsets.set(mCurLeft, mCurTop,
3492                        availRight - mCurRight, availBottom - mCurBottom);
3493            } else {
3494                outContentInsets.set(mCurLeft, mCurTop,
3495                        availRight - mCurRight, availBottom - mCurBottom);
3496            }
3497
3498            outStableInsets.set(mStableLeft, mStableTop,
3499                    availRight - mStableRight, availBottom - mStableBottom);
3500            return;
3501        }
3502        outContentInsets.setEmpty();
3503        outStableInsets.setEmpty();
3504    }
3505
3506    private boolean shouldUseOutsets(WindowManager.LayoutParams attrs, int fl) {
3507        return attrs.type == TYPE_WALLPAPER || (fl & (WindowManager.LayoutParams.FLAG_FULLSCREEN
3508                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN)) != 0;
3509    }
3510
3511    /** {@inheritDoc} */
3512    @Override
3513    public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
3514                              int displayRotation) {
3515        mDisplayRotation = displayRotation;
3516        final int overscanLeft, overscanTop, overscanRight, overscanBottom;
3517        if (isDefaultDisplay) {
3518            switch (displayRotation) {
3519                case Surface.ROTATION_90:
3520                    overscanLeft = mOverscanTop;
3521                    overscanTop = mOverscanRight;
3522                    overscanRight = mOverscanBottom;
3523                    overscanBottom = mOverscanLeft;
3524                    break;
3525                case Surface.ROTATION_180:
3526                    overscanLeft = mOverscanRight;
3527                    overscanTop = mOverscanBottom;
3528                    overscanRight = mOverscanLeft;
3529                    overscanBottom = mOverscanTop;
3530                    break;
3531                case Surface.ROTATION_270:
3532                    overscanLeft = mOverscanBottom;
3533                    overscanTop = mOverscanLeft;
3534                    overscanRight = mOverscanTop;
3535                    overscanBottom = mOverscanRight;
3536                    break;
3537                default:
3538                    overscanLeft = mOverscanLeft;
3539                    overscanTop = mOverscanTop;
3540                    overscanRight = mOverscanRight;
3541                    overscanBottom = mOverscanBottom;
3542                    break;
3543            }
3544        } else {
3545            overscanLeft = 0;
3546            overscanTop = 0;
3547            overscanRight = 0;
3548            overscanBottom = 0;
3549        }
3550        mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
3551        mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
3552        mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
3553        mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
3554        mSystemLeft = 0;
3555        mSystemTop = 0;
3556        mSystemRight = displayWidth;
3557        mSystemBottom = displayHeight;
3558        mUnrestrictedScreenLeft = overscanLeft;
3559        mUnrestrictedScreenTop = overscanTop;
3560        mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
3561        mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
3562        mRestrictedScreenLeft = mUnrestrictedScreenLeft;
3563        mRestrictedScreenTop = mUnrestrictedScreenTop;
3564        mRestrictedScreenWidth = mSystemGestures.screenWidth = mUnrestrictedScreenWidth;
3565        mRestrictedScreenHeight = mSystemGestures.screenHeight = mUnrestrictedScreenHeight;
3566        mDockLeft = mContentLeft = mVoiceContentLeft = mStableLeft = mStableFullscreenLeft
3567                = mCurLeft = mUnrestrictedScreenLeft;
3568        mDockTop = mContentTop = mVoiceContentTop = mStableTop = mStableFullscreenTop
3569                = mCurTop = mUnrestrictedScreenTop;
3570        mDockRight = mContentRight = mVoiceContentRight = mStableRight = mStableFullscreenRight
3571                = mCurRight = displayWidth - overscanRight;
3572        mDockBottom = mContentBottom = mVoiceContentBottom = mStableBottom = mStableFullscreenBottom
3573                = mCurBottom = displayHeight - overscanBottom;
3574        mDockLayer = 0x10000000;
3575        mStatusBarLayer = -1;
3576
3577        // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
3578        final Rect pf = mTmpParentFrame;
3579        final Rect df = mTmpDisplayFrame;
3580        final Rect of = mTmpOverscanFrame;
3581        final Rect vf = mTmpVisibleFrame;
3582        final Rect dcf = mTmpDecorFrame;
3583        final Rect osf = mTmpOutsetFrame;
3584        pf.left = df.left = of.left = vf.left = mDockLeft;
3585        pf.top = df.top = of.top = vf.top = mDockTop;
3586        pf.right = df.right = of.right = vf.right = mDockRight;
3587        pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
3588        dcf.setEmpty();  // Decor frame N/A for system bars.
3589
3590        if (isDefaultDisplay) {
3591            // For purposes of putting out fake window up to steal focus, we will
3592            // drive nav being hidden only by whether it is requested.
3593            final int sysui = mLastSystemUiFlags;
3594            boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
3595            boolean navTranslucent = (sysui
3596                    & (View.NAVIGATION_BAR_TRANSLUCENT | View.SYSTEM_UI_TRANSPARENT)) != 0;
3597            boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
3598            boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
3599            boolean navAllowedHidden = immersive || immersiveSticky;
3600            navTranslucent &= !immersiveSticky;  // transient trumps translucent
3601            boolean isKeyguardShowing = isStatusBarKeyguard() && !mHideLockScreen;
3602            if (!isKeyguardShowing) {
3603                navTranslucent &= areTranslucentBarsAllowed();
3604            }
3605
3606            // When the navigation bar isn't visible, we put up a fake
3607            // input window to catch all touch events.  This way we can
3608            // detect when the user presses anywhere to bring back the nav
3609            // bar and ensure the application doesn't see the event.
3610            if (navVisible || navAllowedHidden) {
3611                if (mInputConsumer != null) {
3612                    mInputConsumer.dismiss();
3613                    mInputConsumer = null;
3614                }
3615            } else if (mInputConsumer == null) {
3616                mInputConsumer = mWindowManagerFuncs.addInputConsumer(mHandler.getLooper(),
3617                        mHideNavInputEventReceiverFactory);
3618            }
3619
3620            // For purposes of positioning and showing the nav bar, if we have
3621            // decided that it can't be hidden (because of the screen aspect ratio),
3622            // then take that into account.
3623            navVisible |= !canHideNavigationBar();
3624
3625            boolean updateSysUiVisibility = false;
3626            if (mNavigationBar != null) {
3627                boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
3628                // Force the navigation bar to its appropriate place and
3629                // size.  We need to do this directly, instead of relying on
3630                // it to bubble up from the nav bar, because this needs to
3631                // change atomically with screen rotations.
3632                mNavigationBarOnBottom = (!mNavigationBarCanMove || displayWidth < displayHeight);
3633                if (mNavigationBarOnBottom) {
3634                    // It's a system nav bar or a portrait screen; nav bar goes on bottom.
3635                    int top = displayHeight - overscanBottom
3636                            - mNavigationBarHeightForRotation[displayRotation];
3637                    mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
3638                    mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
3639                    if (transientNavBarShowing) {
3640                        mNavigationBarController.setBarShowingLw(true);
3641                    } else if (navVisible) {
3642                        mNavigationBarController.setBarShowingLw(true);
3643                        mDockBottom = mTmpNavigationFrame.top;
3644                        mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
3645                        mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
3646                    } else {
3647                        // We currently want to hide the navigation UI.
3648                        mNavigationBarController.setBarShowingLw(false);
3649                    }
3650                    if (navVisible && !navTranslucent && !navAllowedHidden
3651                            && !mNavigationBar.isAnimatingLw()
3652                            && !mNavigationBarController.wasRecentlyTranslucent()) {
3653                        // If the opaque nav bar is currently requested to be visible,
3654                        // and not in the process of animating on or off, then
3655                        // we can tell the app that it is covered by it.
3656                        mSystemBottom = mTmpNavigationFrame.top;
3657                    }
3658                } else {
3659                    // Landscape screen; nav bar goes to the right.
3660                    int left = displayWidth - overscanRight
3661                            - mNavigationBarWidthForRotation[displayRotation];
3662                    mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
3663                    mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
3664                    if (transientNavBarShowing) {
3665                        mNavigationBarController.setBarShowingLw(true);
3666                    } else if (navVisible) {
3667                        mNavigationBarController.setBarShowingLw(true);
3668                        mDockRight = mTmpNavigationFrame.left;
3669                        mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
3670                        mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
3671                    } else {
3672                        // We currently want to hide the navigation UI.
3673                        mNavigationBarController.setBarShowingLw(false);
3674                    }
3675                    if (navVisible && !navTranslucent && !navAllowedHidden
3676                            && !mNavigationBar.isAnimatingLw()
3677                            && !mNavigationBarController.wasRecentlyTranslucent()) {
3678                        // If the nav bar is currently requested to be visible,
3679                        // and not in the process of animating on or off, then
3680                        // we can tell the app that it is covered by it.
3681                        mSystemRight = mTmpNavigationFrame.left;
3682                    }
3683                }
3684                // Make sure the content and current rectangles are updated to
3685                // account for the restrictions from the navigation bar.
3686                mContentTop = mVoiceContentTop = mCurTop = mDockTop;
3687                mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
3688                mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
3689                mContentRight = mVoiceContentRight = mCurRight = mDockRight;
3690                mStatusBarLayer = mNavigationBar.getSurfaceLayer();
3691                // And compute the final frame.
3692                mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
3693                        mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf,
3694                        mTmpNavigationFrame, mTmpNavigationFrame);
3695                if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
3696                if (mNavigationBarController.checkHiddenLw()) {
3697                    updateSysUiVisibility = true;
3698                }
3699            }
3700            if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
3701                    mDockLeft, mDockTop, mDockRight, mDockBottom));
3702
3703            // decide where the status bar goes ahead of time
3704            if (mStatusBar != null) {
3705                // apply any navigation bar insets
3706                pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3707                pf.top = df.top = of.top = mUnrestrictedScreenTop;
3708                pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
3709                pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
3710                        + mUnrestrictedScreenTop;
3711                vf.left = mStableLeft;
3712                vf.top = mStableTop;
3713                vf.right = mStableRight;
3714                vf.bottom = mStableBottom;
3715
3716                mStatusBarLayer = mStatusBar.getSurfaceLayer();
3717
3718                // Let the status bar determine its size.
3719                mStatusBar.computeFrameLw(pf /* parentFrame */, df /* displayFrame */,
3720                        vf /* overlayFrame */, vf /* contentFrame */, vf /* visibleFrame */,
3721                        dcf /* decorFrame */, vf /* stableFrame */, vf /* outsetFrame */);
3722
3723                // For layout, the status bar is always at the top with our fixed height.
3724                mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
3725
3726                boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
3727                boolean statusBarTranslucent = (sysui
3728                        & (View.STATUS_BAR_TRANSLUCENT | View.SYSTEM_UI_TRANSPARENT)) != 0;
3729                if (!isKeyguardShowing) {
3730                    statusBarTranslucent &= areTranslucentBarsAllowed();
3731                }
3732
3733                // If the status bar is hidden, we don't want to cause
3734                // windows behind it to scroll.
3735                if (mStatusBar.isVisibleLw() && !statusBarTransient) {
3736                    // Status bar may go away, so the screen area it occupies
3737                    // is available to apps but just covering them when the
3738                    // status bar is visible.
3739                    mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
3740
3741                    mContentTop = mVoiceContentTop = mCurTop = mDockTop;
3742                    mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
3743                    mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
3744                    mContentRight = mVoiceContentRight = mCurRight = mDockRight;
3745
3746                    if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
3747                        String.format(
3748                            "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
3749                            mDockLeft, mDockTop, mDockRight, mDockBottom,
3750                            mContentLeft, mContentTop, mContentRight, mContentBottom,
3751                            mCurLeft, mCurTop, mCurRight, mCurBottom));
3752                }
3753                if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
3754                        && !statusBarTransient && !statusBarTranslucent
3755                        && !mStatusBarController.wasRecentlyTranslucent()) {
3756                    // If the opaque status bar is currently requested to be visible,
3757                    // and not in the process of animating on or off, then
3758                    // we can tell the app that it is covered by it.
3759                    mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
3760                }
3761                if (mStatusBarController.checkHiddenLw()) {
3762                    updateSysUiVisibility = true;
3763                }
3764            }
3765            if (updateSysUiVisibility) {
3766                updateSystemUiVisibilityLw();
3767            }
3768        }
3769    }
3770
3771    /** {@inheritDoc} */
3772    @Override
3773    public int getSystemDecorLayerLw() {
3774        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
3775            return mStatusBar.getSurfaceLayer();
3776        }
3777
3778        if (mNavigationBar != null && mNavigationBar.isVisibleLw()) {
3779            return mNavigationBar.getSurfaceLayer();
3780        }
3781
3782        return 0;
3783    }
3784
3785    @Override
3786    public void getContentRectLw(Rect r) {
3787        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
3788    }
3789
3790    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
3791            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
3792        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
3793            // Here's a special case: if this attached window is a panel that is
3794            // above the dock window, and the window it is attached to is below
3795            // the dock window, then the frames we computed for the window it is
3796            // attached to can not be used because the dock is effectively part
3797            // of the underlying window and the attached window is floating on top
3798            // of the whole thing.  So, we ignore the attached window and explicitly
3799            // compute the frames that would be appropriate without the dock.
3800            df.left = of.left = cf.left = vf.left = mDockLeft;
3801            df.top = of.top = cf.top = vf.top = mDockTop;
3802            df.right = of.right = cf.right = vf.right = mDockRight;
3803            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
3804        } else {
3805            // The effective display frame of the attached window depends on
3806            // whether it is taking care of insetting its content.  If not,
3807            // we need to use the parent's content frame so that the entire
3808            // window is positioned within that content.  Otherwise we can use
3809            // the overscan frame and let the attached window take care of
3810            // positioning its content appropriately.
3811            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3812                // Set the content frame of the attached window to the parent's decor frame
3813                // (same as content frame when IME isn't present) if specifically requested by
3814                // setting {@link WindowManager.LayoutParams#FLAG_LAYOUT_ATTACHED_IN_DECOR} flag.
3815                // Otherwise, use the overscan frame.
3816                cf.set((fl & FLAG_LAYOUT_ATTACHED_IN_DECOR) != 0
3817                        ? attached.getContentFrameLw() : attached.getOverscanFrameLw());
3818            } else {
3819                // If the window is resizing, then we want to base the content
3820                // frame on our attached content frame to resize...  however,
3821                // things can be tricky if the attached window is NOT in resize
3822                // mode, in which case its content frame will be larger.
3823                // Ungh.  So to deal with that, make sure the content frame
3824                // we end up using is not covering the IM dock.
3825                cf.set(attached.getContentFrameLw());
3826                if (attached.isVoiceInteraction()) {
3827                    if (cf.left < mVoiceContentLeft) cf.left = mVoiceContentLeft;
3828                    if (cf.top < mVoiceContentTop) cf.top = mVoiceContentTop;
3829                    if (cf.right > mVoiceContentRight) cf.right = mVoiceContentRight;
3830                    if (cf.bottom > mVoiceContentBottom) cf.bottom = mVoiceContentBottom;
3831                } else if (attached.getSurfaceLayer() < mDockLayer) {
3832                    if (cf.left < mContentLeft) cf.left = mContentLeft;
3833                    if (cf.top < mContentTop) cf.top = mContentTop;
3834                    if (cf.right > mContentRight) cf.right = mContentRight;
3835                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
3836                }
3837            }
3838            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
3839            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
3840            vf.set(attached.getVisibleFrameLw());
3841        }
3842        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
3843        // window should be positioned relative to its parent or the entire
3844        // screen.
3845        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
3846                ? attached.getFrameLw() : df);
3847    }
3848
3849    private void applyStableConstraints(int sysui, int fl, Rect r) {
3850        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3851            // If app is requesting a stable layout, don't let the
3852            // content insets go below the stable values.
3853            if ((fl & FLAG_FULLSCREEN) != 0) {
3854                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
3855                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
3856                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
3857                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
3858            } else {
3859                if (r.left < mStableLeft) r.left = mStableLeft;
3860                if (r.top < mStableTop) r.top = mStableTop;
3861                if (r.right > mStableRight) r.right = mStableRight;
3862                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
3863            }
3864        }
3865    }
3866
3867    private boolean canReceiveInput(WindowState win) {
3868        boolean notFocusable =
3869                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0;
3870        boolean altFocusableIm =
3871                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0;
3872        boolean notFocusableForIm = notFocusable ^ altFocusableIm;
3873        return !notFocusableForIm;
3874    }
3875
3876    /** {@inheritDoc} */
3877    @Override
3878    public void layoutWindowLw(WindowState win, WindowState attached) {
3879        // We've already done the navigation bar and status bar. If the status bar can receive
3880        // input, we need to layout it again to accomodate for the IME window.
3881        if ((win == mStatusBar && !canReceiveInput(win)) || win == mNavigationBar) {
3882            return;
3883        }
3884        final WindowManager.LayoutParams attrs = win.getAttrs();
3885        final boolean isDefaultDisplay = win.isDefaultDisplay();
3886        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
3887                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
3888        if (needsToOffsetInputMethodTarget) {
3889            if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
3890            offsetInputMethodWindowLw(mLastInputMethodWindow);
3891        }
3892
3893        final int fl = PolicyControl.getWindowFlags(win, attrs);
3894        final int sim = attrs.softInputMode;
3895        final int sysUiFl = PolicyControl.getSystemUiVisibility(win, null);
3896
3897        final Rect pf = mTmpParentFrame;
3898        final Rect df = mTmpDisplayFrame;
3899        final Rect of = mTmpOverscanFrame;
3900        final Rect cf = mTmpContentFrame;
3901        final Rect vf = mTmpVisibleFrame;
3902        final Rect dcf = mTmpDecorFrame;
3903        final Rect sf = mTmpStableFrame;
3904        Rect osf = null;
3905        dcf.setEmpty();
3906
3907        final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
3908                && mNavigationBar != null && mNavigationBar.isVisibleLw());
3909
3910        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
3911
3912        if (isDefaultDisplay) {
3913            sf.set(mStableLeft, mStableTop, mStableRight, mStableBottom);
3914        } else {
3915            sf.set(mOverscanLeft, mOverscanTop, mOverscanRight, mOverscanBottom);
3916        }
3917
3918        if (!isDefaultDisplay) {
3919            if (attached != null) {
3920                // If this window is attached to another, our display
3921                // frame is the same as the one we are attached to.
3922                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
3923            } else {
3924                // Give the window full screen.
3925                pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3926                pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3927                pf.right = df.right = of.right = cf.right
3928                        = mOverscanScreenLeft + mOverscanScreenWidth;
3929                pf.bottom = df.bottom = of.bottom = cf.bottom
3930                        = mOverscanScreenTop + mOverscanScreenHeight;
3931            }
3932        } else if (attrs.type == TYPE_INPUT_METHOD) {
3933            pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
3934            pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
3935            pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
3936            // IM dock windows layout below the nav bar...
3937            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3938            // ...with content insets above the nav bar
3939            cf.bottom = vf.bottom = mStableBottom;
3940            // IM dock windows always go to the bottom of the screen.
3941            attrs.gravity = Gravity.BOTTOM;
3942            mDockLayer = win.getSurfaceLayer();
3943        } else if (attrs.type == TYPE_VOICE_INTERACTION) {
3944            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3945            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3946            pf.right = df.right = of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3947            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3948            cf.bottom = vf.bottom = mStableBottom;
3949            // Note: In Phone landscape mode, the button bar should also be excluded.
3950            cf.right = vf.right = mStableRight;
3951            cf.left = vf.left = mStableLeft;
3952            cf.top = vf.top = mStableTop;
3953        } else if (win == mStatusBar) {
3954            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3955            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3956            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
3957            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight + mUnrestrictedScreenTop;
3958            cf.left = vf.left = mStableLeft;
3959            cf.top = vf.top = mStableTop;
3960            cf.right = vf.right = mStableRight;
3961            vf.bottom = mStableBottom;
3962            cf.bottom = mContentBottom;
3963        } else {
3964
3965            // Default policy decor for the default display
3966            dcf.left = mSystemLeft;
3967            dcf.top = mSystemTop;
3968            dcf.right = mSystemRight;
3969            dcf.bottom = mSystemBottom;
3970            final boolean inheritTranslucentDecor = (attrs.privateFlags
3971                    & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
3972            final boolean isAppWindow =
3973                    attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
3974                    attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
3975            final boolean topAtRest =
3976                    win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
3977            if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
3978                if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
3979                        && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
3980                        && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0
3981                        && (fl & WindowManager.LayoutParams.
3982                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
3983                    // Ensure policy decor includes status bar
3984                    dcf.top = mStableTop;
3985                }
3986                if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
3987                        && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
3988                        && (fl & WindowManager.LayoutParams.
3989                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
3990                    // Ensure policy decor includes navigation bar
3991                    dcf.bottom = mStableBottom;
3992                    dcf.right = mStableRight;
3993                }
3994            }
3995
3996            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3997                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3998                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
3999                            + "): IN_SCREEN, INSET_DECOR");
4000                // This is the case for a normal activity window: we want it
4001                // to cover all of the screen space, and it can take care of
4002                // moving its contents to account for screen decorations that
4003                // intrude into that space.
4004                if (attached != null) {
4005                    // If this window is attached to another, our display
4006                    // frame is the same as the one we are attached to.
4007                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4008                } else {
4009                    if (attrs.type == TYPE_STATUS_BAR_PANEL
4010                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
4011                        // Status bar panels are the only windows who can go on top of
4012                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
4013                        // permission, so they have the same privileges as the status
4014                        // bar itself.
4015                        //
4016                        // However, they should still dodge the navigation bar if it exists.
4017
4018                        pf.left = df.left = of.left = hasNavBar
4019                                ? mDockLeft : mUnrestrictedScreenLeft;
4020                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
4021                        pf.right = df.right = of.right = hasNavBar
4022                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
4023                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4024                        pf.bottom = df.bottom = of.bottom = hasNavBar
4025                                ? mRestrictedScreenTop+mRestrictedScreenHeight
4026                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4027
4028                        if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4029                                        "Laying out status bar window: (%d,%d - %d,%d)",
4030                                        pf.left, pf.top, pf.right, pf.bottom));
4031                    } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4032                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4033                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4034                        // Asking to layout into the overscan region, so give it that pure
4035                        // unrestricted area.
4036                        pf.left = df.left = of.left = mOverscanScreenLeft;
4037                        pf.top = df.top = of.top = mOverscanScreenTop;
4038                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
4039                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
4040                                + mOverscanScreenHeight;
4041                    } else if (canHideNavigationBar()
4042                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4043                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4044                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4045                        // Asking for layout as if the nav bar is hidden, lets the
4046                        // application extend into the unrestricted overscan screen area.  We
4047                        // only do this for application windows to ensure no window that
4048                        // can be above the nav bar can do this.
4049                        pf.left = df.left = mOverscanScreenLeft;
4050                        pf.top = df.top = mOverscanScreenTop;
4051                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4052                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4053                        // We need to tell the app about where the frame inside the overscan
4054                        // is, so it can inset its content by that amount -- it didn't ask
4055                        // to actually extend itself into the overscan region.
4056                        of.left = mUnrestrictedScreenLeft;
4057                        of.top = mUnrestrictedScreenTop;
4058                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4059                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4060                    } else {
4061                        pf.left = df.left = mRestrictedOverscanScreenLeft;
4062                        pf.top = df.top = mRestrictedOverscanScreenTop;
4063                        pf.right = df.right = mRestrictedOverscanScreenLeft
4064                                + mRestrictedOverscanScreenWidth;
4065                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
4066                                + mRestrictedOverscanScreenHeight;
4067                        // We need to tell the app about where the frame inside the overscan
4068                        // is, so it can inset its content by that amount -- it didn't ask
4069                        // to actually extend itself into the overscan region.
4070                        of.left = mUnrestrictedScreenLeft;
4071                        of.top = mUnrestrictedScreenTop;
4072                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4073                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4074                    }
4075
4076                    if ((fl & FLAG_FULLSCREEN) == 0) {
4077                        if (win.isVoiceInteraction()) {
4078                            cf.left = mVoiceContentLeft;
4079                            cf.top = mVoiceContentTop;
4080                            cf.right = mVoiceContentRight;
4081                            cf.bottom = mVoiceContentBottom;
4082                        } else {
4083                            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4084                                cf.left = mDockLeft;
4085                                cf.top = mDockTop;
4086                                cf.right = mDockRight;
4087                                cf.bottom = mDockBottom;
4088                            } else {
4089                                cf.left = mContentLeft;
4090                                cf.top = mContentTop;
4091                                cf.right = mContentRight;
4092                                cf.bottom = mContentBottom;
4093                            }
4094                        }
4095                    } else {
4096                        // Full screen windows are always given a layout that is as if the
4097                        // status bar and other transient decors are gone.  This is to avoid
4098                        // bad states when moving from a window that is not hding the
4099                        // status bar to one that is.
4100                        cf.left = mRestrictedScreenLeft;
4101                        cf.top = mRestrictedScreenTop;
4102                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4103                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
4104                    }
4105                    applyStableConstraints(sysUiFl, fl, cf);
4106                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4107                        vf.left = mCurLeft;
4108                        vf.top = mCurTop;
4109                        vf.right = mCurRight;
4110                        vf.bottom = mCurBottom;
4111                    } else {
4112                        vf.set(cf);
4113                    }
4114                }
4115            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
4116                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
4117                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
4118                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4119                        "): IN_SCREEN");
4120                // A window that has requested to fill the entire screen just
4121                // gets everything, period.
4122                if (attrs.type == TYPE_STATUS_BAR_PANEL
4123                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL
4124                        || attrs.type == TYPE_VOLUME_OVERLAY) {
4125                    pf.left = df.left = of.left = cf.left = hasNavBar
4126                            ? mDockLeft : mUnrestrictedScreenLeft;
4127                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4128                    pf.right = df.right = of.right = cf.right = hasNavBar
4129                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
4130                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4131                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
4132                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
4133                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4134                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4135                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
4136                                    pf.left, pf.top, pf.right, pf.bottom));
4137                } else if (attrs.type == TYPE_NAVIGATION_BAR
4138                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
4139                    // The navigation bar has Real Ultimate Power.
4140                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4141                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
4142                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
4143                            + mUnrestrictedScreenWidth;
4144                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
4145                            + mUnrestrictedScreenHeight;
4146                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4147                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
4148                                    pf.left, pf.top, pf.right, pf.bottom));
4149                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
4150                                || attrs.type == TYPE_BOOT_PROGRESS)
4151                        && ((fl & FLAG_FULLSCREEN) != 0)) {
4152                    // Fullscreen secure system overlays get what they ask for.
4153                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4154                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4155                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4156                            + mOverscanScreenWidth;
4157                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4158                            + mOverscanScreenHeight;
4159                } else if (attrs.type == TYPE_BOOT_PROGRESS) {
4160                    // Boot progress screen always covers entire display.
4161                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4162                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4163                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4164                            + mOverscanScreenWidth;
4165                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4166                            + mOverscanScreenHeight;
4167                } else if (attrs.type == TYPE_WALLPAPER) {
4168                    // The wallpaper also has Real Ultimate Power, but we want to tell
4169                    // it about the overscan area.
4170                    pf.left = df.left = mOverscanScreenLeft;
4171                    pf.top = df.top = mOverscanScreenTop;
4172                    pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4173                    pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4174                    of.left = cf.left = mUnrestrictedScreenLeft;
4175                    of.top = cf.top = mUnrestrictedScreenTop;
4176                    of.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4177                    of.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4178                } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4179                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4180                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4181                    // Asking to layout into the overscan region, so give it that pure
4182                    // unrestricted area.
4183                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4184                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4185                    pf.right = df.right = of.right = cf.right
4186                            = mOverscanScreenLeft + mOverscanScreenWidth;
4187                    pf.bottom = df.bottom = of.bottom = cf.bottom
4188                            = mOverscanScreenTop + mOverscanScreenHeight;
4189                } else if (canHideNavigationBar()
4190                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4191                        && (attrs.type == TYPE_STATUS_BAR
4192                            || attrs.type == TYPE_TOAST
4193                            || attrs.type == TYPE_VOICE_INTERACTION_STARTING
4194                            || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4195                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
4196                    // Asking for layout as if the nav bar is hidden, lets the
4197                    // application extend into the unrestricted screen area.  We
4198                    // only do this for application windows (or toasts) to ensure no window that
4199                    // can be above the nav bar can do this.
4200                    // XXX This assumes that an app asking for this will also
4201                    // ask for layout in only content.  We can't currently figure out
4202                    // what the screen would be if only laying out to hide the nav bar.
4203                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
4204                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4205                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
4206                            + mUnrestrictedScreenWidth;
4207                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
4208                            + mUnrestrictedScreenHeight;
4209                } else {
4210                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4211                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4212                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4213                            + mRestrictedScreenWidth;
4214                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4215                            + mRestrictedScreenHeight;
4216                }
4217
4218                applyStableConstraints(sysUiFl, fl, cf);
4219
4220                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4221                    vf.left = mCurLeft;
4222                    vf.top = mCurTop;
4223                    vf.right = mCurRight;
4224                    vf.bottom = mCurBottom;
4225                } else {
4226                    vf.set(cf);
4227                }
4228            } else if (attached != null) {
4229                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4230                        "): attached to " + attached);
4231                // A child window should be placed inside of the same visible
4232                // frame that its parent had.
4233                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
4234            } else {
4235                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4236                        "): normal window");
4237                // Otherwise, a normal window must be placed inside the content
4238                // of all screen decorations.
4239                if (attrs.type == TYPE_STATUS_BAR_PANEL || attrs.type == TYPE_VOLUME_OVERLAY) {
4240                    // Status bar panels and the volume dialog are the only windows who can go on
4241                    // top of the status bar.  They are protected by the STATUS_BAR_SERVICE
4242                    // permission, so they have the same privileges as the status
4243                    // bar itself.
4244                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4245                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4246                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4247                            + mRestrictedScreenWidth;
4248                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4249                            + mRestrictedScreenHeight;
4250                } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT) {
4251                    // These dialogs are stable to interim decor changes.
4252                    pf.left = df.left = of.left = cf.left = mStableLeft;
4253                    pf.top = df.top = of.top = cf.top = mStableTop;
4254                    pf.right = df.right = of.right = cf.right = mStableRight;
4255                    pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
4256                } else {
4257                    pf.left = mContentLeft;
4258                    pf.top = mContentTop;
4259                    pf.right = mContentRight;
4260                    pf.bottom = mContentBottom;
4261                    if (win.isVoiceInteraction()) {
4262                        df.left = of.left = cf.left = mVoiceContentLeft;
4263                        df.top = of.top = cf.top = mVoiceContentTop;
4264                        df.right = of.right = cf.right = mVoiceContentRight;
4265                        df.bottom = of.bottom = cf.bottom = mVoiceContentBottom;
4266                    } else if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4267                        df.left = of.left = cf.left = mDockLeft;
4268                        df.top = of.top = cf.top = mDockTop;
4269                        df.right = of.right = cf.right = mDockRight;
4270                        df.bottom = of.bottom = cf.bottom = mDockBottom;
4271                    } else {
4272                        df.left = of.left = cf.left = mContentLeft;
4273                        df.top = of.top = cf.top = mContentTop;
4274                        df.right = of.right = cf.right = mContentRight;
4275                        df.bottom = of.bottom = cf.bottom = mContentBottom;
4276                    }
4277                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4278                        vf.left = mCurLeft;
4279                        vf.top = mCurTop;
4280                        vf.right = mCurRight;
4281                        vf.bottom = mCurBottom;
4282                    } else {
4283                        vf.set(cf);
4284                    }
4285                }
4286            }
4287        }
4288
4289        // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
4290        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR) {
4291            df.left = df.top = -10000;
4292            df.right = df.bottom = 10000;
4293            if (attrs.type != TYPE_WALLPAPER) {
4294                of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
4295                of.right = of.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
4296            }
4297        }
4298
4299        // If the device has a chin (e.g. some watches), a dead area at the bottom of the screen we
4300        // need to provide information to the clients that want to pretend that you can draw there.
4301        // We only want to apply outsets to certain types of windows. For example, we never want to
4302        // apply the outsets to floating dialogs, because they wouldn't make sense there.
4303        final boolean useOutsets = shouldUseOutsets(attrs, fl);
4304        if (isDefaultDisplay && useOutsets) {
4305            osf = mTmpOutsetFrame;
4306            osf.set(cf.left, cf.top, cf.right, cf.bottom);
4307            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
4308            if (outset > 0) {
4309                int rotation = mDisplayRotation;
4310                if (rotation == Surface.ROTATION_0) {
4311                    osf.bottom += outset;
4312                } else if (rotation == Surface.ROTATION_90) {
4313                    osf.right += outset;
4314                } else if (rotation == Surface.ROTATION_180) {
4315                    osf.top -= outset;
4316                } else if (rotation == Surface.ROTATION_270) {
4317                    osf.left -= outset;
4318                }
4319                if (DEBUG_LAYOUT) Slog.v(TAG, "applying bottom outset of " + outset
4320                        + " with rotation " + rotation + ", result: " + osf);
4321            }
4322        }
4323
4324        if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
4325                + ": sim=#" + Integer.toHexString(sim)
4326                + " attach=" + attached + " type=" + attrs.type
4327                + String.format(" flags=0x%08x", fl)
4328                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
4329                + " of=" + of.toShortString()
4330                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
4331                + " dcf=" + dcf.toShortString()
4332                + " sf=" + sf.toShortString()
4333                + " osf=" + (osf == null ? "null" : osf.toShortString()));
4334
4335        win.computeFrameLw(pf, df, of, cf, vf, dcf, sf, osf);
4336
4337        // Dock windows carve out the bottom of the screen, so normal windows
4338        // can't appear underneath them.
4339        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
4340                && !win.getGivenInsetsPendingLw()) {
4341            setLastInputMethodWindowLw(null, null);
4342            offsetInputMethodWindowLw(win);
4343        }
4344        if (attrs.type == TYPE_VOICE_INTERACTION && win.isVisibleOrBehindKeyguardLw()
4345                && !win.getGivenInsetsPendingLw()) {
4346            offsetVoiceInputWindowLw(win);
4347        }
4348    }
4349
4350    private void offsetInputMethodWindowLw(WindowState win) {
4351        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4352        top += win.getGivenContentInsetsLw().top;
4353        if (mContentBottom > top) {
4354            mContentBottom = top;
4355        }
4356        if (mVoiceContentBottom > top) {
4357            mVoiceContentBottom = top;
4358        }
4359        top = win.getVisibleFrameLw().top;
4360        top += win.getGivenVisibleInsetsLw().top;
4361        if (mCurBottom > top) {
4362            mCurBottom = top;
4363        }
4364        if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
4365                + mDockBottom + " mContentBottom="
4366                + mContentBottom + " mCurBottom=" + mCurBottom);
4367    }
4368
4369    private void offsetVoiceInputWindowLw(WindowState win) {
4370        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4371        top += win.getGivenContentInsetsLw().top;
4372        if (mVoiceContentBottom > top) {
4373            mVoiceContentBottom = top;
4374        }
4375    }
4376
4377    /** {@inheritDoc} */
4378    @Override
4379    public void finishLayoutLw() {
4380        return;
4381    }
4382
4383    /** {@inheritDoc} */
4384    @Override
4385    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
4386        mTopFullscreenOpaqueWindowState = null;
4387        mTopFullscreenOpaqueOrDimmingWindowState = null;
4388        mAppsToBeHidden.clear();
4389        mAppsThatDismissKeyguard.clear();
4390        mForceStatusBar = false;
4391        mForceStatusBarFromKeyguard = false;
4392        mForceStatusBarTransparent = false;
4393        mForcingShowNavBar = false;
4394        mForcingShowNavBarLayer = -1;
4395
4396        mHideLockScreen = false;
4397        mAllowLockscreenWhenOn = false;
4398        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
4399        mShowingLockscreen = false;
4400        mShowingDream = false;
4401        mWinShowWhenLocked = null;
4402        mKeyguardSecure = isKeyguardSecure();
4403        mKeyguardSecureIncludingHidden = mKeyguardSecure
4404                && (mKeyguardDelegate != null && mKeyguardDelegate.isShowing());
4405    }
4406
4407    /** {@inheritDoc} */
4408    @Override
4409    public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs,
4410            WindowState attached) {
4411        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
4412                + win.isVisibleOrBehindKeyguardLw());
4413        final int fl = PolicyControl.getWindowFlags(win, attrs);
4414        if (mTopFullscreenOpaqueWindowState == null
4415                && win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD) {
4416            mForcingShowNavBar = true;
4417            mForcingShowNavBarLayer = win.getSurfaceLayer();
4418        }
4419        if (attrs.type == TYPE_STATUS_BAR) {
4420            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4421                mForceStatusBarFromKeyguard = true;
4422            }
4423            if ((attrs.privateFlags & PRIVATE_FLAG_FORCE_STATUS_BAR_VISIBLE_TRANSPARENT) != 0) {
4424                mForceStatusBarTransparent = true;
4425            }
4426        }
4427
4428        boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
4429                && attrs.type < FIRST_SYSTEM_WINDOW;
4430        final boolean showWhenLocked = (fl & FLAG_SHOW_WHEN_LOCKED) != 0;
4431        final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
4432
4433        if (mTopFullscreenOpaqueWindowState == null &&
4434                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
4435            if ((fl & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
4436                if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4437                    mForceStatusBarFromKeyguard = true;
4438                } else {
4439                    mForceStatusBar = true;
4440                }
4441            }
4442            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4443                mShowingLockscreen = true;
4444            }
4445            if (attrs.type == TYPE_DREAM) {
4446                // If the lockscreen was showing when the dream started then wait
4447                // for the dream to draw before hiding the lockscreen.
4448                if (!mDreamingLockscreen
4449                        || (win.isVisibleLw() && win.hasDrawnLw())) {
4450                    mShowingDream = true;
4451                    appWindow = true;
4452                }
4453            }
4454
4455            final IApplicationToken appToken = win.getAppToken();
4456
4457            // For app windows that are not attached, we decide if all windows in the app they
4458            // represent should be hidden or if we should hide the lockscreen. For attached app
4459            // windows we defer the decision to the window it is attached to.
4460            if (appWindow && attached == null) {
4461                if (showWhenLocked) {
4462                    // Remove any previous windows with the same appToken.
4463                    mAppsToBeHidden.remove(appToken);
4464                    mAppsThatDismissKeyguard.remove(appToken);
4465                    if (mAppsToBeHidden.isEmpty()) {
4466                        if (dismissKeyguard && !mKeyguardSecure) {
4467                            mAppsThatDismissKeyguard.add(appToken);
4468                        } else if (win.isDrawnLw() || win.hasAppShownWindows()) {
4469                            mWinShowWhenLocked = win;
4470                            mHideLockScreen = true;
4471                            mForceStatusBarFromKeyguard = false;
4472                        }
4473                    }
4474                } else if (dismissKeyguard) {
4475                    if (mKeyguardSecure) {
4476                        mAppsToBeHidden.add(appToken);
4477                    } else {
4478                        mAppsToBeHidden.remove(appToken);
4479                    }
4480                    mAppsThatDismissKeyguard.add(appToken);
4481                } else {
4482                    mAppsToBeHidden.add(appToken);
4483                }
4484                if (attrs.x == 0 && attrs.y == 0
4485                        && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
4486                        && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
4487                    if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
4488                    mTopFullscreenOpaqueWindowState = win;
4489                    if (mTopFullscreenOpaqueOrDimmingWindowState == null) {
4490                        mTopFullscreenOpaqueOrDimmingWindowState = win;
4491                    }
4492                    if (!mAppsThatDismissKeyguard.isEmpty() &&
4493                            mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
4494                        if (DEBUG_LAYOUT) Slog.v(TAG,
4495                                "Setting mDismissKeyguard true by win " + win);
4496                        mDismissKeyguard = (mWinDismissingKeyguard == win
4497                                && mSecureDismissingKeyguard == mKeyguardSecure)
4498                                ? DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
4499                        mWinDismissingKeyguard = win;
4500                        mSecureDismissingKeyguard = mKeyguardSecure;
4501                        mForceStatusBarFromKeyguard = mShowingLockscreen && mKeyguardSecure;
4502                    } else if (mAppsToBeHidden.isEmpty() && showWhenLocked
4503                            && (win.isDrawnLw() || win.hasAppShownWindows())) {
4504                        if (DEBUG_LAYOUT) Slog.v(TAG,
4505                                "Setting mHideLockScreen to true by win " + win);
4506                        mHideLockScreen = true;
4507                        mForceStatusBarFromKeyguard = false;
4508                    }
4509                    if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
4510                        mAllowLockscreenWhenOn = true;
4511                    }
4512                }
4513
4514                if (mWinShowWhenLocked != null &&
4515                        mWinShowWhenLocked.getAppToken() != win.getAppToken() &&
4516                        (attrs.flags & FLAG_SHOW_WHEN_LOCKED) == 0) {
4517                    win.hideLw(false);
4518                }
4519            }
4520        } else if (mTopFullscreenOpaqueWindowState == null && mWinShowWhenLocked == null) {
4521            // No TopFullscreenOpaqueWindow is showing, but we found a SHOW_WHEN_LOCKED window
4522            // that is being hidden in an animation - keep the
4523            // keyguard hidden until the new window shows up and
4524            // we know whether to show the keyguard or not.
4525            if (win.isAnimatingLw() && appWindow && showWhenLocked && mKeyguardHidden) {
4526                mHideLockScreen = true;
4527                mWinShowWhenLocked = win;
4528            }
4529        }
4530        if (mTopFullscreenOpaqueOrDimmingWindowState == null
4531                && win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()
4532                && win.isDimming()) {
4533            mTopFullscreenOpaqueOrDimmingWindowState = win;
4534        }
4535    }
4536
4537    /** {@inheritDoc} */
4538    @Override
4539    public int finishPostLayoutPolicyLw() {
4540        if (mWinShowWhenLocked != null && mTopFullscreenOpaqueWindowState != null &&
4541                mWinShowWhenLocked.getAppToken() != mTopFullscreenOpaqueWindowState.getAppToken()
4542                && isKeyguardLocked()) {
4543            // A dialog is dismissing the keyguard. Put the wallpaper behind it and hide the
4544            // fullscreen window.
4545            // TODO: Make sure FLAG_SHOW_WALLPAPER is restored when dialog is dismissed. Or not.
4546            mWinShowWhenLocked.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4547            mTopFullscreenOpaqueWindowState.hideLw(false);
4548            mTopFullscreenOpaqueWindowState = mWinShowWhenLocked;
4549        }
4550
4551        int changes = 0;
4552        boolean topIsFullscreen = false;
4553
4554        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
4555                ? mTopFullscreenOpaqueWindowState.getAttrs()
4556                : null;
4557
4558        // If we are not currently showing a dream then remember the current
4559        // lockscreen state.  We will use this to determine whether the dream
4560        // started while the lockscreen was showing and remember this state
4561        // while the dream is showing.
4562        if (!mShowingDream) {
4563            mDreamingLockscreen = mShowingLockscreen;
4564            if (mDreamingSleepTokenNeeded) {
4565                mDreamingSleepTokenNeeded = false;
4566                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 0, 1).sendToTarget();
4567            }
4568        } else {
4569            if (!mDreamingSleepTokenNeeded) {
4570                mDreamingSleepTokenNeeded = true;
4571                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 1, 1).sendToTarget();
4572            }
4573        }
4574
4575        if (mStatusBar != null) {
4576            if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
4577                    + " forcefkg=" + mForceStatusBarFromKeyguard
4578                    + " top=" + mTopFullscreenOpaqueWindowState);
4579            boolean shouldBeTransparent = mForceStatusBarTransparent
4580                    && !mForceStatusBar
4581                    && !mForceStatusBarFromKeyguard;
4582            if (!shouldBeTransparent) {
4583                mStatusBarController.setShowTransparent(false /* transparent */);
4584            } else if (!mStatusBar.isVisibleLw()) {
4585                mStatusBarController.setShowTransparent(true /* transparent */);
4586            }
4587            if (mForceStatusBar || mForceStatusBarFromKeyguard || mForceStatusBarTransparent) {
4588                if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
4589                if (mStatusBarController.setBarShowingLw(true)) {
4590                    changes |= FINISH_LAYOUT_REDO_LAYOUT;
4591                }
4592                // Maintain fullscreen layout until incoming animation is complete.
4593                topIsFullscreen = mTopIsFullscreen && mStatusBar.isAnimatingLw();
4594                // Transient status bar on the lockscreen is not allowed
4595                if (mForceStatusBarFromKeyguard && mStatusBarController.isTransientShowing()) {
4596                    mStatusBarController.updateVisibilityLw(false /*transientAllowed*/,
4597                            mLastSystemUiFlags, mLastSystemUiFlags);
4598                }
4599            } else if (mTopFullscreenOpaqueWindowState != null) {
4600                final int fl = PolicyControl.getWindowFlags(null, lp);
4601                if (localLOGV) {
4602                    Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
4603                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
4604                    Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
4605                            + " lp.flags=0x" + Integer.toHexString(fl));
4606                }
4607                topIsFullscreen = (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
4608                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
4609                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
4610                // and mTopIsFullscreen is that mTopIsFullscreen is set only if the window
4611                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
4612                // case though.
4613                if (mStatusBarController.isTransientShowing()) {
4614                    if (mStatusBarController.setBarShowingLw(true)) {
4615                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4616                    }
4617                } else if (topIsFullscreen) {
4618                    if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
4619                    if (mStatusBarController.setBarShowingLw(false)) {
4620                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4621                    } else {
4622                        if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
4623                    }
4624                } else {
4625                    if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
4626                    if (mStatusBarController.setBarShowingLw(true)) {
4627                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4628                    }
4629                }
4630            }
4631        }
4632
4633        if (mTopIsFullscreen != topIsFullscreen) {
4634            if (!topIsFullscreen) {
4635                // Force another layout when status bar becomes fully shown.
4636                changes |= FINISH_LAYOUT_REDO_LAYOUT;
4637            }
4638            mTopIsFullscreen = topIsFullscreen;
4639        }
4640
4641        // Hide the key guard if a visible window explicitly specifies that it wants to be
4642        // displayed when the screen is locked.
4643        if (mKeyguardDelegate != null && mStatusBar != null) {
4644            if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
4645                    + mHideLockScreen);
4646            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardSecure) {
4647                mKeyguardHidden = true;
4648                if (setKeyguardOccludedLw(true)) {
4649                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4650                            | FINISH_LAYOUT_REDO_CONFIG
4651                            | FINISH_LAYOUT_REDO_WALLPAPER;
4652                }
4653                if (mKeyguardDelegate.isShowing()) {
4654                    mHandler.post(new Runnable() {
4655                        @Override
4656                        public void run() {
4657                            mKeyguardDelegate.keyguardDone(false, false);
4658                        }
4659                    });
4660                }
4661            } else if (mHideLockScreen) {
4662                mKeyguardHidden = true;
4663                mWinDismissingKeyguard = null;
4664                if (setKeyguardOccludedLw(true)) {
4665                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4666                            | FINISH_LAYOUT_REDO_CONFIG
4667                            | FINISH_LAYOUT_REDO_WALLPAPER;
4668                }
4669            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
4670                mKeyguardHidden = false;
4671                if (setKeyguardOccludedLw(false)) {
4672                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4673                            | FINISH_LAYOUT_REDO_CONFIG
4674                            | FINISH_LAYOUT_REDO_WALLPAPER;
4675                }
4676                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
4677                    // Only launch the next keyguard unlock window once per window.
4678                    mHandler.post(new Runnable() {
4679                        @Override
4680                        public void run() {
4681                            mKeyguardDelegate.dismiss();
4682                        }
4683                    });
4684                }
4685            } else {
4686                mWinDismissingKeyguard = null;
4687                mSecureDismissingKeyguard = false;
4688                mKeyguardHidden = false;
4689                if (setKeyguardOccludedLw(false)) {
4690                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4691                            | FINISH_LAYOUT_REDO_CONFIG
4692                            | FINISH_LAYOUT_REDO_WALLPAPER;
4693                }
4694            }
4695        }
4696
4697        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
4698            // If the navigation bar has been hidden or shown, we need to do another
4699            // layout pass to update that window.
4700            changes |= FINISH_LAYOUT_REDO_LAYOUT;
4701        }
4702
4703        // update since mAllowLockscreenWhenOn might have changed
4704        updateLockScreenTimeout();
4705        return changes;
4706    }
4707
4708    /**
4709     * Updates the occluded state of the Keyguard.
4710     *
4711     * @return Whether the flags have changed and we have to redo the layout.
4712     */
4713    private boolean setKeyguardOccludedLw(boolean isOccluded) {
4714        boolean wasOccluded = mKeyguardOccluded;
4715        boolean showing = mKeyguardDelegate.isShowing();
4716        if (wasOccluded && !isOccluded && showing) {
4717            mKeyguardOccluded = false;
4718            mKeyguardDelegate.setOccluded(false);
4719            mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
4720            mStatusBar.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4721            return true;
4722        } else if (!wasOccluded && isOccluded && showing) {
4723            mKeyguardOccluded = true;
4724            mKeyguardDelegate.setOccluded(true);
4725            mStatusBar.getAttrs().privateFlags &= ~PRIVATE_FLAG_KEYGUARD;
4726            mStatusBar.getAttrs().flags &= ~FLAG_SHOW_WALLPAPER;
4727            return true;
4728        } else {
4729            return false;
4730        }
4731    }
4732
4733    private boolean isStatusBarKeyguard() {
4734        return mStatusBar != null
4735                && (mStatusBar.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
4736    }
4737
4738    @Override
4739    public boolean allowAppAnimationsLw() {
4740        if (isStatusBarKeyguard() || mShowingDream) {
4741            // If keyguard or dreams is currently visible, no reason to animate behind it.
4742            return false;
4743        }
4744        return true;
4745    }
4746
4747    @Override
4748    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
4749        mFocusedWindow = newFocus;
4750        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
4751            // If the navigation bar has been hidden or shown, we need to do another
4752            // layout pass to update that window.
4753            return FINISH_LAYOUT_REDO_LAYOUT;
4754        }
4755        return 0;
4756    }
4757
4758    /** {@inheritDoc} */
4759    @Override
4760    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
4761        // lid changed state
4762        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
4763        if (newLidState == mLidState) {
4764            return;
4765        }
4766
4767        mLidState = newLidState;
4768        applyLidSwitchState();
4769        updateRotation(true);
4770
4771        if (lidOpen) {
4772            wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromLidSwitch,
4773                    "android.policy:LID");
4774        } else if (!mLidControlsSleep) {
4775            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4776        }
4777    }
4778
4779    @Override
4780    public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered) {
4781        int lensCoverState = lensCovered ? CAMERA_LENS_COVERED : CAMERA_LENS_UNCOVERED;
4782        if (mCameraLensCoverState == lensCoverState) {
4783            return;
4784        }
4785        if (mCameraLensCoverState == CAMERA_LENS_COVERED &&
4786                lensCoverState == CAMERA_LENS_UNCOVERED) {
4787            Intent intent;
4788            final boolean keyguardActive = mKeyguardDelegate == null ? false :
4789                    mKeyguardDelegate.isShowing();
4790            if (keyguardActive) {
4791                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
4792            } else {
4793                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
4794            }
4795            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromCameraLens,
4796                    "android.policy:CAMERA_COVER");
4797            startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
4798        }
4799        mCameraLensCoverState = lensCoverState;
4800    }
4801
4802    void setHdmiPlugged(boolean plugged) {
4803        if (mHdmiPlugged != plugged) {
4804            mHdmiPlugged = plugged;
4805            updateRotation(true, true);
4806            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
4807            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4808            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
4809            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
4810        }
4811    }
4812
4813    void initializeHdmiState() {
4814        boolean plugged = false;
4815        // watch for HDMI plug messages if the hdmi switch exists
4816        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
4817            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
4818
4819            final String filename = "/sys/class/switch/hdmi/state";
4820            FileReader reader = null;
4821            try {
4822                reader = new FileReader(filename);
4823                char[] buf = new char[15];
4824                int n = reader.read(buf);
4825                if (n > 1) {
4826                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
4827                }
4828            } catch (IOException ex) {
4829                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
4830            } catch (NumberFormatException ex) {
4831                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
4832            } finally {
4833                if (reader != null) {
4834                    try {
4835                        reader.close();
4836                    } catch (IOException ex) {
4837                    }
4838                }
4839            }
4840        }
4841        // This dance forces the code in setHdmiPlugged to run.
4842        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
4843        mHdmiPlugged = !plugged;
4844        setHdmiPlugged(!mHdmiPlugged);
4845    }
4846
4847    final Object mScreenshotLock = new Object();
4848    ServiceConnection mScreenshotConnection = null;
4849
4850    final Runnable mScreenshotTimeout = new Runnable() {
4851        @Override public void run() {
4852            synchronized (mScreenshotLock) {
4853                if (mScreenshotConnection != null) {
4854                    mContext.unbindService(mScreenshotConnection);
4855                    mScreenshotConnection = null;
4856                }
4857            }
4858        }
4859    };
4860
4861    // Assume this is called from the Handler thread.
4862    private void takeScreenshot() {
4863        synchronized (mScreenshotLock) {
4864            if (mScreenshotConnection != null) {
4865                return;
4866            }
4867            ComponentName cn = new ComponentName("com.android.systemui",
4868                    "com.android.systemui.screenshot.TakeScreenshotService");
4869            Intent intent = new Intent();
4870            intent.setComponent(cn);
4871            ServiceConnection conn = new ServiceConnection() {
4872                @Override
4873                public void onServiceConnected(ComponentName name, IBinder service) {
4874                    synchronized (mScreenshotLock) {
4875                        if (mScreenshotConnection != this) {
4876                            return;
4877                        }
4878                        Messenger messenger = new Messenger(service);
4879                        Message msg = Message.obtain(null, 1);
4880                        final ServiceConnection myConn = this;
4881                        Handler h = new Handler(mHandler.getLooper()) {
4882                            @Override
4883                            public void handleMessage(Message msg) {
4884                                synchronized (mScreenshotLock) {
4885                                    if (mScreenshotConnection == myConn) {
4886                                        mContext.unbindService(mScreenshotConnection);
4887                                        mScreenshotConnection = null;
4888                                        mHandler.removeCallbacks(mScreenshotTimeout);
4889                                    }
4890                                }
4891                            }
4892                        };
4893                        msg.replyTo = new Messenger(h);
4894                        msg.arg1 = msg.arg2 = 0;
4895                        if (mStatusBar != null && mStatusBar.isVisibleLw())
4896                            msg.arg1 = 1;
4897                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
4898                            msg.arg2 = 1;
4899                        try {
4900                            messenger.send(msg);
4901                        } catch (RemoteException e) {
4902                        }
4903                    }
4904                }
4905                @Override
4906                public void onServiceDisconnected(ComponentName name) {}
4907            };
4908            if (mContext.bindServiceAsUser(
4909                    intent, conn, Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
4910                mScreenshotConnection = conn;
4911                mHandler.postDelayed(mScreenshotTimeout, 10000);
4912            }
4913        }
4914    }
4915
4916    /** {@inheritDoc} */
4917    @Override
4918    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
4919        if (!mSystemBooted) {
4920            // If we have not yet booted, don't let key events do anything.
4921            return 0;
4922        }
4923
4924        final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;
4925        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
4926        final boolean canceled = event.isCanceled();
4927        final int keyCode = event.getKeyCode();
4928
4929        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
4930
4931        // If screen is off then we treat the case where the keyguard is open but hidden
4932        // the same as if it were open and in front.
4933        // This will prevent any keys other than the power button from waking the screen
4934        // when the keyguard is hidden by another activity.
4935        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
4936                                            (interactive ?
4937                                                isKeyguardShowingAndNotOccluded() :
4938                                                mKeyguardDelegate.isShowing()));
4939
4940        if (DEBUG_INPUT) {
4941            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
4942                    + " interactive=" + interactive + " keyguardActive=" + keyguardActive
4943                    + " policyFlags=" + Integer.toHexString(policyFlags));
4944        }
4945
4946        // Basic policy based on interactive state.
4947        int result;
4948        boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
4949                || event.isWakeKey();
4950        if (interactive || (isInjected && !isWakeKey)) {
4951            // When the device is interactive or the key is injected pass the
4952            // key to the application.
4953            result = ACTION_PASS_TO_USER;
4954            isWakeKey = false;
4955        } else if (!interactive && shouldDispatchInputWhenNonInteractive()) {
4956            // If we're currently dozing with the screen on and the keyguard showing, pass the key
4957            // to the application but preserve its wake key status to make sure we still move
4958            // from dozing to fully interactive if we would normally go from off to fully
4959            // interactive.
4960            result = ACTION_PASS_TO_USER;
4961        } else {
4962            // When the screen is off and the key is not injected, determine whether
4963            // to wake the device but don't pass the key to the application.
4964            result = 0;
4965            if (isWakeKey && (!down || !isWakeKeyWhenScreenOff(keyCode))) {
4966                isWakeKey = false;
4967            }
4968        }
4969
4970        // If the key would be handled globally, just return the result, don't worry about special
4971        // key processing.
4972        if (isValidGlobalKey(keyCode)
4973                && mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
4974            if (isWakeKey) {
4975                wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
4976            }
4977            return result;
4978        }
4979
4980        boolean useHapticFeedback = down
4981                && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
4982                && event.getRepeatCount() == 0;
4983
4984        // Handle special keys.
4985        switch (keyCode) {
4986            case KeyEvent.KEYCODE_VOLUME_DOWN:
4987            case KeyEvent.KEYCODE_VOLUME_UP:
4988            case KeyEvent.KEYCODE_VOLUME_MUTE: {
4989                if (mUseTvRouting) {
4990                    // On TVs volume keys never go to the foreground app
4991                    result &= ~ACTION_PASS_TO_USER;
4992                }
4993                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
4994                    if (down) {
4995                        if (interactive && !mScreenshotChordVolumeDownKeyTriggered
4996                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4997                            mScreenshotChordVolumeDownKeyTriggered = true;
4998                            mScreenshotChordVolumeDownKeyTime = event.getDownTime();
4999                            mScreenshotChordVolumeDownKeyConsumed = false;
5000                            cancelPendingPowerKeyAction();
5001                            interceptScreenshotChord();
5002                        }
5003                    } else {
5004                        mScreenshotChordVolumeDownKeyTriggered = false;
5005                        cancelPendingScreenshotChordAction();
5006                    }
5007                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
5008                    if (down) {
5009                        if (interactive && !mScreenshotChordVolumeUpKeyTriggered
5010                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5011                            mScreenshotChordVolumeUpKeyTriggered = true;
5012                            cancelPendingPowerKeyAction();
5013                            cancelPendingScreenshotChordAction();
5014                        }
5015                    } else {
5016                        mScreenshotChordVolumeUpKeyTriggered = false;
5017                        cancelPendingScreenshotChordAction();
5018                    }
5019                }
5020                if (down) {
5021                    TelecomManager telecomManager = getTelecommService();
5022                    if (telecomManager != null) {
5023                        if (telecomManager.isRinging()) {
5024                            // If an incoming call is ringing, either VOLUME key means
5025                            // "silence ringer".  We handle these keys here, rather than
5026                            // in the InCallScreen, to make sure we'll respond to them
5027                            // even if the InCallScreen hasn't come to the foreground yet.
5028                            // Look for the DOWN event here, to agree with the "fallback"
5029                            // behavior in the InCallScreen.
5030                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5031                                  + " VOLUME key-down while ringing: Silence ringer!");
5032
5033                            // Silence the ringer.  (It's safe to call this
5034                            // even if the ringer has already been silenced.)
5035                            telecomManager.silenceRinger();
5036
5037                            // And *don't* pass this key thru to the current activity
5038                            // (which is probably the InCallScreen.)
5039                            result &= ~ACTION_PASS_TO_USER;
5040                            break;
5041                        }
5042                        if (telecomManager.isInCall()
5043                                && (result & ACTION_PASS_TO_USER) == 0) {
5044                            // If we are in call but we decided not to pass the key to
5045                            // the application, just pass it to the session service.
5046
5047                            MediaSessionLegacyHelper.getHelper(mContext)
5048                                    .sendVolumeKeyEvent(event, false);
5049                            break;
5050                        }
5051                    }
5052
5053                    if ((result & ACTION_PASS_TO_USER) == 0) {
5054                        if (mUseTvRouting) {
5055                            dispatchDirectAudioEvent(event);
5056                        } else {
5057                            // If we aren't passing to the user and no one else
5058                            // handled it send it to the session manager to
5059                            // figure out.
5060                            MediaSessionLegacyHelper.getHelper(mContext)
5061                                    .sendVolumeKeyEvent(event, true);
5062                        }
5063                        break;
5064                    }
5065                }
5066                break;
5067            }
5068
5069            case KeyEvent.KEYCODE_ENDCALL: {
5070                result &= ~ACTION_PASS_TO_USER;
5071                if (down) {
5072                    TelecomManager telecomManager = getTelecommService();
5073                    boolean hungUp = false;
5074                    if (telecomManager != null) {
5075                        hungUp = telecomManager.endCall();
5076                    }
5077                    if (interactive && !hungUp) {
5078                        mEndCallKeyHandled = false;
5079                        mHandler.postDelayed(mEndCallLongPress,
5080                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5081                    } else {
5082                        mEndCallKeyHandled = true;
5083                    }
5084                } else {
5085                    if (!mEndCallKeyHandled) {
5086                        mHandler.removeCallbacks(mEndCallLongPress);
5087                        if (!canceled) {
5088                            if ((mEndcallBehavior
5089                                    & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
5090                                if (goHome()) {
5091                                    break;
5092                                }
5093                            }
5094                            if ((mEndcallBehavior
5095                                    & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
5096                                mPowerManager.goToSleep(event.getEventTime(),
5097                                        PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
5098                                isWakeKey = false;
5099                            }
5100                        }
5101                    }
5102                }
5103                break;
5104            }
5105
5106            case KeyEvent.KEYCODE_POWER: {
5107                result &= ~ACTION_PASS_TO_USER;
5108                isWakeKey = false; // wake-up will be handled separately
5109                if (down) {
5110                    interceptPowerKeyDown(event, interactive);
5111                } else {
5112                    interceptPowerKeyUp(event, interactive, canceled);
5113                }
5114                break;
5115            }
5116
5117            case KeyEvent.KEYCODE_SLEEP: {
5118                result &= ~ACTION_PASS_TO_USER;
5119                isWakeKey = false;
5120                if (!mPowerManager.isInteractive()) {
5121                    useHapticFeedback = false; // suppress feedback if already non-interactive
5122                }
5123                if (down) {
5124                    sleepPress(event.getEventTime());
5125                } else {
5126                    sleepRelease(event.getEventTime());
5127                }
5128                break;
5129            }
5130
5131            case KeyEvent.KEYCODE_SOFT_SLEEP: {
5132                result &= ~ACTION_PASS_TO_USER;
5133                isWakeKey = false;
5134                if (!down) {
5135                    mPowerManagerInternal.setUserInactiveOverrideFromWindowManager();
5136                }
5137                break;
5138            }
5139
5140            case KeyEvent.KEYCODE_WAKEUP: {
5141                result &= ~ACTION_PASS_TO_USER;
5142                isWakeKey = true;
5143                break;
5144            }
5145
5146            case KeyEvent.KEYCODE_MEDIA_PLAY:
5147            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5148            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5149            case KeyEvent.KEYCODE_HEADSETHOOK:
5150            case KeyEvent.KEYCODE_MUTE:
5151            case KeyEvent.KEYCODE_MEDIA_STOP:
5152            case KeyEvent.KEYCODE_MEDIA_NEXT:
5153            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5154            case KeyEvent.KEYCODE_MEDIA_REWIND:
5155            case KeyEvent.KEYCODE_MEDIA_RECORD:
5156            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5157            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
5158                if (MediaSessionLegacyHelper.getHelper(mContext).isGlobalPriorityActive()) {
5159                    // If the global session is active pass all media keys to it
5160                    // instead of the active window.
5161                    result &= ~ACTION_PASS_TO_USER;
5162                }
5163                if ((result & ACTION_PASS_TO_USER) == 0) {
5164                    // Only do this if we would otherwise not pass it to the user. In that
5165                    // case, the PhoneWindow class will do the same thing, except it will
5166                    // only do it if the showing app doesn't process the key on its own.
5167                    // Note that we need to make a copy of the key event here because the
5168                    // original key event will be recycled when we return.
5169                    mBroadcastWakeLock.acquire();
5170                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
5171                            new KeyEvent(event));
5172                    msg.setAsynchronous(true);
5173                    msg.sendToTarget();
5174                }
5175                break;
5176            }
5177
5178            case KeyEvent.KEYCODE_CALL: {
5179                if (down) {
5180                    TelecomManager telecomManager = getTelecommService();
5181                    if (telecomManager != null) {
5182                        if (telecomManager.isRinging()) {
5183                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5184                                  + " CALL key-down while ringing: Answer the call!");
5185                            telecomManager.acceptRingingCall();
5186
5187                            // And *don't* pass this key thru to the current activity
5188                            // (which is presumably the InCallScreen.)
5189                            result &= ~ACTION_PASS_TO_USER;
5190                        }
5191                    }
5192                }
5193                break;
5194            }
5195            case KeyEvent.KEYCODE_VOICE_ASSIST: {
5196                // Only do this if we would otherwise not pass it to the user. In that case,
5197                // interceptKeyBeforeDispatching would apply a similar but different policy in
5198                // order to invoke voice assist actions. Note that we need to make a copy of the
5199                // key event here because the original key event will be recycled when we return.
5200                if ((result & ACTION_PASS_TO_USER) == 0 && !down) {
5201                    mBroadcastWakeLock.acquire();
5202                    Message msg = mHandler.obtainMessage(MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK,
5203                            keyguardActive ? 1 : 0, 0);
5204                    msg.setAsynchronous(true);
5205                    msg.sendToTarget();
5206                }
5207            }
5208        }
5209
5210        if (useHapticFeedback) {
5211            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
5212        }
5213
5214        if (isWakeKey) {
5215            wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5216        }
5217
5218        return result;
5219    }
5220
5221    /**
5222     * Returns true if the key can have global actions attached to it.
5223     * We reserve all power management keys for the system since they require
5224     * very careful handling.
5225     */
5226    private static boolean isValidGlobalKey(int keyCode) {
5227        switch (keyCode) {
5228            case KeyEvent.KEYCODE_POWER:
5229            case KeyEvent.KEYCODE_WAKEUP:
5230            case KeyEvent.KEYCODE_SLEEP:
5231                return false;
5232            default:
5233                return true;
5234        }
5235    }
5236
5237    /**
5238     * When the screen is off we ignore some keys that might otherwise typically
5239     * be considered wake keys.  We filter them out here.
5240     *
5241     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
5242     * is always considered a wake key.
5243     */
5244    private boolean isWakeKeyWhenScreenOff(int keyCode) {
5245        switch (keyCode) {
5246            // ignore volume keys unless docked
5247            case KeyEvent.KEYCODE_VOLUME_UP:
5248            case KeyEvent.KEYCODE_VOLUME_DOWN:
5249            case KeyEvent.KEYCODE_VOLUME_MUTE:
5250                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
5251
5252            // ignore media and camera keys
5253            case KeyEvent.KEYCODE_MUTE:
5254            case KeyEvent.KEYCODE_HEADSETHOOK:
5255            case KeyEvent.KEYCODE_MEDIA_PLAY:
5256            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5257            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5258            case KeyEvent.KEYCODE_MEDIA_STOP:
5259            case KeyEvent.KEYCODE_MEDIA_NEXT:
5260            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5261            case KeyEvent.KEYCODE_MEDIA_REWIND:
5262            case KeyEvent.KEYCODE_MEDIA_RECORD:
5263            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5264            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
5265            case KeyEvent.KEYCODE_CAMERA:
5266                return false;
5267        }
5268        return true;
5269    }
5270
5271
5272    /** {@inheritDoc} */
5273    @Override
5274    public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
5275        if ((policyFlags & FLAG_WAKE) != 0) {
5276            if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion,
5277                    "android.policy:MOTION")) {
5278                return 0;
5279            }
5280        }
5281
5282        if (shouldDispatchInputWhenNonInteractive()) {
5283            return ACTION_PASS_TO_USER;
5284        }
5285
5286        // If we have not passed the action up and we are in theater mode without dreaming,
5287        // there will be no dream to intercept the touch and wake into ambient.  The device should
5288        // wake up in this case.
5289        if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
5290            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotionWhenNotDreaming,
5291                    "android.policy:MOTION");
5292        }
5293
5294        return 0;
5295    }
5296
5297    private boolean shouldDispatchInputWhenNonInteractive() {
5298        if (mDisplay == null || mDisplay.getState() == Display.STATE_OFF) {
5299            return false;
5300        }
5301        // Send events to keyguard while the screen is on and it's showing.
5302        if (isKeyguardShowingAndNotOccluded()) {
5303            return true;
5304        }
5305
5306        // Send events to a dozing dream even if the screen is off since the dream
5307        // is in control of the state of the screen.
5308        IDreamManager dreamManager = getDreamManager();
5309
5310        try {
5311            if (dreamManager != null && dreamManager.isDreaming()) {
5312                return true;
5313            }
5314        } catch (RemoteException e) {
5315            Slog.e(TAG, "RemoteException when checking if dreaming", e);
5316        }
5317
5318        // Otherwise, consume events since the user can't see what is being
5319        // interacted with.
5320        return false;
5321    }
5322
5323    private void dispatchDirectAudioEvent(KeyEvent event) {
5324        if (event.getAction() != KeyEvent.ACTION_DOWN) {
5325            return;
5326        }
5327        int keyCode = event.getKeyCode();
5328        int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
5329                | AudioManager.FLAG_FROM_KEY;
5330        String pkgName = mContext.getOpPackageName();
5331        switch (keyCode) {
5332            case KeyEvent.KEYCODE_VOLUME_UP:
5333                try {
5334                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
5335                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5336                } catch (RemoteException e) {
5337                    Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
5338                }
5339                break;
5340            case KeyEvent.KEYCODE_VOLUME_DOWN:
5341                try {
5342                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
5343                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5344                } catch (RemoteException e) {
5345                    Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
5346                }
5347                break;
5348            case KeyEvent.KEYCODE_VOLUME_MUTE:
5349                try {
5350                    if (event.getRepeatCount() == 0) {
5351                        getAudioService().adjustSuggestedStreamVolume(
5352                                AudioManager.ADJUST_TOGGLE_MUTE,
5353                                AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5354                    }
5355                } catch (RemoteException e) {
5356                    Log.e(TAG, "Error dispatching mute in dispatchTvAudioEvent.", e);
5357                }
5358                break;
5359        }
5360    }
5361
5362    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
5363        if (DEBUG_INPUT) {
5364            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
5365        }
5366
5367        if (mHavePendingMediaKeyRepeatWithWakeLock) {
5368            if (DEBUG_INPUT) {
5369                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
5370            }
5371
5372            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
5373            mHavePendingMediaKeyRepeatWithWakeLock = false;
5374            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
5375        }
5376
5377        dispatchMediaKeyWithWakeLockToAudioService(event);
5378
5379        if (event.getAction() == KeyEvent.ACTION_DOWN
5380                && event.getRepeatCount() == 0) {
5381            mHavePendingMediaKeyRepeatWithWakeLock = true;
5382
5383            Message msg = mHandler.obtainMessage(
5384                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
5385            msg.setAsynchronous(true);
5386            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
5387        } else {
5388            mBroadcastWakeLock.release();
5389        }
5390    }
5391
5392    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
5393        mHavePendingMediaKeyRepeatWithWakeLock = false;
5394
5395        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
5396                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
5397        if (DEBUG_INPUT) {
5398            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
5399        }
5400
5401        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
5402        mBroadcastWakeLock.release();
5403    }
5404
5405    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
5406        if (ActivityManagerNative.isSystemReady()) {
5407            MediaSessionLegacyHelper.getHelper(mContext).sendMediaButtonEvent(event, true);
5408        }
5409    }
5410
5411    void launchVoiceAssistWithWakeLock(boolean keyguardActive) {
5412        IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
5413                ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
5414        if (dic != null) {
5415            try {
5416                dic.exitIdle("voice-search");
5417            } catch (RemoteException e) {
5418            }
5419        }
5420        Intent voiceIntent =
5421            new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
5422        voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, keyguardActive);
5423        startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
5424        mBroadcastWakeLock.release();
5425    }
5426
5427    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
5428        @Override
5429        public void onReceive(Context context, Intent intent) {
5430            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
5431                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
5432                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
5433            } else {
5434                try {
5435                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
5436                            ServiceManager.getService(Context.UI_MODE_SERVICE));
5437                    mUiMode = uiModeService.getCurrentModeType();
5438                } catch (RemoteException e) {
5439                }
5440            }
5441            updateRotation(true);
5442            synchronized (mLock) {
5443                updateOrientationListenerLp();
5444            }
5445        }
5446    };
5447
5448    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
5449        @Override
5450        public void onReceive(Context context, Intent intent) {
5451            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
5452                if (mKeyguardDelegate != null) {
5453                    mKeyguardDelegate.onDreamingStarted();
5454                }
5455            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
5456                if (mKeyguardDelegate != null) {
5457                    mKeyguardDelegate.onDreamingStopped();
5458                }
5459            }
5460        }
5461    };
5462
5463    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
5464        @Override
5465        public void onReceive(Context context, Intent intent) {
5466            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
5467                // tickle the settings observer: this first ensures that we're
5468                // observing the relevant settings for the newly-active user,
5469                // and then updates our own bookkeeping based on the now-
5470                // current user.
5471                mSettingsObserver.onChange(false);
5472
5473                // force a re-application of focused window sysui visibility.
5474                // the window may never have been shown for this user
5475                // e.g. the keyguard when going through the new-user setup flow
5476                synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5477                    mLastSystemUiFlags = 0;
5478                    updateSystemUiVisibilityLw();
5479                }
5480            }
5481        }
5482    };
5483
5484    private final Runnable mHiddenNavPanic = new Runnable() {
5485        @Override
5486        public void run() {
5487            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5488                if (!isUserSetupComplete()) {
5489                    // Swipe-up for navigation bar is disabled during setup
5490                    return;
5491                }
5492                mPendingPanicGestureUptime = SystemClock.uptimeMillis();
5493                mNavigationBarController.showTransient();
5494            }
5495        }
5496    };
5497
5498    private void requestTransientBars(WindowState swipeTarget) {
5499        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5500            if (!isUserSetupComplete()) {
5501                // Swipe-up for navigation bar is disabled during setup
5502                return;
5503            }
5504            boolean sb = mStatusBarController.checkShowTransientBarLw();
5505            boolean nb = mNavigationBarController.checkShowTransientBarLw();
5506            if (sb || nb) {
5507                // Don't show status bar when swiping on already visible navigation bar
5508                if (!nb && swipeTarget == mNavigationBar) {
5509                    if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
5510                    return;
5511                }
5512                if (sb) mStatusBarController.showTransient();
5513                if (nb) mNavigationBarController.showTransient();
5514                mImmersiveModeConfirmation.confirmCurrentPrompt();
5515                updateSystemUiVisibilityLw();
5516            }
5517        }
5518    }
5519
5520    // Called on the PowerManager's Notifier thread.
5521    @Override
5522    public void startedGoingToSleep(int why) {
5523        if (DEBUG_WAKEUP) Slog.i(TAG, "Started going to sleep... (why=" + why + ")");
5524        if (mKeyguardDelegate != null) {
5525            mKeyguardDelegate.onStartedGoingToSleep(why);
5526        }
5527    }
5528
5529    // Called on the PowerManager's Notifier thread.
5530    @Override
5531    public void finishedGoingToSleep(int why) {
5532        EventLog.writeEvent(70000, 0);
5533        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished going to sleep... (why=" + why + ")");
5534        MetricsLogger.histogram(mContext, "screen_timeout", mLockScreenTimeout / 1000);
5535
5536        // We must get this work done here because the power manager will drop
5537        // the wake lock and let the system suspend once this function returns.
5538        synchronized (mLock) {
5539            mAwake = false;
5540            updateWakeGestureListenerLp();
5541            updateOrientationListenerLp();
5542            updateLockScreenTimeout();
5543        }
5544        if (mKeyguardDelegate != null) {
5545            mKeyguardDelegate.onFinishedGoingToSleep(why);
5546        }
5547    }
5548
5549    // Called on the PowerManager's Notifier thread.
5550    @Override
5551    public void startedWakingUp() {
5552        EventLog.writeEvent(70000, 1);
5553        if (DEBUG_WAKEUP) Slog.i(TAG, "Started waking up...");
5554
5555        // Since goToSleep performs these functions synchronously, we must
5556        // do the same here.  We cannot post this work to a handler because
5557        // that might cause it to become reordered with respect to what
5558        // may happen in a future call to goToSleep.
5559        synchronized (mLock) {
5560            mAwake = true;
5561
5562            updateWakeGestureListenerLp();
5563            updateOrientationListenerLp();
5564            updateLockScreenTimeout();
5565        }
5566
5567        if (mKeyguardDelegate != null) {
5568            mKeyguardDelegate.onStartedWakingUp();
5569        }
5570    }
5571
5572    // Called on the PowerManager's Notifier thread.
5573    @Override
5574    public void finishedWakingUp() {
5575        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");
5576    }
5577
5578    private void wakeUpFromPowerKey(long eventTime) {
5579        wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey, "android.policy:POWER");
5580    }
5581
5582    private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode, String reason) {
5583        final boolean theaterModeEnabled = isTheaterModeEnabled();
5584        if (!wakeInTheaterMode && theaterModeEnabled) {
5585            return false;
5586        }
5587
5588        if (theaterModeEnabled) {
5589            Settings.Global.putInt(mContext.getContentResolver(),
5590                    Settings.Global.THEATER_MODE_ON, 0);
5591        }
5592
5593        mPowerManager.wakeUp(wakeTime, reason);
5594        return true;
5595    }
5596
5597    private void finishKeyguardDrawn() {
5598        synchronized (mLock) {
5599            if (!mScreenOnEarly || mKeyguardDrawComplete) {
5600                return; // We are not awake yet or we have already informed of this event.
5601            }
5602
5603            mKeyguardDrawComplete = true;
5604            if (mKeyguardDelegate != null) {
5605                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
5606            }
5607            mWindowManagerDrawComplete = false;
5608        }
5609
5610        // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
5611        // as well as enabling the orientation change logic/sensor.
5612        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
5613                WAITING_FOR_DRAWN_TIMEOUT);
5614    }
5615
5616    // Called on the DisplayManager's DisplayPowerController thread.
5617    @Override
5618    public void screenTurnedOff() {
5619        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turned off...");
5620
5621        updateScreenOffSleepToken(true);
5622        synchronized (mLock) {
5623            mScreenOnEarly = false;
5624            mScreenOnFully = false;
5625            mKeyguardDrawComplete = false;
5626            mWindowManagerDrawComplete = false;
5627            mScreenOnListener = null;
5628            updateOrientationListenerLp();
5629
5630            if (mKeyguardDelegate != null) {
5631                mKeyguardDelegate.onScreenTurnedOff();
5632            }
5633        }
5634    }
5635
5636    // Called on the DisplayManager's DisplayPowerController thread.
5637    @Override
5638    public void screenTurningOn(final ScreenOnListener screenOnListener) {
5639        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
5640
5641        updateScreenOffSleepToken(false);
5642        synchronized (mLock) {
5643            mScreenOnEarly = true;
5644            mScreenOnFully = false;
5645            mKeyguardDrawComplete = false;
5646            mWindowManagerDrawComplete = false;
5647            mScreenOnListener = screenOnListener;
5648
5649            if (mKeyguardDelegate != null) {
5650                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
5651                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
5652                mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
5653            } else {
5654                if (DEBUG_WAKEUP) Slog.d(TAG,
5655                        "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
5656                finishKeyguardDrawn();
5657            }
5658        }
5659    }
5660
5661    // Called on the DisplayManager's DisplayPowerController thread.
5662    @Override
5663    public void screenTurnedOn() {
5664        synchronized (mLock) {
5665            if (mKeyguardDelegate != null) {
5666                mKeyguardDelegate.onScreenTurnedOn();
5667            }
5668        }
5669    }
5670
5671    private void finishWindowsDrawn() {
5672        synchronized (mLock) {
5673            if (!mScreenOnEarly || mWindowManagerDrawComplete) {
5674                return; // Screen is not turned on or we did already handle this case earlier.
5675            }
5676
5677            mWindowManagerDrawComplete = true;
5678        }
5679
5680        finishScreenTurningOn();
5681    }
5682
5683    private void finishScreenTurningOn() {
5684        synchronized (mLock) {
5685            // We have just finished drawing screen content. Since the orientation listener
5686            // gets only installed when all windows are drawn, we try to install it again.
5687            updateOrientationListenerLp();
5688        }
5689        final ScreenOnListener listener;
5690        final boolean enableScreen;
5691        synchronized (mLock) {
5692            if (DEBUG_WAKEUP) Slog.d(TAG,
5693                    "finishScreenTurningOn: mAwake=" + mAwake
5694                            + ", mScreenOnEarly=" + mScreenOnEarly
5695                            + ", mScreenOnFully=" + mScreenOnFully
5696                            + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
5697                            + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
5698
5699            if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
5700                    || (mAwake && !mKeyguardDrawComplete)) {
5701                return; // spurious or not ready yet
5702            }
5703
5704            if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
5705            listener = mScreenOnListener;
5706            mScreenOnListener = null;
5707            mScreenOnFully = true;
5708
5709            // Remember the first time we draw the keyguard so we know when we're done with
5710            // the main part of booting and can enable the screen and hide boot messages.
5711            if (!mKeyguardDrawnOnce && mAwake) {
5712                mKeyguardDrawnOnce = true;
5713                enableScreen = true;
5714                if (mBootMessageNeedsHiding) {
5715                    mBootMessageNeedsHiding = false;
5716                    hideBootMessages();
5717                }
5718            } else {
5719                enableScreen = false;
5720            }
5721        }
5722
5723        if (listener != null) {
5724            listener.onScreenOn();
5725        }
5726
5727        if (enableScreen) {
5728            try {
5729                mWindowManager.enableScreenIfNeeded();
5730            } catch (RemoteException unhandled) {
5731            }
5732        }
5733    }
5734
5735    private void handleHideBootMessage() {
5736        synchronized (mLock) {
5737            if (!mKeyguardDrawnOnce) {
5738                mBootMessageNeedsHiding = true;
5739                return; // keyguard hasn't drawn the first time yet, not done booting
5740            }
5741        }
5742
5743        if (mBootMsgDialog != null) {
5744            if (DEBUG_WAKEUP) Slog.d(TAG, "handleHideBootMessage: dismissing");
5745            mBootMsgDialog.dismiss();
5746            mBootMsgDialog = null;
5747        }
5748    }
5749
5750    @Override
5751    public boolean isScreenOn() {
5752        return mScreenOnFully;
5753    }
5754
5755    /** {@inheritDoc} */
5756    @Override
5757    public void enableKeyguard(boolean enabled) {
5758        if (mKeyguardDelegate != null) {
5759            mKeyguardDelegate.setKeyguardEnabled(enabled);
5760        }
5761    }
5762
5763    /** {@inheritDoc} */
5764    @Override
5765    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
5766        if (mKeyguardDelegate != null) {
5767            mKeyguardDelegate.verifyUnlock(callback);
5768        }
5769    }
5770
5771    private boolean isKeyguardShowingAndNotOccluded() {
5772        if (mKeyguardDelegate == null) return false;
5773        return mKeyguardDelegate.isShowing() && !mKeyguardOccluded;
5774    }
5775
5776    /** {@inheritDoc} */
5777    @Override
5778    public boolean isKeyguardLocked() {
5779        return keyguardOn();
5780    }
5781
5782    /** {@inheritDoc} */
5783    @Override
5784    public boolean isKeyguardSecure() {
5785        if (mKeyguardDelegate == null) return false;
5786        return mKeyguardDelegate.isSecure();
5787    }
5788
5789    /** {@inheritDoc} */
5790    @Override
5791    public boolean isKeyguardShowingOrOccluded() {
5792        return mKeyguardDelegate == null ? false : mKeyguardDelegate.isShowing();
5793    }
5794
5795    /** {@inheritDoc} */
5796    @Override
5797    public boolean inKeyguardRestrictedKeyInputMode() {
5798        if (mKeyguardDelegate == null) return false;
5799        return mKeyguardDelegate.isInputRestricted();
5800    }
5801
5802    @Override
5803    public void dismissKeyguardLw() {
5804        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
5805            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.dismissKeyguardLw");
5806            mHandler.post(new Runnable() {
5807                @Override
5808                public void run() {
5809                    // ask the keyguard to prompt the user to authenticate if necessary
5810                    mKeyguardDelegate.dismiss();
5811                }
5812            });
5813        }
5814    }
5815
5816    public void notifyActivityDrawnForKeyguardLw() {
5817        if (mKeyguardDelegate != null) {
5818            mHandler.post(new Runnable() {
5819                @Override
5820                public void run() {
5821                    mKeyguardDelegate.onActivityDrawn();
5822                }
5823            });
5824        }
5825    }
5826
5827    @Override
5828    public boolean isKeyguardDrawnLw() {
5829        synchronized (mLock) {
5830            return mKeyguardDrawnOnce;
5831        }
5832    }
5833
5834    @Override
5835    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
5836        if (mKeyguardDelegate != null) {
5837            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation");
5838            mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration);
5839        }
5840    }
5841
5842    void sendCloseSystemWindows() {
5843        PhoneWindow.sendCloseSystemWindows(mContext, null);
5844    }
5845
5846    void sendCloseSystemWindows(String reason) {
5847        PhoneWindow.sendCloseSystemWindows(mContext, reason);
5848    }
5849
5850    @Override
5851    public int rotationForOrientationLw(int orientation, int lastRotation) {
5852        if (false) {
5853            Slog.v(TAG, "rotationForOrientationLw(orient="
5854                        + orientation + ", last=" + lastRotation
5855                        + "); user=" + mUserRotation + " "
5856                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
5857                            ? "USER_ROTATION_LOCKED" : "")
5858                        );
5859        }
5860
5861        if (mForceDefaultOrientation) {
5862            return Surface.ROTATION_0;
5863        }
5864
5865        synchronized (mLock) {
5866            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
5867            if (sensorRotation < 0) {
5868                sensorRotation = lastRotation;
5869            }
5870
5871            final int preferredRotation;
5872            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
5873                // Ignore sensor when lid switch is open and rotation is forced.
5874                preferredRotation = mLidOpenRotation;
5875            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
5876                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
5877                // Ignore sensor when in car dock unless explicitly enabled.
5878                // This case can override the behavior of NOSENSOR, and can also
5879                // enable 180 degree rotation while docked.
5880                preferredRotation = mCarDockEnablesAccelerometer
5881                        ? sensorRotation : mCarDockRotation;
5882            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
5883                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
5884                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
5885                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
5886                // Ignore sensor when in desk dock unless explicitly enabled.
5887                // This case can override the behavior of NOSENSOR, and can also
5888                // enable 180 degree rotation while docked.
5889                preferredRotation = mDeskDockEnablesAccelerometer
5890                        ? sensorRotation : mDeskDockRotation;
5891            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
5892                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
5893                // Note that the dock orientation overrides the HDMI orientation.
5894                preferredRotation = mDemoHdmiRotation;
5895            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
5896                    && mUndockedHdmiRotation >= 0) {
5897                // Ignore sensor when plugged into HDMI and an undocked orientation has
5898                // been specified in the configuration (only for legacy devices without
5899                // full multi-display support).
5900                // Note that the dock orientation overrides the HDMI orientation.
5901                preferredRotation = mUndockedHdmiRotation;
5902            } else if (mDemoRotationLock) {
5903                // Ignore sensor when demo rotation lock is enabled.
5904                // Note that the dock orientation and HDMI rotation lock override this.
5905                preferredRotation = mDemoRotation;
5906            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
5907                // Application just wants to remain locked in the last rotation.
5908                preferredRotation = lastRotation;
5909            } else if (!mSupportAutoRotation) {
5910                // If we don't support auto-rotation then bail out here and ignore
5911                // the sensor and any rotation lock settings.
5912                preferredRotation = -1;
5913            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
5914                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
5915                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
5916                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
5917                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
5918                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
5919                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
5920                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
5921                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
5922                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
5923                // Otherwise, use sensor only if requested by the application or enabled
5924                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
5925                if (mAllowAllRotations < 0) {
5926                    // Can't read this during init() because the context doesn't
5927                    // have display metrics at that time so we cannot determine
5928                    // tablet vs. phone then.
5929                    mAllowAllRotations = mContext.getResources().getBoolean(
5930                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
5931                }
5932                if (sensorRotation != Surface.ROTATION_180
5933                        || mAllowAllRotations == 1
5934                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
5935                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
5936                    preferredRotation = sensorRotation;
5937                } else {
5938                    preferredRotation = lastRotation;
5939                }
5940            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
5941                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
5942                // Apply rotation lock.  Does not apply to NOSENSOR.
5943                // The idea is that the user rotation expresses a weak preference for the direction
5944                // of gravity and as NOSENSOR is never affected by gravity, then neither should
5945                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
5946                preferredRotation = mUserRotation;
5947            } else {
5948                // No overriding preference.
5949                // We will do exactly what the application asked us to do.
5950                preferredRotation = -1;
5951            }
5952
5953            switch (orientation) {
5954                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
5955                    // Return portrait unless overridden.
5956                    if (isAnyPortrait(preferredRotation)) {
5957                        return preferredRotation;
5958                    }
5959                    return mPortraitRotation;
5960
5961                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
5962                    // Return landscape unless overridden.
5963                    if (isLandscapeOrSeascape(preferredRotation)) {
5964                        return preferredRotation;
5965                    }
5966                    return mLandscapeRotation;
5967
5968                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
5969                    // Return reverse portrait unless overridden.
5970                    if (isAnyPortrait(preferredRotation)) {
5971                        return preferredRotation;
5972                    }
5973                    return mUpsideDownRotation;
5974
5975                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
5976                    // Return seascape unless overridden.
5977                    if (isLandscapeOrSeascape(preferredRotation)) {
5978                        return preferredRotation;
5979                    }
5980                    return mSeascapeRotation;
5981
5982                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
5983                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
5984                    // Return either landscape rotation.
5985                    if (isLandscapeOrSeascape(preferredRotation)) {
5986                        return preferredRotation;
5987                    }
5988                    if (isLandscapeOrSeascape(lastRotation)) {
5989                        return lastRotation;
5990                    }
5991                    return mLandscapeRotation;
5992
5993                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
5994                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
5995                    // Return either portrait rotation.
5996                    if (isAnyPortrait(preferredRotation)) {
5997                        return preferredRotation;
5998                    }
5999                    if (isAnyPortrait(lastRotation)) {
6000                        return lastRotation;
6001                    }
6002                    return mPortraitRotation;
6003
6004                default:
6005                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
6006                    // just return the preferred orientation we already calculated.
6007                    if (preferredRotation >= 0) {
6008                        return preferredRotation;
6009                    }
6010                    return Surface.ROTATION_0;
6011            }
6012        }
6013    }
6014
6015    @Override
6016    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
6017        switch (orientation) {
6018            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6019            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6020            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6021                return isAnyPortrait(rotation);
6022
6023            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6024            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6025            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6026                return isLandscapeOrSeascape(rotation);
6027
6028            default:
6029                return true;
6030        }
6031    }
6032
6033    @Override
6034    public void setRotationLw(int rotation) {
6035        mOrientationListener.setCurrentRotation(rotation);
6036    }
6037
6038    private boolean isLandscapeOrSeascape(int rotation) {
6039        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
6040    }
6041
6042    private boolean isAnyPortrait(int rotation) {
6043        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
6044    }
6045
6046    @Override
6047    public int getUserRotationMode() {
6048        return Settings.System.getIntForUser(mContext.getContentResolver(),
6049                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
6050                        WindowManagerPolicy.USER_ROTATION_FREE :
6051                                WindowManagerPolicy.USER_ROTATION_LOCKED;
6052    }
6053
6054    // User rotation: to be used when all else fails in assigning an orientation to the device
6055    @Override
6056    public void setUserRotationMode(int mode, int rot) {
6057        ContentResolver res = mContext.getContentResolver();
6058
6059        // mUserRotationMode and mUserRotation will be assigned by the content observer
6060        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
6061            Settings.System.putIntForUser(res,
6062                    Settings.System.USER_ROTATION,
6063                    rot,
6064                    UserHandle.USER_CURRENT);
6065            Settings.System.putIntForUser(res,
6066                    Settings.System.ACCELEROMETER_ROTATION,
6067                    0,
6068                    UserHandle.USER_CURRENT);
6069        } else {
6070            Settings.System.putIntForUser(res,
6071                    Settings.System.ACCELEROMETER_ROTATION,
6072                    1,
6073                    UserHandle.USER_CURRENT);
6074        }
6075    }
6076
6077    @Override
6078    public void setSafeMode(boolean safeMode) {
6079        mSafeMode = safeMode;
6080        performHapticFeedbackLw(null, safeMode
6081                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
6082                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
6083    }
6084
6085    static long[] getLongIntArray(Resources r, int resid) {
6086        int[] ar = r.getIntArray(resid);
6087        if (ar == null) {
6088            return null;
6089        }
6090        long[] out = new long[ar.length];
6091        for (int i=0; i<ar.length; i++) {
6092            out[i] = ar[i];
6093        }
6094        return out;
6095    }
6096
6097    /** {@inheritDoc} */
6098    @Override
6099    public void systemReady() {
6100        mKeyguardDelegate = new KeyguardServiceDelegate(mContext);
6101        mKeyguardDelegate.onSystemReady();
6102
6103        readCameraLensCoverState();
6104        updateUiMode();
6105        boolean bindKeyguardNow;
6106        synchronized (mLock) {
6107            updateOrientationListenerLp();
6108            mSystemReady = true;
6109            mHandler.post(new Runnable() {
6110                @Override
6111                public void run() {
6112                    updateSettings();
6113                }
6114            });
6115
6116            bindKeyguardNow = mDeferBindKeyguard;
6117            if (bindKeyguardNow) {
6118                // systemBooted ran but wasn't able to bind to the Keyguard, we'll do it now.
6119                mDeferBindKeyguard = false;
6120            }
6121        }
6122
6123        if (bindKeyguardNow) {
6124            mKeyguardDelegate.bindService(mContext);
6125            mKeyguardDelegate.onBootCompleted();
6126        }
6127    }
6128
6129    /** {@inheritDoc} */
6130    @Override
6131    public void systemBooted() {
6132        boolean bindKeyguardNow = false;
6133        synchronized (mLock) {
6134            // Time to bind Keyguard; take care to only bind it once, either here if ready or
6135            // in systemReady if not.
6136            if (mKeyguardDelegate != null) {
6137                bindKeyguardNow = true;
6138            } else {
6139                // Because mKeyguardDelegate is null, we know that the synchronized block in
6140                // systemReady didn't run yet and setting this will actually have an effect.
6141                mDeferBindKeyguard = true;
6142            }
6143        }
6144        if (bindKeyguardNow) {
6145            mKeyguardDelegate.bindService(mContext);
6146            mKeyguardDelegate.onBootCompleted();
6147        }
6148        synchronized (mLock) {
6149            mSystemBooted = true;
6150        }
6151        startedWakingUp();
6152        screenTurningOn(null);
6153        screenTurnedOn();
6154    }
6155
6156    ProgressDialog mBootMsgDialog = null;
6157
6158    /** {@inheritDoc} */
6159    @Override
6160    public void showBootMessage(final CharSequence msg, final boolean always) {
6161        mHandler.post(new Runnable() {
6162            @Override public void run() {
6163                if (mBootMsgDialog == null) {
6164                    int theme;
6165                    if (mContext.getPackageManager().hasSystemFeature(
6166                            PackageManager.FEATURE_WATCH)) {
6167                        theme = com.android.internal.R.style.Theme_Micro_Dialog_Alert;
6168                    } else if (mContext.getPackageManager().hasSystemFeature(
6169                            PackageManager.FEATURE_TELEVISION)) {
6170                        theme = com.android.internal.R.style.Theme_Leanback_Dialog_Alert;
6171                    } else {
6172                        theme = 0;
6173                    }
6174
6175                    mBootMsgDialog = new ProgressDialog(mContext, theme) {
6176                        // This dialog will consume all events coming in to
6177                        // it, to avoid it trying to do things too early in boot.
6178                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
6179                            return true;
6180                        }
6181                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6182                            return true;
6183                        }
6184                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
6185                            return true;
6186                        }
6187                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
6188                            return true;
6189                        }
6190                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
6191                            return true;
6192                        }
6193                        @Override public boolean dispatchPopulateAccessibilityEvent(
6194                                AccessibilityEvent event) {
6195                            return true;
6196                        }
6197                    };
6198                    if (mContext.getPackageManager().isUpgrade()) {
6199                        mBootMsgDialog.setTitle(R.string.android_upgrading_title);
6200                    } else {
6201                        mBootMsgDialog.setTitle(R.string.android_start_title);
6202                    }
6203                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
6204                    mBootMsgDialog.setIndeterminate(true);
6205                    mBootMsgDialog.getWindow().setType(
6206                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
6207                    mBootMsgDialog.getWindow().addFlags(
6208                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
6209                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
6210                    mBootMsgDialog.getWindow().setDimAmount(1);
6211                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
6212                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
6213                    mBootMsgDialog.getWindow().setAttributes(lp);
6214                    mBootMsgDialog.setCancelable(false);
6215                    mBootMsgDialog.show();
6216                }
6217                mBootMsgDialog.setMessage(msg);
6218            }
6219        });
6220    }
6221
6222    /** {@inheritDoc} */
6223    @Override
6224    public void hideBootMessages() {
6225        mHandler.sendEmptyMessage(MSG_HIDE_BOOT_MESSAGE);
6226    }
6227
6228    /** {@inheritDoc} */
6229    @Override
6230    public void userActivity() {
6231        // ***************************************
6232        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
6233        // ***************************************
6234        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
6235        // WITH ITS LOCKS HELD.
6236        //
6237        // This code must be VERY careful about the locks
6238        // it acquires.
6239        // In fact, the current code acquires way too many,
6240        // and probably has lurking deadlocks.
6241
6242        synchronized (mScreenLockTimeout) {
6243            if (mLockScreenTimerActive) {
6244                // reset the timer
6245                mHandler.removeCallbacks(mScreenLockTimeout);
6246                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6247            }
6248        }
6249    }
6250
6251    class ScreenLockTimeout implements Runnable {
6252        Bundle options;
6253
6254        @Override
6255        public void run() {
6256            synchronized (this) {
6257                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
6258                if (mKeyguardDelegate != null) {
6259                    mKeyguardDelegate.doKeyguardTimeout(options);
6260                }
6261                mLockScreenTimerActive = false;
6262                options = null;
6263            }
6264        }
6265
6266        public void setLockOptions(Bundle options) {
6267            this.options = options;
6268        }
6269    }
6270
6271    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
6272
6273    @Override
6274    public void lockNow(Bundle options) {
6275        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
6276        mHandler.removeCallbacks(mScreenLockTimeout);
6277        if (options != null) {
6278            // In case multiple calls are made to lockNow, we don't wipe out the options
6279            // until the runnable actually executes.
6280            mScreenLockTimeout.setLockOptions(options);
6281        }
6282        mHandler.post(mScreenLockTimeout);
6283    }
6284
6285    private void updateLockScreenTimeout() {
6286        synchronized (mScreenLockTimeout) {
6287            boolean enable = (mAllowLockscreenWhenOn && mAwake &&
6288                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
6289            if (mLockScreenTimerActive != enable) {
6290                if (enable) {
6291                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
6292                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6293                } else {
6294                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
6295                    mHandler.removeCallbacks(mScreenLockTimeout);
6296                }
6297                mLockScreenTimerActive = enable;
6298            }
6299        }
6300    }
6301
6302    private void updateDreamingSleepToken(boolean acquire) {
6303        if (acquire) {
6304            if (mDreamingSleepToken == null) {
6305                mDreamingSleepToken = mActivityManagerInternal.acquireSleepToken("Dream");
6306            }
6307        } else {
6308            if (mDreamingSleepToken != null) {
6309                mDreamingSleepToken.release();
6310                mDreamingSleepToken = null;
6311            }
6312        }
6313    }
6314
6315    private void updateScreenOffSleepToken(boolean acquire) {
6316        if (acquire) {
6317            if (mScreenOffSleepToken == null) {
6318                mScreenOffSleepToken = mActivityManagerInternal.acquireSleepToken("ScreenOff");
6319            }
6320        } else {
6321            if (mScreenOffSleepToken != null) {
6322                mScreenOffSleepToken.release();
6323                mScreenOffSleepToken = null;
6324            }
6325        }
6326    }
6327
6328    /** {@inheritDoc} */
6329    @Override
6330    public void enableScreenAfterBoot() {
6331        readLidState();
6332        applyLidSwitchState();
6333        updateRotation(true);
6334    }
6335
6336    private void applyLidSwitchState() {
6337        if (mLidState == LID_CLOSED && mLidControlsSleep) {
6338            mPowerManager.goToSleep(SystemClock.uptimeMillis(),
6339                    PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
6340                    PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
6341        }
6342
6343        synchronized (mLock) {
6344            updateWakeGestureListenerLp();
6345        }
6346    }
6347
6348    void updateUiMode() {
6349        if (mUiModeManager == null) {
6350            mUiModeManager = IUiModeManager.Stub.asInterface(
6351                    ServiceManager.getService(Context.UI_MODE_SERVICE));
6352        }
6353        try {
6354            mUiMode = mUiModeManager.getCurrentModeType();
6355        } catch (RemoteException e) {
6356        }
6357    }
6358
6359    void updateRotation(boolean alwaysSendConfiguration) {
6360        try {
6361            //set orientation on WindowManager
6362            mWindowManager.updateRotation(alwaysSendConfiguration, false);
6363        } catch (RemoteException e) {
6364            // Ignore
6365        }
6366    }
6367
6368    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
6369        try {
6370            //set orientation on WindowManager
6371            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
6372        } catch (RemoteException e) {
6373            // Ignore
6374        }
6375    }
6376
6377    /**
6378     * Return an Intent to launch the currently active dock app as home.  Returns
6379     * null if the standard home should be launched, which is the case if any of the following is
6380     * true:
6381     * <ul>
6382     *  <li>The device is not in either car mode or desk mode
6383     *  <li>The device is in car mode but ENABLE_CAR_DOCK_HOME_CAPTURE is false
6384     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
6385     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
6386     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
6387     * </ul>
6388     * @return A dock intent.
6389     */
6390    Intent createHomeDockIntent() {
6391        Intent intent = null;
6392
6393        // What home does is based on the mode, not the dock state.  That
6394        // is, when in car mode you should be taken to car home regardless
6395        // of whether we are actually in a car dock.
6396        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
6397            if (ENABLE_CAR_DOCK_HOME_CAPTURE) {
6398                intent = mCarDockIntent;
6399            }
6400        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
6401            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
6402                intent = mDeskDockIntent;
6403            }
6404        } else if (mUiMode == Configuration.UI_MODE_TYPE_WATCH
6405                && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6406                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK
6407                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK)) {
6408            // Always launch dock home from home when watch is docked, if it exists.
6409            intent = mDeskDockIntent;
6410        }
6411
6412        if (intent == null) {
6413            return null;
6414        }
6415
6416        ActivityInfo ai = null;
6417        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
6418                intent,
6419                PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
6420                mCurrentUserId);
6421        if (info != null) {
6422            ai = info.activityInfo;
6423        }
6424        if (ai != null
6425                && ai.metaData != null
6426                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
6427            intent = new Intent(intent);
6428            intent.setClassName(ai.packageName, ai.name);
6429            return intent;
6430        }
6431
6432        return null;
6433    }
6434
6435    void startDockOrHome(boolean fromHomeKey, boolean awakenFromDreams) {
6436        if (awakenFromDreams) {
6437            awakenDreams();
6438        }
6439
6440        Intent dock = createHomeDockIntent();
6441        if (dock != null) {
6442            try {
6443                if (fromHomeKey) {
6444                    dock.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6445                }
6446                startActivityAsUser(dock, UserHandle.CURRENT);
6447                return;
6448            } catch (ActivityNotFoundException e) {
6449            }
6450        }
6451
6452        Intent intent;
6453
6454        if (fromHomeKey) {
6455            intent = new Intent(mHomeIntent);
6456            intent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6457        } else {
6458            intent = mHomeIntent;
6459        }
6460
6461        startActivityAsUser(intent, UserHandle.CURRENT);
6462    }
6463
6464    /**
6465     * goes to the home screen
6466     * @return whether it did anything
6467     */
6468    boolean goHome() {
6469        if (!isUserSetupComplete()) {
6470            Slog.i(TAG, "Not going home because user setup is in progress.");
6471            return false;
6472        }
6473        if (false) {
6474            // This code always brings home to the front.
6475            try {
6476                ActivityManagerNative.getDefault().stopAppSwitches();
6477            } catch (RemoteException e) {
6478            }
6479            sendCloseSystemWindows();
6480            startDockOrHome(false /*fromHomeKey*/, true /* awakenFromDreams */);
6481        } else {
6482            // This code brings home to the front or, if it is already
6483            // at the front, puts the device to sleep.
6484            try {
6485                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
6486                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
6487                    Log.d(TAG, "UTS-TEST-MODE");
6488                } else {
6489                    ActivityManagerNative.getDefault().stopAppSwitches();
6490                    sendCloseSystemWindows();
6491                    Intent dock = createHomeDockIntent();
6492                    if (dock != null) {
6493                        int result = ActivityManagerNative.getDefault()
6494                                .startActivityAsUser(null, null, dock,
6495                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
6496                                        null, null, 0,
6497                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6498                                        null, null, UserHandle.USER_CURRENT);
6499                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6500                            return false;
6501                        }
6502                    }
6503                }
6504                int result = ActivityManagerNative.getDefault()
6505                        .startActivityAsUser(null, null, mHomeIntent,
6506                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
6507                                null, null, 0,
6508                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6509                                null, null, UserHandle.USER_CURRENT);
6510                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6511                    return false;
6512                }
6513            } catch (RemoteException ex) {
6514                // bummer, the activity manager, which is in this process, is dead
6515            }
6516        }
6517        return true;
6518    }
6519
6520    @Override
6521    public void setCurrentOrientationLw(int newOrientation) {
6522        synchronized (mLock) {
6523            if (newOrientation != mCurrentAppOrientation) {
6524                mCurrentAppOrientation = newOrientation;
6525                updateOrientationListenerLp();
6526            }
6527        }
6528    }
6529
6530    private void performAuditoryFeedbackForAccessibilityIfNeed() {
6531        if (!isGlobalAccessibilityGestureEnabled()) {
6532            return;
6533        }
6534        AudioManager audioManager = (AudioManager) mContext.getSystemService(
6535                Context.AUDIO_SERVICE);
6536        if (audioManager.isSilentMode()) {
6537            return;
6538        }
6539        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
6540                Settings.System.DEFAULT_NOTIFICATION_URI);
6541        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
6542        ringTone.play();
6543    }
6544
6545    private boolean isTheaterModeEnabled() {
6546        return Settings.Global.getInt(mContext.getContentResolver(),
6547                Settings.Global.THEATER_MODE_ON, 0) == 1;
6548    }
6549
6550    private boolean isGlobalAccessibilityGestureEnabled() {
6551        return Settings.Global.getInt(mContext.getContentResolver(),
6552                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
6553    }
6554
6555    @Override
6556    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
6557        if (!mVibrator.hasVibrator()) {
6558            return false;
6559        }
6560        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
6561                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
6562        if (hapticsDisabled && !always) {
6563            return false;
6564        }
6565        long[] pattern = null;
6566        switch (effectId) {
6567            case HapticFeedbackConstants.LONG_PRESS:
6568                pattern = mLongPressVibePattern;
6569                break;
6570            case HapticFeedbackConstants.VIRTUAL_KEY:
6571                pattern = mVirtualKeyVibePattern;
6572                break;
6573            case HapticFeedbackConstants.KEYBOARD_TAP:
6574                pattern = mKeyboardTapVibePattern;
6575                break;
6576            case HapticFeedbackConstants.CLOCK_TICK:
6577                pattern = mClockTickVibePattern;
6578                break;
6579            case HapticFeedbackConstants.CALENDAR_DATE:
6580                pattern = mCalendarDateVibePattern;
6581                break;
6582            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
6583                pattern = mSafeModeDisabledVibePattern;
6584                break;
6585            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
6586                pattern = mSafeModeEnabledVibePattern;
6587                break;
6588            case HapticFeedbackConstants.CONTEXT_CLICK:
6589                pattern = mContextClickVibePattern;
6590                break;
6591            default:
6592                return false;
6593        }
6594        int owningUid;
6595        String owningPackage;
6596        if (win != null) {
6597            owningUid = win.getOwningUid();
6598            owningPackage = win.getOwningPackage();
6599        } else {
6600            owningUid = android.os.Process.myUid();
6601            owningPackage = mContext.getOpPackageName();
6602        }
6603        if (pattern.length == 1) {
6604            // One-shot vibration
6605            mVibrator.vibrate(owningUid, owningPackage, pattern[0], VIBRATION_ATTRIBUTES);
6606        } else {
6607            // Pattern vibration
6608            mVibrator.vibrate(owningUid, owningPackage, pattern, -1, VIBRATION_ATTRIBUTES);
6609        }
6610        return true;
6611    }
6612
6613    @Override
6614    public void keepScreenOnStartedLw() {
6615    }
6616
6617    @Override
6618    public void keepScreenOnStoppedLw() {
6619        if (isKeyguardShowingAndNotOccluded()) {
6620            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
6621        }
6622    }
6623
6624    private int updateSystemUiVisibilityLw() {
6625        // If there is no window focused, there will be nobody to handle the events
6626        // anyway, so just hang on in whatever state we're in until things settle down.
6627        final WindowState win = mFocusedWindow != null ? mFocusedWindow
6628                : mTopFullscreenOpaqueWindowState;
6629        if (win == null) {
6630            return 0;
6631        }
6632        if ((win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 && mHideLockScreen == true) {
6633            // We are updating at a point where the keyguard has gotten
6634            // focus, but we were last in a state where the top window is
6635            // hiding it.  This is probably because the keyguard as been
6636            // shown while the top window was displayed, so we want to ignore
6637            // it here because this is just a very transient change and it
6638            // will quickly lose focus once it correctly gets hidden.
6639            return 0;
6640        }
6641
6642        int tmpVisibility = PolicyControl.getSystemUiVisibility(win, null)
6643                & ~mResettingSystemUiFlags
6644                & ~mForceClearedSystemUiFlags;
6645        if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
6646            tmpVisibility &= ~PolicyControl.adjustClearableFlags(win, View.SYSTEM_UI_CLEARABLE_FLAGS);
6647        }
6648
6649        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
6650            tmpVisibility |= StatusBarManager.DISABLE_RECENT;
6651        }
6652
6653        tmpVisibility = updateLightStatusBarLw(tmpVisibility);
6654        final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
6655        final int diff = visibility ^ mLastSystemUiFlags;
6656        final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
6657        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
6658                && mFocusedApp == win.getAppToken()) {
6659            return 0;
6660        }
6661        mLastSystemUiFlags = visibility;
6662        mLastFocusNeedsMenu = needsMenu;
6663        mFocusedApp = win.getAppToken();
6664        mHandler.post(new Runnable() {
6665                @Override
6666                public void run() {
6667                    try {
6668                        IStatusBarService statusbar = getStatusBarService();
6669                        if (statusbar != null) {
6670                            statusbar.setSystemUiVisibility(visibility, 0xffffffff, win.toString());
6671                            statusbar.topAppWindowChanged(needsMenu);
6672                        }
6673                    } catch (RemoteException e) {
6674                        // re-acquire status bar service next time it is needed.
6675                        mStatusBarService = null;
6676                    }
6677                }
6678            });
6679        return diff;
6680    }
6681
6682    private int updateLightStatusBarLw(int vis) {
6683        WindowState statusColorWin = isStatusBarKeyguard() && !mHideLockScreen
6684                ? mStatusBar
6685                : mTopFullscreenOpaqueOrDimmingWindowState;
6686
6687        if (statusColorWin != null) {
6688            if (statusColorWin == mTopFullscreenOpaqueWindowState) {
6689                // If the top fullscreen-or-dimming window is also the top fullscreen, respect
6690                // its light flag.
6691                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6692                vis |= PolicyControl.getSystemUiVisibility(statusColorWin, null)
6693                        & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6694            } else if (statusColorWin != null && statusColorWin.isDimming()) {
6695                // Otherwise if it's dimming, clear the light flag.
6696                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6697            }
6698        }
6699        return vis;
6700    }
6701
6702    private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
6703        // apply translucent bar vis flags
6704        WindowState transWin = isStatusBarKeyguard() && !mHideLockScreen
6705                ? mStatusBar
6706                : mTopFullscreenOpaqueWindowState;
6707        vis = mStatusBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
6708        vis = mNavigationBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
6709
6710        // prevent status bar interaction from clearing certain flags
6711        int type = win.getAttrs().type;
6712        boolean statusBarHasFocus = type == TYPE_STATUS_BAR;
6713        if (statusBarHasFocus && !isStatusBarKeyguard()) {
6714            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
6715                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
6716                    | View.SYSTEM_UI_FLAG_IMMERSIVE
6717                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
6718                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6719            if (mHideLockScreen) {
6720                flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
6721            }
6722            vis = (vis & ~flags) | (oldVis & flags);
6723        }
6724
6725        if (!areTranslucentBarsAllowed() && transWin != mStatusBar) {
6726            vis &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSLUCENT
6727                    | View.SYSTEM_UI_TRANSPARENT);
6728        }
6729
6730        // update status bar
6731        boolean immersiveSticky =
6732                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
6733        boolean hideStatusBarWM =
6734                mTopFullscreenOpaqueWindowState != null &&
6735                (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
6736                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
6737        boolean hideStatusBarSysui =
6738                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
6739        boolean hideNavBarSysui =
6740                (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
6741
6742        boolean transientStatusBarAllowed =
6743                mStatusBar != null && (
6744                hideStatusBarWM
6745                || (hideStatusBarSysui && immersiveSticky)
6746                || statusBarHasFocus);
6747
6748        boolean transientNavBarAllowed =
6749                mNavigationBar != null &&
6750                hideNavBarSysui && immersiveSticky;
6751
6752        final long now = SystemClock.uptimeMillis();
6753        final boolean pendingPanic = mPendingPanicGestureUptime != 0
6754                && now - mPendingPanicGestureUptime <= PANIC_GESTURE_EXPIRATION;
6755        if (pendingPanic && hideNavBarSysui && !isStatusBarKeyguard() && mKeyguardDrawComplete) {
6756            // The user performed the panic gesture recently, we're about to hide the bars,
6757            // we're no longer on the Keyguard and the screen is ready. We can now request the bars.
6758            mPendingPanicGestureUptime = 0;
6759            mStatusBarController.showTransient();
6760            mNavigationBarController.showTransient();
6761        }
6762
6763        boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
6764                && !transientStatusBarAllowed && hideStatusBarSysui;
6765        boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
6766                && !transientNavBarAllowed;
6767        if (denyTransientStatus || denyTransientNav) {
6768            // clear the clearable flags instead
6769            clearClearableFlagsLw();
6770            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
6771        }
6772
6773        final boolean immersive = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
6774        immersiveSticky = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
6775        final boolean navAllowedHidden = immersive || immersiveSticky;
6776
6777        if (hideNavBarSysui && !navAllowedHidden && windowTypeToLayerLw(win.getBaseType())
6778                > windowTypeToLayerLw(TYPE_INPUT_CONSUMER)) {
6779            // We can't hide the navbar from this window otherwise the input consumer would not get
6780            // the input events.
6781            vis = (vis & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
6782        }
6783
6784        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
6785
6786        // update navigation bar
6787        boolean oldImmersiveMode = isImmersiveMode(oldVis);
6788        boolean newImmersiveMode = isImmersiveMode(vis);
6789        if (win != null && oldImmersiveMode != newImmersiveMode) {
6790            final String pkg = win.getOwningPackage();
6791            mImmersiveModeConfirmation.immersiveModeChanged(pkg, newImmersiveMode,
6792                    isUserSetupComplete());
6793        }
6794
6795        vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
6796
6797        return vis;
6798    }
6799
6800    private void clearClearableFlagsLw() {
6801        int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
6802        if (newVal != mResettingSystemUiFlags) {
6803            mResettingSystemUiFlags = newVal;
6804            mWindowManagerFuncs.reevaluateStatusBarVisibility();
6805        }
6806    }
6807
6808    private boolean isImmersiveMode(int vis) {
6809        final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
6810        return mNavigationBar != null
6811                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
6812                && (vis & flags) != 0
6813                && canHideNavigationBar();
6814    }
6815
6816    /**
6817     * @return whether the navigation or status bar can be made translucent
6818     *
6819     * This should return true unless touch exploration is not enabled or
6820     * R.boolean.config_enableTranslucentDecor is false.
6821     */
6822    private boolean areTranslucentBarsAllowed() {
6823        return mTranslucentDecorEnabled;
6824    }
6825
6826    // Use this instead of checking config_showNavigationBar so that it can be consistently
6827    // overridden by qemu.hw.mainkeys in the emulator.
6828    @Override
6829    public boolean hasNavigationBar() {
6830        return mHasNavigationBar;
6831    }
6832
6833    @Override
6834    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
6835        mLastInputMethodWindow = ime;
6836        mLastInputMethodTargetWindow = target;
6837    }
6838
6839    @Override
6840    public int getInputMethodWindowVisibleHeightLw() {
6841        return mDockBottom - mCurBottom;
6842    }
6843
6844    @Override
6845    public void setCurrentUserLw(int newUserId) {
6846        mCurrentUserId = newUserId;
6847        if (mKeyguardDelegate != null) {
6848            mKeyguardDelegate.setCurrentUser(newUserId);
6849        }
6850        if (mStatusBarService != null) {
6851            try {
6852                mStatusBarService.setCurrentUser(newUserId);
6853            } catch (RemoteException e) {
6854                // oh well
6855            }
6856        }
6857        setLastInputMethodWindowLw(null, null);
6858    }
6859
6860    @Override
6861    public boolean canMagnifyWindow(int windowType) {
6862        switch (windowType) {
6863            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
6864            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
6865            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
6866            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
6867                return false;
6868            }
6869        }
6870        return true;
6871    }
6872
6873    @Override
6874    public boolean isTopLevelWindow(int windowType) {
6875        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
6876                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
6877            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
6878        }
6879        return true;
6880    }
6881
6882    @Override
6883    public void dump(String prefix, PrintWriter pw, String[] args) {
6884        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
6885                pw.print(" mSystemReady="); pw.print(mSystemReady);
6886                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
6887        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
6888                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
6889                pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
6890                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
6891        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
6892                || mForceClearedSystemUiFlags != 0) {
6893            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
6894                    pw.print(Integer.toHexString(mLastSystemUiFlags));
6895                    pw.print(" mResettingSystemUiFlags=0x");
6896                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
6897                    pw.print(" mForceClearedSystemUiFlags=0x");
6898                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
6899        }
6900        if (mLastFocusNeedsMenu) {
6901            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
6902                    pw.println(mLastFocusNeedsMenu);
6903        }
6904        pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
6905                pw.println(mWakeGestureEnabledSetting);
6906
6907        pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
6908        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
6909                pw.print(" mDockMode="); pw.print(mDockMode);
6910                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
6911                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
6912        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
6913                pw.print(" mUserRotation="); pw.print(mUserRotation);
6914                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
6915        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
6916        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
6917                pw.print(mCarDockEnablesAccelerometer);
6918                pw.print(" mDeskDockEnablesAccelerometer=");
6919                pw.println(mDeskDockEnablesAccelerometer);
6920        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
6921                pw.print(mLidKeyboardAccessibility);
6922                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
6923                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
6924        pw.print(prefix);
6925                pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
6926                pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
6927        pw.print(prefix);
6928                pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
6929                pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
6930        pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
6931        pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
6932        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
6933                pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
6934        pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
6935                pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
6936        pw.print(prefix); pw.print("mOrientationSensorEnabled=");
6937                pw.println(mOrientationSensorEnabled);
6938        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
6939                pw.print(","); pw.print(mOverscanScreenTop);
6940                pw.print(") "); pw.print(mOverscanScreenWidth);
6941                pw.print("x"); pw.println(mOverscanScreenHeight);
6942        if (mOverscanLeft != 0 || mOverscanTop != 0
6943                || mOverscanRight != 0 || mOverscanBottom != 0) {
6944            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
6945                    pw.print(" top="); pw.print(mOverscanTop);
6946                    pw.print(" right="); pw.print(mOverscanRight);
6947                    pw.print(" bottom="); pw.println(mOverscanBottom);
6948        }
6949        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
6950                pw.print(mRestrictedOverscanScreenLeft);
6951                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
6952                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
6953                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
6954        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
6955                pw.print(","); pw.print(mUnrestrictedScreenTop);
6956                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
6957                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
6958        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
6959                pw.print(","); pw.print(mRestrictedScreenTop);
6960                pw.print(") "); pw.print(mRestrictedScreenWidth);
6961                pw.print("x"); pw.println(mRestrictedScreenHeight);
6962        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
6963                pw.print(","); pw.print(mStableFullscreenTop);
6964                pw.print(")-("); pw.print(mStableFullscreenRight);
6965                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
6966        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
6967                pw.print(","); pw.print(mStableTop);
6968                pw.print(")-("); pw.print(mStableRight);
6969                pw.print(","); pw.print(mStableBottom); pw.println(")");
6970        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
6971                pw.print(","); pw.print(mSystemTop);
6972                pw.print(")-("); pw.print(mSystemRight);
6973                pw.print(","); pw.print(mSystemBottom); pw.println(")");
6974        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
6975                pw.print(","); pw.print(mCurTop);
6976                pw.print(")-("); pw.print(mCurRight);
6977                pw.print(","); pw.print(mCurBottom); pw.println(")");
6978        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
6979                pw.print(","); pw.print(mContentTop);
6980                pw.print(")-("); pw.print(mContentRight);
6981                pw.print(","); pw.print(mContentBottom); pw.println(")");
6982        pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
6983                pw.print(","); pw.print(mVoiceContentTop);
6984                pw.print(")-("); pw.print(mVoiceContentRight);
6985                pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
6986        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
6987                pw.print(","); pw.print(mDockTop);
6988                pw.print(")-("); pw.print(mDockRight);
6989                pw.print(","); pw.print(mDockBottom); pw.println(")");
6990        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
6991                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
6992        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
6993                pw.print(" mShowingDream="); pw.print(mShowingDream);
6994                pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
6995                pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
6996        if (mLastInputMethodWindow != null) {
6997            pw.print(prefix); pw.print("mLastInputMethodWindow=");
6998                    pw.println(mLastInputMethodWindow);
6999        }
7000        if (mLastInputMethodTargetWindow != null) {
7001            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
7002                    pw.println(mLastInputMethodTargetWindow);
7003        }
7004        if (mStatusBar != null) {
7005            pw.print(prefix); pw.print("mStatusBar=");
7006                    pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
7007                    pw.println(isStatusBarKeyguard());
7008        }
7009        if (mNavigationBar != null) {
7010            pw.print(prefix); pw.print("mNavigationBar=");
7011                    pw.println(mNavigationBar);
7012        }
7013        if (mFocusedWindow != null) {
7014            pw.print(prefix); pw.print("mFocusedWindow=");
7015                    pw.println(mFocusedWindow);
7016        }
7017        if (mFocusedApp != null) {
7018            pw.print(prefix); pw.print("mFocusedApp=");
7019                    pw.println(mFocusedApp);
7020        }
7021        if (mWinDismissingKeyguard != null) {
7022            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
7023                    pw.println(mWinDismissingKeyguard);
7024        }
7025        if (mTopFullscreenOpaqueWindowState != null) {
7026            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
7027                    pw.println(mTopFullscreenOpaqueWindowState);
7028        }
7029        if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
7030            pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
7031                    pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
7032        }
7033        if (mForcingShowNavBar) {
7034            pw.print(prefix); pw.print("mForcingShowNavBar=");
7035                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
7036                    pw.println(mForcingShowNavBarLayer);
7037        }
7038        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
7039                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
7040        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
7041                pw.print(" mForceStatusBarFromKeyguard=");
7042                pw.println(mForceStatusBarFromKeyguard);
7043        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
7044                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
7045                pw.print(" mHomePressed="); pw.println(mHomePressed);
7046        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
7047                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
7048                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
7049        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
7050                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
7051                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
7052        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
7053                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
7054        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
7055                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
7056        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
7057                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
7058        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
7059
7060        mGlobalKeyManager.dump(prefix, pw);
7061        mStatusBarController.dump(pw, prefix);
7062        mNavigationBarController.dump(pw, prefix);
7063        PolicyControl.dump(prefix, pw);
7064
7065        if (mWakeGestureListener != null) {
7066            mWakeGestureListener.dump(pw, prefix);
7067        }
7068        if (mOrientationListener != null) {
7069            mOrientationListener.dump(pw, prefix);
7070        }
7071        if (mBurnInProtectionHelper != null) {
7072            mBurnInProtectionHelper.dump(prefix, pw);
7073        }
7074    }
7075}
7076