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