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