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