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