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