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