PhoneWindowManager.java revision 602c68e4ffa1d17b2032c0e05c5d4d4dc8795adf
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
2155            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
2156                // Assumes it's safe to show starting windows of launched apps while
2157                // the keyguard is being hidden. This is okay because starting windows never show
2158                // secret information.
2159                if (mKeyguardHidden) {
2160                    windowFlags |= FLAG_SHOW_WHEN_LOCKED;
2161                }
2162            }
2163
2164            // Force the window flags: this is a fake window, so it is not really
2165            // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
2166            // flag because we do know that the next window will take input
2167            // focus, so we want to get the IME window up on top of us right away.
2168            win.setFlags(
2169                windowFlags|
2170                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2171                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2172                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
2173                windowFlags|
2174                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2175                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2176                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
2177
2178            win.setDefaultIcon(icon);
2179            win.setDefaultLogo(logo);
2180
2181            win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
2182                    WindowManager.LayoutParams.MATCH_PARENT);
2183
2184            final WindowManager.LayoutParams params = win.getAttributes();
2185            params.token = appToken;
2186            params.packageName = packageName;
2187            params.windowAnimations = win.getWindowStyle().getResourceId(
2188                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2189            params.privateFlags |=
2190                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED;
2191            params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
2192
2193            if (!compatInfo.supportsScreen()) {
2194                params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
2195            }
2196
2197            params.setTitle("Starting " + packageName);
2198
2199            wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
2200            view = win.getDecorView();
2201
2202            if (win.isFloating()) {
2203                // Whoops, there is no way to display an animation/preview
2204                // of such a thing!  After all that work...  let's skip it.
2205                // (Note that we must do this here because it is in
2206                // getDecorView() where the theme is evaluated...  maybe
2207                // we should peek the floating attribute from the theme
2208                // earlier.)
2209                return null;
2210            }
2211
2212            if (DEBUG_STARTING_WINDOW) Slog.d(
2213                TAG, "Adding starting window for " + packageName
2214                + " / " + appToken + ": "
2215                + (view.getParent() != null ? view : null));
2216
2217            wm.addView(view, params);
2218
2219            // Only return the view if it was successfully added to the
2220            // window manager... which we can tell by it having a parent.
2221            return view.getParent() != null ? view : null;
2222        } catch (WindowManager.BadTokenException e) {
2223            // ignore
2224            Log.w(TAG, appToken + " already running, starting window not displayed. " +
2225                    e.getMessage());
2226        } catch (RuntimeException e) {
2227            // don't crash if something else bad happens, for example a
2228            // failure loading resources because we are loading from an app
2229            // on external storage that has been unmounted.
2230            Log.w(TAG, appToken + " failed creating starting window", e);
2231        } finally {
2232            if (view != null && view.getParent() == null) {
2233                Log.w(TAG, "view not successfully added to wm, removing view");
2234                wm.removeViewImmediate(view);
2235            }
2236        }
2237
2238        return null;
2239    }
2240
2241    /** {@inheritDoc} */
2242    @Override
2243    public void removeStartingWindow(IBinder appToken, View window) {
2244        if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Removing starting window for " + appToken + ": "
2245                + window + " Callers=" + Debug.getCallers(4));
2246
2247        if (window != null) {
2248            WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
2249            wm.removeView(window);
2250        }
2251    }
2252
2253    /**
2254     * Preflight adding a window to the system.
2255     *
2256     * Currently enforces that three window types are singletons:
2257     * <ul>
2258     * <li>STATUS_BAR_TYPE</li>
2259     * <li>KEYGUARD_TYPE</li>
2260     * </ul>
2261     *
2262     * @param win The window to be added
2263     * @param attrs Information about the window to be added
2264     *
2265     * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons,
2266     * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
2267     */
2268    @Override
2269    public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
2270        switch (attrs.type) {
2271            case TYPE_STATUS_BAR:
2272                mContext.enforceCallingOrSelfPermission(
2273                        android.Manifest.permission.STATUS_BAR_SERVICE,
2274                        "PhoneWindowManager");
2275                if (mStatusBar != null) {
2276                    if (mStatusBar.isAlive()) {
2277                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2278                    }
2279                }
2280                mStatusBar = win;
2281                mStatusBarController.setWindow(win);
2282                break;
2283            case TYPE_NAVIGATION_BAR:
2284                mContext.enforceCallingOrSelfPermission(
2285                        android.Manifest.permission.STATUS_BAR_SERVICE,
2286                        "PhoneWindowManager");
2287                if (mNavigationBar != null) {
2288                    if (mNavigationBar.isAlive()) {
2289                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2290                    }
2291                }
2292                mNavigationBar = win;
2293                mNavigationBarController.setWindow(win);
2294                if (DEBUG_LAYOUT) Slog.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
2295                break;
2296            case TYPE_NAVIGATION_BAR_PANEL:
2297            case TYPE_STATUS_BAR_PANEL:
2298            case TYPE_STATUS_BAR_SUB_PANEL:
2299            case TYPE_VOICE_INTERACTION_STARTING:
2300                mContext.enforceCallingOrSelfPermission(
2301                        android.Manifest.permission.STATUS_BAR_SERVICE,
2302                        "PhoneWindowManager");
2303                break;
2304            case TYPE_KEYGUARD_SCRIM:
2305                if (mKeyguardScrim != null) {
2306                    return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2307                }
2308                mKeyguardScrim = win;
2309                break;
2310        }
2311        return WindowManagerGlobal.ADD_OKAY;
2312    }
2313
2314    /** {@inheritDoc} */
2315    @Override
2316    public void removeWindowLw(WindowState win) {
2317        if (mStatusBar == win) {
2318            mStatusBar = null;
2319            mStatusBarController.setWindow(null);
2320            mKeyguardDelegate.showScrim();
2321        } else if (mKeyguardScrim == win) {
2322            Log.v(TAG, "Removing keyguard scrim");
2323            mKeyguardScrim = null;
2324        } if (mNavigationBar == win) {
2325            mNavigationBar = null;
2326            mNavigationBarController.setWindow(null);
2327        }
2328    }
2329
2330    static final boolean PRINT_ANIM = false;
2331
2332    /** {@inheritDoc} */
2333    @Override
2334    public int selectAnimationLw(WindowState win, int transit) {
2335        if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
2336              + ": transit=" + transit);
2337        if (win == mStatusBar) {
2338            boolean isKeyguard = (win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
2339            if (transit == TRANSIT_EXIT
2340                    || transit == TRANSIT_HIDE) {
2341                return isKeyguard ? -1 : R.anim.dock_top_exit;
2342            } else if (transit == TRANSIT_ENTER
2343                    || transit == TRANSIT_SHOW) {
2344                return isKeyguard ? -1 : R.anim.dock_top_enter;
2345            }
2346        } else if (win == mNavigationBar) {
2347            // This can be on either the bottom or the right.
2348            if (mNavigationBarOnBottom) {
2349                if (transit == TRANSIT_EXIT
2350                        || transit == TRANSIT_HIDE) {
2351                    return R.anim.dock_bottom_exit;
2352                } else if (transit == TRANSIT_ENTER
2353                        || transit == TRANSIT_SHOW) {
2354                    return R.anim.dock_bottom_enter;
2355                }
2356            } else {
2357                if (transit == TRANSIT_EXIT
2358                        || transit == TRANSIT_HIDE) {
2359                    return R.anim.dock_right_exit;
2360                } else if (transit == TRANSIT_ENTER
2361                        || transit == TRANSIT_SHOW) {
2362                    return R.anim.dock_right_enter;
2363                }
2364            }
2365        }
2366
2367        if (transit == TRANSIT_PREVIEW_DONE) {
2368            if (win.hasAppShownWindows()) {
2369                if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
2370                return com.android.internal.R.anim.app_starting_exit;
2371            }
2372        } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
2373                && transit == TRANSIT_ENTER) {
2374            // Special case: we are animating in a dream, while the keyguard
2375            // is shown.  We don't want an animation on the dream, because
2376            // we need it shown immediately with the keyguard animating away
2377            // to reveal it.
2378            return -1;
2379        }
2380
2381        return 0;
2382    }
2383
2384    @Override
2385    public void selectRotationAnimationLw(int anim[]) {
2386        if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
2387                + mTopFullscreenOpaqueWindowState + " rotationAnimation="
2388                + (mTopFullscreenOpaqueWindowState == null ?
2389                        "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
2390        if (mTopFullscreenOpaqueWindowState != null && mTopIsFullscreen) {
2391            switch (mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation) {
2392                case ROTATION_ANIMATION_CROSSFADE:
2393                    anim[0] = R.anim.rotation_animation_xfade_exit;
2394                    anim[1] = R.anim.rotation_animation_enter;
2395                    break;
2396                case ROTATION_ANIMATION_JUMPCUT:
2397                    anim[0] = R.anim.rotation_animation_jump_exit;
2398                    anim[1] = R.anim.rotation_animation_enter;
2399                    break;
2400                case ROTATION_ANIMATION_ROTATE:
2401                default:
2402                    anim[0] = anim[1] = 0;
2403                    break;
2404            }
2405        } else {
2406            anim[0] = anim[1] = 0;
2407        }
2408    }
2409
2410    @Override
2411    public boolean validateRotationAnimationLw(int exitAnimId, int enterAnimId,
2412            boolean forceDefault) {
2413        switch (exitAnimId) {
2414            case R.anim.rotation_animation_xfade_exit:
2415            case R.anim.rotation_animation_jump_exit:
2416                // These are the only cases that matter.
2417                if (forceDefault) {
2418                    return false;
2419                }
2420                int anim[] = new int[2];
2421                selectRotationAnimationLw(anim);
2422                return (exitAnimId == anim[0] && enterAnimId == anim[1]);
2423            default:
2424                return true;
2425        }
2426    }
2427
2428    @Override
2429    public Animation createForceHideEnterAnimation(boolean onWallpaper,
2430            boolean goingToNotificationShade) {
2431        if (goingToNotificationShade) {
2432            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_behind_enter_fade_in);
2433        }
2434
2435        AnimationSet set = (AnimationSet) AnimationUtils.loadAnimation(mContext, onWallpaper ?
2436                    R.anim.lock_screen_behind_enter_wallpaper :
2437                    R.anim.lock_screen_behind_enter);
2438
2439        // TODO: Use XML interpolators when we have log interpolators available in XML.
2440        final List<Animation> animations = set.getAnimations();
2441        for (int i = animations.size() - 1; i >= 0; --i) {
2442            animations.get(i).setInterpolator(mLogDecelerateInterpolator);
2443        }
2444
2445        return set;
2446    }
2447
2448
2449    @Override
2450    public Animation createForceHideWallpaperExitAnimation(boolean goingToNotificationShade) {
2451        if (goingToNotificationShade) {
2452            return null;
2453        } else {
2454            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_wallpaper_exit);
2455        }
2456    }
2457
2458    private static void awakenDreams() {
2459        IDreamManager dreamManager = getDreamManager();
2460        if (dreamManager != null) {
2461            try {
2462                dreamManager.awaken();
2463            } catch (RemoteException e) {
2464                // fine, stay asleep then
2465            }
2466        }
2467    }
2468
2469    static IDreamManager getDreamManager() {
2470        return IDreamManager.Stub.asInterface(
2471                ServiceManager.checkService(DreamService.DREAM_SERVICE));
2472    }
2473
2474    TelecomManager getTelecommService() {
2475        return (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2476    }
2477
2478    static IAudioService getAudioService() {
2479        IAudioService audioService = IAudioService.Stub.asInterface(
2480                ServiceManager.checkService(Context.AUDIO_SERVICE));
2481        if (audioService == null) {
2482            Log.w(TAG, "Unable to find IAudioService interface.");
2483        }
2484        return audioService;
2485    }
2486
2487    boolean keyguardOn() {
2488        return isKeyguardShowingAndNotOccluded() || inKeyguardRestrictedKeyInputMode();
2489    }
2490
2491    private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
2492            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
2493            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
2494        };
2495
2496    /** {@inheritDoc} */
2497    @Override
2498    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
2499        final boolean keyguardOn = keyguardOn();
2500        final int keyCode = event.getKeyCode();
2501        final int repeatCount = event.getRepeatCount();
2502        final int metaState = event.getMetaState();
2503        final int flags = event.getFlags();
2504        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
2505        final boolean canceled = event.isCanceled();
2506
2507        if (DEBUG_INPUT) {
2508            Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
2509                    + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
2510                    + " canceled=" + canceled);
2511        }
2512
2513        // If we think we might have a volume down & power key chord on the way
2514        // but we're not sure, then tell the dispatcher to wait a little while and
2515        // try again later before dispatching.
2516        if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
2517            if (mScreenshotChordVolumeDownKeyTriggered && !mScreenshotChordPowerKeyTriggered) {
2518                final long now = SystemClock.uptimeMillis();
2519                final long timeoutTime = mScreenshotChordVolumeDownKeyTime
2520                        + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
2521                if (now < timeoutTime) {
2522                    return timeoutTime - now;
2523                }
2524            }
2525            if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
2526                    && mScreenshotChordVolumeDownKeyConsumed) {
2527                if (!down) {
2528                    mScreenshotChordVolumeDownKeyConsumed = false;
2529                }
2530                return -1;
2531            }
2532        }
2533
2534        // Cancel any pending meta actions if we see any other keys being pressed between the down
2535        // of the meta key and its corresponding up.
2536        if (mPendingMetaAction && !KeyEvent.isMetaKey(keyCode)) {
2537            mPendingMetaAction = false;
2538        }
2539
2540        // First we always handle the home key here, so applications
2541        // can never break it, although if keyguard is on, we do let
2542        // it handle it, because that gives us the correct 5 second
2543        // timeout.
2544        if (keyCode == KeyEvent.KEYCODE_HOME) {
2545
2546            // If we have released the home key, and didn't do anything else
2547            // while it was pressed, then it is time to go home!
2548            if (!down) {
2549                cancelPreloadRecentApps();
2550
2551                mHomePressed = false;
2552                if (mHomeConsumed) {
2553                    mHomeConsumed = false;
2554                    return -1;
2555                }
2556
2557                if (canceled) {
2558                    Log.i(TAG, "Ignoring HOME; event canceled.");
2559                    return -1;
2560                }
2561
2562                // If an incoming call is ringing, HOME is totally disabled.
2563                // (The user is already on the InCallUI at this point,
2564                // and his ONLY options are to answer or reject the call.)
2565                TelecomManager telecomManager = getTelecommService();
2566                if (telecomManager != null && telecomManager.isRinging()) {
2567                    Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
2568                    return -1;
2569                }
2570
2571                // Delay handling home if a double-tap is possible.
2572                if (mDoubleTapOnHomeBehavior != DOUBLE_TAP_HOME_NOTHING) {
2573                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable); // just in case
2574                    mHomeDoubleTapPending = true;
2575                    mHandler.postDelayed(mHomeDoubleTapTimeoutRunnable,
2576                            ViewConfiguration.getDoubleTapTimeout());
2577                    return -1;
2578                }
2579
2580                handleShortPressOnHome();
2581                return -1;
2582            }
2583
2584            // If a system window has focus, then it doesn't make sense
2585            // right now to interact with applications.
2586            WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
2587            if (attrs != null) {
2588                final int type = attrs.type;
2589                if (type == WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM
2590                        || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
2591                        || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
2592                    // the "app" is keyguard, so give it the key
2593                    return 0;
2594                }
2595                final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
2596                for (int i=0; i<typeCount; i++) {
2597                    if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
2598                        // don't do anything, but also don't pass it to the app
2599                        return -1;
2600                    }
2601                }
2602            }
2603
2604            // Remember that home is pressed and handle special actions.
2605            if (repeatCount == 0) {
2606                mHomePressed = true;
2607                if (mHomeDoubleTapPending) {
2608                    mHomeDoubleTapPending = false;
2609                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable);
2610                    handleDoubleTapOnHome();
2611                } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI
2612                        || mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
2613                    preloadRecentApps();
2614                }
2615            } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
2616                if (!keyguardOn) {
2617                    handleLongPressOnHome();
2618                }
2619            }
2620            return -1;
2621        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
2622            // Hijack modified menu keys for debugging features
2623            final int chordBug = KeyEvent.META_SHIFT_ON;
2624
2625            if (down && repeatCount == 0) {
2626                if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
2627                    Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
2628                    mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
2629                            null, null, null, 0, null, null);
2630                    return -1;
2631                } else if (SHOW_PROCESSES_ON_ALT_MENU &&
2632                        (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
2633                    Intent service = new Intent();
2634                    service.setClassName(mContext, "com.android.server.LoadAverageService");
2635                    ContentResolver res = mContext.getContentResolver();
2636                    boolean shown = Settings.Global.getInt(
2637                            res, Settings.Global.SHOW_PROCESSES, 0) != 0;
2638                    if (!shown) {
2639                        mContext.startService(service);
2640                    } else {
2641                        mContext.stopService(service);
2642                    }
2643                    Settings.Global.putInt(
2644                            res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
2645                    return -1;
2646                }
2647            }
2648        } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
2649            if (down) {
2650                if (repeatCount == 0) {
2651                    mSearchKeyShortcutPending = true;
2652                    mConsumeSearchKeyUp = false;
2653                }
2654            } else {
2655                mSearchKeyShortcutPending = false;
2656                if (mConsumeSearchKeyUp) {
2657                    mConsumeSearchKeyUp = false;
2658                    return -1;
2659                }
2660            }
2661            return 0;
2662        } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
2663            if (!keyguardOn) {
2664                if (down && repeatCount == 0) {
2665                    preloadRecentApps();
2666                } else if (!down) {
2667                    toggleRecentApps();
2668                }
2669            }
2670            return -1;
2671        } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
2672            if (down) {
2673                if (repeatCount == 0) {
2674                    mAssistKeyLongPressed = false;
2675                } else if (repeatCount == 1) {
2676                    mAssistKeyLongPressed = true;
2677                    if (!keyguardOn) {
2678                         launchAssistLongPressAction();
2679                    }
2680                }
2681            } else {
2682                if (mAssistKeyLongPressed) {
2683                    mAssistKeyLongPressed = false;
2684                } else {
2685                    if (!keyguardOn) {
2686                        launchAssistAction();
2687                    }
2688                }
2689            }
2690            return -1;
2691        } else if (keyCode == KeyEvent.KEYCODE_VOICE_ASSIST) {
2692            if (!down) {
2693                Intent voiceIntent;
2694                if (!keyguardOn) {
2695                    voiceIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2696                } else {
2697                    voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
2698                    voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, true);
2699                }
2700                startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
2701            }
2702        } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
2703            if (down && repeatCount == 0) {
2704                mHandler.post(mScreenshotRunnable);
2705            }
2706            return -1;
2707        } else if (keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP
2708                || keyCode == KeyEvent.KEYCODE_BRIGHTNESS_DOWN) {
2709            if (down) {
2710                int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1;
2711
2712                // Disable autobrightness if it's on
2713                int auto = Settings.System.getIntForUser(
2714                        mContext.getContentResolver(),
2715                        Settings.System.SCREEN_BRIGHTNESS_MODE,
2716                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
2717                        UserHandle.USER_CURRENT_OR_SELF);
2718                if (auto != 0) {
2719                    Settings.System.putIntForUser(mContext.getContentResolver(),
2720                            Settings.System.SCREEN_BRIGHTNESS_MODE,
2721                            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
2722                            UserHandle.USER_CURRENT_OR_SELF);
2723                }
2724
2725                int min = mPowerManager.getMinimumScreenBrightnessSetting();
2726                int max = mPowerManager.getMaximumScreenBrightnessSetting();
2727                int step = (max - min + BRIGHTNESS_STEPS - 1) / BRIGHTNESS_STEPS * direction;
2728                int brightness = Settings.System.getIntForUser(mContext.getContentResolver(),
2729                        Settings.System.SCREEN_BRIGHTNESS,
2730                        mPowerManager.getDefaultScreenBrightnessSetting(),
2731                        UserHandle.USER_CURRENT_OR_SELF);
2732                brightness += step;
2733                // Make sure we don't go beyond the limits.
2734                brightness = Math.min(max, brightness);
2735                brightness = Math.max(min, brightness);
2736
2737                Settings.System.putIntForUser(mContext.getContentResolver(),
2738                        Settings.System.SCREEN_BRIGHTNESS, brightness,
2739                        UserHandle.USER_CURRENT_OR_SELF);
2740                startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG),
2741                        UserHandle.CURRENT_OR_SELF);
2742            }
2743            return -1;
2744        } else if (KeyEvent.isMetaKey(keyCode)) {
2745            if (down) {
2746                mPendingMetaAction = true;
2747            } else if (mPendingMetaAction) {
2748                launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD);
2749            }
2750            return -1;
2751        }
2752
2753        // Shortcuts are invoked through Search+key, so intercept those here
2754        // Any printing key that is chorded with Search should be consumed
2755        // even if no shortcut was invoked.  This prevents text from being
2756        // inadvertently inserted when using a keyboard that has built-in macro
2757        // shortcut keys (that emit Search+x) and some of them are not registered.
2758        if (mSearchKeyShortcutPending) {
2759            final KeyCharacterMap kcm = event.getKeyCharacterMap();
2760            if (kcm.isPrintingKey(keyCode)) {
2761                mConsumeSearchKeyUp = true;
2762                mSearchKeyShortcutPending = false;
2763                if (down && repeatCount == 0 && !keyguardOn) {
2764                    Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
2765                    if (shortcutIntent != null) {
2766                        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2767                        try {
2768                            startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
2769                        } catch (ActivityNotFoundException ex) {
2770                            Slog.w(TAG, "Dropping shortcut key combination because "
2771                                    + "the activity to which it is registered was not found: "
2772                                    + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
2773                        }
2774                    } else {
2775                        Slog.i(TAG, "Dropping unregistered shortcut key combination: "
2776                                + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
2777                    }
2778                }
2779                return -1;
2780            }
2781        }
2782
2783        // Invoke shortcuts using Meta.
2784        if (down && repeatCount == 0 && !keyguardOn
2785                && (metaState & KeyEvent.META_META_ON) != 0) {
2786            final KeyCharacterMap kcm = event.getKeyCharacterMap();
2787            if (kcm.isPrintingKey(keyCode)) {
2788                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
2789                        metaState & ~(KeyEvent.META_META_ON
2790                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
2791                if (shortcutIntent != null) {
2792                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2793                    try {
2794                        startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
2795                    } catch (ActivityNotFoundException ex) {
2796                        Slog.w(TAG, "Dropping shortcut key combination because "
2797                                + "the activity to which it is registered was not found: "
2798                                + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
2799                    }
2800                    return -1;
2801                }
2802            }
2803        }
2804
2805        // Handle application launch keys.
2806        if (down && repeatCount == 0 && !keyguardOn) {
2807            String category = sApplicationLaunchKeyCategories.get(keyCode);
2808            if (category != null) {
2809                Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
2810                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2811                try {
2812                    startActivityAsUser(intent, UserHandle.CURRENT);
2813                } catch (ActivityNotFoundException ex) {
2814                    Slog.w(TAG, "Dropping application launch key because "
2815                            + "the activity to which it is registered was not found: "
2816                            + "keyCode=" + keyCode + ", category=" + category, ex);
2817                }
2818                return -1;
2819            }
2820        }
2821
2822        // Display task switcher for ALT-TAB.
2823        if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
2824            if (mRecentAppsHeldModifiers == 0 && !keyguardOn) {
2825                final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
2826                if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)) {
2827                    mRecentAppsHeldModifiers = shiftlessModifiers;
2828                    showRecentApps(true);
2829                    return -1;
2830                }
2831            }
2832        } else if (!down && mRecentAppsHeldModifiers != 0
2833                && (metaState & mRecentAppsHeldModifiers) == 0) {
2834            mRecentAppsHeldModifiers = 0;
2835            hideRecentApps(true, false);
2836        }
2837
2838        // Handle keyboard language switching.
2839        if (down && repeatCount == 0
2840                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
2841                        || (keyCode == KeyEvent.KEYCODE_SPACE
2842                                && (metaState & KeyEvent.META_CTRL_MASK) != 0))) {
2843            int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1;
2844            mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction);
2845            return -1;
2846        }
2847        if (mLanguageSwitchKeyPressed && !down
2848                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
2849                        || keyCode == KeyEvent.KEYCODE_SPACE)) {
2850            mLanguageSwitchKeyPressed = false;
2851            return -1;
2852        }
2853
2854        if (isValidGlobalKey(keyCode)
2855                && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
2856            return -1;
2857        }
2858
2859        // Reserve all the META modifier combos for system behavior
2860        if ((metaState & KeyEvent.META_META_ON) != 0) {
2861            return -1;
2862        }
2863
2864        // Let the application handle the key.
2865        return 0;
2866    }
2867
2868    /** {@inheritDoc} */
2869    @Override
2870    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
2871        // Note: This method is only called if the initial down was unhandled.
2872        if (DEBUG_INPUT) {
2873            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
2874                    + ", flags=" + event.getFlags()
2875                    + ", keyCode=" + event.getKeyCode()
2876                    + ", scanCode=" + event.getScanCode()
2877                    + ", metaState=" + event.getMetaState()
2878                    + ", repeatCount=" + event.getRepeatCount()
2879                    + ", policyFlags=" + policyFlags);
2880        }
2881
2882        KeyEvent fallbackEvent = null;
2883        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
2884            final KeyCharacterMap kcm = event.getKeyCharacterMap();
2885            final int keyCode = event.getKeyCode();
2886            final int metaState = event.getMetaState();
2887            final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
2888                    && event.getRepeatCount() == 0;
2889
2890            // Check for fallback actions specified by the key character map.
2891            final FallbackAction fallbackAction;
2892            if (initialDown) {
2893                fallbackAction = kcm.getFallbackAction(keyCode, metaState);
2894            } else {
2895                fallbackAction = mFallbackActions.get(keyCode);
2896            }
2897
2898            if (fallbackAction != null) {
2899                if (DEBUG_INPUT) {
2900                    Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
2901                            + " metaState=" + Integer.toHexString(fallbackAction.metaState));
2902                }
2903
2904                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
2905                fallbackEvent = KeyEvent.obtain(
2906                        event.getDownTime(), event.getEventTime(),
2907                        event.getAction(), fallbackAction.keyCode,
2908                        event.getRepeatCount(), fallbackAction.metaState,
2909                        event.getDeviceId(), event.getScanCode(),
2910                        flags, event.getSource(), null);
2911
2912                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
2913                    fallbackEvent.recycle();
2914                    fallbackEvent = null;
2915                }
2916
2917                if (initialDown) {
2918                    mFallbackActions.put(keyCode, fallbackAction);
2919                } else if (event.getAction() == KeyEvent.ACTION_UP) {
2920                    mFallbackActions.remove(keyCode);
2921                    fallbackAction.recycle();
2922                }
2923            }
2924        }
2925
2926        if (DEBUG_INPUT) {
2927            if (fallbackEvent == null) {
2928                Slog.d(TAG, "No fallback.");
2929            } else {
2930                Slog.d(TAG, "Performing fallback: " + fallbackEvent);
2931            }
2932        }
2933        return fallbackEvent;
2934    }
2935
2936    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
2937        int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
2938        if ((actions & ACTION_PASS_TO_USER) != 0) {
2939            long delayMillis = interceptKeyBeforeDispatching(
2940                    win, fallbackEvent, policyFlags);
2941            if (delayMillis == 0) {
2942                return true;
2943            }
2944        }
2945        return false;
2946    }
2947
2948    private void launchAssistLongPressAction() {
2949        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
2950        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
2951
2952        // launch the search activity
2953        Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
2954        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2955        try {
2956            // TODO: This only stops the factory-installed search manager.
2957            // Need to formalize an API to handle others
2958            SearchManager searchManager = getSearchManager();
2959            if (searchManager != null) {
2960                searchManager.stopSearch();
2961            }
2962            startActivityAsUser(intent, UserHandle.CURRENT);
2963        } catch (ActivityNotFoundException e) {
2964            Slog.w(TAG, "No activity to handle assist long press action.", e);
2965        }
2966    }
2967
2968    private void launchAssistAction() {
2969        launchAssistAction(null);
2970    }
2971
2972    private void launchAssistAction(String hint) {
2973        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
2974        Intent intent = ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
2975                .getAssistIntent(mContext, true, UserHandle.USER_CURRENT);
2976        if (intent != null) {
2977            if (hint != null) {
2978                intent.putExtra(hint, true);
2979            }
2980            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
2981                    | Intent.FLAG_ACTIVITY_SINGLE_TOP
2982                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2983            try {
2984                startActivityAsUser(intent, UserHandle.CURRENT);
2985            } catch (ActivityNotFoundException e) {
2986                Slog.w(TAG, "No activity to handle assist action.", e);
2987            }
2988        }
2989    }
2990
2991    private void startActivityAsUser(Intent intent, UserHandle handle) {
2992        if (isUserSetupComplete()) {
2993            mContext.startActivityAsUser(intent, handle);
2994        } else {
2995            Slog.i(TAG, "Not starting activity because user setup is in progress: " + intent);
2996        }
2997    }
2998
2999    private SearchManager getSearchManager() {
3000        if (mSearchManager == null) {
3001            mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
3002        }
3003        return mSearchManager;
3004    }
3005
3006    private void preloadRecentApps() {
3007        mPreloadedRecentApps = true;
3008        try {
3009            IStatusBarService statusbar = getStatusBarService();
3010            if (statusbar != null) {
3011                statusbar.preloadRecentApps();
3012            }
3013        } catch (RemoteException e) {
3014            Slog.e(TAG, "RemoteException when preloading recent apps", e);
3015            // re-acquire status bar service next time it is needed.
3016            mStatusBarService = null;
3017        }
3018    }
3019
3020    private void cancelPreloadRecentApps() {
3021        if (mPreloadedRecentApps) {
3022            mPreloadedRecentApps = false;
3023            try {
3024                IStatusBarService statusbar = getStatusBarService();
3025                if (statusbar != null) {
3026                    statusbar.cancelPreloadRecentApps();
3027                }
3028            } catch (RemoteException e) {
3029                Slog.e(TAG, "RemoteException when cancelling recent apps preload", e);
3030                // re-acquire status bar service next time it is needed.
3031                mStatusBarService = null;
3032            }
3033        }
3034    }
3035
3036    private void toggleRecentApps() {
3037        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3038        try {
3039            IStatusBarService statusbar = getStatusBarService();
3040            if (statusbar != null) {
3041                statusbar.toggleRecentApps();
3042            }
3043        } catch (RemoteException e) {
3044            Slog.e(TAG, "RemoteException when toggling recent apps", e);
3045            // re-acquire status bar service next time it is needed.
3046            mStatusBarService = null;
3047        }
3048    }
3049
3050    @Override
3051    public void showRecentApps() {
3052        mHandler.removeMessages(MSG_DISPATCH_SHOW_RECENTS);
3053        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_RECENTS);
3054    }
3055
3056    private void showRecentApps(boolean triggeredFromAltTab) {
3057        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3058        try {
3059            IStatusBarService statusbar = getStatusBarService();
3060            if (statusbar != null) {
3061                statusbar.showRecentApps(triggeredFromAltTab);
3062            }
3063        } catch (RemoteException e) {
3064            Slog.e(TAG, "RemoteException when showing recent apps", e);
3065            // re-acquire status bar service next time it is needed.
3066            mStatusBarService = null;
3067        }
3068    }
3069
3070    private void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHome) {
3071        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3072        try {
3073            IStatusBarService statusbar = getStatusBarService();
3074            if (statusbar != null) {
3075                statusbar.hideRecentApps(triggeredFromAltTab, triggeredFromHome);
3076            }
3077        } catch (RemoteException e) {
3078            Slog.e(TAG, "RemoteException when closing recent apps", e);
3079            // re-acquire status bar service next time it is needed.
3080            mStatusBarService = null;
3081        }
3082    }
3083
3084    void launchHomeFromHotKey() {
3085        launchHomeFromHotKey(true /* awakenFromDreams */, true /*respectKeyguard*/);
3086    }
3087
3088    /**
3089     * A home key -> launch home action was detected.  Take the appropriate action
3090     * given the situation with the keyguard.
3091     */
3092    void launchHomeFromHotKey(final boolean awakenFromDreams, final boolean respectKeyguard) {
3093        if (respectKeyguard) {
3094            if (isKeyguardShowingAndNotOccluded()) {
3095                // don't launch home if keyguard showing
3096                return;
3097            }
3098
3099            if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
3100                // when in keyguard restricted mode, must first verify unlock
3101                // before launching home
3102                mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
3103                    @Override
3104                    public void onKeyguardExitResult(boolean success) {
3105                        if (success) {
3106                            try {
3107                                ActivityManagerNative.getDefault().stopAppSwitches();
3108                            } catch (RemoteException e) {
3109                            }
3110                            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3111                            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3112                        }
3113                    }
3114                });
3115                return;
3116            }
3117        }
3118
3119        // no keyguard stuff to worry about, just launch home!
3120        try {
3121            ActivityManagerNative.getDefault().stopAppSwitches();
3122        } catch (RemoteException e) {
3123        }
3124        if (mRecentsVisible) {
3125            // Hide Recents and notify it to launch Home
3126            if (awakenFromDreams) {
3127                awakenDreams();
3128            }
3129            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3130            hideRecentApps(false, true);
3131        } else {
3132            // Otherwise, just launch Home
3133            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3134            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3135        }
3136    }
3137
3138    private final Runnable mClearHideNavigationFlag = new Runnable() {
3139        @Override
3140        public void run() {
3141            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3142                // Clear flags.
3143                mForceClearedSystemUiFlags &=
3144                        ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3145            }
3146            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3147        }
3148    };
3149
3150    /**
3151     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
3152     * to determine when the nav bar should be shown and prevent applications from
3153     * receiving those touches.
3154     */
3155    final class HideNavInputEventReceiver extends InputEventReceiver {
3156        public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
3157            super(inputChannel, looper);
3158        }
3159
3160        @Override
3161        public void onInputEvent(InputEvent event) {
3162            boolean handled = false;
3163            try {
3164                if (event instanceof MotionEvent
3165                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3166                    final MotionEvent motionEvent = (MotionEvent)event;
3167                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
3168                        // When the user taps down, we re-show the nav bar.
3169                        boolean changed = false;
3170                        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3171                            // Any user activity always causes us to show the
3172                            // navigation controls, if they had been hidden.
3173                            // We also clear the low profile and only content
3174                            // flags so that tapping on the screen will atomically
3175                            // restore all currently hidden screen decorations.
3176                            int newVal = mResettingSystemUiFlags |
3177                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3178                                    View.SYSTEM_UI_FLAG_LOW_PROFILE |
3179                                    View.SYSTEM_UI_FLAG_FULLSCREEN;
3180                            if (mResettingSystemUiFlags != newVal) {
3181                                mResettingSystemUiFlags = newVal;
3182                                changed = true;
3183                            }
3184                            // We don't allow the system's nav bar to be hidden
3185                            // again for 1 second, to prevent applications from
3186                            // spamming us and keeping it from being shown.
3187                            newVal = mForceClearedSystemUiFlags |
3188                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3189                            if (mForceClearedSystemUiFlags != newVal) {
3190                                mForceClearedSystemUiFlags = newVal;
3191                                changed = true;
3192                                mHandler.postDelayed(mClearHideNavigationFlag, 1000);
3193                            }
3194                        }
3195                        if (changed) {
3196                            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3197                        }
3198                    }
3199                }
3200            } finally {
3201                finishInputEvent(event, handled);
3202            }
3203        }
3204    }
3205    final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
3206            new InputEventReceiver.Factory() {
3207        @Override
3208        public InputEventReceiver createInputEventReceiver(
3209                InputChannel inputChannel, Looper looper) {
3210            return new HideNavInputEventReceiver(inputChannel, looper);
3211        }
3212    };
3213
3214    @Override
3215    public int adjustSystemUiVisibilityLw(int visibility) {
3216        mStatusBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3217        mNavigationBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3218        mRecentsVisible = (visibility & View.RECENT_APPS_VISIBLE) > 0;
3219
3220        // Reset any bits in mForceClearingStatusBarVisibility that
3221        // are now clear.
3222        mResettingSystemUiFlags &= visibility;
3223        // Clear any bits in the new visibility that are currently being
3224        // force cleared, before reporting it.
3225        return visibility & ~mResettingSystemUiFlags
3226                & ~mForceClearedSystemUiFlags;
3227    }
3228
3229    @Override
3230    public void getInsetHintLw(WindowManager.LayoutParams attrs, Rect outContentInsets,
3231            Rect outStableInsets) {
3232        final int fl = PolicyControl.getWindowFlags(null, attrs);
3233        final int sysuiVis = PolicyControl.getSystemUiVisibility(null, attrs);
3234        final int systemUiVisibility = (sysuiVis | attrs.subtreeSystemUiVisibility);
3235
3236        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3237                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3238            int availRight, availBottom;
3239            if (canHideNavigationBar() &&
3240                    (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
3241                availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3242                availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3243            } else {
3244                availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
3245                availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3246            }
3247            if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3248                if ((fl & FLAG_FULLSCREEN) != 0) {
3249                    outContentInsets.set(mStableFullscreenLeft, mStableFullscreenTop,
3250                            availRight - mStableFullscreenRight,
3251                            availBottom - mStableFullscreenBottom);
3252                } else {
3253                    outContentInsets.set(mStableLeft, mStableTop,
3254                            availRight - mStableRight, availBottom - mStableBottom);
3255                }
3256            } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
3257                outContentInsets.setEmpty();
3258            } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
3259                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
3260                outContentInsets.set(mCurLeft, mCurTop,
3261                        availRight - mCurRight, availBottom - mCurBottom);
3262            } else {
3263                outContentInsets.set(mCurLeft, mCurTop,
3264                        availRight - mCurRight, availBottom - mCurBottom);
3265            }
3266
3267            outStableInsets.set(mStableLeft, mStableTop,
3268                    availRight - mStableRight, availBottom - mStableBottom);
3269            return;
3270        }
3271        outContentInsets.setEmpty();
3272        outStableInsets.setEmpty();
3273    }
3274
3275    /** {@inheritDoc} */
3276    @Override
3277    public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
3278                              int displayRotation) {
3279        final int overscanLeft, overscanTop, overscanRight, overscanBottom;
3280        if (isDefaultDisplay) {
3281            switch (displayRotation) {
3282                case Surface.ROTATION_90:
3283                    overscanLeft = mOverscanTop;
3284                    overscanTop = mOverscanRight;
3285                    overscanRight = mOverscanBottom;
3286                    overscanBottom = mOverscanLeft;
3287                    break;
3288                case Surface.ROTATION_180:
3289                    overscanLeft = mOverscanRight;
3290                    overscanTop = mOverscanBottom;
3291                    overscanRight = mOverscanLeft;
3292                    overscanBottom = mOverscanTop;
3293                    break;
3294                case Surface.ROTATION_270:
3295                    overscanLeft = mOverscanBottom;
3296                    overscanTop = mOverscanLeft;
3297                    overscanRight = mOverscanTop;
3298                    overscanBottom = mOverscanRight;
3299                    break;
3300                default:
3301                    overscanLeft = mOverscanLeft;
3302                    overscanTop = mOverscanTop;
3303                    overscanRight = mOverscanRight;
3304                    overscanBottom = mOverscanBottom;
3305                    break;
3306            }
3307        } else {
3308            overscanLeft = 0;
3309            overscanTop = 0;
3310            overscanRight = 0;
3311            overscanBottom = 0;
3312        }
3313        mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
3314        mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
3315        mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
3316        mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
3317        mSystemLeft = 0;
3318        mSystemTop = 0;
3319        mSystemRight = displayWidth;
3320        mSystemBottom = displayHeight;
3321        mUnrestrictedScreenLeft = overscanLeft;
3322        mUnrestrictedScreenTop = overscanTop;
3323        mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
3324        mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
3325        mRestrictedScreenLeft = mUnrestrictedScreenLeft;
3326        mRestrictedScreenTop = mUnrestrictedScreenTop;
3327        mRestrictedScreenWidth = mSystemGestures.screenWidth = mUnrestrictedScreenWidth;
3328        mRestrictedScreenHeight = mSystemGestures.screenHeight = mUnrestrictedScreenHeight;
3329        mDockLeft = mContentLeft = mVoiceContentLeft = mStableLeft = mStableFullscreenLeft
3330                = mCurLeft = mUnrestrictedScreenLeft;
3331        mDockTop = mContentTop = mVoiceContentTop = mStableTop = mStableFullscreenTop
3332                = mCurTop = mUnrestrictedScreenTop;
3333        mDockRight = mContentRight = mVoiceContentRight = mStableRight = mStableFullscreenRight
3334                = mCurRight = displayWidth - overscanRight;
3335        mDockBottom = mContentBottom = mVoiceContentBottom = mStableBottom = mStableFullscreenBottom
3336                = mCurBottom = displayHeight - overscanBottom;
3337        mDockLayer = 0x10000000;
3338        mStatusBarLayer = -1;
3339
3340        // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
3341        final Rect pf = mTmpParentFrame;
3342        final Rect df = mTmpDisplayFrame;
3343        final Rect of = mTmpOverscanFrame;
3344        final Rect vf = mTmpVisibleFrame;
3345        final Rect dcf = mTmpDecorFrame;
3346        pf.left = df.left = of.left = vf.left = mDockLeft;
3347        pf.top = df.top = of.top = vf.top = mDockTop;
3348        pf.right = df.right = of.right = vf.right = mDockRight;
3349        pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
3350        dcf.setEmpty();  // Decor frame N/A for system bars.
3351
3352        if (isDefaultDisplay) {
3353            // For purposes of putting out fake window up to steal focus, we will
3354            // drive nav being hidden only by whether it is requested.
3355            final int sysui = mLastSystemUiFlags;
3356            boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
3357            boolean navTranslucent = (sysui
3358                    & (View.NAVIGATION_BAR_TRANSLUCENT | View.SYSTEM_UI_TRANSPARENT)) != 0;
3359            boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
3360            boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
3361            boolean navAllowedHidden = immersive || immersiveSticky;
3362            navTranslucent &= !immersiveSticky;  // transient trumps translucent
3363            boolean isKeyguardShowing = isStatusBarKeyguard() && !mHideLockScreen;
3364            if (!isKeyguardShowing) {
3365                navTranslucent &= areTranslucentBarsAllowed();
3366            }
3367
3368            // When the navigation bar isn't visible, we put up a fake
3369            // input window to catch all touch events.  This way we can
3370            // detect when the user presses anywhere to bring back the nav
3371            // bar and ensure the application doesn't see the event.
3372            if (navVisible || navAllowedHidden) {
3373                if (mHideNavFakeWindow != null) {
3374                    mHideNavFakeWindow.dismiss();
3375                    mHideNavFakeWindow = null;
3376                }
3377            } else if (mHideNavFakeWindow == null) {
3378                mHideNavFakeWindow = mWindowManagerFuncs.addFakeWindow(
3379                        mHandler.getLooper(), mHideNavInputEventReceiverFactory,
3380                        "hidden nav", WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER, 0,
3381                        0, false, false, true);
3382            }
3383
3384            // For purposes of positioning and showing the nav bar, if we have
3385            // decided that it can't be hidden (because of the screen aspect ratio),
3386            // then take that into account.
3387            navVisible |= !canHideNavigationBar();
3388
3389            boolean updateSysUiVisibility = false;
3390            if (mNavigationBar != null) {
3391                boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
3392                // Force the navigation bar to its appropriate place and
3393                // size.  We need to do this directly, instead of relying on
3394                // it to bubble up from the nav bar, because this needs to
3395                // change atomically with screen rotations.
3396                mNavigationBarOnBottom = (!mNavigationBarCanMove || displayWidth < displayHeight);
3397                if (mNavigationBarOnBottom) {
3398                    // It's a system nav bar or a portrait screen; nav bar goes on bottom.
3399                    int top = displayHeight - overscanBottom
3400                            - mNavigationBarHeightForRotation[displayRotation];
3401                    mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
3402                    mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
3403                    if (transientNavBarShowing) {
3404                        mNavigationBarController.setBarShowingLw(true);
3405                    } else if (navVisible) {
3406                        mNavigationBarController.setBarShowingLw(true);
3407                        mDockBottom = mTmpNavigationFrame.top;
3408                        mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
3409                        mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
3410                    } else {
3411                        // We currently want to hide the navigation UI.
3412                        mNavigationBarController.setBarShowingLw(false);
3413                    }
3414                    if (navVisible && !navTranslucent && !navAllowedHidden
3415                            && !mNavigationBar.isAnimatingLw()
3416                            && !mNavigationBarController.wasRecentlyTranslucent()) {
3417                        // If the opaque nav bar is currently requested to be visible,
3418                        // and not in the process of animating on or off, then
3419                        // we can tell the app that it is covered by it.
3420                        mSystemBottom = mTmpNavigationFrame.top;
3421                    }
3422                } else {
3423                    // Landscape screen; nav bar goes to the right.
3424                    int left = displayWidth - overscanRight
3425                            - mNavigationBarWidthForRotation[displayRotation];
3426                    mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
3427                    mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
3428                    if (transientNavBarShowing) {
3429                        mNavigationBarController.setBarShowingLw(true);
3430                    } else if (navVisible) {
3431                        mNavigationBarController.setBarShowingLw(true);
3432                        mDockRight = mTmpNavigationFrame.left;
3433                        mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
3434                        mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
3435                    } else {
3436                        // We currently want to hide the navigation UI.
3437                        mNavigationBarController.setBarShowingLw(false);
3438                    }
3439                    if (navVisible && !navTranslucent && !mNavigationBar.isAnimatingLw()
3440                            && !mNavigationBarController.wasRecentlyTranslucent()) {
3441                        // If the nav bar is currently requested to be visible,
3442                        // and not in the process of animating on or off, then
3443                        // we can tell the app that it is covered by it.
3444                        mSystemRight = mTmpNavigationFrame.left;
3445                    }
3446                }
3447                // Make sure the content and current rectangles are updated to
3448                // account for the restrictions from the navigation bar.
3449                mContentTop = mVoiceContentTop = mCurTop = mDockTop;
3450                mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
3451                mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
3452                mContentRight = mVoiceContentRight = mCurRight = mDockRight;
3453                mStatusBarLayer = mNavigationBar.getSurfaceLayer();
3454                // And compute the final frame.
3455                mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
3456                        mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf,
3457                        mTmpNavigationFrame);
3458                if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
3459                if (mNavigationBarController.checkHiddenLw()) {
3460                    updateSysUiVisibility = true;
3461                }
3462            }
3463            if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
3464                    mDockLeft, mDockTop, mDockRight, mDockBottom));
3465
3466            // decide where the status bar goes ahead of time
3467            if (mStatusBar != null) {
3468                // apply any navigation bar insets
3469                pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3470                pf.top = df.top = of.top = mUnrestrictedScreenTop;
3471                pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
3472                pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
3473                        + mUnrestrictedScreenTop;
3474                vf.left = mStableLeft;
3475                vf.top = mStableTop;
3476                vf.right = mStableRight;
3477                vf.bottom = mStableBottom;
3478
3479                mStatusBarLayer = mStatusBar.getSurfaceLayer();
3480
3481                // Let the status bar determine its size.
3482                mStatusBar.computeFrameLw(pf, df, vf, vf, vf, dcf, vf);
3483
3484                // For layout, the status bar is always at the top with our fixed height.
3485                mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
3486
3487                boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
3488                boolean statusBarTranslucent = (sysui
3489                        & (View.STATUS_BAR_TRANSLUCENT | View.SYSTEM_UI_TRANSPARENT)) != 0;
3490                if (!isKeyguardShowing) {
3491                    statusBarTranslucent &= areTranslucentBarsAllowed();
3492                }
3493
3494                // If the status bar is hidden, we don't want to cause
3495                // windows behind it to scroll.
3496                if (mStatusBar.isVisibleLw() && !statusBarTransient) {
3497                    // Status bar may go away, so the screen area it occupies
3498                    // is available to apps but just covering them when the
3499                    // status bar is visible.
3500                    mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
3501
3502                    mContentTop = mVoiceContentTop = mCurTop = mDockTop;
3503                    mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
3504                    mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
3505                    mContentRight = mVoiceContentRight = mCurRight = mDockRight;
3506
3507                    if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
3508                        String.format(
3509                            "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
3510                            mDockLeft, mDockTop, mDockRight, mDockBottom,
3511                            mContentLeft, mContentTop, mContentRight, mContentBottom,
3512                            mCurLeft, mCurTop, mCurRight, mCurBottom));
3513                }
3514                if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
3515                        && !statusBarTransient && !statusBarTranslucent
3516                        && !mStatusBarController.wasRecentlyTranslucent()) {
3517                    // If the opaque status bar is currently requested to be visible,
3518                    // and not in the process of animating on or off, then
3519                    // we can tell the app that it is covered by it.
3520                    mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
3521                }
3522                if (mStatusBarController.checkHiddenLw()) {
3523                    updateSysUiVisibility = true;
3524                }
3525            }
3526            if (updateSysUiVisibility) {
3527                updateSystemUiVisibilityLw();
3528            }
3529        }
3530    }
3531
3532    /** {@inheritDoc} */
3533    @Override
3534    public int getSystemDecorLayerLw() {
3535        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
3536            return mStatusBar.getSurfaceLayer();
3537        }
3538
3539        if (mNavigationBar != null && mNavigationBar.isVisibleLw()) {
3540            return mNavigationBar.getSurfaceLayer();
3541        }
3542
3543        return 0;
3544    }
3545
3546    @Override
3547    public void getContentRectLw(Rect r) {
3548        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
3549    }
3550
3551    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
3552            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
3553        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
3554            // Here's a special case: if this attached window is a panel that is
3555            // above the dock window, and the window it is attached to is below
3556            // the dock window, then the frames we computed for the window it is
3557            // attached to can not be used because the dock is effectively part
3558            // of the underlying window and the attached window is floating on top
3559            // of the whole thing.  So, we ignore the attached window and explicitly
3560            // compute the frames that would be appropriate without the dock.
3561            df.left = of.left = cf.left = vf.left = mDockLeft;
3562            df.top = of.top = cf.top = vf.top = mDockTop;
3563            df.right = of.right = cf.right = vf.right = mDockRight;
3564            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
3565        } else {
3566            // The effective display frame of the attached window depends on
3567            // whether it is taking care of insetting its content.  If not,
3568            // we need to use the parent's content frame so that the entire
3569            // window is positioned within that content.  Otherwise we can use
3570            // the overscan frame and let the attached window take care of
3571            // positioning its content appropriately.
3572            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3573                // Set the content frame of the attached window to the parent's decor frame
3574                // (same as content frame when IME isn't present) if specifically requested by
3575                // setting {@link WindowManager.LayoutParams#FLAG_LAYOUT_ATTACHED_IN_DECOR} flag.
3576                // Otherwise, use the overscan frame.
3577                cf.set((fl & FLAG_LAYOUT_ATTACHED_IN_DECOR) != 0
3578                        ? attached.getContentFrameLw() : attached.getOverscanFrameLw());
3579            } else {
3580                // If the window is resizing, then we want to base the content
3581                // frame on our attached content frame to resize...  however,
3582                // things can be tricky if the attached window is NOT in resize
3583                // mode, in which case its content frame will be larger.
3584                // Ungh.  So to deal with that, make sure the content frame
3585                // we end up using is not covering the IM dock.
3586                cf.set(attached.getContentFrameLw());
3587                if (attached.isVoiceInteraction()) {
3588                    if (cf.left < mVoiceContentLeft) cf.left = mVoiceContentLeft;
3589                    if (cf.top < mVoiceContentTop) cf.top = mVoiceContentTop;
3590                    if (cf.right > mVoiceContentRight) cf.right = mVoiceContentRight;
3591                    if (cf.bottom > mVoiceContentBottom) cf.bottom = mVoiceContentBottom;
3592                } else if (attached.getSurfaceLayer() < mDockLayer) {
3593                    if (cf.left < mContentLeft) cf.left = mContentLeft;
3594                    if (cf.top < mContentTop) cf.top = mContentTop;
3595                    if (cf.right > mContentRight) cf.right = mContentRight;
3596                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
3597                }
3598            }
3599            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
3600            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
3601            vf.set(attached.getVisibleFrameLw());
3602        }
3603        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
3604        // window should be positioned relative to its parent or the entire
3605        // screen.
3606        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
3607                ? attached.getFrameLw() : df);
3608    }
3609
3610    private void applyStableConstraints(int sysui, int fl, Rect r) {
3611        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3612            // If app is requesting a stable layout, don't let the
3613            // content insets go below the stable values.
3614            if ((fl & FLAG_FULLSCREEN) != 0) {
3615                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
3616                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
3617                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
3618                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
3619            } else {
3620                if (r.left < mStableLeft) r.left = mStableLeft;
3621                if (r.top < mStableTop) r.top = mStableTop;
3622                if (r.right > mStableRight) r.right = mStableRight;
3623                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
3624            }
3625        }
3626    }
3627
3628    /** {@inheritDoc} */
3629    @Override
3630    public void layoutWindowLw(WindowState win, WindowState attached) {
3631        // we've already done the status bar
3632        final WindowManager.LayoutParams attrs = win.getAttrs();
3633        if ((win == mStatusBar && (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) == 0) ||
3634                win == mNavigationBar) {
3635            return;
3636        }
3637        final boolean isDefaultDisplay = win.isDefaultDisplay();
3638        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
3639                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
3640        if (needsToOffsetInputMethodTarget) {
3641            if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
3642            offsetInputMethodWindowLw(mLastInputMethodWindow);
3643        }
3644
3645        final int fl = PolicyControl.getWindowFlags(win, attrs);
3646        final int sim = attrs.softInputMode;
3647        final int sysUiFl = PolicyControl.getSystemUiVisibility(win, null);
3648
3649        final Rect pf = mTmpParentFrame;
3650        final Rect df = mTmpDisplayFrame;
3651        final Rect of = mTmpOverscanFrame;
3652        final Rect cf = mTmpContentFrame;
3653        final Rect vf = mTmpVisibleFrame;
3654        final Rect dcf = mTmpDecorFrame;
3655        final Rect sf = mTmpStableFrame;
3656        dcf.setEmpty();
3657
3658        final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
3659                && mNavigationBar != null && mNavigationBar.isVisibleLw());
3660
3661        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
3662
3663        if (isDefaultDisplay) {
3664            sf.set(mStableLeft, mStableTop, mStableRight, mStableBottom);
3665        } else {
3666            sf.set(mOverscanLeft, mOverscanTop, mOverscanRight, mOverscanBottom);
3667        }
3668
3669        if (!isDefaultDisplay) {
3670            if (attached != null) {
3671                // If this window is attached to another, our display
3672                // frame is the same as the one we are attached to.
3673                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
3674            } else {
3675                // Give the window full screen.
3676                pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3677                pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3678                pf.right = df.right = of.right = cf.right
3679                        = mOverscanScreenLeft + mOverscanScreenWidth;
3680                pf.bottom = df.bottom = of.bottom = cf.bottom
3681                        = mOverscanScreenTop + mOverscanScreenHeight;
3682            }
3683        } else if (attrs.type == TYPE_INPUT_METHOD) {
3684            pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
3685            pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
3686            pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
3687            // IM dock windows layout below the nav bar...
3688            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3689            // ...with content insets above the nav bar
3690            cf.bottom = vf.bottom = mStableBottom;
3691            // IM dock windows always go to the bottom of the screen.
3692            attrs.gravity = Gravity.BOTTOM;
3693            mDockLayer = win.getSurfaceLayer();
3694        } else if (attrs.type == TYPE_VOICE_INTERACTION) {
3695            pf.left = df.left = of.left = cf.left = vf.left = mUnrestrictedScreenLeft;
3696            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3697            pf.right = df.right = of.right = cf.right = vf.right = mUnrestrictedScreenLeft
3698                    + mUnrestrictedScreenWidth;
3699            pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
3700                    + mUnrestrictedScreenHeight;
3701            cf.bottom = vf.bottom = mStableBottom;
3702            cf.top = vf.top = mStableTop;
3703        } else if (win == mStatusBar && (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
3704            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3705            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3706            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
3707            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight + mUnrestrictedScreenTop;
3708            cf.left = vf.left = mStableLeft;
3709            cf.top = vf.top = mStableTop;
3710            cf.right = vf.right = mStableRight;
3711            vf.bottom = mStableBottom;
3712            cf.bottom = mContentBottom;
3713        } else {
3714
3715            // Default policy decor for the default display
3716            dcf.left = mSystemLeft;
3717            dcf.top = mSystemTop;
3718            dcf.right = mSystemRight;
3719            dcf.bottom = mSystemBottom;
3720            final boolean inheritTranslucentDecor = (attrs.privateFlags
3721                    & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
3722            final boolean isAppWindow =
3723                    attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
3724                    attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
3725            final boolean topAtRest =
3726                    win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
3727            if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
3728                if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
3729                        && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
3730                        && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0
3731                        && (fl & WindowManager.LayoutParams.
3732                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
3733                    // Ensure policy decor includes status bar
3734                    dcf.top = mStableTop;
3735                }
3736                if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
3737                        && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
3738                        && (fl & WindowManager.LayoutParams.
3739                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
3740                    // Ensure policy decor includes navigation bar
3741                    dcf.bottom = mStableBottom;
3742                    dcf.right = mStableRight;
3743                }
3744            }
3745
3746            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3747                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3748                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
3749                            + "): IN_SCREEN, INSET_DECOR");
3750                // This is the case for a normal activity window: we want it
3751                // to cover all of the screen space, and it can take care of
3752                // moving its contents to account for screen decorations that
3753                // intrude into that space.
3754                if (attached != null) {
3755                    // If this window is attached to another, our display
3756                    // frame is the same as the one we are attached to.
3757                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
3758                } else {
3759                    if (attrs.type == TYPE_STATUS_BAR_PANEL
3760                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
3761                        // Status bar panels are the only windows who can go on top of
3762                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
3763                        // permission, so they have the same privileges as the status
3764                        // bar itself.
3765                        //
3766                        // However, they should still dodge the navigation bar if it exists.
3767
3768                        pf.left = df.left = of.left = hasNavBar
3769                                ? mDockLeft : mUnrestrictedScreenLeft;
3770                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
3771                        pf.right = df.right = of.right = hasNavBar
3772                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
3773                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3774                        pf.bottom = df.bottom = of.bottom = hasNavBar
3775                                ? mRestrictedScreenTop+mRestrictedScreenHeight
3776                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3777
3778                        if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3779                                        "Laying out status bar window: (%d,%d - %d,%d)",
3780                                        pf.left, pf.top, pf.right, pf.bottom));
3781                    } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
3782                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3783                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3784                        // Asking to layout into the overscan region, so give it that pure
3785                        // unrestricted area.
3786                        pf.left = df.left = of.left = mOverscanScreenLeft;
3787                        pf.top = df.top = of.top = mOverscanScreenTop;
3788                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
3789                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
3790                                + mOverscanScreenHeight;
3791                    } else if (canHideNavigationBar()
3792                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
3793                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3794                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3795                        // Asking for layout as if the nav bar is hidden, lets the
3796                        // application extend into the unrestricted overscan screen area.  We
3797                        // only do this for application windows to ensure no window that
3798                        // can be above the nav bar can do this.
3799                        pf.left = df.left = mOverscanScreenLeft;
3800                        pf.top = df.top = mOverscanScreenTop;
3801                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
3802                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
3803                        // We need to tell the app about where the frame inside the overscan
3804                        // is, so it can inset its content by that amount -- it didn't ask
3805                        // to actually extend itself into the overscan region.
3806                        of.left = mUnrestrictedScreenLeft;
3807                        of.top = mUnrestrictedScreenTop;
3808                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3809                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3810                    } else {
3811                        pf.left = df.left = mRestrictedOverscanScreenLeft;
3812                        pf.top = df.top = mRestrictedOverscanScreenTop;
3813                        pf.right = df.right = mRestrictedOverscanScreenLeft
3814                                + mRestrictedOverscanScreenWidth;
3815                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
3816                                + mRestrictedOverscanScreenHeight;
3817                        // We need to tell the app about where the frame inside the overscan
3818                        // is, so it can inset its content by that amount -- it didn't ask
3819                        // to actually extend itself into the overscan region.
3820                        of.left = mUnrestrictedScreenLeft;
3821                        of.top = mUnrestrictedScreenTop;
3822                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3823                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3824                    }
3825
3826                    if ((fl & FLAG_FULLSCREEN) == 0) {
3827                        if (win.isVoiceInteraction()) {
3828                            cf.left = mVoiceContentLeft;
3829                            cf.top = mVoiceContentTop;
3830                            cf.right = mVoiceContentRight;
3831                            cf.bottom = mVoiceContentBottom;
3832                        } else {
3833                            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3834                                cf.left = mDockLeft;
3835                                cf.top = mDockTop;
3836                                cf.right = mDockRight;
3837                                cf.bottom = mDockBottom;
3838                            } else {
3839                                cf.left = mContentLeft;
3840                                cf.top = mContentTop;
3841                                cf.right = mContentRight;
3842                                cf.bottom = mContentBottom;
3843                            }
3844                        }
3845                    } else {
3846                        // Full screen windows are always given a layout that is as if the
3847                        // status bar and other transient decors are gone.  This is to avoid
3848                        // bad states when moving from a window that is not hding the
3849                        // status bar to one that is.
3850                        cf.left = mRestrictedScreenLeft;
3851                        cf.top = mRestrictedScreenTop;
3852                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
3853                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3854                    }
3855                    applyStableConstraints(sysUiFl, fl, cf);
3856                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3857                        vf.left = mCurLeft;
3858                        vf.top = mCurTop;
3859                        vf.right = mCurRight;
3860                        vf.bottom = mCurBottom;
3861                    } else {
3862                        vf.set(cf);
3863                    }
3864                }
3865            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
3866                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
3867                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
3868                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
3869                        "): IN_SCREEN");
3870                // A window that has requested to fill the entire screen just
3871                // gets everything, period.
3872                if (attrs.type == TYPE_STATUS_BAR_PANEL
3873                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
3874                    pf.left = df.left = of.left = cf.left = hasNavBar
3875                            ? mDockLeft : mUnrestrictedScreenLeft;
3876                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
3877                    pf.right = df.right = of.right = cf.right = hasNavBar
3878                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
3879                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3880                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
3881                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
3882                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3883                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3884                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
3885                                    pf.left, pf.top, pf.right, pf.bottom));
3886                } else if (attrs.type == TYPE_NAVIGATION_BAR
3887                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
3888                    // The navigation bar has Real Ultimate Power.
3889                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3890                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
3891                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
3892                            + mUnrestrictedScreenWidth;
3893                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
3894                            + mUnrestrictedScreenHeight;
3895                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3896                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
3897                                    pf.left, pf.top, pf.right, pf.bottom));
3898                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
3899                                || attrs.type == TYPE_BOOT_PROGRESS)
3900                        && ((fl & FLAG_FULLSCREEN) != 0)) {
3901                    // Fullscreen secure system overlays get what they ask for.
3902                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3903                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3904                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
3905                            + mOverscanScreenWidth;
3906                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
3907                            + mOverscanScreenHeight;
3908                } else if (attrs.type == TYPE_BOOT_PROGRESS) {
3909                    // Boot progress screen always covers entire display.
3910                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3911                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3912                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
3913                            + mOverscanScreenWidth;
3914                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
3915                            + mOverscanScreenHeight;
3916                } else if (attrs.type == TYPE_WALLPAPER) {
3917                    // The wallpaper also has Real Ultimate Power, but we want to tell
3918                    // it about the overscan area.
3919                    pf.left = df.left = mOverscanScreenLeft;
3920                    pf.top = df.top = mOverscanScreenTop;
3921                    pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
3922                    pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
3923                    of.left = cf.left = mUnrestrictedScreenLeft;
3924                    of.top = cf.top = mUnrestrictedScreenTop;
3925                    of.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3926                    of.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3927                } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
3928                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3929                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3930                    // Asking to layout into the overscan region, so give it that pure
3931                    // unrestricted area.
3932                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3933                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3934                    pf.right = df.right = of.right = cf.right
3935                            = mOverscanScreenLeft + mOverscanScreenWidth;
3936                    pf.bottom = df.bottom = of.bottom = cf.bottom
3937                            = mOverscanScreenTop + mOverscanScreenHeight;
3938                } else if (canHideNavigationBar()
3939                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
3940                        && (attrs.type == TYPE_STATUS_BAR
3941                            || attrs.type == TYPE_TOAST
3942                            || attrs.type == TYPE_VOICE_INTERACTION_STARTING
3943                            || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3944                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
3945                    // Asking for layout as if the nav bar is hidden, lets the
3946                    // application extend into the unrestricted screen area.  We
3947                    // only do this for application windows (or toasts) to ensure no window that
3948                    // can be above the nav bar can do this.
3949                    // XXX This assumes that an app asking for this will also
3950                    // ask for layout in only content.  We can't currently figure out
3951                    // what the screen would be if only laying out to hide the nav bar.
3952                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
3953                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
3954                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
3955                            + mUnrestrictedScreenWidth;
3956                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
3957                            + mUnrestrictedScreenHeight;
3958                } else {
3959                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
3960                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
3961                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
3962                            + mRestrictedScreenWidth;
3963                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
3964                            + mRestrictedScreenHeight;
3965                }
3966
3967                applyStableConstraints(sysUiFl, fl, cf);
3968
3969                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3970                    vf.left = mCurLeft;
3971                    vf.top = mCurTop;
3972                    vf.right = mCurRight;
3973                    vf.bottom = mCurBottom;
3974                } else {
3975                    vf.set(cf);
3976                }
3977            } else if (attached != null) {
3978                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
3979                        "): attached to " + attached);
3980                // A child window should be placed inside of the same visible
3981                // frame that its parent had.
3982                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
3983            } else {
3984                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
3985                        "): normal window");
3986                // Otherwise, a normal window must be placed inside the content
3987                // of all screen decorations.
3988                if (attrs.type == TYPE_STATUS_BAR_PANEL) {
3989                    // Status bar panels are the only windows who can go on top of
3990                    // the status bar.  They are protected by the STATUS_BAR_SERVICE
3991                    // permission, so they have the same privileges as the status
3992                    // bar itself.
3993                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
3994                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
3995                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
3996                            + mRestrictedScreenWidth;
3997                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
3998                            + mRestrictedScreenHeight;
3999                } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT
4000                        || attrs.type == TYPE_VOLUME_OVERLAY) {
4001                    // These dialogs are stable to interim decor changes.
4002                    pf.left = df.left = of.left = cf.left = mStableLeft;
4003                    pf.top = df.top = of.top = cf.top = mStableTop;
4004                    pf.right = df.right = of.right = cf.right = mStableRight;
4005                    pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
4006                } else {
4007                    pf.left = mContentLeft;
4008                    pf.top = mContentTop;
4009                    pf.right = mContentRight;
4010                    pf.bottom = mContentBottom;
4011                    if (win.isVoiceInteraction()) {
4012                        df.left = of.left = cf.left = mVoiceContentLeft;
4013                        df.top = of.top = cf.top = mVoiceContentTop;
4014                        df.right = of.right = cf.right = mVoiceContentRight;
4015                        df.bottom = of.bottom = cf.bottom = mVoiceContentBottom;
4016                    } else if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4017                        df.left = of.left = cf.left = mDockLeft;
4018                        df.top = of.top = cf.top = mDockTop;
4019                        df.right = of.right = cf.right = mDockRight;
4020                        df.bottom = of.bottom = cf.bottom = mDockBottom;
4021                    } else {
4022                        df.left = of.left = cf.left = mContentLeft;
4023                        df.top = of.top = cf.top = mContentTop;
4024                        df.right = of.right = cf.right = mContentRight;
4025                        df.bottom = of.bottom = cf.bottom = mContentBottom;
4026                    }
4027                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4028                        vf.left = mCurLeft;
4029                        vf.top = mCurTop;
4030                        vf.right = mCurRight;
4031                        vf.bottom = mCurBottom;
4032                    } else {
4033                        vf.set(cf);
4034                    }
4035                }
4036            }
4037        }
4038
4039        // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
4040        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR) {
4041            df.left = df.top = -10000;
4042            df.right = df.bottom = 10000;
4043            if (attrs.type != TYPE_WALLPAPER) {
4044                of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
4045                of.right = of.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
4046            }
4047        }
4048
4049        if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
4050                + ": sim=#" + Integer.toHexString(sim)
4051                + " attach=" + attached + " type=" + attrs.type
4052                + String.format(" flags=0x%08x", fl)
4053                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
4054                + " of=" + of.toShortString()
4055                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
4056                + " dcf=" + dcf.toShortString()
4057                + " sf=" + sf.toShortString());
4058
4059        win.computeFrameLw(pf, df, of, cf, vf, dcf, sf);
4060
4061        // Dock windows carve out the bottom of the screen, so normal windows
4062        // can't appear underneath them.
4063        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
4064                && !win.getGivenInsetsPendingLw()) {
4065            setLastInputMethodWindowLw(null, null);
4066            offsetInputMethodWindowLw(win);
4067        }
4068        if (attrs.type == TYPE_VOICE_INTERACTION && win.isVisibleOrBehindKeyguardLw()
4069                && !win.getGivenInsetsPendingLw()) {
4070            offsetVoiceInputWindowLw(win);
4071        }
4072    }
4073
4074    private void offsetInputMethodWindowLw(WindowState win) {
4075        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4076        top += win.getGivenContentInsetsLw().top;
4077        if (mContentBottom > top) {
4078            mContentBottom = top;
4079        }
4080        if (mVoiceContentBottom > top) {
4081            mVoiceContentBottom = top;
4082        }
4083        top = win.getVisibleFrameLw().top;
4084        top += win.getGivenVisibleInsetsLw().top;
4085        if (mCurBottom > top) {
4086            mCurBottom = top;
4087        }
4088        if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
4089                + mDockBottom + " mContentBottom="
4090                + mContentBottom + " mCurBottom=" + mCurBottom);
4091    }
4092
4093    private void offsetVoiceInputWindowLw(WindowState win) {
4094        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4095        top += win.getGivenContentInsetsLw().top;
4096        if (mVoiceContentBottom > top) {
4097            mVoiceContentBottom = top;
4098        }
4099    }
4100
4101    /** {@inheritDoc} */
4102    @Override
4103    public void finishLayoutLw() {
4104        return;
4105    }
4106
4107    /** {@inheritDoc} */
4108    @Override
4109    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
4110        mTopFullscreenOpaqueWindowState = null;
4111        mTopFullscreenOpaqueOrDimmingWindowState = null;
4112        mAppsToBeHidden.clear();
4113        mAppsThatDismissKeyguard.clear();
4114        mForceStatusBar = false;
4115        mForceStatusBarFromKeyguard = false;
4116        mForcingShowNavBar = false;
4117        mForcingShowNavBarLayer = -1;
4118
4119        mHideLockScreen = false;
4120        mAllowLockscreenWhenOn = false;
4121        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
4122        mShowingLockscreen = false;
4123        mShowingDream = false;
4124        mWinShowWhenLocked = null;
4125        mKeyguardSecure = isKeyguardSecure();
4126        mKeyguardSecureIncludingHidden = mKeyguardSecure
4127                && (mKeyguardDelegate != null && mKeyguardDelegate.isShowing());
4128    }
4129
4130    /** {@inheritDoc} */
4131    @Override
4132    public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs) {
4133        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
4134                + win.isVisibleOrBehindKeyguardLw());
4135        final int fl = PolicyControl.getWindowFlags(win, attrs);
4136        if (mTopFullscreenOpaqueWindowState == null
4137                && win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD) {
4138            mForcingShowNavBar = true;
4139            mForcingShowNavBarLayer = win.getSurfaceLayer();
4140        }
4141        if (attrs.type == TYPE_STATUS_BAR && (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4142            mForceStatusBarFromKeyguard = true;
4143        }
4144
4145        boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
4146                && attrs.type < FIRST_SYSTEM_WINDOW;
4147        final boolean showWhenLocked = (fl & FLAG_SHOW_WHEN_LOCKED) != 0;
4148        final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
4149
4150        if (mTopFullscreenOpaqueWindowState == null &&
4151                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
4152            if ((fl & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
4153                if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4154                    mForceStatusBarFromKeyguard = true;
4155                } else {
4156                    mForceStatusBar = true;
4157                }
4158            }
4159            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4160                mShowingLockscreen = true;
4161            }
4162            if (attrs.type == TYPE_DREAM) {
4163                // If the lockscreen was showing when the dream started then wait
4164                // for the dream to draw before hiding the lockscreen.
4165                if (!mDreamingLockscreen
4166                        || (win.isVisibleLw() && win.hasDrawnLw())) {
4167                    mShowingDream = true;
4168                    appWindow = true;
4169                }
4170            }
4171
4172            if (appWindow) {
4173                final IApplicationToken appToken = win.getAppToken();
4174                if (showWhenLocked) {
4175                    // Remove any previous windows with the same appToken.
4176                    mAppsToBeHidden.remove(appToken);
4177                    mAppsThatDismissKeyguard.remove(appToken);
4178                    if (mAppsToBeHidden.isEmpty()) {
4179                        if (dismissKeyguard && !mKeyguardSecure) {
4180                            mAppsThatDismissKeyguard.add(appToken);
4181                        } else {
4182                            mWinShowWhenLocked = win;
4183                            mHideLockScreen = true;
4184                            mForceStatusBarFromKeyguard = false;
4185                        }
4186                    }
4187                } else if (dismissKeyguard) {
4188                    if (mKeyguardSecure) {
4189                        mAppsToBeHidden.add(appToken);
4190                    } else {
4191                        mAppsToBeHidden.remove(appToken);
4192                    }
4193                    mAppsThatDismissKeyguard.add(appToken);
4194                } else {
4195                    mAppsToBeHidden.add(appToken);
4196                }
4197                if (attrs.x == 0 && attrs.y == 0
4198                        && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
4199                        && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
4200                    if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
4201                    mTopFullscreenOpaqueWindowState = win;
4202                    if (mTopFullscreenOpaqueOrDimmingWindowState == null) {
4203                        mTopFullscreenOpaqueOrDimmingWindowState = win;
4204                    }
4205                    if (!mAppsThatDismissKeyguard.isEmpty() &&
4206                            mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
4207                        if (DEBUG_LAYOUT) Slog.v(TAG,
4208                                "Setting mDismissKeyguard true by win " + win);
4209                        mDismissKeyguard = mWinDismissingKeyguard == win ?
4210                                DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
4211                        mWinDismissingKeyguard = win;
4212                        mForceStatusBarFromKeyguard = mShowingLockscreen && mKeyguardSecure;
4213                    } else if (mAppsToBeHidden.isEmpty() && showWhenLocked) {
4214                        if (DEBUG_LAYOUT) Slog.v(TAG,
4215                                "Setting mHideLockScreen to true by win " + win);
4216                        mHideLockScreen = true;
4217                        mForceStatusBarFromKeyguard = false;
4218                    }
4219                    if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
4220                        mAllowLockscreenWhenOn = true;
4221                    }
4222                }
4223
4224                if (mWinShowWhenLocked != null &&
4225                        mWinShowWhenLocked.getAppToken() != win.getAppToken() &&
4226                        (attrs.flags & FLAG_SHOW_WHEN_LOCKED) == 0) {
4227                    win.hideLw(false);
4228                }
4229            }
4230        } else if (mTopFullscreenOpaqueWindowState == null && mWinShowWhenLocked == null) {
4231            // No TopFullscreenOpaqueWindow is showing, but we found a SHOW_WHEN_LOCKED window
4232            // that is being hidden in an animation - keep the
4233            // keyguard hidden until the new window shows up and
4234            // we know whether to show the keyguard or not.
4235            if (win.isAnimatingLw() && appWindow && showWhenLocked) {
4236                mHideLockScreen = true;
4237                mWinShowWhenLocked = win;
4238            }
4239        }
4240        if (mTopFullscreenOpaqueOrDimmingWindowState == null
4241                && win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()
4242                && win.isDimming()) {
4243            mTopFullscreenOpaqueOrDimmingWindowState = win;
4244        }
4245    }
4246
4247    /** {@inheritDoc} */
4248    @Override
4249    public int finishPostLayoutPolicyLw() {
4250        if (mWinShowWhenLocked != null && mTopFullscreenOpaqueWindowState != null &&
4251                mWinShowWhenLocked.getAppToken() != mTopFullscreenOpaqueWindowState.getAppToken()
4252                && isKeyguardLocked()) {
4253            // A dialog is dismissing the keyguard. Put the wallpaper behind it and hide the
4254            // fullscreen window.
4255            // TODO: Make sure FLAG_SHOW_WALLPAPER is restored when dialog is dismissed. Or not.
4256            mWinShowWhenLocked.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4257            mTopFullscreenOpaqueWindowState.hideLw(false);
4258            mTopFullscreenOpaqueWindowState = mWinShowWhenLocked;
4259        }
4260
4261        int changes = 0;
4262        boolean topIsFullscreen = false;
4263
4264        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
4265                ? mTopFullscreenOpaqueWindowState.getAttrs()
4266                : null;
4267
4268        // If we are not currently showing a dream then remember the current
4269        // lockscreen state.  We will use this to determine whether the dream
4270        // started while the lockscreen was showing and remember this state
4271        // while the dream is showing.
4272        if (!mShowingDream) {
4273            mDreamingLockscreen = mShowingLockscreen;
4274            if (mDreamingSleepTokenNeeded) {
4275                mDreamingSleepTokenNeeded = false;
4276                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 0, 1).sendToTarget();
4277            }
4278        } else {
4279            if (!mDreamingSleepTokenNeeded) {
4280                mDreamingSleepTokenNeeded = true;
4281                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 1, 1).sendToTarget();
4282            }
4283        }
4284
4285        if (mStatusBar != null) {
4286            if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
4287                    + " forcefkg=" + mForceStatusBarFromKeyguard
4288                    + " top=" + mTopFullscreenOpaqueWindowState);
4289            if (mForceStatusBar || mForceStatusBarFromKeyguard) {
4290                if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
4291                if (mStatusBarController.setBarShowingLw(true)) {
4292                    changes |= FINISH_LAYOUT_REDO_LAYOUT;
4293                }
4294                // Maintain fullscreen layout until incoming animation is complete.
4295                topIsFullscreen = mTopIsFullscreen && mStatusBar.isAnimatingLw();
4296                // Transient status bar on the lockscreen is not allowed
4297                if (mForceStatusBarFromKeyguard && mStatusBarController.isTransientShowing()) {
4298                    mStatusBarController.updateVisibilityLw(false /*transientAllowed*/,
4299                            mLastSystemUiFlags, mLastSystemUiFlags);
4300                }
4301            } else if (mTopFullscreenOpaqueWindowState != null) {
4302                final int fl = PolicyControl.getWindowFlags(null, lp);
4303                if (localLOGV) {
4304                    Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
4305                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
4306                    Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
4307                            + " lp.flags=0x" + Integer.toHexString(fl));
4308                }
4309                topIsFullscreen = (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
4310                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
4311                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
4312                // and mTopIsFullscreen is that mTopIsFullscreen is set only if the window
4313                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
4314                // case though.
4315                if (mStatusBarController.isTransientShowing()) {
4316                    if (mStatusBarController.setBarShowingLw(true)) {
4317                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4318                    }
4319                } else if (topIsFullscreen) {
4320                    if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
4321                    if (mStatusBarController.setBarShowingLw(false)) {
4322                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4323                    } else {
4324                        if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
4325                    }
4326                } else {
4327                    if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
4328                    if (mStatusBarController.setBarShowingLw(true)) {
4329                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4330                    }
4331                }
4332            }
4333        }
4334
4335        if (mTopIsFullscreen != topIsFullscreen) {
4336            if (!topIsFullscreen) {
4337                // Force another layout when status bar becomes fully shown.
4338                changes |= FINISH_LAYOUT_REDO_LAYOUT;
4339            }
4340            mTopIsFullscreen = topIsFullscreen;
4341        }
4342
4343        // Hide the key guard if a visible window explicitly specifies that it wants to be
4344        // displayed when the screen is locked.
4345        if (mKeyguardDelegate != null && mStatusBar != null) {
4346            if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
4347                    + mHideLockScreen);
4348            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardSecure) {
4349                mKeyguardHidden = true;
4350                if (setKeyguardOccludedLw(true)) {
4351                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4352                            | FINISH_LAYOUT_REDO_CONFIG
4353                            | FINISH_LAYOUT_REDO_WALLPAPER;
4354                }
4355                if (mKeyguardDelegate.isShowing()) {
4356                    mHandler.post(new Runnable() {
4357                        @Override
4358                        public void run() {
4359                            mKeyguardDelegate.keyguardDone(false, false);
4360                        }
4361                    });
4362                }
4363            } else if (mHideLockScreen) {
4364                mKeyguardHidden = true;
4365                if (setKeyguardOccludedLw(true)) {
4366                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4367                            | FINISH_LAYOUT_REDO_CONFIG
4368                            | FINISH_LAYOUT_REDO_WALLPAPER;
4369                }
4370            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
4371                // This is the case of keyguard isSecure() and not mHideLockScreen.
4372                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
4373                    // Only launch the next keyguard unlock window once per window.
4374                    mKeyguardHidden = false;
4375                    if (setKeyguardOccludedLw(false)) {
4376                        changes |= FINISH_LAYOUT_REDO_LAYOUT
4377                                | FINISH_LAYOUT_REDO_CONFIG
4378                                | FINISH_LAYOUT_REDO_WALLPAPER;
4379                    }
4380                    mHandler.post(new Runnable() {
4381                        @Override
4382                        public void run() {
4383                            mKeyguardDelegate.dismiss();
4384                        }
4385                    });
4386                }
4387            } else {
4388                mWinDismissingKeyguard = null;
4389                mKeyguardHidden = false;
4390                if (setKeyguardOccludedLw(false)) {
4391                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4392                            | FINISH_LAYOUT_REDO_CONFIG
4393                            | FINISH_LAYOUT_REDO_WALLPAPER;
4394                }
4395            }
4396        }
4397
4398        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
4399            // If the navigation bar has been hidden or shown, we need to do another
4400            // layout pass to update that window.
4401            changes |= FINISH_LAYOUT_REDO_LAYOUT;
4402        }
4403
4404        // update since mAllowLockscreenWhenOn might have changed
4405        updateLockScreenTimeout();
4406        return changes;
4407    }
4408
4409    /**
4410     * Updates the occluded state of the Keyguard.
4411     *
4412     * @return Whether the flags have changed and we have to redo the layout.
4413     */
4414    private boolean setKeyguardOccludedLw(boolean isOccluded) {
4415        boolean wasOccluded = mKeyguardOccluded;
4416        boolean showing = mKeyguardDelegate.isShowing();
4417        if (wasOccluded && !isOccluded && showing) {
4418            mKeyguardOccluded = false;
4419            mKeyguardDelegate.setOccluded(false);
4420            mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
4421            mStatusBar.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4422            return true;
4423        } else if (!wasOccluded && isOccluded && showing) {
4424            mKeyguardOccluded = true;
4425            mKeyguardDelegate.setOccluded(true);
4426            mStatusBar.getAttrs().privateFlags &= ~PRIVATE_FLAG_KEYGUARD;
4427            mStatusBar.getAttrs().flags &= ~FLAG_SHOW_WALLPAPER;
4428            return true;
4429        } else {
4430            return false;
4431        }
4432    }
4433
4434    private boolean isStatusBarKeyguard() {
4435        return mStatusBar != null
4436                && (mStatusBar.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
4437    }
4438
4439    @Override
4440    public boolean allowAppAnimationsLw() {
4441        if (isStatusBarKeyguard() || mShowingDream) {
4442            // If keyguard or dreams is currently visible, no reason to animate behind it.
4443            return false;
4444        }
4445        return true;
4446    }
4447
4448    @Override
4449    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
4450        mFocusedWindow = newFocus;
4451        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
4452            // If the navigation bar has been hidden or shown, we need to do another
4453            // layout pass to update that window.
4454            return FINISH_LAYOUT_REDO_LAYOUT;
4455        }
4456        return 0;
4457    }
4458
4459    /** {@inheritDoc} */
4460    @Override
4461    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
4462        // lid changed state
4463        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
4464        if (newLidState == mLidState) {
4465            return;
4466        }
4467
4468        mLidState = newLidState;
4469        applyLidSwitchState();
4470        updateRotation(true);
4471
4472        if (lidOpen) {
4473            wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromLidSwitch);
4474        } else if (!mLidControlsSleep) {
4475            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4476        }
4477    }
4478
4479    @Override
4480    public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered) {
4481        int lensCoverState = lensCovered ? CAMERA_LENS_COVERED : CAMERA_LENS_UNCOVERED;
4482        if (mCameraLensCoverState == lensCoverState) {
4483            return;
4484        }
4485        if (mCameraLensCoverState == CAMERA_LENS_COVERED &&
4486                lensCoverState == CAMERA_LENS_UNCOVERED) {
4487            Intent intent;
4488            final boolean keyguardActive = mKeyguardDelegate == null ? false :
4489                    mKeyguardDelegate.isShowing();
4490            if (keyguardActive) {
4491                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
4492            } else {
4493                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
4494            }
4495            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromCameraLens);
4496            startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
4497        }
4498        mCameraLensCoverState = lensCoverState;
4499    }
4500
4501    void setHdmiPlugged(boolean plugged) {
4502        if (mHdmiPlugged != plugged) {
4503            mHdmiPlugged = plugged;
4504            updateRotation(true, true);
4505            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
4506            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4507            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
4508            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
4509        }
4510    }
4511
4512    void initializeHdmiState() {
4513        boolean plugged = false;
4514        // watch for HDMI plug messages if the hdmi switch exists
4515        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
4516            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
4517
4518            final String filename = "/sys/class/switch/hdmi/state";
4519            FileReader reader = null;
4520            try {
4521                reader = new FileReader(filename);
4522                char[] buf = new char[15];
4523                int n = reader.read(buf);
4524                if (n > 1) {
4525                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
4526                }
4527            } catch (IOException ex) {
4528                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
4529            } catch (NumberFormatException ex) {
4530                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
4531            } finally {
4532                if (reader != null) {
4533                    try {
4534                        reader.close();
4535                    } catch (IOException ex) {
4536                    }
4537                }
4538            }
4539        }
4540        // This dance forces the code in setHdmiPlugged to run.
4541        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
4542        mHdmiPlugged = !plugged;
4543        setHdmiPlugged(!mHdmiPlugged);
4544    }
4545
4546    final Object mScreenshotLock = new Object();
4547    ServiceConnection mScreenshotConnection = null;
4548
4549    final Runnable mScreenshotTimeout = new Runnable() {
4550        @Override public void run() {
4551            synchronized (mScreenshotLock) {
4552                if (mScreenshotConnection != null) {
4553                    mContext.unbindService(mScreenshotConnection);
4554                    mScreenshotConnection = null;
4555                }
4556            }
4557        }
4558    };
4559
4560    // Assume this is called from the Handler thread.
4561    private void takeScreenshot() {
4562        synchronized (mScreenshotLock) {
4563            if (mScreenshotConnection != null) {
4564                return;
4565            }
4566            ComponentName cn = new ComponentName("com.android.systemui",
4567                    "com.android.systemui.screenshot.TakeScreenshotService");
4568            Intent intent = new Intent();
4569            intent.setComponent(cn);
4570            ServiceConnection conn = new ServiceConnection() {
4571                @Override
4572                public void onServiceConnected(ComponentName name, IBinder service) {
4573                    synchronized (mScreenshotLock) {
4574                        if (mScreenshotConnection != this) {
4575                            return;
4576                        }
4577                        Messenger messenger = new Messenger(service);
4578                        Message msg = Message.obtain(null, 1);
4579                        final ServiceConnection myConn = this;
4580                        Handler h = new Handler(mHandler.getLooper()) {
4581                            @Override
4582                            public void handleMessage(Message msg) {
4583                                synchronized (mScreenshotLock) {
4584                                    if (mScreenshotConnection == myConn) {
4585                                        mContext.unbindService(mScreenshotConnection);
4586                                        mScreenshotConnection = null;
4587                                        mHandler.removeCallbacks(mScreenshotTimeout);
4588                                    }
4589                                }
4590                            }
4591                        };
4592                        msg.replyTo = new Messenger(h);
4593                        msg.arg1 = msg.arg2 = 0;
4594                        if (mStatusBar != null && mStatusBar.isVisibleLw())
4595                            msg.arg1 = 1;
4596                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
4597                            msg.arg2 = 1;
4598                        try {
4599                            messenger.send(msg);
4600                        } catch (RemoteException e) {
4601                        }
4602                    }
4603                }
4604                @Override
4605                public void onServiceDisconnected(ComponentName name) {}
4606            };
4607            if (mContext.bindServiceAsUser(
4608                    intent, conn, Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
4609                mScreenshotConnection = conn;
4610                mHandler.postDelayed(mScreenshotTimeout, 10000);
4611            }
4612        }
4613    }
4614
4615    /** {@inheritDoc} */
4616    @Override
4617    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
4618        if (!mSystemBooted) {
4619            // If we have not yet booted, don't let key events do anything.
4620            return 0;
4621        }
4622
4623        final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;
4624        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
4625        final boolean canceled = event.isCanceled();
4626        final int keyCode = event.getKeyCode();
4627
4628        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
4629
4630        // If screen is off then we treat the case where the keyguard is open but hidden
4631        // the same as if it were open and in front.
4632        // This will prevent any keys other than the power button from waking the screen
4633        // when the keyguard is hidden by another activity.
4634        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
4635                                            (interactive ?
4636                                                isKeyguardShowingAndNotOccluded() :
4637                                                mKeyguardDelegate.isShowing()));
4638
4639        if (DEBUG_INPUT) {
4640            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
4641                    + " interactive=" + interactive + " keyguardActive=" + keyguardActive
4642                    + " policyFlags=" + Integer.toHexString(policyFlags));
4643        }
4644
4645        // Basic policy based on interactive state.
4646        int result;
4647        boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
4648                || event.isWakeKey();
4649        if (interactive || (isInjected && !isWakeKey)) {
4650            // When the device is interactive or the key is injected pass the
4651            // key to the application.
4652            result = ACTION_PASS_TO_USER;
4653            isWakeKey = false;
4654        } else if (!interactive && shouldDispatchInputWhenNonInteractive()) {
4655            // If we're currently dozing with the screen on and the keyguard showing, pass the key
4656            // to the application but preserve its wake key status to make sure we still move
4657            // from dozing to fully interactive if we would normally go from off to fully
4658            // interactive.
4659            result = ACTION_PASS_TO_USER;
4660        } else {
4661            // When the screen is off and the key is not injected, determine whether
4662            // to wake the device but don't pass the key to the application.
4663            result = 0;
4664            if (isWakeKey && (!down || !isWakeKeyWhenScreenOff(keyCode))) {
4665                isWakeKey = false;
4666            }
4667        }
4668
4669        // If the key would be handled globally, just return the result, don't worry about special
4670        // key processing.
4671        if (isValidGlobalKey(keyCode)
4672                && mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
4673            if (isWakeKey) {
4674                wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey);
4675            }
4676            return result;
4677        }
4678
4679        boolean useHapticFeedback = down
4680                && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
4681                && event.getRepeatCount() == 0;
4682
4683        // Handle special keys.
4684        switch (keyCode) {
4685            case KeyEvent.KEYCODE_VOLUME_DOWN:
4686            case KeyEvent.KEYCODE_VOLUME_UP:
4687            case KeyEvent.KEYCODE_VOLUME_MUTE: {
4688                if (mUseTvRouting) {
4689                    // On TVs volume keys never go to the foreground app
4690                    result &= ~ACTION_PASS_TO_USER;
4691                }
4692                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
4693                    if (down) {
4694                        if (interactive && !mScreenshotChordVolumeDownKeyTriggered
4695                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4696                            mScreenshotChordVolumeDownKeyTriggered = true;
4697                            mScreenshotChordVolumeDownKeyTime = event.getDownTime();
4698                            mScreenshotChordVolumeDownKeyConsumed = false;
4699                            cancelPendingPowerKeyAction();
4700                            interceptScreenshotChord();
4701                        }
4702                    } else {
4703                        mScreenshotChordVolumeDownKeyTriggered = false;
4704                        cancelPendingScreenshotChordAction();
4705                    }
4706                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
4707                    if (down) {
4708                        if (interactive && !mScreenshotChordVolumeUpKeyTriggered
4709                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4710                            mScreenshotChordVolumeUpKeyTriggered = true;
4711                            cancelPendingPowerKeyAction();
4712                            cancelPendingScreenshotChordAction();
4713                        }
4714                    } else {
4715                        mScreenshotChordVolumeUpKeyTriggered = false;
4716                        cancelPendingScreenshotChordAction();
4717                    }
4718                }
4719                if (down) {
4720                    TelecomManager telecomManager = getTelecommService();
4721                    if (telecomManager != null) {
4722                        if (telecomManager.isRinging()) {
4723                            // If an incoming call is ringing, either VOLUME key means
4724                            // "silence ringer".  We handle these keys here, rather than
4725                            // in the InCallScreen, to make sure we'll respond to them
4726                            // even if the InCallScreen hasn't come to the foreground yet.
4727                            // Look for the DOWN event here, to agree with the "fallback"
4728                            // behavior in the InCallScreen.
4729                            Log.i(TAG, "interceptKeyBeforeQueueing:"
4730                                  + " VOLUME key-down while ringing: Silence ringer!");
4731
4732                            // Silence the ringer.  (It's safe to call this
4733                            // even if the ringer has already been silenced.)
4734                            telecomManager.silenceRinger();
4735
4736                            // And *don't* pass this key thru to the current activity
4737                            // (which is probably the InCallScreen.)
4738                            result &= ~ACTION_PASS_TO_USER;
4739                            break;
4740                        }
4741                        if (telecomManager.isInCall()
4742                                && (result & ACTION_PASS_TO_USER) == 0) {
4743                            // If we are in call but we decided not to pass the key to
4744                            // the application, just pass it to the session service.
4745
4746                            MediaSessionLegacyHelper.getHelper(mContext)
4747                                    .sendVolumeKeyEvent(event, false);
4748                            break;
4749                        }
4750                    }
4751
4752                    if ((result & ACTION_PASS_TO_USER) == 0) {
4753                        if (mUseTvRouting) {
4754                            dispatchDirectAudioEvent(event);
4755                        } else {
4756                            // If we aren't passing to the user and no one else
4757                            // handled it send it to the session manager to
4758                            // figure out.
4759                            MediaSessionLegacyHelper.getHelper(mContext)
4760                                    .sendVolumeKeyEvent(event, true);
4761                        }
4762                        break;
4763                    }
4764                }
4765                break;
4766            }
4767
4768            case KeyEvent.KEYCODE_ENDCALL: {
4769                result &= ~ACTION_PASS_TO_USER;
4770                if (down) {
4771                    TelecomManager telecomManager = getTelecommService();
4772                    boolean hungUp = false;
4773                    if (telecomManager != null) {
4774                        hungUp = telecomManager.endCall();
4775                    }
4776                    if (interactive && !hungUp) {
4777                        mEndCallKeyHandled = false;
4778                        mHandler.postDelayed(mEndCallLongPress,
4779                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
4780                    } else {
4781                        mEndCallKeyHandled = true;
4782                    }
4783                } else {
4784                    if (!mEndCallKeyHandled) {
4785                        mHandler.removeCallbacks(mEndCallLongPress);
4786                        if (!canceled) {
4787                            if ((mEndcallBehavior
4788                                    & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
4789                                if (goHome()) {
4790                                    break;
4791                                }
4792                            }
4793                            if ((mEndcallBehavior
4794                                    & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
4795                                mPowerManager.goToSleep(event.getEventTime(),
4796                                        PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
4797                                isWakeKey = false;
4798                            }
4799                        }
4800                    }
4801                }
4802                break;
4803            }
4804
4805            case KeyEvent.KEYCODE_POWER: {
4806                result &= ~ACTION_PASS_TO_USER;
4807                isWakeKey = false; // wake-up will be handled separately
4808                if (down) {
4809                    interceptPowerKeyDown(event, interactive);
4810                } else {
4811                    interceptPowerKeyUp(event, interactive, canceled);
4812                }
4813                break;
4814            }
4815
4816            case KeyEvent.KEYCODE_SLEEP: {
4817                result &= ~ACTION_PASS_TO_USER;
4818                isWakeKey = false;
4819                if (!mPowerManager.isInteractive()) {
4820                    useHapticFeedback = false; // suppress feedback if already non-interactive
4821                }
4822                sleepPress(event);
4823                break;
4824            }
4825
4826            case KeyEvent.KEYCODE_WAKEUP: {
4827                result &= ~ACTION_PASS_TO_USER;
4828                isWakeKey = true;
4829                break;
4830            }
4831
4832            case KeyEvent.KEYCODE_MEDIA_PLAY:
4833            case KeyEvent.KEYCODE_MEDIA_PAUSE:
4834            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
4835            case KeyEvent.KEYCODE_HEADSETHOOK:
4836            case KeyEvent.KEYCODE_MUTE:
4837            case KeyEvent.KEYCODE_MEDIA_STOP:
4838            case KeyEvent.KEYCODE_MEDIA_NEXT:
4839            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
4840            case KeyEvent.KEYCODE_MEDIA_REWIND:
4841            case KeyEvent.KEYCODE_MEDIA_RECORD:
4842            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
4843            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
4844                if (MediaSessionLegacyHelper.getHelper(mContext).isGlobalPriorityActive()) {
4845                    // If the global session is active pass all media keys to it
4846                    // instead of the active window.
4847                    result &= ~ACTION_PASS_TO_USER;
4848                }
4849                if ((result & ACTION_PASS_TO_USER) == 0) {
4850                    // Only do this if we would otherwise not pass it to the user. In that
4851                    // case, the PhoneWindow class will do the same thing, except it will
4852                    // only do it if the showing app doesn't process the key on its own.
4853                    // Note that we need to make a copy of the key event here because the
4854                    // original key event will be recycled when we return.
4855                    mBroadcastWakeLock.acquire();
4856                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
4857                            new KeyEvent(event));
4858                    msg.setAsynchronous(true);
4859                    msg.sendToTarget();
4860                }
4861                break;
4862            }
4863
4864            case KeyEvent.KEYCODE_CALL: {
4865                if (down) {
4866                    TelecomManager telecomManager = getTelecommService();
4867                    if (telecomManager != null) {
4868                        if (telecomManager.isRinging()) {
4869                            Log.i(TAG, "interceptKeyBeforeQueueing:"
4870                                  + " CALL key-down while ringing: Answer the call!");
4871                            telecomManager.acceptRingingCall();
4872
4873                            // And *don't* pass this key thru to the current activity
4874                            // (which is presumably the InCallScreen.)
4875                            result &= ~ACTION_PASS_TO_USER;
4876                        }
4877                    }
4878                }
4879                break;
4880            }
4881            case KeyEvent.KEYCODE_VOICE_ASSIST: {
4882                // Only do this if we would otherwise not pass it to the user. In that case,
4883                // interceptKeyBeforeDispatching would apply a similar but different policy in
4884                // order to invoke voice assist actions. Note that we need to make a copy of the
4885                // key event here because the original key event will be recycled when we return.
4886                if ((result & ACTION_PASS_TO_USER) == 0 && !down) {
4887                    mBroadcastWakeLock.acquire();
4888                    Message msg = mHandler.obtainMessage(MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK,
4889                            keyguardActive ? 1 : 0, 0);
4890                    msg.setAsynchronous(true);
4891                    msg.sendToTarget();
4892                }
4893            }
4894        }
4895
4896        if (useHapticFeedback) {
4897            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
4898        }
4899
4900        if (isWakeKey) {
4901            wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey);
4902        }
4903
4904        return result;
4905    }
4906
4907    /**
4908     * Returns true if the key can have global actions attached to it.
4909     * We reserve all power management keys for the system since they require
4910     * very careful handling.
4911     */
4912    private static boolean isValidGlobalKey(int keyCode) {
4913        switch (keyCode) {
4914            case KeyEvent.KEYCODE_POWER:
4915            case KeyEvent.KEYCODE_WAKEUP:
4916            case KeyEvent.KEYCODE_SLEEP:
4917                return false;
4918            default:
4919                return true;
4920        }
4921    }
4922
4923    /**
4924     * When the screen is off we ignore some keys that might otherwise typically
4925     * be considered wake keys.  We filter them out here.
4926     *
4927     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
4928     * is always considered a wake key.
4929     */
4930    private boolean isWakeKeyWhenScreenOff(int keyCode) {
4931        switch (keyCode) {
4932            // ignore volume keys unless docked
4933            case KeyEvent.KEYCODE_VOLUME_UP:
4934            case KeyEvent.KEYCODE_VOLUME_DOWN:
4935            case KeyEvent.KEYCODE_VOLUME_MUTE:
4936                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
4937
4938            // ignore media and camera keys
4939            case KeyEvent.KEYCODE_MUTE:
4940            case KeyEvent.KEYCODE_HEADSETHOOK:
4941            case KeyEvent.KEYCODE_MEDIA_PLAY:
4942            case KeyEvent.KEYCODE_MEDIA_PAUSE:
4943            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
4944            case KeyEvent.KEYCODE_MEDIA_STOP:
4945            case KeyEvent.KEYCODE_MEDIA_NEXT:
4946            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
4947            case KeyEvent.KEYCODE_MEDIA_REWIND:
4948            case KeyEvent.KEYCODE_MEDIA_RECORD:
4949            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
4950            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
4951            case KeyEvent.KEYCODE_CAMERA:
4952                return false;
4953        }
4954        return true;
4955    }
4956
4957
4958    /** {@inheritDoc} */
4959    @Override
4960    public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
4961        if ((policyFlags & FLAG_WAKE) != 0) {
4962            if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion)) {
4963                return 0;
4964            }
4965        }
4966
4967        if (shouldDispatchInputWhenNonInteractive()) {
4968            return ACTION_PASS_TO_USER;
4969        }
4970
4971        // If we have not passed the action up and we are in theater mode without dreaming,
4972        // there will be no dream to intercept the touch and wake into ambient.  The device should
4973        // wake up in this case.
4974        if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
4975            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotionWhenNotDreaming);
4976        }
4977
4978        return 0;
4979    }
4980
4981    private boolean shouldDispatchInputWhenNonInteractive() {
4982        // Send events to keyguard while the screen is on.
4983        if (isKeyguardShowingAndNotOccluded() && mDisplay != null
4984                && mDisplay.getState() != Display.STATE_OFF) {
4985            return true;
4986        }
4987
4988        // Send events to a dozing dream even if the screen is off since the dream
4989        // is in control of the state of the screen.
4990        IDreamManager dreamManager = getDreamManager();
4991
4992        try {
4993            if (dreamManager != null && dreamManager.isDreaming()) {
4994                return true;
4995            }
4996        } catch (RemoteException e) {
4997            Slog.e(TAG, "RemoteException when checking if dreaming", e);
4998        }
4999
5000        // Otherwise, consume events since the user can't see what is being
5001        // interacted with.
5002        return false;
5003    }
5004
5005    private void dispatchDirectAudioEvent(KeyEvent event) {
5006        if (event.getAction() != KeyEvent.ACTION_DOWN) {
5007            return;
5008        }
5009        int keyCode = event.getKeyCode();
5010        int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
5011                | AudioManager.FLAG_FROM_KEY;
5012        String pkgName = mContext.getOpPackageName();
5013        switch (keyCode) {
5014            case KeyEvent.KEYCODE_VOLUME_UP:
5015                try {
5016                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
5017                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5018                } catch (RemoteException e) {
5019                    Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
5020                }
5021                break;
5022            case KeyEvent.KEYCODE_VOLUME_DOWN:
5023                try {
5024                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
5025                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5026                } catch (RemoteException e) {
5027                    Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
5028                }
5029                break;
5030            case KeyEvent.KEYCODE_VOLUME_MUTE:
5031                try {
5032                    if (event.getRepeatCount() == 0) {
5033                        getAudioService().adjustSuggestedStreamVolume(
5034                                AudioManager.ADJUST_TOGGLE_MUTE,
5035                                AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5036                    }
5037                } catch (RemoteException e) {
5038                    Log.e(TAG, "Error dispatching mute in dispatchTvAudioEvent.", e);
5039                }
5040                break;
5041        }
5042    }
5043
5044    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
5045        if (DEBUG_INPUT) {
5046            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
5047        }
5048
5049        if (mHavePendingMediaKeyRepeatWithWakeLock) {
5050            if (DEBUG_INPUT) {
5051                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
5052            }
5053
5054            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
5055            mHavePendingMediaKeyRepeatWithWakeLock = false;
5056            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
5057        }
5058
5059        dispatchMediaKeyWithWakeLockToAudioService(event);
5060
5061        if (event.getAction() == KeyEvent.ACTION_DOWN
5062                && event.getRepeatCount() == 0) {
5063            mHavePendingMediaKeyRepeatWithWakeLock = true;
5064
5065            Message msg = mHandler.obtainMessage(
5066                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
5067            msg.setAsynchronous(true);
5068            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
5069        } else {
5070            mBroadcastWakeLock.release();
5071        }
5072    }
5073
5074    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
5075        mHavePendingMediaKeyRepeatWithWakeLock = false;
5076
5077        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
5078                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
5079        if (DEBUG_INPUT) {
5080            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
5081        }
5082
5083        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
5084        mBroadcastWakeLock.release();
5085    }
5086
5087    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
5088        if (ActivityManagerNative.isSystemReady()) {
5089            MediaSessionLegacyHelper.getHelper(mContext).sendMediaButtonEvent(event, true);
5090        }
5091    }
5092
5093    void launchVoiceAssistWithWakeLock(boolean keyguardActive) {
5094        Intent voiceIntent =
5095            new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
5096        voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, keyguardActive);
5097        startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
5098        mBroadcastWakeLock.release();
5099    }
5100
5101    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
5102        @Override
5103        public void onReceive(Context context, Intent intent) {
5104            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
5105                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
5106                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
5107            } else {
5108                try {
5109                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
5110                            ServiceManager.getService(Context.UI_MODE_SERVICE));
5111                    mUiMode = uiModeService.getCurrentModeType();
5112                } catch (RemoteException e) {
5113                }
5114            }
5115            updateRotation(true);
5116            synchronized (mLock) {
5117                updateOrientationListenerLp();
5118            }
5119        }
5120    };
5121
5122    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
5123        @Override
5124        public void onReceive(Context context, Intent intent) {
5125            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
5126                if (mKeyguardDelegate != null) {
5127                    mKeyguardDelegate.onDreamingStarted();
5128                }
5129            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
5130                if (mKeyguardDelegate != null) {
5131                    mKeyguardDelegate.onDreamingStopped();
5132                }
5133            }
5134        }
5135    };
5136
5137    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
5138        @Override
5139        public void onReceive(Context context, Intent intent) {
5140            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
5141                // tickle the settings observer: this first ensures that we're
5142                // observing the relevant settings for the newly-active user,
5143                // and then updates our own bookkeeping based on the now-
5144                // current user.
5145                mSettingsObserver.onChange(false);
5146
5147                // force a re-application of focused window sysui visibility.
5148                // the window may never have been shown for this user
5149                // e.g. the keyguard when going through the new-user setup flow
5150                synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5151                    mLastSystemUiFlags = 0;
5152                    updateSystemUiVisibilityLw();
5153                }
5154            }
5155        }
5156    };
5157
5158    private final Runnable mRequestTransientNav = new Runnable() {
5159        @Override
5160        public void run() {
5161            requestTransientBars(mNavigationBar);
5162        }
5163    };
5164
5165    private void requestTransientBars(WindowState swipeTarget) {
5166        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5167            if (!isUserSetupComplete()) {
5168                // Swipe-up for navigation bar is disabled during setup
5169                return;
5170            }
5171            boolean sb = mStatusBarController.checkShowTransientBarLw();
5172            boolean nb = mNavigationBarController.checkShowTransientBarLw();
5173            if (sb || nb) {
5174                // Don't show status bar when swiping on already visible navigation bar
5175                if (!nb && swipeTarget == mNavigationBar) {
5176                    if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
5177                    return;
5178                }
5179                if (sb) mStatusBarController.showTransient();
5180                if (nb) mNavigationBarController.showTransient();
5181                mImmersiveModeConfirmation.confirmCurrentPrompt();
5182                updateSystemUiVisibilityLw();
5183            }
5184        }
5185    }
5186
5187    // Called on the PowerManager's Notifier thread.
5188    @Override
5189    public void goingToSleep(int why) {
5190        EventLog.writeEvent(70000, 0);
5191        if (DEBUG_WAKEUP) Slog.i(TAG, "Going to sleep...");
5192
5193        // We must get this work done here because the power manager will drop
5194        // the wake lock and let the system suspend once this function returns.
5195        synchronized (mLock) {
5196            mAwake = false;
5197            mKeyguardDrawComplete = false;
5198            updateWakeGestureListenerLp();
5199            updateOrientationListenerLp();
5200            updateLockScreenTimeout();
5201        }
5202
5203        if (mKeyguardDelegate != null) {
5204            mKeyguardDelegate.onScreenTurnedOff(why);
5205        }
5206    }
5207
5208    private void wakeUpFromPowerKey(long eventTime) {
5209        wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey);
5210    }
5211
5212    private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode) {
5213        if (!wakeInTheaterMode && isTheaterModeEnabled()) {
5214            return false;
5215        }
5216
5217        mPowerManager.wakeUp(wakeTime);
5218        return true;
5219    }
5220
5221    // Called on the PowerManager's Notifier thread.
5222    @Override
5223    public void wakingUp() {
5224        EventLog.writeEvent(70000, 1);
5225        if (DEBUG_WAKEUP) Slog.i(TAG, "Waking up...");
5226
5227        // Since goToSleep performs these functions synchronously, we must
5228        // do the same here.  We cannot post this work to a handler because
5229        // that might cause it to become reordered with respect to what
5230        // may happen in a future call to goToSleep.
5231        synchronized (mLock) {
5232            mAwake = true;
5233            mKeyguardDrawComplete = false;
5234            if (mKeyguardDelegate != null) {
5235                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
5236                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
5237            }
5238
5239            updateWakeGestureListenerLp();
5240            updateOrientationListenerLp();
5241            updateLockScreenTimeout();
5242        }
5243
5244        if (mKeyguardDelegate != null) {
5245            mKeyguardDelegate.onScreenTurnedOn(mKeyguardDelegateCallback);
5246            // ... eventually calls finishKeyguardDrawn
5247        } else {
5248            if (DEBUG_WAKEUP) Slog.d(TAG, "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
5249            finishKeyguardDrawn();
5250        }
5251    }
5252
5253    private void finishKeyguardDrawn() {
5254        synchronized (mLock) {
5255            if (!mAwake || mKeyguardDrawComplete) {
5256                return; // spurious
5257            }
5258
5259            mKeyguardDrawComplete = true;
5260            if (mKeyguardDelegate != null) {
5261                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
5262            }
5263        }
5264
5265        finishScreenTurningOn();
5266    }
5267
5268    // Called on the DisplayManager's DisplayPowerController thread.
5269    @Override
5270    public void screenTurnedOff() {
5271        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turned off...");
5272
5273        synchronized (mLock) {
5274            mScreenOnEarly = false;
5275            mScreenOnFully = false;
5276            mWindowManagerDrawComplete = false;
5277            mScreenOnListener = null;
5278            updateOrientationListenerLp();
5279        }
5280    }
5281
5282    // Called on the DisplayManager's DisplayPowerController thread.
5283    @Override
5284    public void screenTurningOn(final ScreenOnListener screenOnListener) {
5285        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
5286
5287        synchronized (mLock) {
5288            mScreenOnEarly = true;
5289            mScreenOnFully = false;
5290            mWindowManagerDrawComplete = false;
5291            mScreenOnListener = screenOnListener;
5292            updateOrientationListenerLp();
5293        }
5294
5295        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
5296                WAITING_FOR_DRAWN_TIMEOUT);
5297        // ... eventually calls finishWindowsDrawn
5298    }
5299
5300    private void finishWindowsDrawn() {
5301        synchronized (mLock) {
5302            if (!mScreenOnEarly || mWindowManagerDrawComplete) {
5303                return; // spurious
5304            }
5305
5306            mWindowManagerDrawComplete = true;
5307        }
5308
5309        finishScreenTurningOn();
5310    }
5311
5312    private void finishScreenTurningOn() {
5313        final ScreenOnListener listener;
5314        final boolean enableScreen;
5315        synchronized (mLock) {
5316            if (DEBUG_WAKEUP) Slog.d(TAG,
5317                    "finishScreenTurningOn: mAwake=" + mAwake
5318                            + ", mScreenOnEarly=" + mScreenOnEarly
5319                            + ", mScreenOnFully=" + mScreenOnFully
5320                            + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
5321                            + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
5322
5323            if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
5324                    || (mAwake && !mKeyguardDrawComplete)) {
5325                return; // spurious or not ready yet
5326            }
5327
5328            if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
5329            listener = mScreenOnListener;
5330            mScreenOnListener = null;
5331            mScreenOnFully = true;
5332
5333            // Remember the first time we draw the keyguard so we know when we're done with
5334            // the main part of booting and can enable the screen and hide boot messages.
5335            if (!mKeyguardDrawnOnce && mAwake) {
5336                mKeyguardDrawnOnce = true;
5337                enableScreen = true;
5338                if (mBootMessageNeedsHiding) {
5339                    mBootMessageNeedsHiding = false;
5340                    hideBootMessages();
5341                }
5342            } else {
5343                enableScreen = false;
5344            }
5345        }
5346
5347        if (listener != null) {
5348            listener.onScreenOn();
5349        }
5350
5351        if (enableScreen) {
5352            try {
5353                mWindowManager.enableScreenIfNeeded();
5354            } catch (RemoteException unhandled) {
5355            }
5356        }
5357    }
5358
5359    private void handleHideBootMessage() {
5360        synchronized (mLock) {
5361            if (!mKeyguardDrawnOnce) {
5362                mBootMessageNeedsHiding = true;
5363                return; // keyguard hasn't drawn the first time yet, not done booting
5364            }
5365        }
5366
5367        if (mBootMsgDialog != null) {
5368            if (DEBUG_WAKEUP) Slog.d(TAG, "handleHideBootMessage: dismissing");
5369            mBootMsgDialog.dismiss();
5370            mBootMsgDialog = null;
5371        }
5372    }
5373
5374    @Override
5375    public boolean isScreenOn() {
5376        return mScreenOnFully;
5377    }
5378
5379    /** {@inheritDoc} */
5380    @Override
5381    public void enableKeyguard(boolean enabled) {
5382        if (mKeyguardDelegate != null) {
5383            mKeyguardDelegate.setKeyguardEnabled(enabled);
5384        }
5385    }
5386
5387    /** {@inheritDoc} */
5388    @Override
5389    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
5390        if (mKeyguardDelegate != null) {
5391            mKeyguardDelegate.verifyUnlock(callback);
5392        }
5393    }
5394
5395    private boolean isKeyguardShowingAndNotOccluded() {
5396        if (mKeyguardDelegate == null) return false;
5397        return mKeyguardDelegate.isShowing() && !mKeyguardOccluded;
5398    }
5399
5400    /** {@inheritDoc} */
5401    @Override
5402    public boolean isKeyguardLocked() {
5403        return keyguardOn();
5404    }
5405
5406    /** {@inheritDoc} */
5407    @Override
5408    public boolean isKeyguardSecure() {
5409        if (mKeyguardDelegate == null) return false;
5410        return mKeyguardDelegate.isSecure();
5411    }
5412
5413    /** {@inheritDoc} */
5414    @Override
5415    public boolean inKeyguardRestrictedKeyInputMode() {
5416        if (mKeyguardDelegate == null) return false;
5417        return mKeyguardDelegate.isInputRestricted();
5418    }
5419
5420    @Override
5421    public void dismissKeyguardLw() {
5422        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
5423            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.dismissKeyguardLw");
5424            mHandler.post(new Runnable() {
5425                @Override
5426                public void run() {
5427                    // ask the keyguard to prompt the user to authenticate if necessary
5428                    mKeyguardDelegate.dismiss();
5429                }
5430            });
5431        }
5432    }
5433
5434    public void notifyActivityDrawnForKeyguardLw() {
5435        if (mKeyguardDelegate != null) {
5436            mHandler.post(new Runnable() {
5437                @Override
5438                public void run() {
5439                    mKeyguardDelegate.onActivityDrawn();
5440                }
5441            });
5442        }
5443    }
5444
5445    @Override
5446    public boolean isKeyguardDrawnLw() {
5447        synchronized (mLock) {
5448            return mKeyguardDrawnOnce;
5449        }
5450    }
5451
5452    @Override
5453    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
5454        if (mKeyguardDelegate != null) {
5455            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation");
5456            mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration);
5457        }
5458    }
5459
5460    void sendCloseSystemWindows() {
5461        PhoneWindow.sendCloseSystemWindows(mContext, null);
5462    }
5463
5464    void sendCloseSystemWindows(String reason) {
5465        PhoneWindow.sendCloseSystemWindows(mContext, reason);
5466    }
5467
5468    @Override
5469    public int rotationForOrientationLw(int orientation, int lastRotation) {
5470        if (false) {
5471            Slog.v(TAG, "rotationForOrientationLw(orient="
5472                        + orientation + ", last=" + lastRotation
5473                        + "); user=" + mUserRotation + " "
5474                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
5475                            ? "USER_ROTATION_LOCKED" : "")
5476                        );
5477        }
5478
5479        if (mForceDefaultOrientation) {
5480            return Surface.ROTATION_0;
5481        }
5482
5483        synchronized (mLock) {
5484            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
5485            if (sensorRotation < 0) {
5486                sensorRotation = lastRotation;
5487            }
5488
5489            final int preferredRotation;
5490            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
5491                // Ignore sensor when lid switch is open and rotation is forced.
5492                preferredRotation = mLidOpenRotation;
5493            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
5494                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
5495                // Ignore sensor when in car dock unless explicitly enabled.
5496                // This case can override the behavior of NOSENSOR, and can also
5497                // enable 180 degree rotation while docked.
5498                preferredRotation = mCarDockEnablesAccelerometer
5499                        ? sensorRotation : mCarDockRotation;
5500            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
5501                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
5502                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
5503                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
5504                // Ignore sensor when in desk dock unless explicitly enabled.
5505                // This case can override the behavior of NOSENSOR, and can also
5506                // enable 180 degree rotation while docked.
5507                preferredRotation = mDeskDockEnablesAccelerometer
5508                        ? sensorRotation : mDeskDockRotation;
5509            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
5510                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
5511                // Note that the dock orientation overrides the HDMI orientation.
5512                preferredRotation = mDemoHdmiRotation;
5513            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
5514                    && mUndockedHdmiRotation >= 0) {
5515                // Ignore sensor when plugged into HDMI and an undocked orientation has
5516                // been specified in the configuration (only for legacy devices without
5517                // full multi-display support).
5518                // Note that the dock orientation overrides the HDMI orientation.
5519                preferredRotation = mUndockedHdmiRotation;
5520            } else if (mDemoRotationLock) {
5521                // Ignore sensor when demo rotation lock is enabled.
5522                // Note that the dock orientation and HDMI rotation lock override this.
5523                preferredRotation = mDemoRotation;
5524            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
5525                // Application just wants to remain locked in the last rotation.
5526                preferredRotation = lastRotation;
5527            } else if (!mSupportAutoRotation) {
5528                // If we don't support auto-rotation then bail out here and ignore
5529                // the sensor and any rotation lock settings.
5530                preferredRotation = -1;
5531            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
5532                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
5533                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
5534                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
5535                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
5536                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
5537                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
5538                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
5539                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
5540                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
5541                // Otherwise, use sensor only if requested by the application or enabled
5542                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
5543                if (mAllowAllRotations < 0) {
5544                    // Can't read this during init() because the context doesn't
5545                    // have display metrics at that time so we cannot determine
5546                    // tablet vs. phone then.
5547                    mAllowAllRotations = mContext.getResources().getBoolean(
5548                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
5549                }
5550                if (sensorRotation != Surface.ROTATION_180
5551                        || mAllowAllRotations == 1
5552                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
5553                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
5554                    preferredRotation = sensorRotation;
5555                } else {
5556                    preferredRotation = lastRotation;
5557                }
5558            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
5559                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
5560                // Apply rotation lock.  Does not apply to NOSENSOR.
5561                // The idea is that the user rotation expresses a weak preference for the direction
5562                // of gravity and as NOSENSOR is never affected by gravity, then neither should
5563                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
5564                preferredRotation = mUserRotation;
5565            } else {
5566                // No overriding preference.
5567                // We will do exactly what the application asked us to do.
5568                preferredRotation = -1;
5569            }
5570
5571            switch (orientation) {
5572                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
5573                    // Return portrait unless overridden.
5574                    if (isAnyPortrait(preferredRotation)) {
5575                        return preferredRotation;
5576                    }
5577                    return mPortraitRotation;
5578
5579                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
5580                    // Return landscape unless overridden.
5581                    if (isLandscapeOrSeascape(preferredRotation)) {
5582                        return preferredRotation;
5583                    }
5584                    return mLandscapeRotation;
5585
5586                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
5587                    // Return reverse portrait unless overridden.
5588                    if (isAnyPortrait(preferredRotation)) {
5589                        return preferredRotation;
5590                    }
5591                    return mUpsideDownRotation;
5592
5593                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
5594                    // Return seascape unless overridden.
5595                    if (isLandscapeOrSeascape(preferredRotation)) {
5596                        return preferredRotation;
5597                    }
5598                    return mSeascapeRotation;
5599
5600                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
5601                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
5602                    // Return either landscape rotation.
5603                    if (isLandscapeOrSeascape(preferredRotation)) {
5604                        return preferredRotation;
5605                    }
5606                    if (isLandscapeOrSeascape(lastRotation)) {
5607                        return lastRotation;
5608                    }
5609                    return mLandscapeRotation;
5610
5611                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
5612                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
5613                    // Return either portrait rotation.
5614                    if (isAnyPortrait(preferredRotation)) {
5615                        return preferredRotation;
5616                    }
5617                    if (isAnyPortrait(lastRotation)) {
5618                        return lastRotation;
5619                    }
5620                    return mPortraitRotation;
5621
5622                default:
5623                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
5624                    // just return the preferred orientation we already calculated.
5625                    if (preferredRotation >= 0) {
5626                        return preferredRotation;
5627                    }
5628                    return Surface.ROTATION_0;
5629            }
5630        }
5631    }
5632
5633    @Override
5634    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
5635        switch (orientation) {
5636            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
5637            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
5638            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
5639                return isAnyPortrait(rotation);
5640
5641            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
5642            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
5643            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
5644                return isLandscapeOrSeascape(rotation);
5645
5646            default:
5647                return true;
5648        }
5649    }
5650
5651    @Override
5652    public void setRotationLw(int rotation) {
5653        mOrientationListener.setCurrentRotation(rotation);
5654    }
5655
5656    private boolean isLandscapeOrSeascape(int rotation) {
5657        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
5658    }
5659
5660    private boolean isAnyPortrait(int rotation) {
5661        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
5662    }
5663
5664    @Override
5665    public int getUserRotationMode() {
5666        return Settings.System.getIntForUser(mContext.getContentResolver(),
5667                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
5668                        WindowManagerPolicy.USER_ROTATION_FREE :
5669                                WindowManagerPolicy.USER_ROTATION_LOCKED;
5670    }
5671
5672    // User rotation: to be used when all else fails in assigning an orientation to the device
5673    @Override
5674    public void setUserRotationMode(int mode, int rot) {
5675        ContentResolver res = mContext.getContentResolver();
5676
5677        // mUserRotationMode and mUserRotation will be assigned by the content observer
5678        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
5679            Settings.System.putIntForUser(res,
5680                    Settings.System.USER_ROTATION,
5681                    rot,
5682                    UserHandle.USER_CURRENT);
5683            Settings.System.putIntForUser(res,
5684                    Settings.System.ACCELEROMETER_ROTATION,
5685                    0,
5686                    UserHandle.USER_CURRENT);
5687        } else {
5688            Settings.System.putIntForUser(res,
5689                    Settings.System.ACCELEROMETER_ROTATION,
5690                    1,
5691                    UserHandle.USER_CURRENT);
5692        }
5693    }
5694
5695    @Override
5696    public void setSafeMode(boolean safeMode) {
5697        mSafeMode = safeMode;
5698        performHapticFeedbackLw(null, safeMode
5699                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
5700                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
5701    }
5702
5703    static long[] getLongIntArray(Resources r, int resid) {
5704        int[] ar = r.getIntArray(resid);
5705        if (ar == null) {
5706            return null;
5707        }
5708        long[] out = new long[ar.length];
5709        for (int i=0; i<ar.length; i++) {
5710            out[i] = ar[i];
5711        }
5712        return out;
5713    }
5714
5715    /** {@inheritDoc} */
5716    @Override
5717    public void systemReady() {
5718        mKeyguardDelegate = new KeyguardServiceDelegate(mContext);
5719        mKeyguardDelegate.onSystemReady();
5720
5721        readCameraLensCoverState();
5722        updateUiMode();
5723        synchronized (mLock) {
5724            updateOrientationListenerLp();
5725            mSystemReady = true;
5726            mHandler.post(new Runnable() {
5727                @Override
5728                public void run() {
5729                    updateSettings();
5730                }
5731            });
5732        }
5733    }
5734
5735    /** {@inheritDoc} */
5736    @Override
5737    public void systemBooted() {
5738        if (mKeyguardDelegate != null) {
5739            mKeyguardDelegate.bindService(mContext);
5740            mKeyguardDelegate.onBootCompleted();
5741        }
5742        synchronized (mLock) {
5743            mSystemBooted = true;
5744        }
5745        wakingUp();
5746        screenTurningOn(null);
5747    }
5748
5749    ProgressDialog mBootMsgDialog = null;
5750
5751    /** {@inheritDoc} */
5752    @Override
5753    public void showBootMessage(final CharSequence msg, final boolean always) {
5754        mHandler.post(new Runnable() {
5755            @Override public void run() {
5756                if (mBootMsgDialog == null) {
5757                    int theme;
5758                    if (mContext.getPackageManager().hasSystemFeature(
5759                            PackageManager.FEATURE_WATCH)) {
5760                        theme = com.android.internal.R.style.Theme_Micro_Dialog_Alert;
5761                    } else if (mContext.getPackageManager().hasSystemFeature(
5762                            PackageManager.FEATURE_TELEVISION)) {
5763                        theme = com.android.internal.R.style.Theme_Leanback_Dialog_Alert;
5764                    } else {
5765                        theme = 0;
5766                    }
5767
5768                    mBootMsgDialog = new ProgressDialog(mContext, theme) {
5769                        // This dialog will consume all events coming in to
5770                        // it, to avoid it trying to do things too early in boot.
5771                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
5772                            return true;
5773                        }
5774                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5775                            return true;
5776                        }
5777                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
5778                            return true;
5779                        }
5780                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
5781                            return true;
5782                        }
5783                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
5784                            return true;
5785                        }
5786                        @Override public boolean dispatchPopulateAccessibilityEvent(
5787                                AccessibilityEvent event) {
5788                            return true;
5789                        }
5790                    };
5791                    if (mContext.getPackageManager().isUpgrade()) {
5792                        mBootMsgDialog.setTitle(R.string.android_upgrading_title);
5793                    } else {
5794                        mBootMsgDialog.setTitle(R.string.android_start_title);
5795                    }
5796                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
5797                    mBootMsgDialog.setIndeterminate(true);
5798                    mBootMsgDialog.getWindow().setType(
5799                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
5800                    mBootMsgDialog.getWindow().addFlags(
5801                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
5802                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
5803                    mBootMsgDialog.getWindow().setDimAmount(1);
5804                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
5805                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
5806                    mBootMsgDialog.getWindow().setAttributes(lp);
5807                    mBootMsgDialog.setCancelable(false);
5808                    mBootMsgDialog.show();
5809                }
5810                mBootMsgDialog.setMessage(msg);
5811            }
5812        });
5813    }
5814
5815    /** {@inheritDoc} */
5816    @Override
5817    public void hideBootMessages() {
5818        mHandler.sendEmptyMessage(MSG_HIDE_BOOT_MESSAGE);
5819    }
5820
5821    /** {@inheritDoc} */
5822    @Override
5823    public void userActivity() {
5824        // ***************************************
5825        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
5826        // ***************************************
5827        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
5828        // WITH ITS LOCKS HELD.
5829        //
5830        // This code must be VERY careful about the locks
5831        // it acquires.
5832        // In fact, the current code acquires way too many,
5833        // and probably has lurking deadlocks.
5834
5835        synchronized (mScreenLockTimeout) {
5836            if (mLockScreenTimerActive) {
5837                // reset the timer
5838                mHandler.removeCallbacks(mScreenLockTimeout);
5839                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
5840            }
5841        }
5842    }
5843
5844    class ScreenLockTimeout implements Runnable {
5845        Bundle options;
5846
5847        @Override
5848        public void run() {
5849            synchronized (this) {
5850                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
5851                if (mKeyguardDelegate != null) {
5852                    mKeyguardDelegate.doKeyguardTimeout(options);
5853                }
5854                mLockScreenTimerActive = false;
5855                options = null;
5856            }
5857        }
5858
5859        public void setLockOptions(Bundle options) {
5860            this.options = options;
5861        }
5862    }
5863
5864    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
5865
5866    @Override
5867    public void lockNow(Bundle options) {
5868        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
5869        mHandler.removeCallbacks(mScreenLockTimeout);
5870        if (options != null) {
5871            // In case multiple calls are made to lockNow, we don't wipe out the options
5872            // until the runnable actually executes.
5873            mScreenLockTimeout.setLockOptions(options);
5874        }
5875        mHandler.post(mScreenLockTimeout);
5876    }
5877
5878    private void updateLockScreenTimeout() {
5879        synchronized (mScreenLockTimeout) {
5880            boolean enable = (mAllowLockscreenWhenOn && mAwake &&
5881                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
5882            if (mLockScreenTimerActive != enable) {
5883                if (enable) {
5884                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
5885                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
5886                } else {
5887                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
5888                    mHandler.removeCallbacks(mScreenLockTimeout);
5889                }
5890                mLockScreenTimerActive = enable;
5891            }
5892        }
5893    }
5894
5895    private void updateDreamingSleepToken(boolean acquire) {
5896        if (acquire) {
5897            if (mDreamingSleepToken == null) {
5898                mDreamingSleepToken = mActivityManagerInternal.acquireSleepToken("Dream");
5899            }
5900        } else {
5901            if (mDreamingSleepToken != null) {
5902                mDreamingSleepToken.release();
5903            }
5904        }
5905    }
5906
5907    /** {@inheritDoc} */
5908    @Override
5909    public void enableScreenAfterBoot() {
5910        readLidState();
5911        applyLidSwitchState();
5912        updateRotation(true);
5913    }
5914
5915    private void applyLidSwitchState() {
5916        if (mLidState == LID_CLOSED && mLidControlsSleep) {
5917            mPowerManager.goToSleep(SystemClock.uptimeMillis(),
5918                    PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
5919                    PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
5920        }
5921
5922        synchronized (mLock) {
5923            updateWakeGestureListenerLp();
5924        }
5925    }
5926
5927    void updateUiMode() {
5928        if (mUiModeManager == null) {
5929            mUiModeManager = IUiModeManager.Stub.asInterface(
5930                    ServiceManager.getService(Context.UI_MODE_SERVICE));
5931        }
5932        try {
5933            mUiMode = mUiModeManager.getCurrentModeType();
5934        } catch (RemoteException e) {
5935        }
5936    }
5937
5938    void updateRotation(boolean alwaysSendConfiguration) {
5939        try {
5940            //set orientation on WindowManager
5941            mWindowManager.updateRotation(alwaysSendConfiguration, false);
5942        } catch (RemoteException e) {
5943            // Ignore
5944        }
5945    }
5946
5947    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
5948        try {
5949            //set orientation on WindowManager
5950            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
5951        } catch (RemoteException e) {
5952            // Ignore
5953        }
5954    }
5955
5956    /**
5957     * Return an Intent to launch the currently active dock app as home.  Returns
5958     * null if the standard home should be launched, which is the case if any of the following is
5959     * true:
5960     * <ul>
5961     *  <li>The device is not in either car mode or desk mode
5962     *  <li>The device is in car mode but ENABLE_CAR_DOCK_HOME_CAPTURE is false
5963     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
5964     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
5965     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
5966     * </ul>
5967     * @return A dock intent.
5968     */
5969    Intent createHomeDockIntent() {
5970        Intent intent = null;
5971
5972        // What home does is based on the mode, not the dock state.  That
5973        // is, when in car mode you should be taken to car home regardless
5974        // of whether we are actually in a car dock.
5975        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
5976            if (ENABLE_CAR_DOCK_HOME_CAPTURE) {
5977                intent = mCarDockIntent;
5978            }
5979        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
5980            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
5981                intent = mDeskDockIntent;
5982            }
5983        } else if (mUiMode == Configuration.UI_MODE_TYPE_WATCH
5984                && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
5985                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK
5986                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK)) {
5987            // Always launch dock home from home when watch is docked, if it exists.
5988            intent = mDeskDockIntent;
5989        }
5990
5991        if (intent == null) {
5992            return null;
5993        }
5994
5995        ActivityInfo ai = null;
5996        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
5997                intent,
5998                PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
5999                mCurrentUserId);
6000        if (info != null) {
6001            ai = info.activityInfo;
6002        }
6003        if (ai != null
6004                && ai.metaData != null
6005                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
6006            intent = new Intent(intent);
6007            intent.setClassName(ai.packageName, ai.name);
6008            return intent;
6009        }
6010
6011        return null;
6012    }
6013
6014    void startDockOrHome(boolean fromHomeKey, boolean awakenFromDreams) {
6015        if (awakenFromDreams) {
6016            awakenDreams();
6017        }
6018
6019        Intent dock = createHomeDockIntent();
6020        if (dock != null) {
6021            try {
6022                if (fromHomeKey) {
6023                    dock.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6024                }
6025                startActivityAsUser(dock, UserHandle.CURRENT);
6026                return;
6027            } catch (ActivityNotFoundException e) {
6028            }
6029        }
6030
6031        Intent intent;
6032
6033        if (fromHomeKey) {
6034            intent = new Intent(mHomeIntent);
6035            intent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6036        } else {
6037            intent = mHomeIntent;
6038        }
6039
6040        startActivityAsUser(intent, UserHandle.CURRENT);
6041    }
6042
6043    /**
6044     * goes to the home screen
6045     * @return whether it did anything
6046     */
6047    boolean goHome() {
6048        if (!isUserSetupComplete()) {
6049            Slog.i(TAG, "Not going home because user setup is in progress.");
6050            return false;
6051        }
6052        if (false) {
6053            // This code always brings home to the front.
6054            try {
6055                ActivityManagerNative.getDefault().stopAppSwitches();
6056            } catch (RemoteException e) {
6057            }
6058            sendCloseSystemWindows();
6059            startDockOrHome(false /*fromHomeKey*/, true /* awakenFromDreams */);
6060        } else {
6061            // This code brings home to the front or, if it is already
6062            // at the front, puts the device to sleep.
6063            try {
6064                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
6065                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
6066                    Log.d(TAG, "UTS-TEST-MODE");
6067                } else {
6068                    ActivityManagerNative.getDefault().stopAppSwitches();
6069                    sendCloseSystemWindows();
6070                    Intent dock = createHomeDockIntent();
6071                    if (dock != null) {
6072                        int result = ActivityManagerNative.getDefault()
6073                                .startActivityAsUser(null, null, dock,
6074                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
6075                                        null, null, 0,
6076                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6077                                        null, null, UserHandle.USER_CURRENT);
6078                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6079                            return false;
6080                        }
6081                    }
6082                }
6083                int result = ActivityManagerNative.getDefault()
6084                        .startActivityAsUser(null, null, mHomeIntent,
6085                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
6086                                null, null, 0,
6087                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6088                                null, null, UserHandle.USER_CURRENT);
6089                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6090                    return false;
6091                }
6092            } catch (RemoteException ex) {
6093                // bummer, the activity manager, which is in this process, is dead
6094            }
6095        }
6096        return true;
6097    }
6098
6099    @Override
6100    public void setCurrentOrientationLw(int newOrientation) {
6101        synchronized (mLock) {
6102            if (newOrientation != mCurrentAppOrientation) {
6103                mCurrentAppOrientation = newOrientation;
6104                updateOrientationListenerLp();
6105            }
6106        }
6107    }
6108
6109    private void performAuditoryFeedbackForAccessibilityIfNeed() {
6110        if (!isGlobalAccessibilityGestureEnabled()) {
6111            return;
6112        }
6113        AudioManager audioManager = (AudioManager) mContext.getSystemService(
6114                Context.AUDIO_SERVICE);
6115        if (audioManager.isSilentMode()) {
6116            return;
6117        }
6118        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
6119                Settings.System.DEFAULT_NOTIFICATION_URI);
6120        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
6121        ringTone.play();
6122    }
6123
6124    private boolean isTheaterModeEnabled() {
6125        return Settings.Global.getInt(mContext.getContentResolver(),
6126                Settings.Global.THEATER_MODE_ON, 0) == 1;
6127    }
6128
6129    private boolean isGlobalAccessibilityGestureEnabled() {
6130        return Settings.Global.getInt(mContext.getContentResolver(),
6131                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
6132    }
6133
6134    @Override
6135    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
6136        if (!mVibrator.hasVibrator()) {
6137            return false;
6138        }
6139        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
6140                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
6141        if (hapticsDisabled && !always) {
6142            return false;
6143        }
6144        long[] pattern = null;
6145        switch (effectId) {
6146            case HapticFeedbackConstants.LONG_PRESS:
6147                pattern = mLongPressVibePattern;
6148                break;
6149            case HapticFeedbackConstants.VIRTUAL_KEY:
6150                pattern = mVirtualKeyVibePattern;
6151                break;
6152            case HapticFeedbackConstants.KEYBOARD_TAP:
6153                pattern = mKeyboardTapVibePattern;
6154                break;
6155            case HapticFeedbackConstants.CLOCK_TICK:
6156                pattern = mClockTickVibePattern;
6157                break;
6158            case HapticFeedbackConstants.CALENDAR_DATE:
6159                pattern = mCalendarDateVibePattern;
6160                break;
6161            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
6162                pattern = mSafeModeDisabledVibePattern;
6163                break;
6164            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
6165                pattern = mSafeModeEnabledVibePattern;
6166                break;
6167            default:
6168                return false;
6169        }
6170        int owningUid;
6171        String owningPackage;
6172        if (win != null) {
6173            owningUid = win.getOwningUid();
6174            owningPackage = win.getOwningPackage();
6175        } else {
6176            owningUid = android.os.Process.myUid();
6177            owningPackage = mContext.getOpPackageName();
6178        }
6179        if (pattern.length == 1) {
6180            // One-shot vibration
6181            mVibrator.vibrate(owningUid, owningPackage, pattern[0], VIBRATION_ATTRIBUTES);
6182        } else {
6183            // Pattern vibration
6184            mVibrator.vibrate(owningUid, owningPackage, pattern, -1, VIBRATION_ATTRIBUTES);
6185        }
6186        return true;
6187    }
6188
6189    @Override
6190    public void keepScreenOnStartedLw() {
6191    }
6192
6193    @Override
6194    public void keepScreenOnStoppedLw() {
6195        if (isKeyguardShowingAndNotOccluded()) {
6196            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
6197        }
6198    }
6199
6200    private int updateSystemUiVisibilityLw() {
6201        // If there is no window focused, there will be nobody to handle the events
6202        // anyway, so just hang on in whatever state we're in until things settle down.
6203        final WindowState win = mFocusedWindow != null ? mFocusedWindow
6204                : mTopFullscreenOpaqueWindowState;
6205        if (win == null) {
6206            return 0;
6207        }
6208        if ((win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 && mHideLockScreen == true) {
6209            // We are updating at a point where the keyguard has gotten
6210            // focus, but we were last in a state where the top window is
6211            // hiding it.  This is probably because the keyguard as been
6212            // shown while the top window was displayed, so we want to ignore
6213            // it here because this is just a very transient change and it
6214            // will quickly lose focus once it correctly gets hidden.
6215            return 0;
6216        }
6217
6218        int tmpVisibility = PolicyControl.getSystemUiVisibility(win, null)
6219                & ~mResettingSystemUiFlags
6220                & ~mForceClearedSystemUiFlags;
6221        if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
6222            tmpVisibility &= ~PolicyControl.adjustClearableFlags(win, View.SYSTEM_UI_CLEARABLE_FLAGS);
6223        }
6224        tmpVisibility = updateLightStatusBarLw(tmpVisibility);
6225        final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
6226        final int diff = visibility ^ mLastSystemUiFlags;
6227        final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
6228        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
6229                && mFocusedApp == win.getAppToken()) {
6230            return 0;
6231        }
6232        mLastSystemUiFlags = visibility;
6233        mLastFocusNeedsMenu = needsMenu;
6234        mFocusedApp = win.getAppToken();
6235        mHandler.post(new Runnable() {
6236                @Override
6237                public void run() {
6238                    try {
6239                        IStatusBarService statusbar = getStatusBarService();
6240                        if (statusbar != null) {
6241                            statusbar.setSystemUiVisibility(visibility, 0xffffffff, win.toString());
6242                            statusbar.topAppWindowChanged(needsMenu);
6243                        }
6244                    } catch (RemoteException e) {
6245                        // re-acquire status bar service next time it is needed.
6246                        mStatusBarService = null;
6247                    }
6248                }
6249            });
6250        return diff;
6251    }
6252
6253    private int updateLightStatusBarLw(int vis) {
6254        WindowState statusColorWin = isStatusBarKeyguard() && !mHideLockScreen
6255                ? mStatusBar
6256                : mTopFullscreenOpaqueOrDimmingWindowState;
6257
6258        if (statusColorWin != null) {
6259            if (statusColorWin == mTopFullscreenOpaqueWindowState) {
6260                // If the top fullscreen-or-dimming window is also the top fullscreen, respect
6261                // its light flag.
6262                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6263                vis |= PolicyControl.getSystemUiVisibility(statusColorWin, null)
6264                        & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6265            } else if (statusColorWin != null && statusColorWin.isDimming()) {
6266                // Otherwise if it's dimming, clear the light flag.
6267                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6268            }
6269        }
6270        return vis;
6271    }
6272
6273    private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
6274        // apply translucent bar vis flags
6275        WindowState transWin = isStatusBarKeyguard() && !mHideLockScreen
6276                ? mStatusBar
6277                : mTopFullscreenOpaqueWindowState;
6278        vis = mStatusBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
6279        vis = mNavigationBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
6280
6281        // prevent status bar interaction from clearing certain flags
6282        boolean statusBarHasFocus = win.getAttrs().type == TYPE_STATUS_BAR;
6283        if (statusBarHasFocus && !isStatusBarKeyguard()) {
6284            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
6285                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
6286                    | View.SYSTEM_UI_FLAG_IMMERSIVE
6287                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
6288                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6289            if (mHideLockScreen) {
6290                flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
6291            }
6292            vis = (vis & ~flags) | (oldVis & flags);
6293        }
6294
6295        if (!areTranslucentBarsAllowed() && transWin != mStatusBar) {
6296            vis &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSLUCENT
6297                    | View.SYSTEM_UI_TRANSPARENT);
6298        }
6299
6300        // update status bar
6301        boolean immersiveSticky =
6302                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
6303        boolean hideStatusBarWM =
6304                mTopFullscreenOpaqueWindowState != null &&
6305                (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
6306                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
6307        boolean hideStatusBarSysui =
6308                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
6309        boolean hideNavBarSysui =
6310                (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
6311
6312        boolean transientStatusBarAllowed =
6313                mStatusBar != null && (
6314                hideStatusBarWM
6315                || (hideStatusBarSysui && immersiveSticky)
6316                || statusBarHasFocus);
6317
6318        boolean transientNavBarAllowed =
6319                mNavigationBar != null &&
6320                hideNavBarSysui && immersiveSticky;
6321
6322        boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
6323                && !transientStatusBarAllowed && hideStatusBarSysui;
6324        boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
6325                && !transientNavBarAllowed;
6326        if (denyTransientStatus || denyTransientNav) {
6327            // clear the clearable flags instead
6328            clearClearableFlagsLw();
6329            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
6330        }
6331
6332        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
6333
6334        // update navigation bar
6335        boolean oldImmersiveMode = isImmersiveMode(oldVis);
6336        boolean newImmersiveMode = isImmersiveMode(vis);
6337        if (win != null && oldImmersiveMode != newImmersiveMode) {
6338            final String pkg = win.getOwningPackage();
6339            mImmersiveModeConfirmation.immersiveModeChanged(pkg, newImmersiveMode,
6340                    isUserSetupComplete());
6341        }
6342
6343        vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
6344
6345        return vis;
6346    }
6347
6348    private void clearClearableFlagsLw() {
6349        int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
6350        if (newVal != mResettingSystemUiFlags) {
6351            mResettingSystemUiFlags = newVal;
6352            mWindowManagerFuncs.reevaluateStatusBarVisibility();
6353        }
6354    }
6355
6356    private boolean isImmersiveMode(int vis) {
6357        final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
6358        return mNavigationBar != null
6359                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
6360                && (vis & flags) != 0
6361                && canHideNavigationBar();
6362    }
6363
6364    /**
6365     * @return whether the navigation or status bar can be made translucent
6366     *
6367     * This should return true unless touch exploration is not enabled or
6368     * R.boolean.config_enableTranslucentDecor is false.
6369     */
6370    private boolean areTranslucentBarsAllowed() {
6371        return mTranslucentDecorEnabled
6372                && !mAccessibilityManager.isTouchExplorationEnabled();
6373    }
6374
6375    // Use this instead of checking config_showNavigationBar so that it can be consistently
6376    // overridden by qemu.hw.mainkeys in the emulator.
6377    @Override
6378    public boolean hasNavigationBar() {
6379        return mHasNavigationBar;
6380    }
6381
6382    @Override
6383    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
6384        mLastInputMethodWindow = ime;
6385        mLastInputMethodTargetWindow = target;
6386    }
6387
6388    @Override
6389    public int getInputMethodWindowVisibleHeightLw() {
6390        return mDockBottom - mCurBottom;
6391    }
6392
6393    @Override
6394    public void setCurrentUserLw(int newUserId) {
6395        mCurrentUserId = newUserId;
6396        if (mKeyguardDelegate != null) {
6397            mKeyguardDelegate.setCurrentUser(newUserId);
6398        }
6399        if (mStatusBarService != null) {
6400            try {
6401                mStatusBarService.setCurrentUser(newUserId);
6402            } catch (RemoteException e) {
6403                // oh well
6404            }
6405        }
6406        setLastInputMethodWindowLw(null, null);
6407    }
6408
6409    @Override
6410    public boolean canMagnifyWindow(int windowType) {
6411        switch (windowType) {
6412            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
6413            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
6414            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
6415            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
6416                return false;
6417            }
6418        }
6419        return true;
6420    }
6421
6422    @Override
6423    public boolean isTopLevelWindow(int windowType) {
6424        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
6425                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
6426            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
6427        }
6428        return true;
6429    }
6430
6431    @Override
6432    public void dump(String prefix, PrintWriter pw, String[] args) {
6433        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
6434                pw.print(" mSystemReady="); pw.print(mSystemReady);
6435                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
6436        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
6437                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
6438                pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
6439                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
6440        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
6441                || mForceClearedSystemUiFlags != 0) {
6442            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
6443                    pw.print(Integer.toHexString(mLastSystemUiFlags));
6444                    pw.print(" mResettingSystemUiFlags=0x");
6445                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
6446                    pw.print(" mForceClearedSystemUiFlags=0x");
6447                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
6448        }
6449        if (mLastFocusNeedsMenu) {
6450            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
6451                    pw.println(mLastFocusNeedsMenu);
6452        }
6453        pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
6454                pw.println(mWakeGestureEnabledSetting);
6455
6456        pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
6457        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
6458                pw.print(" mDockMode="); pw.print(mDockMode);
6459                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
6460                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
6461        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
6462                pw.print(" mUserRotation="); pw.print(mUserRotation);
6463                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
6464        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
6465        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
6466                pw.print(mCarDockEnablesAccelerometer);
6467                pw.print(" mDeskDockEnablesAccelerometer=");
6468                pw.println(mDeskDockEnablesAccelerometer);
6469        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
6470                pw.print(mLidKeyboardAccessibility);
6471                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
6472                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
6473        pw.print(prefix);
6474                pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
6475                pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
6476        pw.print(prefix);
6477                pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
6478                pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
6479        pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
6480        pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
6481        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
6482                pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
6483        pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
6484                pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
6485        pw.print(prefix); pw.print("mOrientationSensorEnabled=");
6486                pw.println(mOrientationSensorEnabled);
6487        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
6488                pw.print(","); pw.print(mOverscanScreenTop);
6489                pw.print(") "); pw.print(mOverscanScreenWidth);
6490                pw.print("x"); pw.println(mOverscanScreenHeight);
6491        if (mOverscanLeft != 0 || mOverscanTop != 0
6492                || mOverscanRight != 0 || mOverscanBottom != 0) {
6493            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
6494                    pw.print(" top="); pw.print(mOverscanTop);
6495                    pw.print(" right="); pw.print(mOverscanRight);
6496                    pw.print(" bottom="); pw.println(mOverscanBottom);
6497        }
6498        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
6499                pw.print(mRestrictedOverscanScreenLeft);
6500                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
6501                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
6502                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
6503        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
6504                pw.print(","); pw.print(mUnrestrictedScreenTop);
6505                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
6506                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
6507        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
6508                pw.print(","); pw.print(mRestrictedScreenTop);
6509                pw.print(") "); pw.print(mRestrictedScreenWidth);
6510                pw.print("x"); pw.println(mRestrictedScreenHeight);
6511        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
6512                pw.print(","); pw.print(mStableFullscreenTop);
6513                pw.print(")-("); pw.print(mStableFullscreenRight);
6514                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
6515        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
6516                pw.print(","); pw.print(mStableTop);
6517                pw.print(")-("); pw.print(mStableRight);
6518                pw.print(","); pw.print(mStableBottom); pw.println(")");
6519        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
6520                pw.print(","); pw.print(mSystemTop);
6521                pw.print(")-("); pw.print(mSystemRight);
6522                pw.print(","); pw.print(mSystemBottom); pw.println(")");
6523        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
6524                pw.print(","); pw.print(mCurTop);
6525                pw.print(")-("); pw.print(mCurRight);
6526                pw.print(","); pw.print(mCurBottom); pw.println(")");
6527        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
6528                pw.print(","); pw.print(mContentTop);
6529                pw.print(")-("); pw.print(mContentRight);
6530                pw.print(","); pw.print(mContentBottom); pw.println(")");
6531        pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
6532                pw.print(","); pw.print(mVoiceContentTop);
6533                pw.print(")-("); pw.print(mVoiceContentRight);
6534                pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
6535        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
6536                pw.print(","); pw.print(mDockTop);
6537                pw.print(")-("); pw.print(mDockRight);
6538                pw.print(","); pw.print(mDockBottom); pw.println(")");
6539        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
6540                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
6541        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
6542                pw.print(" mShowingDream="); pw.print(mShowingDream);
6543                pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
6544                pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
6545        if (mLastInputMethodWindow != null) {
6546            pw.print(prefix); pw.print("mLastInputMethodWindow=");
6547                    pw.println(mLastInputMethodWindow);
6548        }
6549        if (mLastInputMethodTargetWindow != null) {
6550            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
6551                    pw.println(mLastInputMethodTargetWindow);
6552        }
6553        if (mStatusBar != null) {
6554            pw.print(prefix); pw.print("mStatusBar=");
6555                    pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
6556                    pw.println(isStatusBarKeyguard());
6557        }
6558        if (mNavigationBar != null) {
6559            pw.print(prefix); pw.print("mNavigationBar=");
6560                    pw.println(mNavigationBar);
6561        }
6562        if (mFocusedWindow != null) {
6563            pw.print(prefix); pw.print("mFocusedWindow=");
6564                    pw.println(mFocusedWindow);
6565        }
6566        if (mFocusedApp != null) {
6567            pw.print(prefix); pw.print("mFocusedApp=");
6568                    pw.println(mFocusedApp);
6569        }
6570        if (mWinDismissingKeyguard != null) {
6571            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
6572                    pw.println(mWinDismissingKeyguard);
6573        }
6574        if (mTopFullscreenOpaqueWindowState != null) {
6575            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
6576                    pw.println(mTopFullscreenOpaqueWindowState);
6577        }
6578        if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
6579            pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
6580                    pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
6581        }
6582        if (mForcingShowNavBar) {
6583            pw.print(prefix); pw.print("mForcingShowNavBar=");
6584                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
6585                    pw.println(mForcingShowNavBarLayer);
6586        }
6587        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
6588                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
6589        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
6590                pw.print(" mForceStatusBarFromKeyguard=");
6591                pw.println(mForceStatusBarFromKeyguard);
6592        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
6593                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
6594                pw.print(" mHomePressed="); pw.println(mHomePressed);
6595        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
6596                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
6597                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
6598        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
6599                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
6600                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
6601        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
6602                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
6603        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
6604                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
6605        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
6606                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
6607        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
6608
6609        mGlobalKeyManager.dump(prefix, pw);
6610        mStatusBarController.dump(pw, prefix);
6611        mNavigationBarController.dump(pw, prefix);
6612        PolicyControl.dump(prefix, pw);
6613
6614        if (mWakeGestureListener != null) {
6615            mWakeGestureListener.dump(pw, prefix);
6616        }
6617        if (mOrientationListener != null) {
6618            mOrientationListener.dump(pw, prefix);
6619        }
6620        if (mBurnInProtectionHelper != null) {
6621            mBurnInProtectionHelper.dump(prefix, pw);
6622        }
6623    }
6624}
6625