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