PhoneWindowManager.java revision 9326dc1407e3942c35b197b7e0287ea4a50a56d8
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 = cf.left = vf.left = mUnrestrictedScreenLeft;
3743            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3744            pf.right = df.right = of.right = cf.right = vf.right = mUnrestrictedScreenLeft
3745                    + mUnrestrictedScreenWidth;
3746            pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
3747                    + mUnrestrictedScreenHeight;
3748            cf.bottom = vf.bottom = mStableBottom;
3749            cf.top = vf.top = mStableTop;
3750        } else if (win == mStatusBar) {
3751            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3752            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3753            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
3754            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight + mUnrestrictedScreenTop;
3755            cf.left = vf.left = mStableLeft;
3756            cf.top = vf.top = mStableTop;
3757            cf.right = vf.right = mStableRight;
3758            vf.bottom = mStableBottom;
3759            cf.bottom = mContentBottom;
3760        } else {
3761
3762            // Default policy decor for the default display
3763            dcf.left = mSystemLeft;
3764            dcf.top = mSystemTop;
3765            dcf.right = mSystemRight;
3766            dcf.bottom = mSystemBottom;
3767            final boolean inheritTranslucentDecor = (attrs.privateFlags
3768                    & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
3769            final boolean isAppWindow =
3770                    attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
3771                    attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
3772            final boolean topAtRest =
3773                    win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
3774            if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
3775                if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
3776                        && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
3777                        && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0
3778                        && (fl & WindowManager.LayoutParams.
3779                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
3780                    // Ensure policy decor includes status bar
3781                    dcf.top = mStableTop;
3782                }
3783                if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
3784                        && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
3785                        && (fl & WindowManager.LayoutParams.
3786                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
3787                    // Ensure policy decor includes navigation bar
3788                    dcf.bottom = mStableBottom;
3789                    dcf.right = mStableRight;
3790                }
3791            }
3792
3793            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3794                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3795                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
3796                            + "): IN_SCREEN, INSET_DECOR");
3797                // This is the case for a normal activity window: we want it
3798                // to cover all of the screen space, and it can take care of
3799                // moving its contents to account for screen decorations that
3800                // intrude into that space.
3801                if (attached != null) {
3802                    // If this window is attached to another, our display
3803                    // frame is the same as the one we are attached to.
3804                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
3805                } else {
3806                    if (attrs.type == TYPE_STATUS_BAR_PANEL
3807                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
3808                        // Status bar panels are the only windows who can go on top of
3809                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
3810                        // permission, so they have the same privileges as the status
3811                        // bar itself.
3812                        //
3813                        // However, they should still dodge the navigation bar if it exists.
3814
3815                        pf.left = df.left = of.left = hasNavBar
3816                                ? mDockLeft : mUnrestrictedScreenLeft;
3817                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
3818                        pf.right = df.right = of.right = hasNavBar
3819                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
3820                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3821                        pf.bottom = df.bottom = of.bottom = hasNavBar
3822                                ? mRestrictedScreenTop+mRestrictedScreenHeight
3823                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3824
3825                        if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3826                                        "Laying out status bar window: (%d,%d - %d,%d)",
3827                                        pf.left, pf.top, pf.right, pf.bottom));
3828                    } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
3829                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3830                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3831                        // Asking to layout into the overscan region, so give it that pure
3832                        // unrestricted area.
3833                        pf.left = df.left = of.left = mOverscanScreenLeft;
3834                        pf.top = df.top = of.top = mOverscanScreenTop;
3835                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
3836                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
3837                                + mOverscanScreenHeight;
3838                    } else if (canHideNavigationBar()
3839                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
3840                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3841                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3842                        // Asking for layout as if the nav bar is hidden, lets the
3843                        // application extend into the unrestricted overscan screen area.  We
3844                        // only do this for application windows to ensure no window that
3845                        // can be above the nav bar can do this.
3846                        pf.left = df.left = mOverscanScreenLeft;
3847                        pf.top = df.top = mOverscanScreenTop;
3848                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
3849                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
3850                        // We need to tell the app about where the frame inside the overscan
3851                        // is, so it can inset its content by that amount -- it didn't ask
3852                        // to actually extend itself into the overscan region.
3853                        of.left = mUnrestrictedScreenLeft;
3854                        of.top = mUnrestrictedScreenTop;
3855                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3856                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3857                    } else {
3858                        pf.left = df.left = mRestrictedOverscanScreenLeft;
3859                        pf.top = df.top = mRestrictedOverscanScreenTop;
3860                        pf.right = df.right = mRestrictedOverscanScreenLeft
3861                                + mRestrictedOverscanScreenWidth;
3862                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
3863                                + mRestrictedOverscanScreenHeight;
3864                        // We need to tell the app about where the frame inside the overscan
3865                        // is, so it can inset its content by that amount -- it didn't ask
3866                        // to actually extend itself into the overscan region.
3867                        of.left = mUnrestrictedScreenLeft;
3868                        of.top = mUnrestrictedScreenTop;
3869                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3870                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3871                    }
3872
3873                    if ((fl & FLAG_FULLSCREEN) == 0) {
3874                        if (win.isVoiceInteraction()) {
3875                            cf.left = mVoiceContentLeft;
3876                            cf.top = mVoiceContentTop;
3877                            cf.right = mVoiceContentRight;
3878                            cf.bottom = mVoiceContentBottom;
3879                        } else {
3880                            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3881                                cf.left = mDockLeft;
3882                                cf.top = mDockTop;
3883                                cf.right = mDockRight;
3884                                cf.bottom = mDockBottom;
3885                            } else {
3886                                cf.left = mContentLeft;
3887                                cf.top = mContentTop;
3888                                cf.right = mContentRight;
3889                                cf.bottom = mContentBottom;
3890                            }
3891                        }
3892                    } else {
3893                        // Full screen windows are always given a layout that is as if the
3894                        // status bar and other transient decors are gone.  This is to avoid
3895                        // bad states when moving from a window that is not hding the
3896                        // status bar to one that is.
3897                        cf.left = mRestrictedScreenLeft;
3898                        cf.top = mRestrictedScreenTop;
3899                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
3900                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3901                    }
3902                    applyStableConstraints(sysUiFl, fl, cf);
3903                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3904                        vf.left = mCurLeft;
3905                        vf.top = mCurTop;
3906                        vf.right = mCurRight;
3907                        vf.bottom = mCurBottom;
3908                    } else {
3909                        vf.set(cf);
3910                    }
3911                }
3912            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
3913                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
3914                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
3915                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
3916                        "): IN_SCREEN");
3917                // A window that has requested to fill the entire screen just
3918                // gets everything, period.
3919                if (attrs.type == TYPE_STATUS_BAR_PANEL
3920                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
3921                    pf.left = df.left = of.left = cf.left = hasNavBar
3922                            ? mDockLeft : mUnrestrictedScreenLeft;
3923                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
3924                    pf.right = df.right = of.right = cf.right = hasNavBar
3925                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
3926                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3927                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
3928                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
3929                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3930                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3931                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
3932                                    pf.left, pf.top, pf.right, pf.bottom));
3933                } else if (attrs.type == TYPE_NAVIGATION_BAR
3934                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
3935                    // The navigation bar has Real Ultimate Power.
3936                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3937                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
3938                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
3939                            + mUnrestrictedScreenWidth;
3940                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
3941                            + mUnrestrictedScreenHeight;
3942                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3943                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
3944                                    pf.left, pf.top, pf.right, pf.bottom));
3945                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
3946                                || attrs.type == TYPE_BOOT_PROGRESS)
3947                        && ((fl & FLAG_FULLSCREEN) != 0)) {
3948                    // Fullscreen secure system overlays get what they ask for.
3949                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3950                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3951                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
3952                            + mOverscanScreenWidth;
3953                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
3954                            + mOverscanScreenHeight;
3955                } else if (attrs.type == TYPE_BOOT_PROGRESS) {
3956                    // Boot progress screen always covers entire display.
3957                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3958                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3959                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
3960                            + mOverscanScreenWidth;
3961                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
3962                            + mOverscanScreenHeight;
3963                } else if (attrs.type == TYPE_WALLPAPER) {
3964                    // The wallpaper also has Real Ultimate Power, but we want to tell
3965                    // it about the overscan area.
3966                    pf.left = df.left = mOverscanScreenLeft;
3967                    pf.top = df.top = mOverscanScreenTop;
3968                    pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
3969                    pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
3970                    of.left = cf.left = mUnrestrictedScreenLeft;
3971                    of.top = cf.top = mUnrestrictedScreenTop;
3972                    of.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3973                    of.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3974                } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
3975                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3976                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3977                    // Asking to layout into the overscan region, so give it that pure
3978                    // unrestricted area.
3979                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3980                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3981                    pf.right = df.right = of.right = cf.right
3982                            = mOverscanScreenLeft + mOverscanScreenWidth;
3983                    pf.bottom = df.bottom = of.bottom = cf.bottom
3984                            = mOverscanScreenTop + mOverscanScreenHeight;
3985                } else if (canHideNavigationBar()
3986                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
3987                        && (attrs.type == TYPE_STATUS_BAR
3988                            || attrs.type == TYPE_TOAST
3989                            || attrs.type == TYPE_VOICE_INTERACTION_STARTING
3990                            || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3991                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
3992                    // Asking for layout as if the nav bar is hidden, lets the
3993                    // application extend into the unrestricted screen area.  We
3994                    // only do this for application windows (or toasts) to ensure no window that
3995                    // can be above the nav bar can do this.
3996                    // XXX This assumes that an app asking for this will also
3997                    // ask for layout in only content.  We can't currently figure out
3998                    // what the screen would be if only laying out to hide the nav bar.
3999                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
4000                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4001                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
4002                            + mUnrestrictedScreenWidth;
4003                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
4004                            + mUnrestrictedScreenHeight;
4005                } else {
4006                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4007                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4008                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4009                            + mRestrictedScreenWidth;
4010                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4011                            + mRestrictedScreenHeight;
4012                }
4013
4014                applyStableConstraints(sysUiFl, fl, cf);
4015
4016                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4017                    vf.left = mCurLeft;
4018                    vf.top = mCurTop;
4019                    vf.right = mCurRight;
4020                    vf.bottom = mCurBottom;
4021                } else {
4022                    vf.set(cf);
4023                }
4024            } else if (attached != null) {
4025                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4026                        "): attached to " + attached);
4027                // A child window should be placed inside of the same visible
4028                // frame that its parent had.
4029                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
4030            } else {
4031                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4032                        "): normal window");
4033                // Otherwise, a normal window must be placed inside the content
4034                // of all screen decorations.
4035                if (attrs.type == TYPE_STATUS_BAR_PANEL) {
4036                    // Status bar panels are the only windows who can go on top of
4037                    // the status bar.  They are protected by the STATUS_BAR_SERVICE
4038                    // permission, so they have the same privileges as the status
4039                    // bar itself.
4040                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4041                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4042                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4043                            + mRestrictedScreenWidth;
4044                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4045                            + mRestrictedScreenHeight;
4046                } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT
4047                        || attrs.type == TYPE_VOLUME_OVERLAY) {
4048                    // These dialogs are stable to interim decor changes.
4049                    pf.left = df.left = of.left = cf.left = mStableLeft;
4050                    pf.top = df.top = of.top = cf.top = mStableTop;
4051                    pf.right = df.right = of.right = cf.right = mStableRight;
4052                    pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
4053                } else {
4054                    pf.left = mContentLeft;
4055                    pf.top = mContentTop;
4056                    pf.right = mContentRight;
4057                    pf.bottom = mContentBottom;
4058                    if (win.isVoiceInteraction()) {
4059                        df.left = of.left = cf.left = mVoiceContentLeft;
4060                        df.top = of.top = cf.top = mVoiceContentTop;
4061                        df.right = of.right = cf.right = mVoiceContentRight;
4062                        df.bottom = of.bottom = cf.bottom = mVoiceContentBottom;
4063                    } else if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4064                        df.left = of.left = cf.left = mDockLeft;
4065                        df.top = of.top = cf.top = mDockTop;
4066                        df.right = of.right = cf.right = mDockRight;
4067                        df.bottom = of.bottom = cf.bottom = mDockBottom;
4068                    } else {
4069                        df.left = of.left = cf.left = mContentLeft;
4070                        df.top = of.top = cf.top = mContentTop;
4071                        df.right = of.right = cf.right = mContentRight;
4072                        df.bottom = of.bottom = cf.bottom = mContentBottom;
4073                    }
4074                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4075                        vf.left = mCurLeft;
4076                        vf.top = mCurTop;
4077                        vf.right = mCurRight;
4078                        vf.bottom = mCurBottom;
4079                    } else {
4080                        vf.set(cf);
4081                    }
4082                }
4083            }
4084        }
4085
4086        // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
4087        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR) {
4088            df.left = df.top = -10000;
4089            df.right = df.bottom = 10000;
4090            if (attrs.type != TYPE_WALLPAPER) {
4091                of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
4092                of.right = of.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
4093            }
4094        }
4095
4096        // If the device has a chin (e.g. some watches), a dead area at the bottom of the screen we
4097        // need to provide information to the clients that want to pretend that you can draw there.
4098        // We only want to apply outsets to certain types of windows. For example, we never want to
4099        // apply the outsets to floating dialogs, because they wouldn't make sense there.
4100        final boolean useOutsets = attrs.type == TYPE_WALLPAPER
4101                || (fl & (WindowManager.LayoutParams.FLAG_FULLSCREEN
4102                        | WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN)) != 0;
4103        if (isDefaultDisplay && useOutsets) {
4104            osf = mTmpOutsetFrame;
4105            osf.set(cf.left, cf.top, cf.right, cf.bottom);
4106            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
4107            if (outset > 0) {
4108                int rotation = Surface.ROTATION_0;
4109                try {
4110                    rotation = mWindowManager.getRotation();
4111                } catch (RemoteException e) {
4112                }
4113                if (rotation == Surface.ROTATION_0) {
4114                    osf.bottom += outset;
4115                } else if (rotation == Surface.ROTATION_90) {
4116                    osf.right += outset;
4117                } else if (rotation == Surface.ROTATION_180) {
4118                    osf.top -= outset;
4119                } else if (rotation == Surface.ROTATION_270) {
4120                    osf.left -= outset;
4121                }
4122                if (DEBUG_LAYOUT) Slog.v(TAG, "applying bottom outset of " + outset
4123                        + " with rotation " + rotation + ", result: " + osf);
4124            }
4125        }
4126
4127        if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
4128                + ": sim=#" + Integer.toHexString(sim)
4129                + " attach=" + attached + " type=" + attrs.type
4130                + String.format(" flags=0x%08x", fl)
4131                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
4132                + " of=" + of.toShortString()
4133                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
4134                + " dcf=" + dcf.toShortString()
4135                + " sf=" + sf.toShortString()
4136                + " osf=" + (osf == null ? "null" : osf.toShortString()));
4137
4138        win.computeFrameLw(pf, df, of, cf, vf, dcf, sf, osf);
4139
4140        // Dock windows carve out the bottom of the screen, so normal windows
4141        // can't appear underneath them.
4142        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
4143                && !win.getGivenInsetsPendingLw()) {
4144            setLastInputMethodWindowLw(null, null);
4145            offsetInputMethodWindowLw(win);
4146        }
4147        if (attrs.type == TYPE_VOICE_INTERACTION && win.isVisibleOrBehindKeyguardLw()
4148                && !win.getGivenInsetsPendingLw()) {
4149            offsetVoiceInputWindowLw(win);
4150        }
4151    }
4152
4153    private void offsetInputMethodWindowLw(WindowState win) {
4154        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4155        top += win.getGivenContentInsetsLw().top;
4156        if (mContentBottom > top) {
4157            mContentBottom = top;
4158        }
4159        if (mVoiceContentBottom > top) {
4160            mVoiceContentBottom = top;
4161        }
4162        top = win.getVisibleFrameLw().top;
4163        top += win.getGivenVisibleInsetsLw().top;
4164        if (mCurBottom > top) {
4165            mCurBottom = top;
4166        }
4167        if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
4168                + mDockBottom + " mContentBottom="
4169                + mContentBottom + " mCurBottom=" + mCurBottom);
4170    }
4171
4172    private void offsetVoiceInputWindowLw(WindowState win) {
4173        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4174        top += win.getGivenContentInsetsLw().top;
4175        if (mVoiceContentBottom > top) {
4176            mVoiceContentBottom = top;
4177        }
4178    }
4179
4180    /** {@inheritDoc} */
4181    @Override
4182    public void finishLayoutLw() {
4183        return;
4184    }
4185
4186    /** {@inheritDoc} */
4187    @Override
4188    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
4189        mTopFullscreenOpaqueWindowState = null;
4190        mTopFullscreenOpaqueOrDimmingWindowState = null;
4191        mAppsToBeHidden.clear();
4192        mAppsThatDismissKeyguard.clear();
4193        mForceStatusBar = false;
4194        mForceStatusBarFromKeyguard = false;
4195        mForceStatusBarTransparent = false;
4196        mForcingShowNavBar = false;
4197        mForcingShowNavBarLayer = -1;
4198
4199        mHideLockScreen = false;
4200        mAllowLockscreenWhenOn = false;
4201        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
4202        mShowingLockscreen = false;
4203        mShowingDream = false;
4204        mWinShowWhenLocked = null;
4205        mKeyguardSecure = isKeyguardSecure();
4206        mKeyguardSecureIncludingHidden = mKeyguardSecure
4207                && (mKeyguardDelegate != null && mKeyguardDelegate.isShowing());
4208    }
4209
4210    /** {@inheritDoc} */
4211    @Override
4212    public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs) {
4213        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
4214                + win.isVisibleOrBehindKeyguardLw());
4215        final int fl = PolicyControl.getWindowFlags(win, attrs);
4216        if (mTopFullscreenOpaqueWindowState == null
4217                && win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD) {
4218            mForcingShowNavBar = true;
4219            mForcingShowNavBarLayer = win.getSurfaceLayer();
4220        }
4221        if (attrs.type == TYPE_STATUS_BAR) {
4222            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4223                mForceStatusBarFromKeyguard = true;
4224            }
4225            if ((attrs.privateFlags & PRIVATE_FLAG_FORCE_STATUS_BAR_VISIBLE_TRANSPARENT) != 0) {
4226                mForceStatusBarTransparent = true;
4227            }
4228        }
4229
4230        boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
4231                && attrs.type < FIRST_SYSTEM_WINDOW;
4232        final boolean showWhenLocked = (fl & FLAG_SHOW_WHEN_LOCKED) != 0;
4233        final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
4234
4235        if (mTopFullscreenOpaqueWindowState == null &&
4236                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
4237            if ((fl & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
4238                if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4239                    mForceStatusBarFromKeyguard = true;
4240                } else {
4241                    mForceStatusBar = true;
4242                }
4243            }
4244            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4245                mShowingLockscreen = true;
4246            }
4247            if (attrs.type == TYPE_DREAM) {
4248                // If the lockscreen was showing when the dream started then wait
4249                // for the dream to draw before hiding the lockscreen.
4250                if (!mDreamingLockscreen
4251                        || (win.isVisibleLw() && win.hasDrawnLw())) {
4252                    mShowingDream = true;
4253                    appWindow = true;
4254                }
4255            }
4256
4257            if (appWindow) {
4258                final IApplicationToken appToken = win.getAppToken();
4259                if (showWhenLocked) {
4260                    // Remove any previous windows with the same appToken.
4261                    mAppsToBeHidden.remove(appToken);
4262                    mAppsThatDismissKeyguard.remove(appToken);
4263                    if (mAppsToBeHidden.isEmpty()) {
4264                        if (dismissKeyguard && !mKeyguardSecure) {
4265                            mAppsThatDismissKeyguard.add(appToken);
4266                        } else {
4267                            mWinShowWhenLocked = win;
4268                            mHideLockScreen = true;
4269                            mForceStatusBarFromKeyguard = false;
4270                        }
4271                    }
4272                } else if (dismissKeyguard) {
4273                    if (mKeyguardSecure) {
4274                        mAppsToBeHidden.add(appToken);
4275                    } else {
4276                        mAppsToBeHidden.remove(appToken);
4277                    }
4278                    mAppsThatDismissKeyguard.add(appToken);
4279                } else {
4280                    mAppsToBeHidden.add(appToken);
4281                }
4282                if (attrs.x == 0 && attrs.y == 0
4283                        && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
4284                        && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
4285                    if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
4286                    mTopFullscreenOpaqueWindowState = win;
4287                    if (mTopFullscreenOpaqueOrDimmingWindowState == null) {
4288                        mTopFullscreenOpaqueOrDimmingWindowState = win;
4289                    }
4290                    if (!mAppsThatDismissKeyguard.isEmpty() &&
4291                            mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
4292                        if (DEBUG_LAYOUT) Slog.v(TAG,
4293                                "Setting mDismissKeyguard true by win " + win);
4294                        mDismissKeyguard = (mWinDismissingKeyguard == win
4295                                && mSecureDismissingKeyguard == mKeyguardSecure)
4296                                ? DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
4297                        mWinDismissingKeyguard = win;
4298                        mSecureDismissingKeyguard = mKeyguardSecure;
4299                        mForceStatusBarFromKeyguard = mShowingLockscreen && mKeyguardSecure;
4300                    } else if (mAppsToBeHidden.isEmpty() && showWhenLocked) {
4301                        if (DEBUG_LAYOUT) Slog.v(TAG,
4302                                "Setting mHideLockScreen to true by win " + win);
4303                        mHideLockScreen = true;
4304                        mForceStatusBarFromKeyguard = false;
4305                    }
4306                    if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
4307                        mAllowLockscreenWhenOn = true;
4308                    }
4309                }
4310
4311                if (mWinShowWhenLocked != null &&
4312                        mWinShowWhenLocked.getAppToken() != win.getAppToken() &&
4313                        (attrs.flags & FLAG_SHOW_WHEN_LOCKED) == 0) {
4314                    win.hideLw(false);
4315                }
4316            }
4317        } else if (mTopFullscreenOpaqueWindowState == null && mWinShowWhenLocked == null) {
4318            // No TopFullscreenOpaqueWindow is showing, but we found a SHOW_WHEN_LOCKED window
4319            // that is being hidden in an animation - keep the
4320            // keyguard hidden until the new window shows up and
4321            // we know whether to show the keyguard or not.
4322            if (win.isAnimatingLw() && appWindow && showWhenLocked && mKeyguardHidden) {
4323                mHideLockScreen = true;
4324                mWinShowWhenLocked = win;
4325            }
4326        }
4327        if (mTopFullscreenOpaqueOrDimmingWindowState == null
4328                && win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()
4329                && win.isDimming()) {
4330            mTopFullscreenOpaqueOrDimmingWindowState = win;
4331        }
4332    }
4333
4334    /** {@inheritDoc} */
4335    @Override
4336    public int finishPostLayoutPolicyLw() {
4337        if (mWinShowWhenLocked != null && mTopFullscreenOpaqueWindowState != null &&
4338                mWinShowWhenLocked.getAppToken() != mTopFullscreenOpaqueWindowState.getAppToken()
4339                && isKeyguardLocked()) {
4340            // A dialog is dismissing the keyguard. Put the wallpaper behind it and hide the
4341            // fullscreen window.
4342            // TODO: Make sure FLAG_SHOW_WALLPAPER is restored when dialog is dismissed. Or not.
4343            mWinShowWhenLocked.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4344            mTopFullscreenOpaqueWindowState.hideLw(false);
4345            mTopFullscreenOpaqueWindowState = mWinShowWhenLocked;
4346        }
4347
4348        int changes = 0;
4349        boolean topIsFullscreen = false;
4350
4351        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
4352                ? mTopFullscreenOpaqueWindowState.getAttrs()
4353                : null;
4354
4355        // If we are not currently showing a dream then remember the current
4356        // lockscreen state.  We will use this to determine whether the dream
4357        // started while the lockscreen was showing and remember this state
4358        // while the dream is showing.
4359        if (!mShowingDream) {
4360            mDreamingLockscreen = mShowingLockscreen;
4361            if (mDreamingSleepTokenNeeded) {
4362                mDreamingSleepTokenNeeded = false;
4363                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 0, 1).sendToTarget();
4364            }
4365        } else {
4366            if (!mDreamingSleepTokenNeeded) {
4367                mDreamingSleepTokenNeeded = true;
4368                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 1, 1).sendToTarget();
4369            }
4370        }
4371
4372        if (mStatusBar != null) {
4373            if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
4374                    + " forcefkg=" + mForceStatusBarFromKeyguard
4375                    + " top=" + mTopFullscreenOpaqueWindowState);
4376            boolean shouldBeTransparent = mForceStatusBarTransparent
4377                    && !mForceStatusBar
4378                    && !mForceStatusBarFromKeyguard;
4379            if (!shouldBeTransparent) {
4380                mStatusBarController.setShowTransparent(false /* transparent */);
4381            } else if (!mStatusBar.isVisibleLw()) {
4382                mStatusBarController.setShowTransparent(true /* transparent */);
4383            }
4384            if (mForceStatusBar || mForceStatusBarFromKeyguard || mForceStatusBarTransparent) {
4385                if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
4386                if (mStatusBarController.setBarShowingLw(true)) {
4387                    changes |= FINISH_LAYOUT_REDO_LAYOUT;
4388                }
4389                // Maintain fullscreen layout until incoming animation is complete.
4390                topIsFullscreen = mTopIsFullscreen && mStatusBar.isAnimatingLw();
4391                // Transient status bar on the lockscreen is not allowed
4392                if (mForceStatusBarFromKeyguard && mStatusBarController.isTransientShowing()) {
4393                    mStatusBarController.updateVisibilityLw(false /*transientAllowed*/,
4394                            mLastSystemUiFlags, mLastSystemUiFlags);
4395                }
4396            } else if (mTopFullscreenOpaqueWindowState != null) {
4397                final int fl = PolicyControl.getWindowFlags(null, lp);
4398                if (localLOGV) {
4399                    Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
4400                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
4401                    Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
4402                            + " lp.flags=0x" + Integer.toHexString(fl));
4403                }
4404                topIsFullscreen = (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
4405                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
4406                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
4407                // and mTopIsFullscreen is that mTopIsFullscreen is set only if the window
4408                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
4409                // case though.
4410                if (mStatusBarController.isTransientShowing()) {
4411                    if (mStatusBarController.setBarShowingLw(true)) {
4412                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4413                    }
4414                } else if (topIsFullscreen) {
4415                    if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
4416                    if (mStatusBarController.setBarShowingLw(false)) {
4417                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4418                    } else {
4419                        if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
4420                    }
4421                } else {
4422                    if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
4423                    if (mStatusBarController.setBarShowingLw(true)) {
4424                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4425                    }
4426                }
4427            }
4428        }
4429
4430        if (mTopIsFullscreen != topIsFullscreen) {
4431            if (!topIsFullscreen) {
4432                // Force another layout when status bar becomes fully shown.
4433                changes |= FINISH_LAYOUT_REDO_LAYOUT;
4434            }
4435            mTopIsFullscreen = topIsFullscreen;
4436        }
4437
4438        // Hide the key guard if a visible window explicitly specifies that it wants to be
4439        // displayed when the screen is locked.
4440        if (mKeyguardDelegate != null && mStatusBar != null) {
4441            if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
4442                    + mHideLockScreen);
4443            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardSecure) {
4444                mKeyguardHidden = true;
4445                if (setKeyguardOccludedLw(true)) {
4446                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4447                            | FINISH_LAYOUT_REDO_CONFIG
4448                            | FINISH_LAYOUT_REDO_WALLPAPER;
4449                }
4450                if (mKeyguardDelegate.isShowing()) {
4451                    mHandler.post(new Runnable() {
4452                        @Override
4453                        public void run() {
4454                            mKeyguardDelegate.keyguardDone(false, false);
4455                        }
4456                    });
4457                }
4458            } else if (mHideLockScreen) {
4459                mKeyguardHidden = true;
4460                mWinDismissingKeyguard = null;
4461                if (setKeyguardOccludedLw(true)) {
4462                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4463                            | FINISH_LAYOUT_REDO_CONFIG
4464                            | FINISH_LAYOUT_REDO_WALLPAPER;
4465                }
4466            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
4467                mKeyguardHidden = false;
4468                if (setKeyguardOccludedLw(false)) {
4469                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4470                            | FINISH_LAYOUT_REDO_CONFIG
4471                            | FINISH_LAYOUT_REDO_WALLPAPER;
4472                }
4473                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
4474                    // Only launch the next keyguard unlock window once per window.
4475                    mHandler.post(new Runnable() {
4476                        @Override
4477                        public void run() {
4478                            mKeyguardDelegate.dismiss();
4479                        }
4480                    });
4481                }
4482            } else {
4483                mWinDismissingKeyguard = null;
4484                mSecureDismissingKeyguard = false;
4485                mKeyguardHidden = false;
4486                if (setKeyguardOccludedLw(false)) {
4487                    changes |= FINISH_LAYOUT_REDO_LAYOUT
4488                            | FINISH_LAYOUT_REDO_CONFIG
4489                            | FINISH_LAYOUT_REDO_WALLPAPER;
4490                }
4491            }
4492        }
4493
4494        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
4495            // If the navigation bar has been hidden or shown, we need to do another
4496            // layout pass to update that window.
4497            changes |= FINISH_LAYOUT_REDO_LAYOUT;
4498        }
4499
4500        // update since mAllowLockscreenWhenOn might have changed
4501        updateLockScreenTimeout();
4502        return changes;
4503    }
4504
4505    /**
4506     * Updates the occluded state of the Keyguard.
4507     *
4508     * @return Whether the flags have changed and we have to redo the layout.
4509     */
4510    private boolean setKeyguardOccludedLw(boolean isOccluded) {
4511        boolean wasOccluded = mKeyguardOccluded;
4512        boolean showing = mKeyguardDelegate.isShowing();
4513        if (wasOccluded && !isOccluded && showing) {
4514            mKeyguardOccluded = false;
4515            mKeyguardDelegate.setOccluded(false);
4516            mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
4517            mStatusBar.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4518            return true;
4519        } else if (!wasOccluded && isOccluded && showing) {
4520            mKeyguardOccluded = true;
4521            mKeyguardDelegate.setOccluded(true);
4522            mStatusBar.getAttrs().privateFlags &= ~PRIVATE_FLAG_KEYGUARD;
4523            mStatusBar.getAttrs().flags &= ~FLAG_SHOW_WALLPAPER;
4524            return true;
4525        } else {
4526            return false;
4527        }
4528    }
4529
4530    private boolean isStatusBarKeyguard() {
4531        return mStatusBar != null
4532                && (mStatusBar.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
4533    }
4534
4535    @Override
4536    public boolean allowAppAnimationsLw() {
4537        if (isStatusBarKeyguard() || mShowingDream) {
4538            // If keyguard or dreams is currently visible, no reason to animate behind it.
4539            return false;
4540        }
4541        return true;
4542    }
4543
4544    @Override
4545    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
4546        mFocusedWindow = newFocus;
4547        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
4548            // If the navigation bar has been hidden or shown, we need to do another
4549            // layout pass to update that window.
4550            return FINISH_LAYOUT_REDO_LAYOUT;
4551        }
4552        return 0;
4553    }
4554
4555    /** {@inheritDoc} */
4556    @Override
4557    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
4558        // lid changed state
4559        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
4560        if (newLidState == mLidState) {
4561            return;
4562        }
4563
4564        mLidState = newLidState;
4565        applyLidSwitchState();
4566        updateRotation(true);
4567
4568        if (lidOpen) {
4569            wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromLidSwitch);
4570        } else if (!mLidControlsSleep) {
4571            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4572        }
4573    }
4574
4575    @Override
4576    public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered) {
4577        int lensCoverState = lensCovered ? CAMERA_LENS_COVERED : CAMERA_LENS_UNCOVERED;
4578        if (mCameraLensCoverState == lensCoverState) {
4579            return;
4580        }
4581        if (mCameraLensCoverState == CAMERA_LENS_COVERED &&
4582                lensCoverState == CAMERA_LENS_UNCOVERED) {
4583            Intent intent;
4584            final boolean keyguardActive = mKeyguardDelegate == null ? false :
4585                    mKeyguardDelegate.isShowing();
4586            if (keyguardActive) {
4587                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
4588            } else {
4589                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
4590            }
4591            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromCameraLens);
4592            startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
4593        }
4594        mCameraLensCoverState = lensCoverState;
4595    }
4596
4597    void setHdmiPlugged(boolean plugged) {
4598        if (mHdmiPlugged != plugged) {
4599            mHdmiPlugged = plugged;
4600            updateRotation(true, true);
4601            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
4602            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4603            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
4604            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
4605        }
4606    }
4607
4608    void initializeHdmiState() {
4609        boolean plugged = false;
4610        // watch for HDMI plug messages if the hdmi switch exists
4611        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
4612            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
4613
4614            final String filename = "/sys/class/switch/hdmi/state";
4615            FileReader reader = null;
4616            try {
4617                reader = new FileReader(filename);
4618                char[] buf = new char[15];
4619                int n = reader.read(buf);
4620                if (n > 1) {
4621                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
4622                }
4623            } catch (IOException ex) {
4624                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
4625            } catch (NumberFormatException ex) {
4626                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
4627            } finally {
4628                if (reader != null) {
4629                    try {
4630                        reader.close();
4631                    } catch (IOException ex) {
4632                    }
4633                }
4634            }
4635        }
4636        // This dance forces the code in setHdmiPlugged to run.
4637        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
4638        mHdmiPlugged = !plugged;
4639        setHdmiPlugged(!mHdmiPlugged);
4640    }
4641
4642    final Object mScreenshotLock = new Object();
4643    ServiceConnection mScreenshotConnection = null;
4644
4645    final Runnable mScreenshotTimeout = new Runnable() {
4646        @Override public void run() {
4647            synchronized (mScreenshotLock) {
4648                if (mScreenshotConnection != null) {
4649                    mContext.unbindService(mScreenshotConnection);
4650                    mScreenshotConnection = null;
4651                }
4652            }
4653        }
4654    };
4655
4656    // Assume this is called from the Handler thread.
4657    private void takeScreenshot() {
4658        synchronized (mScreenshotLock) {
4659            if (mScreenshotConnection != null) {
4660                return;
4661            }
4662            ComponentName cn = new ComponentName("com.android.systemui",
4663                    "com.android.systemui.screenshot.TakeScreenshotService");
4664            Intent intent = new Intent();
4665            intent.setComponent(cn);
4666            ServiceConnection conn = new ServiceConnection() {
4667                @Override
4668                public void onServiceConnected(ComponentName name, IBinder service) {
4669                    synchronized (mScreenshotLock) {
4670                        if (mScreenshotConnection != this) {
4671                            return;
4672                        }
4673                        Messenger messenger = new Messenger(service);
4674                        Message msg = Message.obtain(null, 1);
4675                        final ServiceConnection myConn = this;
4676                        Handler h = new Handler(mHandler.getLooper()) {
4677                            @Override
4678                            public void handleMessage(Message msg) {
4679                                synchronized (mScreenshotLock) {
4680                                    if (mScreenshotConnection == myConn) {
4681                                        mContext.unbindService(mScreenshotConnection);
4682                                        mScreenshotConnection = null;
4683                                        mHandler.removeCallbacks(mScreenshotTimeout);
4684                                    }
4685                                }
4686                            }
4687                        };
4688                        msg.replyTo = new Messenger(h);
4689                        msg.arg1 = msg.arg2 = 0;
4690                        if (mStatusBar != null && mStatusBar.isVisibleLw())
4691                            msg.arg1 = 1;
4692                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
4693                            msg.arg2 = 1;
4694                        try {
4695                            messenger.send(msg);
4696                        } catch (RemoteException e) {
4697                        }
4698                    }
4699                }
4700                @Override
4701                public void onServiceDisconnected(ComponentName name) {}
4702            };
4703            if (mContext.bindServiceAsUser(
4704                    intent, conn, Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
4705                mScreenshotConnection = conn;
4706                mHandler.postDelayed(mScreenshotTimeout, 10000);
4707            }
4708        }
4709    }
4710
4711    /** {@inheritDoc} */
4712    @Override
4713    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
4714        if (!mSystemBooted) {
4715            // If we have not yet booted, don't let key events do anything.
4716            return 0;
4717        }
4718
4719        final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;
4720        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
4721        final boolean canceled = event.isCanceled();
4722        final int keyCode = event.getKeyCode();
4723
4724        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
4725
4726        // If screen is off then we treat the case where the keyguard is open but hidden
4727        // the same as if it were open and in front.
4728        // This will prevent any keys other than the power button from waking the screen
4729        // when the keyguard is hidden by another activity.
4730        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
4731                                            (interactive ?
4732                                                isKeyguardShowingAndNotOccluded() :
4733                                                mKeyguardDelegate.isShowing()));
4734
4735        if (DEBUG_INPUT) {
4736            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
4737                    + " interactive=" + interactive + " keyguardActive=" + keyguardActive
4738                    + " policyFlags=" + Integer.toHexString(policyFlags));
4739        }
4740
4741        // Basic policy based on interactive state.
4742        int result;
4743        boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
4744                || event.isWakeKey();
4745        if (interactive || (isInjected && !isWakeKey)) {
4746            // When the device is interactive or the key is injected pass the
4747            // key to the application.
4748            result = ACTION_PASS_TO_USER;
4749            isWakeKey = false;
4750        } else if (!interactive && shouldDispatchInputWhenNonInteractive()) {
4751            // If we're currently dozing with the screen on and the keyguard showing, pass the key
4752            // to the application but preserve its wake key status to make sure we still move
4753            // from dozing to fully interactive if we would normally go from off to fully
4754            // interactive.
4755            result = ACTION_PASS_TO_USER;
4756        } else {
4757            // When the screen is off and the key is not injected, determine whether
4758            // to wake the device but don't pass the key to the application.
4759            result = 0;
4760            if (isWakeKey && (!down || !isWakeKeyWhenScreenOff(keyCode))) {
4761                isWakeKey = false;
4762            }
4763        }
4764
4765        // If the key would be handled globally, just return the result, don't worry about special
4766        // key processing.
4767        if (isValidGlobalKey(keyCode)
4768                && mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
4769            if (isWakeKey) {
4770                wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey);
4771            }
4772            return result;
4773        }
4774
4775        boolean useHapticFeedback = down
4776                && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
4777                && event.getRepeatCount() == 0;
4778
4779        // Handle special keys.
4780        switch (keyCode) {
4781            case KeyEvent.KEYCODE_VOLUME_DOWN:
4782            case KeyEvent.KEYCODE_VOLUME_UP:
4783            case KeyEvent.KEYCODE_VOLUME_MUTE: {
4784                if (mUseTvRouting) {
4785                    // On TVs volume keys never go to the foreground app
4786                    result &= ~ACTION_PASS_TO_USER;
4787                }
4788                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
4789                    if (down) {
4790                        if (interactive && !mScreenshotChordVolumeDownKeyTriggered
4791                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4792                            mScreenshotChordVolumeDownKeyTriggered = true;
4793                            mScreenshotChordVolumeDownKeyTime = event.getDownTime();
4794                            mScreenshotChordVolumeDownKeyConsumed = false;
4795                            cancelPendingPowerKeyAction();
4796                            interceptScreenshotChord();
4797                        }
4798                    } else {
4799                        mScreenshotChordVolumeDownKeyTriggered = false;
4800                        cancelPendingScreenshotChordAction();
4801                    }
4802                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
4803                    if (down) {
4804                        if (interactive && !mScreenshotChordVolumeUpKeyTriggered
4805                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
4806                            mScreenshotChordVolumeUpKeyTriggered = true;
4807                            cancelPendingPowerKeyAction();
4808                            cancelPendingScreenshotChordAction();
4809                        }
4810                    } else {
4811                        mScreenshotChordVolumeUpKeyTriggered = false;
4812                        cancelPendingScreenshotChordAction();
4813                    }
4814                }
4815                if (down) {
4816                    TelecomManager telecomManager = getTelecommService();
4817                    if (telecomManager != null) {
4818                        if (telecomManager.isRinging()) {
4819                            // If an incoming call is ringing, either VOLUME key means
4820                            // "silence ringer".  We handle these keys here, rather than
4821                            // in the InCallScreen, to make sure we'll respond to them
4822                            // even if the InCallScreen hasn't come to the foreground yet.
4823                            // Look for the DOWN event here, to agree with the "fallback"
4824                            // behavior in the InCallScreen.
4825                            Log.i(TAG, "interceptKeyBeforeQueueing:"
4826                                  + " VOLUME key-down while ringing: Silence ringer!");
4827
4828                            // Silence the ringer.  (It's safe to call this
4829                            // even if the ringer has already been silenced.)
4830                            telecomManager.silenceRinger();
4831
4832                            // And *don't* pass this key thru to the current activity
4833                            // (which is probably the InCallScreen.)
4834                            result &= ~ACTION_PASS_TO_USER;
4835                            break;
4836                        }
4837                        if (telecomManager.isInCall()
4838                                && (result & ACTION_PASS_TO_USER) == 0) {
4839                            // If we are in call but we decided not to pass the key to
4840                            // the application, just pass it to the session service.
4841
4842                            MediaSessionLegacyHelper.getHelper(mContext)
4843                                    .sendVolumeKeyEvent(event, false);
4844                            break;
4845                        }
4846                    }
4847
4848                    if ((result & ACTION_PASS_TO_USER) == 0) {
4849                        if (mUseTvRouting) {
4850                            dispatchDirectAudioEvent(event);
4851                        } else {
4852                            // If we aren't passing to the user and no one else
4853                            // handled it send it to the session manager to
4854                            // figure out.
4855                            MediaSessionLegacyHelper.getHelper(mContext)
4856                                    .sendVolumeKeyEvent(event, true);
4857                        }
4858                        break;
4859                    }
4860                }
4861                break;
4862            }
4863
4864            case KeyEvent.KEYCODE_ENDCALL: {
4865                result &= ~ACTION_PASS_TO_USER;
4866                if (down) {
4867                    TelecomManager telecomManager = getTelecommService();
4868                    boolean hungUp = false;
4869                    if (telecomManager != null) {
4870                        hungUp = telecomManager.endCall();
4871                    }
4872                    if (interactive && !hungUp) {
4873                        mEndCallKeyHandled = false;
4874                        mHandler.postDelayed(mEndCallLongPress,
4875                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
4876                    } else {
4877                        mEndCallKeyHandled = true;
4878                    }
4879                } else {
4880                    if (!mEndCallKeyHandled) {
4881                        mHandler.removeCallbacks(mEndCallLongPress);
4882                        if (!canceled) {
4883                            if ((mEndcallBehavior
4884                                    & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
4885                                if (goHome()) {
4886                                    break;
4887                                }
4888                            }
4889                            if ((mEndcallBehavior
4890                                    & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
4891                                mPowerManager.goToSleep(event.getEventTime(),
4892                                        PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
4893                                isWakeKey = false;
4894                            }
4895                        }
4896                    }
4897                }
4898                break;
4899            }
4900
4901            case KeyEvent.KEYCODE_POWER: {
4902                result &= ~ACTION_PASS_TO_USER;
4903                isWakeKey = false; // wake-up will be handled separately
4904                if (down) {
4905                    interceptPowerKeyDown(event, interactive);
4906                } else {
4907                    interceptPowerKeyUp(event, interactive, canceled);
4908                }
4909                break;
4910            }
4911
4912            case KeyEvent.KEYCODE_SLEEP: {
4913                result &= ~ACTION_PASS_TO_USER;
4914                isWakeKey = false;
4915                if (!mPowerManager.isInteractive()) {
4916                    useHapticFeedback = false; // suppress feedback if already non-interactive
4917                }
4918                if (down) {
4919                    sleepPress(event.getEventTime());
4920                } else {
4921                    sleepRelease(event.getEventTime());
4922                }
4923                break;
4924            }
4925
4926            case KeyEvent.KEYCODE_WAKEUP: {
4927                result &= ~ACTION_PASS_TO_USER;
4928                isWakeKey = true;
4929                break;
4930            }
4931
4932            case KeyEvent.KEYCODE_MEDIA_PLAY:
4933            case KeyEvent.KEYCODE_MEDIA_PAUSE:
4934            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
4935            case KeyEvent.KEYCODE_HEADSETHOOK:
4936            case KeyEvent.KEYCODE_MUTE:
4937            case KeyEvent.KEYCODE_MEDIA_STOP:
4938            case KeyEvent.KEYCODE_MEDIA_NEXT:
4939            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
4940            case KeyEvent.KEYCODE_MEDIA_REWIND:
4941            case KeyEvent.KEYCODE_MEDIA_RECORD:
4942            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
4943            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
4944                if (MediaSessionLegacyHelper.getHelper(mContext).isGlobalPriorityActive()) {
4945                    // If the global session is active pass all media keys to it
4946                    // instead of the active window.
4947                    result &= ~ACTION_PASS_TO_USER;
4948                }
4949                if ((result & ACTION_PASS_TO_USER) == 0) {
4950                    // Only do this if we would otherwise not pass it to the user. In that
4951                    // case, the PhoneWindow class will do the same thing, except it will
4952                    // only do it if the showing app doesn't process the key on its own.
4953                    // Note that we need to make a copy of the key event here because the
4954                    // original key event will be recycled when we return.
4955                    mBroadcastWakeLock.acquire();
4956                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
4957                            new KeyEvent(event));
4958                    msg.setAsynchronous(true);
4959                    msg.sendToTarget();
4960                }
4961                break;
4962            }
4963
4964            case KeyEvent.KEYCODE_CALL: {
4965                if (down) {
4966                    TelecomManager telecomManager = getTelecommService();
4967                    if (telecomManager != null) {
4968                        if (telecomManager.isRinging()) {
4969                            Log.i(TAG, "interceptKeyBeforeQueueing:"
4970                                  + " CALL key-down while ringing: Answer the call!");
4971                            telecomManager.acceptRingingCall();
4972
4973                            // And *don't* pass this key thru to the current activity
4974                            // (which is presumably the InCallScreen.)
4975                            result &= ~ACTION_PASS_TO_USER;
4976                        }
4977                    }
4978                }
4979                break;
4980            }
4981            case KeyEvent.KEYCODE_VOICE_ASSIST: {
4982                // Only do this if we would otherwise not pass it to the user. In that case,
4983                // interceptKeyBeforeDispatching would apply a similar but different policy in
4984                // order to invoke voice assist actions. Note that we need to make a copy of the
4985                // key event here because the original key event will be recycled when we return.
4986                if ((result & ACTION_PASS_TO_USER) == 0 && !down) {
4987                    mBroadcastWakeLock.acquire();
4988                    Message msg = mHandler.obtainMessage(MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK,
4989                            keyguardActive ? 1 : 0, 0);
4990                    msg.setAsynchronous(true);
4991                    msg.sendToTarget();
4992                }
4993            }
4994        }
4995
4996        if (useHapticFeedback) {
4997            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
4998        }
4999
5000        if (isWakeKey) {
5001            wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey);
5002        }
5003
5004        return result;
5005    }
5006
5007    /**
5008     * Returns true if the key can have global actions attached to it.
5009     * We reserve all power management keys for the system since they require
5010     * very careful handling.
5011     */
5012    private static boolean isValidGlobalKey(int keyCode) {
5013        switch (keyCode) {
5014            case KeyEvent.KEYCODE_POWER:
5015            case KeyEvent.KEYCODE_WAKEUP:
5016            case KeyEvent.KEYCODE_SLEEP:
5017                return false;
5018            default:
5019                return true;
5020        }
5021    }
5022
5023    /**
5024     * When the screen is off we ignore some keys that might otherwise typically
5025     * be considered wake keys.  We filter them out here.
5026     *
5027     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
5028     * is always considered a wake key.
5029     */
5030    private boolean isWakeKeyWhenScreenOff(int keyCode) {
5031        switch (keyCode) {
5032            // ignore volume keys unless docked
5033            case KeyEvent.KEYCODE_VOLUME_UP:
5034            case KeyEvent.KEYCODE_VOLUME_DOWN:
5035            case KeyEvent.KEYCODE_VOLUME_MUTE:
5036                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
5037
5038            // ignore media and camera keys
5039            case KeyEvent.KEYCODE_MUTE:
5040            case KeyEvent.KEYCODE_HEADSETHOOK:
5041            case KeyEvent.KEYCODE_MEDIA_PLAY:
5042            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5043            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5044            case KeyEvent.KEYCODE_MEDIA_STOP:
5045            case KeyEvent.KEYCODE_MEDIA_NEXT:
5046            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5047            case KeyEvent.KEYCODE_MEDIA_REWIND:
5048            case KeyEvent.KEYCODE_MEDIA_RECORD:
5049            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5050            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
5051            case KeyEvent.KEYCODE_CAMERA:
5052                return false;
5053        }
5054        return true;
5055    }
5056
5057
5058    /** {@inheritDoc} */
5059    @Override
5060    public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
5061        if ((policyFlags & FLAG_WAKE) != 0) {
5062            if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion)) {
5063                return 0;
5064            }
5065        }
5066
5067        if (shouldDispatchInputWhenNonInteractive()) {
5068            return ACTION_PASS_TO_USER;
5069        }
5070
5071        // If we have not passed the action up and we are in theater mode without dreaming,
5072        // there will be no dream to intercept the touch and wake into ambient.  The device should
5073        // wake up in this case.
5074        if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
5075            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotionWhenNotDreaming);
5076        }
5077
5078        return 0;
5079    }
5080
5081    private boolean shouldDispatchInputWhenNonInteractive() {
5082        // Send events to keyguard while the screen is on.
5083        if (isKeyguardShowingAndNotOccluded() && mDisplay != null
5084                && mDisplay.getState() != Display.STATE_OFF) {
5085            return true;
5086        }
5087
5088        // Send events to a dozing dream even if the screen is off since the dream
5089        // is in control of the state of the screen.
5090        IDreamManager dreamManager = getDreamManager();
5091
5092        try {
5093            if (dreamManager != null && dreamManager.isDreaming()) {
5094                return true;
5095            }
5096        } catch (RemoteException e) {
5097            Slog.e(TAG, "RemoteException when checking if dreaming", e);
5098        }
5099
5100        // Otherwise, consume events since the user can't see what is being
5101        // interacted with.
5102        return false;
5103    }
5104
5105    private void dispatchDirectAudioEvent(KeyEvent event) {
5106        if (event.getAction() != KeyEvent.ACTION_DOWN) {
5107            return;
5108        }
5109        int keyCode = event.getKeyCode();
5110        int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
5111                | AudioManager.FLAG_FROM_KEY;
5112        String pkgName = mContext.getOpPackageName();
5113        switch (keyCode) {
5114            case KeyEvent.KEYCODE_VOLUME_UP:
5115                try {
5116                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
5117                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5118                } catch (RemoteException e) {
5119                    Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
5120                }
5121                break;
5122            case KeyEvent.KEYCODE_VOLUME_DOWN:
5123                try {
5124                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
5125                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5126                } catch (RemoteException e) {
5127                    Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
5128                }
5129                break;
5130            case KeyEvent.KEYCODE_VOLUME_MUTE:
5131                try {
5132                    if (event.getRepeatCount() == 0) {
5133                        getAudioService().adjustSuggestedStreamVolume(
5134                                AudioManager.ADJUST_TOGGLE_MUTE,
5135                                AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5136                    }
5137                } catch (RemoteException e) {
5138                    Log.e(TAG, "Error dispatching mute in dispatchTvAudioEvent.", e);
5139                }
5140                break;
5141        }
5142    }
5143
5144    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
5145        if (DEBUG_INPUT) {
5146            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
5147        }
5148
5149        if (mHavePendingMediaKeyRepeatWithWakeLock) {
5150            if (DEBUG_INPUT) {
5151                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
5152            }
5153
5154            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
5155            mHavePendingMediaKeyRepeatWithWakeLock = false;
5156            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
5157        }
5158
5159        dispatchMediaKeyWithWakeLockToAudioService(event);
5160
5161        if (event.getAction() == KeyEvent.ACTION_DOWN
5162                && event.getRepeatCount() == 0) {
5163            mHavePendingMediaKeyRepeatWithWakeLock = true;
5164
5165            Message msg = mHandler.obtainMessage(
5166                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
5167            msg.setAsynchronous(true);
5168            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
5169        } else {
5170            mBroadcastWakeLock.release();
5171        }
5172    }
5173
5174    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
5175        mHavePendingMediaKeyRepeatWithWakeLock = false;
5176
5177        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
5178                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
5179        if (DEBUG_INPUT) {
5180            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
5181        }
5182
5183        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
5184        mBroadcastWakeLock.release();
5185    }
5186
5187    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
5188        if (ActivityManagerNative.isSystemReady()) {
5189            MediaSessionLegacyHelper.getHelper(mContext).sendMediaButtonEvent(event, true);
5190        }
5191    }
5192
5193    void launchVoiceAssistWithWakeLock(boolean keyguardActive) {
5194        Intent voiceIntent =
5195            new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
5196        voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, keyguardActive);
5197        startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
5198        mBroadcastWakeLock.release();
5199    }
5200
5201    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
5202        @Override
5203        public void onReceive(Context context, Intent intent) {
5204            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
5205                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
5206                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
5207            } else {
5208                try {
5209                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
5210                            ServiceManager.getService(Context.UI_MODE_SERVICE));
5211                    mUiMode = uiModeService.getCurrentModeType();
5212                } catch (RemoteException e) {
5213                }
5214            }
5215            updateRotation(true);
5216            synchronized (mLock) {
5217                updateOrientationListenerLp();
5218            }
5219        }
5220    };
5221
5222    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
5223        @Override
5224        public void onReceive(Context context, Intent intent) {
5225            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
5226                if (mKeyguardDelegate != null) {
5227                    mKeyguardDelegate.onDreamingStarted();
5228                }
5229            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
5230                if (mKeyguardDelegate != null) {
5231                    mKeyguardDelegate.onDreamingStopped();
5232                }
5233            }
5234        }
5235    };
5236
5237    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
5238        @Override
5239        public void onReceive(Context context, Intent intent) {
5240            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
5241                // tickle the settings observer: this first ensures that we're
5242                // observing the relevant settings for the newly-active user,
5243                // and then updates our own bookkeeping based on the now-
5244                // current user.
5245                mSettingsObserver.onChange(false);
5246
5247                // force a re-application of focused window sysui visibility.
5248                // the window may never have been shown for this user
5249                // e.g. the keyguard when going through the new-user setup flow
5250                synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5251                    mLastSystemUiFlags = 0;
5252                    updateSystemUiVisibilityLw();
5253                }
5254            }
5255        }
5256    };
5257
5258    private final Runnable mHiddenNavPanic = new Runnable() {
5259        @Override
5260        public void run() {
5261            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5262                if (!isUserSetupComplete()) {
5263                    // Swipe-up for navigation bar is disabled during setup
5264                    return;
5265                }
5266                mPendingPanicGestureUptime = SystemClock.uptimeMillis();
5267                mNavigationBarController.showTransient();
5268            }
5269        }
5270    };
5271
5272    private void requestTransientBars(WindowState swipeTarget) {
5273        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5274            if (!isUserSetupComplete()) {
5275                // Swipe-up for navigation bar is disabled during setup
5276                return;
5277            }
5278            boolean sb = mStatusBarController.checkShowTransientBarLw();
5279            boolean nb = mNavigationBarController.checkShowTransientBarLw();
5280            if (sb || nb) {
5281                // Don't show status bar when swiping on already visible navigation bar
5282                if (!nb && swipeTarget == mNavigationBar) {
5283                    if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
5284                    return;
5285                }
5286                if (sb) mStatusBarController.showTransient();
5287                if (nb) mNavigationBarController.showTransient();
5288                mImmersiveModeConfirmation.confirmCurrentPrompt();
5289                updateSystemUiVisibilityLw();
5290            }
5291        }
5292    }
5293
5294    // Called on the PowerManager's Notifier thread.
5295    @Override
5296    public void startedGoingToSleep(int why) {
5297        if (DEBUG_WAKEUP) Slog.i(TAG, "Started going to sleep... (why=" + why + ")");
5298        if (mKeyguardDelegate != null) {
5299            mKeyguardDelegate.onStartedGoingToSleep(why);
5300        }
5301    }
5302
5303    // Called on the PowerManager's Notifier thread.
5304    @Override
5305    public void finishedGoingToSleep(int why) {
5306        EventLog.writeEvent(70000, 0);
5307        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished going to sleep... (why=" + why + ")");
5308
5309        // We must get this work done here because the power manager will drop
5310        // the wake lock and let the system suspend once this function returns.
5311        synchronized (mLock) {
5312            mAwake = false;
5313            mKeyguardDrawComplete = false;
5314            updateWakeGestureListenerLp();
5315            updateOrientationListenerLp();
5316            updateLockScreenTimeout();
5317        }
5318        if (mKeyguardDelegate != null) {
5319            mKeyguardDelegate.onFinishedGoingToSleep(why);
5320        }
5321    }
5322
5323    // Called on the PowerManager's Notifier thread.
5324    @Override
5325    public void startedWakingUp() {
5326        EventLog.writeEvent(70000, 1);
5327        if (DEBUG_WAKEUP) Slog.i(TAG, "Started waking up...");
5328
5329        // Since goToSleep performs these functions synchronously, we must
5330        // do the same here.  We cannot post this work to a handler because
5331        // that might cause it to become reordered with respect to what
5332        // may happen in a future call to goToSleep.
5333        synchronized (mLock) {
5334            mAwake = true;
5335            mKeyguardDrawComplete = false;
5336            if (mKeyguardDelegate != null) {
5337                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
5338                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
5339            }
5340
5341            updateWakeGestureListenerLp();
5342            updateOrientationListenerLp();
5343            updateLockScreenTimeout();
5344        }
5345
5346        if (mKeyguardDelegate != null) {
5347            mKeyguardDelegate.onStartedWakingUp(mKeyguardDelegateCallback);
5348            // ... eventually calls finishKeyguardDrawn
5349        } else {
5350            if (DEBUG_WAKEUP) Slog.d(TAG, "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
5351            finishKeyguardDrawn();
5352        }
5353    }
5354
5355    // Called on the PowerManager's Notifier thread.
5356    @Override
5357    public void finishedWakingUp() {
5358        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");
5359    }
5360
5361    private void wakeUpFromPowerKey(long eventTime) {
5362        wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey);
5363    }
5364
5365    private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode) {
5366        if (!wakeInTheaterMode && isTheaterModeEnabled()) {
5367            return false;
5368        }
5369
5370        mPowerManager.wakeUp(wakeTime);
5371        return true;
5372    }
5373
5374    private void finishKeyguardDrawn() {
5375        synchronized (mLock) {
5376            if (!mAwake || mKeyguardDrawComplete) {
5377                return; // We are not awake yet or we have already informed of this event.
5378            }
5379
5380            mKeyguardDrawComplete = true;
5381            if (mKeyguardDelegate != null) {
5382                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
5383            }
5384        }
5385
5386        finishScreenTurningOn();
5387    }
5388
5389    // Called on the DisplayManager's DisplayPowerController thread.
5390    @Override
5391    public void screenTurnedOff() {
5392        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turned off...");
5393
5394        updateScreenOffSleepToken(true);
5395        synchronized (mLock) {
5396            mScreenOnEarly = false;
5397            mScreenOnFully = false;
5398            mWindowManagerDrawComplete = false;
5399            mScreenOnListener = null;
5400            updateOrientationListenerLp();
5401        }
5402    }
5403
5404    // Called on the DisplayManager's DisplayPowerController thread.
5405    @Override
5406    public void screenTurningOn(final ScreenOnListener screenOnListener) {
5407        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
5408
5409        updateScreenOffSleepToken(false);
5410        synchronized (mLock) {
5411            mScreenOnEarly = true;
5412            mScreenOnFully = false;
5413            mWindowManagerDrawComplete = false;
5414            mScreenOnListener = screenOnListener;
5415        }
5416
5417        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
5418                WAITING_FOR_DRAWN_TIMEOUT);
5419        // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
5420        // as well as enabling the orientation change logic/sensor.
5421    }
5422
5423    private void finishWindowsDrawn() {
5424        synchronized (mLock) {
5425            if (!mScreenOnEarly || mWindowManagerDrawComplete) {
5426                return; // Screen is not turned on or we did already handle this case earlier.
5427            }
5428
5429            mWindowManagerDrawComplete = true;
5430        }
5431
5432        finishScreenTurningOn();
5433    }
5434
5435    private void finishScreenTurningOn() {
5436        synchronized (mLock) {
5437            // We have just finished drawing screen content. Since the orientation listener
5438            // gets only installed when all windows are drawn, we try to install it again.
5439            updateOrientationListenerLp();
5440        }
5441        final ScreenOnListener listener;
5442        final boolean enableScreen;
5443        synchronized (mLock) {
5444            if (DEBUG_WAKEUP) Slog.d(TAG,
5445                    "finishScreenTurningOn: mAwake=" + mAwake
5446                            + ", mScreenOnEarly=" + mScreenOnEarly
5447                            + ", mScreenOnFully=" + mScreenOnFully
5448                            + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
5449                            + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
5450
5451            if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
5452                    || (mAwake && !mKeyguardDrawComplete)) {
5453                return; // spurious or not ready yet
5454            }
5455
5456            if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
5457            listener = mScreenOnListener;
5458            mScreenOnListener = null;
5459            mScreenOnFully = true;
5460
5461            // Remember the first time we draw the keyguard so we know when we're done with
5462            // the main part of booting and can enable the screen and hide boot messages.
5463            if (!mKeyguardDrawnOnce && mAwake) {
5464                mKeyguardDrawnOnce = true;
5465                enableScreen = true;
5466                if (mBootMessageNeedsHiding) {
5467                    mBootMessageNeedsHiding = false;
5468                    hideBootMessages();
5469                }
5470            } else {
5471                enableScreen = false;
5472            }
5473        }
5474
5475        if (listener != null) {
5476            listener.onScreenOn();
5477        }
5478
5479        if (enableScreen) {
5480            try {
5481                mWindowManager.enableScreenIfNeeded();
5482            } catch (RemoteException unhandled) {
5483            }
5484        }
5485    }
5486
5487    private void handleHideBootMessage() {
5488        synchronized (mLock) {
5489            if (!mKeyguardDrawnOnce) {
5490                mBootMessageNeedsHiding = true;
5491                return; // keyguard hasn't drawn the first time yet, not done booting
5492            }
5493        }
5494
5495        if (mBootMsgDialog != null) {
5496            if (DEBUG_WAKEUP) Slog.d(TAG, "handleHideBootMessage: dismissing");
5497            mBootMsgDialog.dismiss();
5498            mBootMsgDialog = null;
5499        }
5500    }
5501
5502    @Override
5503    public boolean isScreenOn() {
5504        return mScreenOnFully;
5505    }
5506
5507    /** {@inheritDoc} */
5508    @Override
5509    public void enableKeyguard(boolean enabled) {
5510        if (mKeyguardDelegate != null) {
5511            mKeyguardDelegate.setKeyguardEnabled(enabled);
5512        }
5513    }
5514
5515    /** {@inheritDoc} */
5516    @Override
5517    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
5518        if (mKeyguardDelegate != null) {
5519            mKeyguardDelegate.verifyUnlock(callback);
5520        }
5521    }
5522
5523    private boolean isKeyguardShowingAndNotOccluded() {
5524        if (mKeyguardDelegate == null) return false;
5525        return mKeyguardDelegate.isShowing() && !mKeyguardOccluded;
5526    }
5527
5528    /** {@inheritDoc} */
5529    @Override
5530    public boolean isKeyguardLocked() {
5531        return keyguardOn();
5532    }
5533
5534    /** {@inheritDoc} */
5535    @Override
5536    public boolean isKeyguardSecure() {
5537        if (mKeyguardDelegate == null) return false;
5538        return mKeyguardDelegate.isSecure();
5539    }
5540
5541    /** {@inheritDoc} */
5542    @Override
5543    public boolean isKeyguardShowingOrOccluded() {
5544        return mKeyguardDelegate == null ? false : mKeyguardDelegate.isShowing();
5545    }
5546
5547    /** {@inheritDoc} */
5548    @Override
5549    public boolean inKeyguardRestrictedKeyInputMode() {
5550        if (mKeyguardDelegate == null) return false;
5551        return mKeyguardDelegate.isInputRestricted();
5552    }
5553
5554    @Override
5555    public void dismissKeyguardLw() {
5556        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
5557            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.dismissKeyguardLw");
5558            mHandler.post(new Runnable() {
5559                @Override
5560                public void run() {
5561                    // ask the keyguard to prompt the user to authenticate if necessary
5562                    mKeyguardDelegate.dismiss();
5563                }
5564            });
5565        }
5566    }
5567
5568    public void notifyActivityDrawnForKeyguardLw() {
5569        if (mKeyguardDelegate != null) {
5570            mHandler.post(new Runnable() {
5571                @Override
5572                public void run() {
5573                    mKeyguardDelegate.onActivityDrawn();
5574                }
5575            });
5576        }
5577    }
5578
5579    @Override
5580    public boolean isKeyguardDrawnLw() {
5581        synchronized (mLock) {
5582            return mKeyguardDrawnOnce;
5583        }
5584    }
5585
5586    @Override
5587    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
5588        if (mKeyguardDelegate != null) {
5589            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation");
5590            mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration);
5591        }
5592    }
5593
5594    void sendCloseSystemWindows() {
5595        PhoneWindow.sendCloseSystemWindows(mContext, null);
5596    }
5597
5598    void sendCloseSystemWindows(String reason) {
5599        PhoneWindow.sendCloseSystemWindows(mContext, reason);
5600    }
5601
5602    @Override
5603    public int rotationForOrientationLw(int orientation, int lastRotation) {
5604        if (false) {
5605            Slog.v(TAG, "rotationForOrientationLw(orient="
5606                        + orientation + ", last=" + lastRotation
5607                        + "); user=" + mUserRotation + " "
5608                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
5609                            ? "USER_ROTATION_LOCKED" : "")
5610                        );
5611        }
5612
5613        if (mForceDefaultOrientation) {
5614            return Surface.ROTATION_0;
5615        }
5616
5617        synchronized (mLock) {
5618            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
5619            if (sensorRotation < 0) {
5620                sensorRotation = lastRotation;
5621            }
5622
5623            final int preferredRotation;
5624            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
5625                // Ignore sensor when lid switch is open and rotation is forced.
5626                preferredRotation = mLidOpenRotation;
5627            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
5628                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
5629                // Ignore sensor when in car dock unless explicitly enabled.
5630                // This case can override the behavior of NOSENSOR, and can also
5631                // enable 180 degree rotation while docked.
5632                preferredRotation = mCarDockEnablesAccelerometer
5633                        ? sensorRotation : mCarDockRotation;
5634            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
5635                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
5636                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
5637                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
5638                // Ignore sensor when in desk dock unless explicitly enabled.
5639                // This case can override the behavior of NOSENSOR, and can also
5640                // enable 180 degree rotation while docked.
5641                preferredRotation = mDeskDockEnablesAccelerometer
5642                        ? sensorRotation : mDeskDockRotation;
5643            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
5644                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
5645                // Note that the dock orientation overrides the HDMI orientation.
5646                preferredRotation = mDemoHdmiRotation;
5647            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
5648                    && mUndockedHdmiRotation >= 0) {
5649                // Ignore sensor when plugged into HDMI and an undocked orientation has
5650                // been specified in the configuration (only for legacy devices without
5651                // full multi-display support).
5652                // Note that the dock orientation overrides the HDMI orientation.
5653                preferredRotation = mUndockedHdmiRotation;
5654            } else if (mDemoRotationLock) {
5655                // Ignore sensor when demo rotation lock is enabled.
5656                // Note that the dock orientation and HDMI rotation lock override this.
5657                preferredRotation = mDemoRotation;
5658            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
5659                // Application just wants to remain locked in the last rotation.
5660                preferredRotation = lastRotation;
5661            } else if (!mSupportAutoRotation) {
5662                // If we don't support auto-rotation then bail out here and ignore
5663                // the sensor and any rotation lock settings.
5664                preferredRotation = -1;
5665            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
5666                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
5667                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
5668                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
5669                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
5670                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
5671                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
5672                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
5673                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
5674                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
5675                // Otherwise, use sensor only if requested by the application or enabled
5676                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
5677                if (mAllowAllRotations < 0) {
5678                    // Can't read this during init() because the context doesn't
5679                    // have display metrics at that time so we cannot determine
5680                    // tablet vs. phone then.
5681                    mAllowAllRotations = mContext.getResources().getBoolean(
5682                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
5683                }
5684                if (sensorRotation != Surface.ROTATION_180
5685                        || mAllowAllRotations == 1
5686                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
5687                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
5688                    preferredRotation = sensorRotation;
5689                } else {
5690                    preferredRotation = lastRotation;
5691                }
5692            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
5693                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
5694                // Apply rotation lock.  Does not apply to NOSENSOR.
5695                // The idea is that the user rotation expresses a weak preference for the direction
5696                // of gravity and as NOSENSOR is never affected by gravity, then neither should
5697                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
5698                preferredRotation = mUserRotation;
5699            } else {
5700                // No overriding preference.
5701                // We will do exactly what the application asked us to do.
5702                preferredRotation = -1;
5703            }
5704
5705            switch (orientation) {
5706                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
5707                    // Return portrait unless overridden.
5708                    if (isAnyPortrait(preferredRotation)) {
5709                        return preferredRotation;
5710                    }
5711                    return mPortraitRotation;
5712
5713                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
5714                    // Return landscape unless overridden.
5715                    if (isLandscapeOrSeascape(preferredRotation)) {
5716                        return preferredRotation;
5717                    }
5718                    return mLandscapeRotation;
5719
5720                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
5721                    // Return reverse portrait unless overridden.
5722                    if (isAnyPortrait(preferredRotation)) {
5723                        return preferredRotation;
5724                    }
5725                    return mUpsideDownRotation;
5726
5727                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
5728                    // Return seascape unless overridden.
5729                    if (isLandscapeOrSeascape(preferredRotation)) {
5730                        return preferredRotation;
5731                    }
5732                    return mSeascapeRotation;
5733
5734                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
5735                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
5736                    // Return either landscape rotation.
5737                    if (isLandscapeOrSeascape(preferredRotation)) {
5738                        return preferredRotation;
5739                    }
5740                    if (isLandscapeOrSeascape(lastRotation)) {
5741                        return lastRotation;
5742                    }
5743                    return mLandscapeRotation;
5744
5745                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
5746                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
5747                    // Return either portrait rotation.
5748                    if (isAnyPortrait(preferredRotation)) {
5749                        return preferredRotation;
5750                    }
5751                    if (isAnyPortrait(lastRotation)) {
5752                        return lastRotation;
5753                    }
5754                    return mPortraitRotation;
5755
5756                default:
5757                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
5758                    // just return the preferred orientation we already calculated.
5759                    if (preferredRotation >= 0) {
5760                        return preferredRotation;
5761                    }
5762                    return Surface.ROTATION_0;
5763            }
5764        }
5765    }
5766
5767    @Override
5768    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
5769        switch (orientation) {
5770            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
5771            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
5772            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
5773                return isAnyPortrait(rotation);
5774
5775            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
5776            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
5777            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
5778                return isLandscapeOrSeascape(rotation);
5779
5780            default:
5781                return true;
5782        }
5783    }
5784
5785    @Override
5786    public void setRotationLw(int rotation) {
5787        mOrientationListener.setCurrentRotation(rotation);
5788    }
5789
5790    private boolean isLandscapeOrSeascape(int rotation) {
5791        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
5792    }
5793
5794    private boolean isAnyPortrait(int rotation) {
5795        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
5796    }
5797
5798    @Override
5799    public int getUserRotationMode() {
5800        return Settings.System.getIntForUser(mContext.getContentResolver(),
5801                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
5802                        WindowManagerPolicy.USER_ROTATION_FREE :
5803                                WindowManagerPolicy.USER_ROTATION_LOCKED;
5804    }
5805
5806    // User rotation: to be used when all else fails in assigning an orientation to the device
5807    @Override
5808    public void setUserRotationMode(int mode, int rot) {
5809        ContentResolver res = mContext.getContentResolver();
5810
5811        // mUserRotationMode and mUserRotation will be assigned by the content observer
5812        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
5813            Settings.System.putIntForUser(res,
5814                    Settings.System.USER_ROTATION,
5815                    rot,
5816                    UserHandle.USER_CURRENT);
5817            Settings.System.putIntForUser(res,
5818                    Settings.System.ACCELEROMETER_ROTATION,
5819                    0,
5820                    UserHandle.USER_CURRENT);
5821        } else {
5822            Settings.System.putIntForUser(res,
5823                    Settings.System.ACCELEROMETER_ROTATION,
5824                    1,
5825                    UserHandle.USER_CURRENT);
5826        }
5827    }
5828
5829    @Override
5830    public void setSafeMode(boolean safeMode) {
5831        mSafeMode = safeMode;
5832        performHapticFeedbackLw(null, safeMode
5833                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
5834                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
5835    }
5836
5837    static long[] getLongIntArray(Resources r, int resid) {
5838        int[] ar = r.getIntArray(resid);
5839        if (ar == null) {
5840            return null;
5841        }
5842        long[] out = new long[ar.length];
5843        for (int i=0; i<ar.length; i++) {
5844            out[i] = ar[i];
5845        }
5846        return out;
5847    }
5848
5849    /** {@inheritDoc} */
5850    @Override
5851    public void systemReady() {
5852        mKeyguardDelegate = new KeyguardServiceDelegate(mContext);
5853        mKeyguardDelegate.onSystemReady();
5854
5855        readCameraLensCoverState();
5856        updateUiMode();
5857        synchronized (mLock) {
5858            updateOrientationListenerLp();
5859            mSystemReady = true;
5860            mHandler.post(new Runnable() {
5861                @Override
5862                public void run() {
5863                    updateSettings();
5864                }
5865            });
5866        }
5867    }
5868
5869    /** {@inheritDoc} */
5870    @Override
5871    public void systemBooted() {
5872        if (mKeyguardDelegate != null) {
5873            mKeyguardDelegate.bindService(mContext);
5874            mKeyguardDelegate.onBootCompleted();
5875        }
5876        synchronized (mLock) {
5877            mSystemBooted = true;
5878        }
5879        startedWakingUp();
5880        screenTurningOn(null);
5881    }
5882
5883    ProgressDialog mBootMsgDialog = null;
5884
5885    /** {@inheritDoc} */
5886    @Override
5887    public void showBootMessage(final CharSequence msg, final boolean always) {
5888        mHandler.post(new Runnable() {
5889            @Override public void run() {
5890                if (mBootMsgDialog == null) {
5891                    int theme;
5892                    if (mContext.getPackageManager().hasSystemFeature(
5893                            PackageManager.FEATURE_WATCH)) {
5894                        theme = com.android.internal.R.style.Theme_Micro_Dialog_Alert;
5895                    } else if (mContext.getPackageManager().hasSystemFeature(
5896                            PackageManager.FEATURE_TELEVISION)) {
5897                        theme = com.android.internal.R.style.Theme_Leanback_Dialog_Alert;
5898                    } else {
5899                        theme = 0;
5900                    }
5901
5902                    mBootMsgDialog = new ProgressDialog(mContext, theme) {
5903                        // This dialog will consume all events coming in to
5904                        // it, to avoid it trying to do things too early in boot.
5905                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
5906                            return true;
5907                        }
5908                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5909                            return true;
5910                        }
5911                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
5912                            return true;
5913                        }
5914                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
5915                            return true;
5916                        }
5917                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
5918                            return true;
5919                        }
5920                        @Override public boolean dispatchPopulateAccessibilityEvent(
5921                                AccessibilityEvent event) {
5922                            return true;
5923                        }
5924                    };
5925                    if (mContext.getPackageManager().isUpgrade()) {
5926                        mBootMsgDialog.setTitle(R.string.android_upgrading_title);
5927                    } else {
5928                        mBootMsgDialog.setTitle(R.string.android_start_title);
5929                    }
5930                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
5931                    mBootMsgDialog.setIndeterminate(true);
5932                    mBootMsgDialog.getWindow().setType(
5933                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
5934                    mBootMsgDialog.getWindow().addFlags(
5935                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
5936                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
5937                    mBootMsgDialog.getWindow().setDimAmount(1);
5938                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
5939                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
5940                    mBootMsgDialog.getWindow().setAttributes(lp);
5941                    mBootMsgDialog.setCancelable(false);
5942                    mBootMsgDialog.show();
5943                }
5944                mBootMsgDialog.setMessage(msg);
5945            }
5946        });
5947    }
5948
5949    /** {@inheritDoc} */
5950    @Override
5951    public void hideBootMessages() {
5952        mHandler.sendEmptyMessage(MSG_HIDE_BOOT_MESSAGE);
5953    }
5954
5955    /** {@inheritDoc} */
5956    @Override
5957    public void userActivity() {
5958        // ***************************************
5959        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
5960        // ***************************************
5961        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
5962        // WITH ITS LOCKS HELD.
5963        //
5964        // This code must be VERY careful about the locks
5965        // it acquires.
5966        // In fact, the current code acquires way too many,
5967        // and probably has lurking deadlocks.
5968
5969        synchronized (mScreenLockTimeout) {
5970            if (mLockScreenTimerActive) {
5971                // reset the timer
5972                mHandler.removeCallbacks(mScreenLockTimeout);
5973                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
5974            }
5975        }
5976    }
5977
5978    class ScreenLockTimeout implements Runnable {
5979        Bundle options;
5980
5981        @Override
5982        public void run() {
5983            synchronized (this) {
5984                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
5985                if (mKeyguardDelegate != null) {
5986                    mKeyguardDelegate.doKeyguardTimeout(options);
5987                }
5988                mLockScreenTimerActive = false;
5989                options = null;
5990            }
5991        }
5992
5993        public void setLockOptions(Bundle options) {
5994            this.options = options;
5995        }
5996    }
5997
5998    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
5999
6000    @Override
6001    public void lockNow(Bundle options) {
6002        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
6003        mHandler.removeCallbacks(mScreenLockTimeout);
6004        if (options != null) {
6005            // In case multiple calls are made to lockNow, we don't wipe out the options
6006            // until the runnable actually executes.
6007            mScreenLockTimeout.setLockOptions(options);
6008        }
6009        mHandler.post(mScreenLockTimeout);
6010    }
6011
6012    private void updateLockScreenTimeout() {
6013        synchronized (mScreenLockTimeout) {
6014            boolean enable = (mAllowLockscreenWhenOn && mAwake &&
6015                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
6016            if (mLockScreenTimerActive != enable) {
6017                if (enable) {
6018                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
6019                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6020                } else {
6021                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
6022                    mHandler.removeCallbacks(mScreenLockTimeout);
6023                }
6024                mLockScreenTimerActive = enable;
6025            }
6026        }
6027    }
6028
6029    private void updateDreamingSleepToken(boolean acquire) {
6030        if (acquire) {
6031            if (mDreamingSleepToken == null) {
6032                mDreamingSleepToken = mActivityManagerInternal.acquireSleepToken("Dream");
6033            }
6034        } else {
6035            if (mDreamingSleepToken != null) {
6036                mDreamingSleepToken.release();
6037                mDreamingSleepToken = null;
6038            }
6039        }
6040    }
6041
6042    private void updateScreenOffSleepToken(boolean acquire) {
6043        if (acquire) {
6044            if (mScreenOffSleepToken == null) {
6045                mScreenOffSleepToken = mActivityManagerInternal.acquireSleepToken("ScreenOff");
6046            }
6047        } else {
6048            if (mScreenOffSleepToken != null) {
6049                mScreenOffSleepToken.release();
6050                mScreenOffSleepToken = null;
6051            }
6052        }
6053    }
6054
6055    /** {@inheritDoc} */
6056    @Override
6057    public void enableScreenAfterBoot() {
6058        readLidState();
6059        applyLidSwitchState();
6060        updateRotation(true);
6061    }
6062
6063    private void applyLidSwitchState() {
6064        if (mLidState == LID_CLOSED && mLidControlsSleep) {
6065            mPowerManager.goToSleep(SystemClock.uptimeMillis(),
6066                    PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
6067                    PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
6068        }
6069
6070        synchronized (mLock) {
6071            updateWakeGestureListenerLp();
6072        }
6073    }
6074
6075    void updateUiMode() {
6076        if (mUiModeManager == null) {
6077            mUiModeManager = IUiModeManager.Stub.asInterface(
6078                    ServiceManager.getService(Context.UI_MODE_SERVICE));
6079        }
6080        try {
6081            mUiMode = mUiModeManager.getCurrentModeType();
6082        } catch (RemoteException e) {
6083        }
6084    }
6085
6086    void updateRotation(boolean alwaysSendConfiguration) {
6087        try {
6088            //set orientation on WindowManager
6089            mWindowManager.updateRotation(alwaysSendConfiguration, false);
6090        } catch (RemoteException e) {
6091            // Ignore
6092        }
6093    }
6094
6095    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
6096        try {
6097            //set orientation on WindowManager
6098            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
6099        } catch (RemoteException e) {
6100            // Ignore
6101        }
6102    }
6103
6104    /**
6105     * Return an Intent to launch the currently active dock app as home.  Returns
6106     * null if the standard home should be launched, which is the case if any of the following is
6107     * true:
6108     * <ul>
6109     *  <li>The device is not in either car mode or desk mode
6110     *  <li>The device is in car mode but ENABLE_CAR_DOCK_HOME_CAPTURE is false
6111     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
6112     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
6113     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
6114     * </ul>
6115     * @return A dock intent.
6116     */
6117    Intent createHomeDockIntent() {
6118        Intent intent = null;
6119
6120        // What home does is based on the mode, not the dock state.  That
6121        // is, when in car mode you should be taken to car home regardless
6122        // of whether we are actually in a car dock.
6123        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
6124            if (ENABLE_CAR_DOCK_HOME_CAPTURE) {
6125                intent = mCarDockIntent;
6126            }
6127        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
6128            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
6129                intent = mDeskDockIntent;
6130            }
6131        } else if (mUiMode == Configuration.UI_MODE_TYPE_WATCH
6132                && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6133                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK
6134                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK)) {
6135            // Always launch dock home from home when watch is docked, if it exists.
6136            intent = mDeskDockIntent;
6137        }
6138
6139        if (intent == null) {
6140            return null;
6141        }
6142
6143        ActivityInfo ai = null;
6144        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
6145                intent,
6146                PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
6147                mCurrentUserId);
6148        if (info != null) {
6149            ai = info.activityInfo;
6150        }
6151        if (ai != null
6152                && ai.metaData != null
6153                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
6154            intent = new Intent(intent);
6155            intent.setClassName(ai.packageName, ai.name);
6156            return intent;
6157        }
6158
6159        return null;
6160    }
6161
6162    void startDockOrHome(boolean fromHomeKey, boolean awakenFromDreams) {
6163        if (awakenFromDreams) {
6164            awakenDreams();
6165        }
6166
6167        Intent dock = createHomeDockIntent();
6168        if (dock != null) {
6169            try {
6170                if (fromHomeKey) {
6171                    dock.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6172                }
6173                startActivityAsUser(dock, UserHandle.CURRENT);
6174                return;
6175            } catch (ActivityNotFoundException e) {
6176            }
6177        }
6178
6179        Intent intent;
6180
6181        if (fromHomeKey) {
6182            intent = new Intent(mHomeIntent);
6183            intent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6184        } else {
6185            intent = mHomeIntent;
6186        }
6187
6188        startActivityAsUser(intent, UserHandle.CURRENT);
6189    }
6190
6191    /**
6192     * goes to the home screen
6193     * @return whether it did anything
6194     */
6195    boolean goHome() {
6196        if (!isUserSetupComplete()) {
6197            Slog.i(TAG, "Not going home because user setup is in progress.");
6198            return false;
6199        }
6200        if (false) {
6201            // This code always brings home to the front.
6202            try {
6203                ActivityManagerNative.getDefault().stopAppSwitches();
6204            } catch (RemoteException e) {
6205            }
6206            sendCloseSystemWindows();
6207            startDockOrHome(false /*fromHomeKey*/, true /* awakenFromDreams */);
6208        } else {
6209            // This code brings home to the front or, if it is already
6210            // at the front, puts the device to sleep.
6211            try {
6212                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
6213                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
6214                    Log.d(TAG, "UTS-TEST-MODE");
6215                } else {
6216                    ActivityManagerNative.getDefault().stopAppSwitches();
6217                    sendCloseSystemWindows();
6218                    Intent dock = createHomeDockIntent();
6219                    if (dock != null) {
6220                        int result = ActivityManagerNative.getDefault()
6221                                .startActivityAsUser(null, null, dock,
6222                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
6223                                        null, null, 0,
6224                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6225                                        null, null, UserHandle.USER_CURRENT);
6226                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6227                            return false;
6228                        }
6229                    }
6230                }
6231                int result = ActivityManagerNative.getDefault()
6232                        .startActivityAsUser(null, null, mHomeIntent,
6233                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
6234                                null, null, 0,
6235                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6236                                null, null, UserHandle.USER_CURRENT);
6237                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6238                    return false;
6239                }
6240            } catch (RemoteException ex) {
6241                // bummer, the activity manager, which is in this process, is dead
6242            }
6243        }
6244        return true;
6245    }
6246
6247    @Override
6248    public void setCurrentOrientationLw(int newOrientation) {
6249        synchronized (mLock) {
6250            if (newOrientation != mCurrentAppOrientation) {
6251                mCurrentAppOrientation = newOrientation;
6252                updateOrientationListenerLp();
6253            }
6254        }
6255    }
6256
6257    private void performAuditoryFeedbackForAccessibilityIfNeed() {
6258        if (!isGlobalAccessibilityGestureEnabled()) {
6259            return;
6260        }
6261        AudioManager audioManager = (AudioManager) mContext.getSystemService(
6262                Context.AUDIO_SERVICE);
6263        if (audioManager.isSilentMode()) {
6264            return;
6265        }
6266        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
6267                Settings.System.DEFAULT_NOTIFICATION_URI);
6268        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
6269        ringTone.play();
6270    }
6271
6272    private boolean isTheaterModeEnabled() {
6273        return Settings.Global.getInt(mContext.getContentResolver(),
6274                Settings.Global.THEATER_MODE_ON, 0) == 1;
6275    }
6276
6277    private boolean isGlobalAccessibilityGestureEnabled() {
6278        return Settings.Global.getInt(mContext.getContentResolver(),
6279                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
6280    }
6281
6282    @Override
6283    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
6284        if (!mVibrator.hasVibrator()) {
6285            return false;
6286        }
6287        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
6288                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
6289        if (hapticsDisabled && !always) {
6290            return false;
6291        }
6292        long[] pattern = null;
6293        switch (effectId) {
6294            case HapticFeedbackConstants.LONG_PRESS:
6295                pattern = mLongPressVibePattern;
6296                break;
6297            case HapticFeedbackConstants.VIRTUAL_KEY:
6298                pattern = mVirtualKeyVibePattern;
6299                break;
6300            case HapticFeedbackConstants.KEYBOARD_TAP:
6301                pattern = mKeyboardTapVibePattern;
6302                break;
6303            case HapticFeedbackConstants.CLOCK_TICK:
6304                pattern = mClockTickVibePattern;
6305                break;
6306            case HapticFeedbackConstants.CALENDAR_DATE:
6307                pattern = mCalendarDateVibePattern;
6308                break;
6309            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
6310                pattern = mSafeModeDisabledVibePattern;
6311                break;
6312            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
6313                pattern = mSafeModeEnabledVibePattern;
6314                break;
6315            case HapticFeedbackConstants.CONTEXT_CLICK:
6316                pattern = mContextClickVibePattern;
6317                break;
6318            default:
6319                return false;
6320        }
6321        int owningUid;
6322        String owningPackage;
6323        if (win != null) {
6324            owningUid = win.getOwningUid();
6325            owningPackage = win.getOwningPackage();
6326        } else {
6327            owningUid = android.os.Process.myUid();
6328            owningPackage = mContext.getOpPackageName();
6329        }
6330        if (pattern.length == 1) {
6331            // One-shot vibration
6332            mVibrator.vibrate(owningUid, owningPackage, pattern[0], VIBRATION_ATTRIBUTES);
6333        } else {
6334            // Pattern vibration
6335            mVibrator.vibrate(owningUid, owningPackage, pattern, -1, VIBRATION_ATTRIBUTES);
6336        }
6337        return true;
6338    }
6339
6340    @Override
6341    public void keepScreenOnStartedLw() {
6342    }
6343
6344    @Override
6345    public void keepScreenOnStoppedLw() {
6346        if (isKeyguardShowingAndNotOccluded()) {
6347            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
6348        }
6349    }
6350
6351    private int updateSystemUiVisibilityLw() {
6352        // If there is no window focused, there will be nobody to handle the events
6353        // anyway, so just hang on in whatever state we're in until things settle down.
6354        final WindowState win = mFocusedWindow != null ? mFocusedWindow
6355                : mTopFullscreenOpaqueWindowState;
6356        if (win == null) {
6357            return 0;
6358        }
6359        if ((win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 && mHideLockScreen == true) {
6360            // We are updating at a point where the keyguard has gotten
6361            // focus, but we were last in a state where the top window is
6362            // hiding it.  This is probably because the keyguard as been
6363            // shown while the top window was displayed, so we want to ignore
6364            // it here because this is just a very transient change and it
6365            // will quickly lose focus once it correctly gets hidden.
6366            return 0;
6367        }
6368
6369        int tmpVisibility = PolicyControl.getSystemUiVisibility(win, null)
6370                & ~mResettingSystemUiFlags
6371                & ~mForceClearedSystemUiFlags;
6372        if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
6373            tmpVisibility &= ~PolicyControl.adjustClearableFlags(win, View.SYSTEM_UI_CLEARABLE_FLAGS);
6374        }
6375        tmpVisibility = updateLightStatusBarLw(tmpVisibility);
6376        final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
6377        final int diff = visibility ^ mLastSystemUiFlags;
6378        final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
6379        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
6380                && mFocusedApp == win.getAppToken()) {
6381            return 0;
6382        }
6383        mLastSystemUiFlags = visibility;
6384        mLastFocusNeedsMenu = needsMenu;
6385        mFocusedApp = win.getAppToken();
6386        mHandler.post(new Runnable() {
6387                @Override
6388                public void run() {
6389                    try {
6390                        IStatusBarService statusbar = getStatusBarService();
6391                        if (statusbar != null) {
6392                            statusbar.setSystemUiVisibility(visibility, 0xffffffff, win.toString());
6393                            statusbar.topAppWindowChanged(needsMenu);
6394                        }
6395                    } catch (RemoteException e) {
6396                        // re-acquire status bar service next time it is needed.
6397                        mStatusBarService = null;
6398                    }
6399                }
6400            });
6401        return diff;
6402    }
6403
6404    private int updateLightStatusBarLw(int vis) {
6405        WindowState statusColorWin = isStatusBarKeyguard() && !mHideLockScreen
6406                ? mStatusBar
6407                : mTopFullscreenOpaqueOrDimmingWindowState;
6408
6409        if (statusColorWin != null) {
6410            if (statusColorWin == mTopFullscreenOpaqueWindowState) {
6411                // If the top fullscreen-or-dimming window is also the top fullscreen, respect
6412                // its light flag.
6413                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6414                vis |= PolicyControl.getSystemUiVisibility(statusColorWin, null)
6415                        & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6416            } else if (statusColorWin != null && statusColorWin.isDimming()) {
6417                // Otherwise if it's dimming, clear the light flag.
6418                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6419            }
6420        }
6421        return vis;
6422    }
6423
6424    private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
6425        // apply translucent bar vis flags
6426        WindowState transWin = isStatusBarKeyguard() && !mHideLockScreen
6427                ? mStatusBar
6428                : mTopFullscreenOpaqueWindowState;
6429        vis = mStatusBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
6430        vis = mNavigationBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
6431
6432        // prevent status bar interaction from clearing certain flags
6433        int type = win.getAttrs().type;
6434        boolean statusBarHasFocus = type == TYPE_STATUS_BAR;
6435        if (statusBarHasFocus && !isStatusBarKeyguard()) {
6436            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
6437                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
6438                    | View.SYSTEM_UI_FLAG_IMMERSIVE
6439                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
6440                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
6441            if (mHideLockScreen) {
6442                flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
6443            }
6444            vis = (vis & ~flags) | (oldVis & flags);
6445        }
6446
6447        if (!areTranslucentBarsAllowed() && transWin != mStatusBar) {
6448            vis &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSLUCENT
6449                    | View.SYSTEM_UI_TRANSPARENT);
6450        }
6451
6452        // update status bar
6453        boolean immersiveSticky =
6454                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
6455        boolean hideStatusBarWM =
6456                mTopFullscreenOpaqueWindowState != null &&
6457                (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
6458                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
6459        boolean hideStatusBarSysui =
6460                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
6461        boolean hideNavBarSysui =
6462                (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
6463
6464        boolean transientStatusBarAllowed =
6465                mStatusBar != null && (
6466                hideStatusBarWM
6467                || (hideStatusBarSysui && immersiveSticky)
6468                || statusBarHasFocus);
6469
6470        boolean transientNavBarAllowed =
6471                mNavigationBar != null &&
6472                hideNavBarSysui && immersiveSticky;
6473
6474        final long now = SystemClock.uptimeMillis();
6475        final boolean pendingPanic = mPendingPanicGestureUptime != 0
6476                && now - mPendingPanicGestureUptime <= PANIC_GESTURE_EXPIRATION;
6477        if (pendingPanic && hideNavBarSysui && !isStatusBarKeyguard() && mKeyguardDrawComplete) {
6478            // The user performed the panic gesture recently, we're about to hide the bars,
6479            // we're no longer on the Keyguard and the screen is ready. We can now request the bars.
6480            mPendingPanicGestureUptime = 0;
6481            mStatusBarController.showTransient();
6482            mNavigationBarController.showTransient();
6483        }
6484
6485        boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
6486                && !transientStatusBarAllowed && hideStatusBarSysui;
6487        boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
6488                && !transientNavBarAllowed;
6489        if (denyTransientStatus || denyTransientNav) {
6490            // clear the clearable flags instead
6491            clearClearableFlagsLw();
6492            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
6493        }
6494
6495        final boolean immersive = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
6496        immersiveSticky = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
6497        final boolean navAllowedHidden = immersive || immersiveSticky;
6498
6499        if (hideNavBarSysui && !navAllowedHidden && windowTypeToLayerLw(win.getBaseType())
6500                > windowTypeToLayerLw(TYPE_INPUT_CONSUMER)) {
6501            // We can't hide the navbar from this window otherwise the input consumer would not get
6502            // the input events.
6503            vis = (vis & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
6504        }
6505
6506        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
6507
6508        // update navigation bar
6509        boolean oldImmersiveMode = isImmersiveMode(oldVis);
6510        boolean newImmersiveMode = isImmersiveMode(vis);
6511        if (win != null && oldImmersiveMode != newImmersiveMode) {
6512            final String pkg = win.getOwningPackage();
6513            mImmersiveModeConfirmation.immersiveModeChanged(pkg, newImmersiveMode,
6514                    isUserSetupComplete());
6515        }
6516
6517        vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
6518
6519        return vis;
6520    }
6521
6522    private void clearClearableFlagsLw() {
6523        int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
6524        if (newVal != mResettingSystemUiFlags) {
6525            mResettingSystemUiFlags = newVal;
6526            mWindowManagerFuncs.reevaluateStatusBarVisibility();
6527        }
6528    }
6529
6530    private boolean isImmersiveMode(int vis) {
6531        final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
6532        return mNavigationBar != null
6533                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
6534                && (vis & flags) != 0
6535                && canHideNavigationBar();
6536    }
6537
6538    /**
6539     * @return whether the navigation or status bar can be made translucent
6540     *
6541     * This should return true unless touch exploration is not enabled or
6542     * R.boolean.config_enableTranslucentDecor is false.
6543     */
6544    private boolean areTranslucentBarsAllowed() {
6545        return mTranslucentDecorEnabled
6546                && !mAccessibilityManager.isTouchExplorationEnabled();
6547    }
6548
6549    // Use this instead of checking config_showNavigationBar so that it can be consistently
6550    // overridden by qemu.hw.mainkeys in the emulator.
6551    @Override
6552    public boolean hasNavigationBar() {
6553        return mHasNavigationBar;
6554    }
6555
6556    @Override
6557    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
6558        mLastInputMethodWindow = ime;
6559        mLastInputMethodTargetWindow = target;
6560    }
6561
6562    @Override
6563    public int getInputMethodWindowVisibleHeightLw() {
6564        return mDockBottom - mCurBottom;
6565    }
6566
6567    @Override
6568    public void setCurrentUserLw(int newUserId) {
6569        mCurrentUserId = newUserId;
6570        if (mKeyguardDelegate != null) {
6571            mKeyguardDelegate.setCurrentUser(newUserId);
6572        }
6573        if (mStatusBarService != null) {
6574            try {
6575                mStatusBarService.setCurrentUser(newUserId);
6576            } catch (RemoteException e) {
6577                // oh well
6578            }
6579        }
6580        setLastInputMethodWindowLw(null, null);
6581    }
6582
6583    @Override
6584    public boolean canMagnifyWindow(int windowType) {
6585        switch (windowType) {
6586            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
6587            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
6588            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
6589            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
6590                return false;
6591            }
6592        }
6593        return true;
6594    }
6595
6596    @Override
6597    public boolean isTopLevelWindow(int windowType) {
6598        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
6599                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
6600            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
6601        }
6602        return true;
6603    }
6604
6605    @Override
6606    public void dump(String prefix, PrintWriter pw, String[] args) {
6607        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
6608                pw.print(" mSystemReady="); pw.print(mSystemReady);
6609                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
6610        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
6611                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
6612                pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
6613                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
6614        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
6615                || mForceClearedSystemUiFlags != 0) {
6616            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
6617                    pw.print(Integer.toHexString(mLastSystemUiFlags));
6618                    pw.print(" mResettingSystemUiFlags=0x");
6619                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
6620                    pw.print(" mForceClearedSystemUiFlags=0x");
6621                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
6622        }
6623        if (mLastFocusNeedsMenu) {
6624            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
6625                    pw.println(mLastFocusNeedsMenu);
6626        }
6627        pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
6628                pw.println(mWakeGestureEnabledSetting);
6629
6630        pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
6631        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
6632                pw.print(" mDockMode="); pw.print(mDockMode);
6633                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
6634                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
6635        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
6636                pw.print(" mUserRotation="); pw.print(mUserRotation);
6637                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
6638        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
6639        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
6640                pw.print(mCarDockEnablesAccelerometer);
6641                pw.print(" mDeskDockEnablesAccelerometer=");
6642                pw.println(mDeskDockEnablesAccelerometer);
6643        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
6644                pw.print(mLidKeyboardAccessibility);
6645                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
6646                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
6647        pw.print(prefix);
6648                pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
6649                pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
6650        pw.print(prefix);
6651                pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
6652                pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
6653        pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
6654        pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
6655        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
6656                pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
6657        pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
6658                pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
6659        pw.print(prefix); pw.print("mOrientationSensorEnabled=");
6660                pw.println(mOrientationSensorEnabled);
6661        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
6662                pw.print(","); pw.print(mOverscanScreenTop);
6663                pw.print(") "); pw.print(mOverscanScreenWidth);
6664                pw.print("x"); pw.println(mOverscanScreenHeight);
6665        if (mOverscanLeft != 0 || mOverscanTop != 0
6666                || mOverscanRight != 0 || mOverscanBottom != 0) {
6667            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
6668                    pw.print(" top="); pw.print(mOverscanTop);
6669                    pw.print(" right="); pw.print(mOverscanRight);
6670                    pw.print(" bottom="); pw.println(mOverscanBottom);
6671        }
6672        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
6673                pw.print(mRestrictedOverscanScreenLeft);
6674                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
6675                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
6676                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
6677        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
6678                pw.print(","); pw.print(mUnrestrictedScreenTop);
6679                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
6680                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
6681        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
6682                pw.print(","); pw.print(mRestrictedScreenTop);
6683                pw.print(") "); pw.print(mRestrictedScreenWidth);
6684                pw.print("x"); pw.println(mRestrictedScreenHeight);
6685        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
6686                pw.print(","); pw.print(mStableFullscreenTop);
6687                pw.print(")-("); pw.print(mStableFullscreenRight);
6688                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
6689        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
6690                pw.print(","); pw.print(mStableTop);
6691                pw.print(")-("); pw.print(mStableRight);
6692                pw.print(","); pw.print(mStableBottom); pw.println(")");
6693        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
6694                pw.print(","); pw.print(mSystemTop);
6695                pw.print(")-("); pw.print(mSystemRight);
6696                pw.print(","); pw.print(mSystemBottom); pw.println(")");
6697        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
6698                pw.print(","); pw.print(mCurTop);
6699                pw.print(")-("); pw.print(mCurRight);
6700                pw.print(","); pw.print(mCurBottom); pw.println(")");
6701        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
6702                pw.print(","); pw.print(mContentTop);
6703                pw.print(")-("); pw.print(mContentRight);
6704                pw.print(","); pw.print(mContentBottom); pw.println(")");
6705        pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
6706                pw.print(","); pw.print(mVoiceContentTop);
6707                pw.print(")-("); pw.print(mVoiceContentRight);
6708                pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
6709        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
6710                pw.print(","); pw.print(mDockTop);
6711                pw.print(")-("); pw.print(mDockRight);
6712                pw.print(","); pw.print(mDockBottom); pw.println(")");
6713        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
6714                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
6715        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
6716                pw.print(" mShowingDream="); pw.print(mShowingDream);
6717                pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
6718                pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
6719        if (mLastInputMethodWindow != null) {
6720            pw.print(prefix); pw.print("mLastInputMethodWindow=");
6721                    pw.println(mLastInputMethodWindow);
6722        }
6723        if (mLastInputMethodTargetWindow != null) {
6724            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
6725                    pw.println(mLastInputMethodTargetWindow);
6726        }
6727        if (mStatusBar != null) {
6728            pw.print(prefix); pw.print("mStatusBar=");
6729                    pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
6730                    pw.println(isStatusBarKeyguard());
6731        }
6732        if (mNavigationBar != null) {
6733            pw.print(prefix); pw.print("mNavigationBar=");
6734                    pw.println(mNavigationBar);
6735        }
6736        if (mFocusedWindow != null) {
6737            pw.print(prefix); pw.print("mFocusedWindow=");
6738                    pw.println(mFocusedWindow);
6739        }
6740        if (mFocusedApp != null) {
6741            pw.print(prefix); pw.print("mFocusedApp=");
6742                    pw.println(mFocusedApp);
6743        }
6744        if (mWinDismissingKeyguard != null) {
6745            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
6746                    pw.println(mWinDismissingKeyguard);
6747        }
6748        if (mTopFullscreenOpaqueWindowState != null) {
6749            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
6750                    pw.println(mTopFullscreenOpaqueWindowState);
6751        }
6752        if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
6753            pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
6754                    pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
6755        }
6756        if (mForcingShowNavBar) {
6757            pw.print(prefix); pw.print("mForcingShowNavBar=");
6758                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
6759                    pw.println(mForcingShowNavBarLayer);
6760        }
6761        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
6762                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
6763        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
6764                pw.print(" mForceStatusBarFromKeyguard=");
6765                pw.println(mForceStatusBarFromKeyguard);
6766        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
6767                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
6768                pw.print(" mHomePressed="); pw.println(mHomePressed);
6769        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
6770                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
6771                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
6772        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
6773                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
6774                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
6775        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
6776                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
6777        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
6778                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
6779        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
6780                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
6781        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
6782
6783        mGlobalKeyManager.dump(prefix, pw);
6784        mStatusBarController.dump(pw, prefix);
6785        mNavigationBarController.dump(pw, prefix);
6786        PolicyControl.dump(prefix, pw);
6787
6788        if (mWakeGestureListener != null) {
6789            mWakeGestureListener.dump(pw, prefix);
6790        }
6791        if (mOrientationListener != null) {
6792            mOrientationListener.dump(pw, prefix);
6793        }
6794        if (mBurnInProtectionHelper != null) {
6795            mBurnInProtectionHelper.dump(prefix, pw);
6796        }
6797    }
6798}
6799