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