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