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