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