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