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