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