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