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