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