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