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