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