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