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