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