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