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