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