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