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