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