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