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