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