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