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