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