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