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