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