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