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