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