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