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