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