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