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