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