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