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