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