PhoneWindowManager.java revision 48143f7ec58f2793e236566e0d25d3b731858996
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 boolean mForceWindowDrawsStatusBarBackground;
696    private final MutableBoolean mTmpBoolean = new MutableBoolean(false);
697
698    private static final int MSG_ENABLE_POINTER_LOCATION = 1;
699    private static final int MSG_DISABLE_POINTER_LOCATION = 2;
700    private static final int MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK = 3;
701    private static final int MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK = 4;
702    private static final int MSG_KEYGUARD_DRAWN_COMPLETE = 5;
703    private static final int MSG_KEYGUARD_DRAWN_TIMEOUT = 6;
704    private static final int MSG_WINDOW_MANAGER_DRAWN_COMPLETE = 7;
705    private static final int MSG_DISPATCH_SHOW_RECENTS = 9;
706    private static final int MSG_DISPATCH_SHOW_GLOBAL_ACTIONS = 10;
707    private static final int MSG_HIDE_BOOT_MESSAGE = 11;
708    private static final int MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK = 12;
709    private static final int MSG_POWER_DELAYED_PRESS = 13;
710    private static final int MSG_POWER_LONG_PRESS = 14;
711    private static final int MSG_UPDATE_DREAMING_SLEEP_TOKEN = 15;
712    private static final int MSG_REQUEST_TRANSIENT_BARS = 16;
713    private static final int MSG_REQUEST_TV_PICTURE_IN_PICTURE = 17;
714    private static final int MSG_BACK_LONG_PRESS = 18;
715
716    private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS = 0;
717    private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION = 1;
718
719    private class PolicyHandler extends Handler {
720        @Override
721        public void handleMessage(Message msg) {
722            switch (msg.what) {
723                case MSG_ENABLE_POINTER_LOCATION:
724                    enablePointerLocation();
725                    break;
726                case MSG_DISABLE_POINTER_LOCATION:
727                    disablePointerLocation();
728                    break;
729                case MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK:
730                    dispatchMediaKeyWithWakeLock((KeyEvent)msg.obj);
731                    break;
732                case MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK:
733                    dispatchMediaKeyRepeatWithWakeLock((KeyEvent)msg.obj);
734                    break;
735                case MSG_DISPATCH_SHOW_RECENTS:
736                    showRecentApps(false);
737                    break;
738                case MSG_DISPATCH_SHOW_GLOBAL_ACTIONS:
739                    showGlobalActionsInternal();
740                    break;
741                case MSG_KEYGUARD_DRAWN_COMPLETE:
742                    if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mKeyguardDrawComplete");
743                    finishKeyguardDrawn();
744                    break;
745                case MSG_KEYGUARD_DRAWN_TIMEOUT:
746                    Slog.w(TAG, "Keyguard drawn timeout. Setting mKeyguardDrawComplete");
747                    finishKeyguardDrawn();
748                    break;
749                case MSG_WINDOW_MANAGER_DRAWN_COMPLETE:
750                    if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mWindowManagerDrawComplete");
751                    finishWindowsDrawn();
752                    break;
753                case MSG_HIDE_BOOT_MESSAGE:
754                    handleHideBootMessage();
755                    break;
756                case MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK:
757                    launchVoiceAssistWithWakeLock(msg.arg1 != 0);
758                    break;
759                case MSG_POWER_DELAYED_PRESS:
760                    powerPress((Long)msg.obj, msg.arg1 != 0, msg.arg2);
761                    finishPowerKeyPress();
762                    break;
763                case MSG_POWER_LONG_PRESS:
764                    powerLongPress();
765                    break;
766                case MSG_UPDATE_DREAMING_SLEEP_TOKEN:
767                    updateDreamingSleepToken(msg.arg1 != 0);
768                    break;
769                case MSG_REQUEST_TRANSIENT_BARS:
770                    WindowState targetBar = (msg.arg1 == MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS) ?
771                            mStatusBar : mNavigationBar;
772                    if (targetBar != null) {
773                        requestTransientBars(targetBar);
774                    }
775                    break;
776                case MSG_REQUEST_TV_PICTURE_IN_PICTURE:
777                    requestTvPictureInPictureInternal();
778                    break;
779                case MSG_BACK_LONG_PRESS:
780                    backLongPress();
781                    break;
782            }
783        }
784    }
785
786    private UEventObserver mHDMIObserver = new UEventObserver() {
787        @Override
788        public void onUEvent(UEventObserver.UEvent event) {
789            setHdmiPlugged("1".equals(event.get("SWITCH_STATE")));
790        }
791    };
792
793    class SettingsObserver extends ContentObserver {
794        SettingsObserver(Handler handler) {
795            super(handler);
796        }
797
798        void observe() {
799            // Observe all users' changes
800            ContentResolver resolver = mContext.getContentResolver();
801            resolver.registerContentObserver(Settings.System.getUriFor(
802                    Settings.System.END_BUTTON_BEHAVIOR), false, this,
803                    UserHandle.USER_ALL);
804            resolver.registerContentObserver(Settings.Secure.getUriFor(
805                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this,
806                    UserHandle.USER_ALL);
807            resolver.registerContentObserver(Settings.Secure.getUriFor(
808                    Settings.Secure.WAKE_GESTURE_ENABLED), false, this,
809                    UserHandle.USER_ALL);
810            resolver.registerContentObserver(Settings.System.getUriFor(
811                    Settings.System.ACCELEROMETER_ROTATION), false, this,
812                    UserHandle.USER_ALL);
813            resolver.registerContentObserver(Settings.System.getUriFor(
814                    Settings.System.USER_ROTATION), false, this,
815                    UserHandle.USER_ALL);
816            resolver.registerContentObserver(Settings.System.getUriFor(
817                    Settings.System.SCREEN_OFF_TIMEOUT), false, this,
818                    UserHandle.USER_ALL);
819            resolver.registerContentObserver(Settings.System.getUriFor(
820                    Settings.System.POINTER_LOCATION), false, this,
821                    UserHandle.USER_ALL);
822            resolver.registerContentObserver(Settings.Secure.getUriFor(
823                    Settings.Secure.DEFAULT_INPUT_METHOD), false, this,
824                    UserHandle.USER_ALL);
825            resolver.registerContentObserver(Settings.Secure.getUriFor(
826                    Settings.Secure.IMMERSIVE_MODE_CONFIRMATIONS), false, this,
827                    UserHandle.USER_ALL);
828            resolver.registerContentObserver(Settings.Global.getUriFor(
829                    Settings.Global.POLICY_CONTROL), false, this,
830                    UserHandle.USER_ALL);
831            updateSettings();
832        }
833
834        @Override public void onChange(boolean selfChange) {
835            updateSettings();
836            updateRotation(false);
837        }
838    }
839
840    class MyWakeGestureListener extends WakeGestureListener {
841        MyWakeGestureListener(Context context, Handler handler) {
842            super(context, handler);
843        }
844
845        @Override
846        public void onWakeUp() {
847            synchronized (mLock) {
848                if (shouldEnableWakeGestureLp()) {
849                    performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
850                    wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromWakeGesture,
851                            "android.policy:GESTURE");
852                }
853            }
854        }
855    }
856
857    class MyOrientationListener extends WindowOrientationListener {
858        private final Runnable mUpdateRotationRunnable = new Runnable() {
859            @Override
860            public void run() {
861                // send interaction hint to improve redraw performance
862                mPowerManagerInternal.powerHint(PowerManagerInternal.POWER_HINT_INTERACTION, 0);
863                updateRotation(false);
864            }
865        };
866
867        MyOrientationListener(Context context, Handler handler) {
868            super(context, handler);
869        }
870
871        @Override
872        public void onProposedRotationChanged(int rotation) {
873            if (localLOGV) Slog.v(TAG, "onProposedRotationChanged, rotation=" + rotation);
874            mHandler.post(mUpdateRotationRunnable);
875        }
876    }
877    MyOrientationListener mOrientationListener;
878
879    private final StatusBarController mStatusBarController = new StatusBarController();
880
881    private final BarController mNavigationBarController = new BarController("NavigationBar",
882            View.NAVIGATION_BAR_TRANSIENT,
883            View.NAVIGATION_BAR_UNHIDE,
884            View.NAVIGATION_BAR_TRANSLUCENT,
885            StatusBarManager.WINDOW_NAVIGATION_BAR,
886            WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
887            View.NAVIGATION_BAR_TRANSPARENT);
888
889    private ImmersiveModeConfirmation mImmersiveModeConfirmation;
890
891    private SystemGesturesPointerEventListener mSystemGestures;
892
893    IStatusBarService getStatusBarService() {
894        synchronized (mServiceAquireLock) {
895            if (mStatusBarService == null) {
896                mStatusBarService = IStatusBarService.Stub.asInterface(
897                        ServiceManager.getService("statusbar"));
898            }
899            return mStatusBarService;
900        }
901    }
902
903    StatusBarManagerInternal getStatusBarManagerInternal() {
904        synchronized (mServiceAquireLock) {
905            if (mStatusBarManagerInternal == null) {
906                mStatusBarManagerInternal =
907                        LocalServices.getService(StatusBarManagerInternal.class);
908            }
909            return mStatusBarManagerInternal;
910        }
911    }
912
913    /*
914     * We always let the sensor be switched on by default except when
915     * the user has explicitly disabled sensor based rotation or when the
916     * screen is switched off.
917     */
918    boolean needSensorRunningLp() {
919        if (mSupportAutoRotation) {
920            if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
921                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
922                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
923                    || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
924                // If the application has explicitly requested to follow the
925                // orientation, then we need to turn the sensor on.
926                return true;
927            }
928        }
929        if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) ||
930                (mDeskDockEnablesAccelerometer && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
931                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
932                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK))) {
933            // enable accelerometer if we are docked in a dock that enables accelerometer
934            // orientation management,
935            return true;
936        }
937        if (mUserRotationMode == USER_ROTATION_LOCKED) {
938            // If the setting for using the sensor by default is enabled, then
939            // we will always leave it on.  Note that the user could go to
940            // a window that forces an orientation that does not use the
941            // sensor and in theory we could turn it off... however, when next
942            // turning it on we won't have a good value for the current
943            // orientation for a little bit, which can cause orientation
944            // changes to lag, so we'd like to keep it always on.  (It will
945            // still be turned off when the screen is off.)
946            return false;
947        }
948        return mSupportAutoRotation;
949    }
950
951    /*
952     * Various use cases for invoking this function
953     * screen turning off, should always disable listeners if already enabled
954     * screen turned on and current app has sensor based orientation, enable listeners
955     * if not already enabled
956     * screen turned on and current app does not have sensor orientation, disable listeners if
957     * already enabled
958     * screen turning on and current app has sensor based orientation, enable listeners if needed
959     * screen turning on and current app has nosensor based orientation, do nothing
960     */
961    void updateOrientationListenerLp() {
962        if (!mOrientationListener.canDetectOrientation()) {
963            // If sensor is turned off or nonexistent for some reason
964            return;
965        }
966        // Could have been invoked due to screen turning on or off or
967        // change of the currently visible window's orientation.
968        if (localLOGV) Slog.v(TAG, "mScreenOnEarly=" + mScreenOnEarly
969                + ", mAwake=" + mAwake + ", mCurrentAppOrientation=" + mCurrentAppOrientation
970                + ", mOrientationSensorEnabled=" + mOrientationSensorEnabled
971                + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
972                + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
973        boolean disable = true;
974        // Note: We postpone the rotating of the screen until the keyguard as well as the
975        // window manager have reported a draw complete.
976        if (mScreenOnEarly && mAwake &&
977                mKeyguardDrawComplete && mWindowManagerDrawComplete) {
978            if (needSensorRunningLp()) {
979                disable = false;
980                //enable listener if not already enabled
981                if (!mOrientationSensorEnabled) {
982                    mOrientationListener.enable();
983                    if(localLOGV) Slog.v(TAG, "Enabling listeners");
984                    mOrientationSensorEnabled = true;
985                }
986            }
987        }
988        //check if sensors need to be disabled
989        if (disable && mOrientationSensorEnabled) {
990            mOrientationListener.disable();
991            if(localLOGV) Slog.v(TAG, "Disabling listeners");
992            mOrientationSensorEnabled = false;
993        }
994    }
995
996    private void interceptPowerKeyDown(KeyEvent event, boolean interactive) {
997        // Hold a wake lock until the power key is released.
998        if (!mPowerKeyWakeLock.isHeld()) {
999            mPowerKeyWakeLock.acquire();
1000        }
1001
1002        // Cancel multi-press detection timeout.
1003        if (mPowerKeyPressCounter != 0) {
1004            mHandler.removeMessages(MSG_POWER_DELAYED_PRESS);
1005        }
1006
1007        // Detect user pressing the power button in panic when an application has
1008        // taken over the whole screen.
1009        boolean panic = mImmersiveModeConfirmation.onPowerKeyDown(interactive,
1010                SystemClock.elapsedRealtime(), isImmersiveMode(mLastSystemUiFlags));
1011        if (panic) {
1012            mHandler.post(mHiddenNavPanic);
1013        }
1014
1015        // Latch power key state to detect screenshot chord.
1016        if (interactive && !mScreenshotChordPowerKeyTriggered
1017                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
1018            mScreenshotChordPowerKeyTriggered = true;
1019            mScreenshotChordPowerKeyTime = event.getDownTime();
1020            interceptScreenshotChord();
1021        }
1022
1023        // Stop ringing or end call if configured to do so when power is pressed.
1024        TelecomManager telecomManager = getTelecommService();
1025        boolean hungUp = false;
1026        if (telecomManager != null) {
1027            if (telecomManager.isRinging()) {
1028                // Pressing Power while there's a ringing incoming
1029                // call should silence the ringer.
1030                telecomManager.silenceRinger();
1031            } else if ((mIncallPowerBehavior
1032                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
1033                    && telecomManager.isInCall() && interactive) {
1034                // Otherwise, if "Power button ends call" is enabled,
1035                // the Power button will hang up any current active call.
1036                hungUp = telecomManager.endCall();
1037            }
1038        }
1039
1040        GestureLauncherService gestureService = LocalServices.getService(
1041                GestureLauncherService.class);
1042        boolean gesturedServiceIntercepted = false;
1043        if (gestureService != null) {
1044            gesturedServiceIntercepted = gestureService.interceptPowerKeyDown(event, interactive,
1045                    mTmpBoolean);
1046            if (mTmpBoolean.value && mGoingToSleep) {
1047                mCameraGestureTriggeredDuringGoingToSleep = true;
1048            }
1049        }
1050
1051        // If the power key has still not yet been handled, then detect short
1052        // press, long press, or multi press and decide what to do.
1053        mPowerKeyHandled = hungUp || mScreenshotChordVolumeDownKeyTriggered
1054                || mScreenshotChordVolumeUpKeyTriggered || gesturedServiceIntercepted;
1055        if (!mPowerKeyHandled) {
1056            if (interactive) {
1057                // When interactive, we're already awake.
1058                // Wait for a long press or for the button to be released to decide what to do.
1059                if (hasLongPressOnPowerBehavior()) {
1060                    Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);
1061                    msg.setAsynchronous(true);
1062                    mHandler.sendMessageDelayed(msg,
1063                            ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
1064                }
1065            } else {
1066                wakeUpFromPowerKey(event.getDownTime());
1067
1068                if (mSupportLongPressPowerWhenNonInteractive && hasLongPressOnPowerBehavior()) {
1069                    Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);
1070                    msg.setAsynchronous(true);
1071                    mHandler.sendMessageDelayed(msg,
1072                            ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
1073                    mBeganFromNonInteractive = true;
1074                } else {
1075                    final int maxCount = getMaxMultiPressPowerCount();
1076
1077                    if (maxCount <= 1) {
1078                        mPowerKeyHandled = true;
1079                    } else {
1080                        mBeganFromNonInteractive = true;
1081                    }
1082                }
1083            }
1084        }
1085    }
1086
1087    private void interceptPowerKeyUp(KeyEvent event, boolean interactive, boolean canceled) {
1088        final boolean handled = canceled || mPowerKeyHandled;
1089        mScreenshotChordPowerKeyTriggered = false;
1090        cancelPendingScreenshotChordAction();
1091        cancelPendingPowerKeyAction();
1092
1093        if (!handled) {
1094            // Figure out how to handle the key now that it has been released.
1095            mPowerKeyPressCounter += 1;
1096
1097            final int maxCount = getMaxMultiPressPowerCount();
1098            final long eventTime = event.getDownTime();
1099            if (mPowerKeyPressCounter < maxCount) {
1100                // This could be a multi-press.  Wait a little bit longer to confirm.
1101                // Continue holding the wake lock.
1102                Message msg = mHandler.obtainMessage(MSG_POWER_DELAYED_PRESS,
1103                        interactive ? 1 : 0, mPowerKeyPressCounter, eventTime);
1104                msg.setAsynchronous(true);
1105                mHandler.sendMessageDelayed(msg, ViewConfiguration.getDoubleTapTimeout());
1106                return;
1107            }
1108
1109            // No other actions.  Handle it immediately.
1110            powerPress(eventTime, interactive, mPowerKeyPressCounter);
1111        }
1112
1113        // Done.  Reset our state.
1114        finishPowerKeyPress();
1115    }
1116
1117    private void finishPowerKeyPress() {
1118        mBeganFromNonInteractive = false;
1119        mPowerKeyPressCounter = 0;
1120        if (mPowerKeyWakeLock.isHeld()) {
1121            mPowerKeyWakeLock.release();
1122        }
1123    }
1124
1125    private void cancelPendingPowerKeyAction() {
1126        if (!mPowerKeyHandled) {
1127            mPowerKeyHandled = true;
1128            mHandler.removeMessages(MSG_POWER_LONG_PRESS);
1129        }
1130    }
1131
1132    private void cancelPendingBackKeyAction() {
1133        if (!mBackKeyHandled) {
1134            mBackKeyHandled = true;
1135            mHandler.removeMessages(MSG_BACK_LONG_PRESS);
1136        }
1137    }
1138
1139    private void powerPress(long eventTime, boolean interactive, int count) {
1140        if (mScreenOnEarly && !mScreenOnFully) {
1141            Slog.i(TAG, "Suppressed redundant power key press while "
1142                    + "already in the process of turning the screen on.");
1143            return;
1144        }
1145
1146        if (count == 2) {
1147            powerMultiPressAction(eventTime, interactive, mDoublePressOnPowerBehavior);
1148        } else if (count == 3) {
1149            powerMultiPressAction(eventTime, interactive, mTriplePressOnPowerBehavior);
1150        } else if (interactive && !mBeganFromNonInteractive) {
1151            switch (mShortPressOnPowerBehavior) {
1152                case SHORT_PRESS_POWER_NOTHING:
1153                    break;
1154                case SHORT_PRESS_POWER_GO_TO_SLEEP:
1155                    mPowerManager.goToSleep(eventTime,
1156                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
1157                    break;
1158                case SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP:
1159                    mPowerManager.goToSleep(eventTime,
1160                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON,
1161                            PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
1162                    break;
1163                case SHORT_PRESS_POWER_REALLY_GO_TO_SLEEP_AND_GO_HOME:
1164                    mPowerManager.goToSleep(eventTime,
1165                            PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON,
1166                            PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
1167                    launchHomeFromHotKey();
1168                    break;
1169                case SHORT_PRESS_POWER_GO_HOME:
1170                    launchHomeFromHotKey(true /* awakenFromDreams */, false /*respectKeyguard*/);
1171                    break;
1172            }
1173        }
1174    }
1175
1176    private void powerMultiPressAction(long eventTime, boolean interactive, int behavior) {
1177        switch (behavior) {
1178            case MULTI_PRESS_POWER_NOTHING:
1179                break;
1180            case MULTI_PRESS_POWER_THEATER_MODE:
1181                if (!isUserSetupComplete()) {
1182                    Slog.i(TAG, "Ignoring toggling theater mode - device not setup.");
1183                    break;
1184                }
1185
1186                if (isTheaterModeEnabled()) {
1187                    Slog.i(TAG, "Toggling theater mode off.");
1188                    Settings.Global.putInt(mContext.getContentResolver(),
1189                            Settings.Global.THEATER_MODE_ON, 0);
1190                    if (!interactive) {
1191                        wakeUpFromPowerKey(eventTime);
1192                    }
1193                } else {
1194                    Slog.i(TAG, "Toggling theater mode on.");
1195                    Settings.Global.putInt(mContext.getContentResolver(),
1196                            Settings.Global.THEATER_MODE_ON, 1);
1197
1198                    if (mGoToSleepOnButtonPressTheaterMode && interactive) {
1199                        mPowerManager.goToSleep(eventTime,
1200                                PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
1201                    }
1202                }
1203                break;
1204            case MULTI_PRESS_POWER_BRIGHTNESS_BOOST:
1205                Slog.i(TAG, "Starting brightness boost.");
1206                if (!interactive) {
1207                    wakeUpFromPowerKey(eventTime);
1208                }
1209                mPowerManager.boostScreenBrightness(eventTime);
1210                break;
1211        }
1212    }
1213
1214    private int getMaxMultiPressPowerCount() {
1215        if (mTriplePressOnPowerBehavior != MULTI_PRESS_POWER_NOTHING) {
1216            return 3;
1217        }
1218        if (mDoublePressOnPowerBehavior != MULTI_PRESS_POWER_NOTHING) {
1219            return 2;
1220        }
1221        return 1;
1222    }
1223
1224    private void powerLongPress() {
1225        final int behavior = getResolvedLongPressOnPowerBehavior();
1226        switch (behavior) {
1227        case LONG_PRESS_POWER_NOTHING:
1228            break;
1229        case LONG_PRESS_POWER_GLOBAL_ACTIONS:
1230            mPowerKeyHandled = true;
1231            if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
1232                performAuditoryFeedbackForAccessibilityIfNeed();
1233            }
1234            showGlobalActionsInternal();
1235            break;
1236        case LONG_PRESS_POWER_SHUT_OFF:
1237        case LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM:
1238            mPowerKeyHandled = true;
1239            performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
1240            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
1241            mWindowManagerFuncs.shutdown(behavior == LONG_PRESS_POWER_SHUT_OFF);
1242            break;
1243        }
1244    }
1245
1246    private void backLongPress() {
1247        mBackKeyHandled = true;
1248
1249        switch (mLongPressOnBackBehavior) {
1250            case LONG_PRESS_BACK_NOTHING:
1251                break;
1252            case LONG_PRESS_BACK_GO_TO_VOICE_ASSIST:
1253                Intent intent = new Intent(Intent.ACTION_VOICE_ASSIST);
1254                startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
1255                break;
1256        }
1257    }
1258
1259    private void sleepPress(long eventTime) {
1260        if (mShortPressOnSleepBehavior == SHORT_PRESS_SLEEP_GO_TO_SLEEP_AND_GO_HOME) {
1261            launchHomeFromHotKey(false /* awakenDreams */, true /*respectKeyguard*/);
1262        }
1263    }
1264
1265    private void sleepRelease(long eventTime) {
1266        switch (mShortPressOnSleepBehavior) {
1267            case SHORT_PRESS_SLEEP_GO_TO_SLEEP:
1268            case SHORT_PRESS_SLEEP_GO_TO_SLEEP_AND_GO_HOME:
1269                Slog.i(TAG, "sleepRelease() calling goToSleep(GO_TO_SLEEP_REASON_SLEEP_BUTTON)");
1270                mPowerManager.goToSleep(eventTime,
1271                       PowerManager.GO_TO_SLEEP_REASON_SLEEP_BUTTON, 0);
1272                break;
1273        }
1274    }
1275
1276    private int getResolvedLongPressOnPowerBehavior() {
1277        if (FactoryTest.isLongPressOnPowerOffEnabled()) {
1278            return LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM;
1279        }
1280        return mLongPressOnPowerBehavior;
1281    }
1282
1283    private boolean hasLongPressOnPowerBehavior() {
1284        return getResolvedLongPressOnPowerBehavior() != LONG_PRESS_POWER_NOTHING;
1285    }
1286
1287    private boolean hasLongPressOnBackBehavior() {
1288        return mLongPressOnBackBehavior != LONG_PRESS_BACK_NOTHING;
1289    }
1290
1291    private void interceptScreenshotChord() {
1292        if (mScreenshotChordEnabled
1293                && mScreenshotChordVolumeDownKeyTriggered && mScreenshotChordPowerKeyTriggered
1294                && !mScreenshotChordVolumeUpKeyTriggered) {
1295            final long now = SystemClock.uptimeMillis();
1296            if (now <= mScreenshotChordVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS
1297                    && now <= mScreenshotChordPowerKeyTime
1298                            + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) {
1299                mScreenshotChordVolumeDownKeyConsumed = true;
1300                cancelPendingPowerKeyAction();
1301                mScreenshotRunnable.setScreenshotType(TAKE_SCREENSHOT_FULLSCREEN);
1302                mHandler.postDelayed(mScreenshotRunnable, getScreenshotChordLongPressDelay());
1303            }
1304        }
1305    }
1306
1307    private long getScreenshotChordLongPressDelay() {
1308        if (mKeyguardDelegate.isShowing()) {
1309            // Double the time it takes to take a screenshot from the keyguard
1310            return (long) (KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER *
1311                    ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
1312        }
1313        return ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout();
1314    }
1315
1316    private void cancelPendingScreenshotChordAction() {
1317        mHandler.removeCallbacks(mScreenshotRunnable);
1318    }
1319
1320    private final Runnable mEndCallLongPress = new Runnable() {
1321        @Override
1322        public void run() {
1323            mEndCallKeyHandled = true;
1324            if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
1325                performAuditoryFeedbackForAccessibilityIfNeed();
1326            }
1327            showGlobalActionsInternal();
1328        }
1329    };
1330
1331    private class ScreenshotRunnable implements Runnable {
1332        private int mScreenshotType = TAKE_SCREENSHOT_FULLSCREEN;
1333
1334        public void setScreenshotType(int screenshotType) {
1335            mScreenshotType = screenshotType;
1336        }
1337
1338        @Override
1339        public void run() {
1340            takeScreenshot(mScreenshotType);
1341        }
1342    }
1343
1344    private final ScreenshotRunnable mScreenshotRunnable = new ScreenshotRunnable();
1345
1346    @Override
1347    public void showGlobalActions() {
1348        mHandler.removeMessages(MSG_DISPATCH_SHOW_GLOBAL_ACTIONS);
1349        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_GLOBAL_ACTIONS);
1350    }
1351
1352    void showGlobalActionsInternal() {
1353        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
1354        if (mGlobalActions == null) {
1355            mGlobalActions = new GlobalActions(mContext, mWindowManagerFuncs);
1356        }
1357        final boolean keyguardShowing = isKeyguardShowingAndNotOccluded();
1358        mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
1359        if (keyguardShowing) {
1360            // since it took two seconds of long press to bring this up,
1361            // poke the wake lock so they have some time to see the dialog.
1362            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
1363        }
1364    }
1365
1366    boolean isDeviceProvisioned() {
1367        return Settings.Global.getInt(
1368                mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1369    }
1370
1371    boolean isUserSetupComplete() {
1372        return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1373                Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_CURRENT) != 0;
1374    }
1375
1376    private void handleShortPressOnHome() {
1377        // Turn on the connected TV and switch HDMI input if we're a HDMI playback device.
1378        getHdmiControl().turnOnTv();
1379
1380        // If there's a dream running then use home to escape the dream
1381        // but don't actually go home.
1382        if (mDreamManagerInternal != null && mDreamManagerInternal.isDreaming()) {
1383            mDreamManagerInternal.stopDream(false /*immediate*/);
1384            return;
1385        }
1386
1387        // Go home!
1388        launchHomeFromHotKey();
1389    }
1390
1391    /**
1392     * Creates an accessor to HDMI control service that performs the operation of
1393     * turning on TV (optional) and switching input to us. If HDMI control service
1394     * is not available or we're not a HDMI playback device, the operation is no-op.
1395     */
1396    private HdmiControl getHdmiControl() {
1397        if (null == mHdmiControl) {
1398            HdmiControlManager manager = (HdmiControlManager) mContext.getSystemService(
1399                        Context.HDMI_CONTROL_SERVICE);
1400            HdmiPlaybackClient client = null;
1401            if (manager != null) {
1402                client = manager.getPlaybackClient();
1403            }
1404            mHdmiControl = new HdmiControl(client);
1405        }
1406        return mHdmiControl;
1407    }
1408
1409    private static class HdmiControl {
1410        private final HdmiPlaybackClient mClient;
1411
1412        private HdmiControl(HdmiPlaybackClient client) {
1413            mClient = client;
1414        }
1415
1416        public void turnOnTv() {
1417            if (mClient == null) {
1418                return;
1419            }
1420            mClient.oneTouchPlay(new OneTouchPlayCallback() {
1421                @Override
1422                public void onComplete(int result) {
1423                    if (result != HdmiControlManager.RESULT_SUCCESS) {
1424                        Log.w(TAG, "One touch play failed: " + result);
1425                    }
1426                }
1427            });
1428        }
1429    }
1430
1431    private void handleLongPressOnHome(int deviceId) {
1432        if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_NOTHING) {
1433            return;
1434        }
1435        mHomeConsumed = true;
1436        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
1437
1438        switch (mLongPressOnHomeBehavior) {
1439            case LONG_PRESS_HOME_RECENT_SYSTEM_UI:
1440                toggleRecentApps();
1441                break;
1442            case LONG_PRESS_HOME_ASSIST:
1443                launchAssistAction(null, deviceId);
1444                break;
1445            default:
1446                Log.w(TAG, "Undefined home long press behavior: " + mLongPressOnHomeBehavior);
1447                break;
1448        }
1449    }
1450
1451    private void handleDoubleTapOnHome() {
1452        if (mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
1453            mHomeConsumed = true;
1454            toggleRecentApps();
1455        }
1456    }
1457
1458    private void requestTvPictureInPicture(KeyEvent event) {
1459        if (DEBUG_INPUT) Log.d(TAG, "requestTvPictureInPicture event=" + event);
1460        mHandler.removeMessages(MSG_REQUEST_TV_PICTURE_IN_PICTURE);
1461        Message msg = mHandler.obtainMessage(MSG_REQUEST_TV_PICTURE_IN_PICTURE);
1462        msg.setAsynchronous(true);
1463        msg.sendToTarget();
1464    }
1465
1466    private void requestTvPictureInPictureInternal() {
1467        try {
1468            IStatusBarService statusbar = getStatusBarService();
1469            if (statusbar != null) {
1470                statusbar.requestTvPictureInPicture();
1471            }
1472        } catch (RemoteException|IllegalArgumentException e) {
1473            Slog.e(TAG, "Cannot handle picture-in-picture key", e);
1474            // re-acquire status bar service next time it is needed.
1475            mStatusBarService = null;
1476        }
1477    }
1478
1479    private final Runnable mHomeDoubleTapTimeoutRunnable = new Runnable() {
1480        @Override
1481        public void run() {
1482            if (mHomeDoubleTapPending) {
1483                mHomeDoubleTapPending = false;
1484                handleShortPressOnHome();
1485            }
1486        }
1487    };
1488
1489    private boolean isRoundWindow() {
1490        return mContext.getResources().getConfiguration().isScreenRound();
1491    }
1492
1493    /** {@inheritDoc} */
1494    @Override
1495    public void init(Context context, IWindowManager windowManager,
1496            WindowManagerFuncs windowManagerFuncs) {
1497        mContext = context;
1498        mWindowManager = windowManager;
1499        mWindowManagerFuncs = windowManagerFuncs;
1500        mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
1501        mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
1502        mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
1503        mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class);
1504        mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
1505        mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1506
1507        // Init display burn-in protection
1508        boolean burnInProtectionEnabled = context.getResources().getBoolean(
1509                com.android.internal.R.bool.config_enableBurnInProtection);
1510        // Allow a system property to override this. Used by developer settings.
1511        boolean burnInProtectionDevMode =
1512                SystemProperties.getBoolean("persist.debug.force_burn_in", false);
1513        if (burnInProtectionEnabled || burnInProtectionDevMode) {
1514            final int minHorizontal;
1515            final int maxHorizontal;
1516            final int minVertical;
1517            final int maxVertical;
1518            final int maxRadius;
1519            if (burnInProtectionDevMode) {
1520                minHorizontal = -8;
1521                maxHorizontal = 8;
1522                minVertical = -8;
1523                maxVertical = -4;
1524                maxRadius = (isRoundWindow()) ? 6 : -1;
1525            } else {
1526                Resources resources = context.getResources();
1527                minHorizontal = resources.getInteger(
1528                        com.android.internal.R.integer.config_burnInProtectionMinHorizontalOffset);
1529                maxHorizontal = resources.getInteger(
1530                        com.android.internal.R.integer.config_burnInProtectionMaxHorizontalOffset);
1531                minVertical = resources.getInteger(
1532                        com.android.internal.R.integer.config_burnInProtectionMinVerticalOffset);
1533                maxVertical = resources.getInteger(
1534                        com.android.internal.R.integer.config_burnInProtectionMaxVerticalOffset);
1535                maxRadius = resources.getInteger(
1536                        com.android.internal.R.integer.config_burnInProtectionMaxRadius);
1537            }
1538            mBurnInProtectionHelper = new BurnInProtectionHelper(
1539                    context, minHorizontal, maxHorizontal, minVertical, maxVertical, maxRadius);
1540        }
1541
1542        mHandler = new PolicyHandler();
1543        mWakeGestureListener = new MyWakeGestureListener(mContext, mHandler);
1544        mOrientationListener = new MyOrientationListener(mContext, mHandler);
1545        try {
1546            mOrientationListener.setCurrentRotation(windowManager.getRotation());
1547        } catch (RemoteException ex) { }
1548        mSettingsObserver = new SettingsObserver(mHandler);
1549        mSettingsObserver.observe();
1550        mShortcutManager = new ShortcutManager(context);
1551        mUiMode = context.getResources().getInteger(
1552                com.android.internal.R.integer.config_defaultUiModeType);
1553        mHomeIntent =  new Intent(Intent.ACTION_MAIN, null);
1554        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
1555        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1556                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1557        mEnableCarDockHomeCapture = context.getResources().getBoolean(
1558                com.android.internal.R.bool.config_enableCarDockHomeLaunch);
1559        mCarDockIntent =  new Intent(Intent.ACTION_MAIN, null);
1560        mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
1561        mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1562                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1563        mDeskDockIntent =  new Intent(Intent.ACTION_MAIN, null);
1564        mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
1565        mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1566                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1567
1568        mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1569        mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1570                "PhoneWindowManager.mBroadcastWakeLock");
1571        mPowerKeyWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
1572                "PhoneWindowManager.mPowerKeyWakeLock");
1573        mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
1574        mSupportAutoRotation = mContext.getResources().getBoolean(
1575                com.android.internal.R.bool.config_supportAutoRotation);
1576        mLidOpenRotation = readRotation(
1577                com.android.internal.R.integer.config_lidOpenRotation);
1578        mCarDockRotation = readRotation(
1579                com.android.internal.R.integer.config_carDockRotation);
1580        mDeskDockRotation = readRotation(
1581                com.android.internal.R.integer.config_deskDockRotation);
1582        mUndockedHdmiRotation = readRotation(
1583                com.android.internal.R.integer.config_undockedHdmiRotation);
1584        mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
1585                com.android.internal.R.bool.config_carDockEnablesAccelerometer);
1586        mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
1587                com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
1588        mLidKeyboardAccessibility = mContext.getResources().getInteger(
1589                com.android.internal.R.integer.config_lidKeyboardAccessibility);
1590        mLidNavigationAccessibility = mContext.getResources().getInteger(
1591                com.android.internal.R.integer.config_lidNavigationAccessibility);
1592        mLidControlsScreenLock = mContext.getResources().getBoolean(
1593                com.android.internal.R.bool.config_lidControlsScreenLock);
1594        mLidControlsSleep = mContext.getResources().getBoolean(
1595                com.android.internal.R.bool.config_lidControlsSleep);
1596        mTranslucentDecorEnabled = mContext.getResources().getBoolean(
1597                com.android.internal.R.bool.config_enableTranslucentDecor);
1598
1599        mAllowTheaterModeWakeFromKey = mContext.getResources().getBoolean(
1600                com.android.internal.R.bool.config_allowTheaterModeWakeFromKey);
1601        mAllowTheaterModeWakeFromPowerKey = mAllowTheaterModeWakeFromKey
1602                || mContext.getResources().getBoolean(
1603                    com.android.internal.R.bool.config_allowTheaterModeWakeFromPowerKey);
1604        mAllowTheaterModeWakeFromMotion = mContext.getResources().getBoolean(
1605                com.android.internal.R.bool.config_allowTheaterModeWakeFromMotion);
1606        mAllowTheaterModeWakeFromMotionWhenNotDreaming = mContext.getResources().getBoolean(
1607                com.android.internal.R.bool.config_allowTheaterModeWakeFromMotionWhenNotDreaming);
1608        mAllowTheaterModeWakeFromCameraLens = mContext.getResources().getBoolean(
1609                com.android.internal.R.bool.config_allowTheaterModeWakeFromCameraLens);
1610        mAllowTheaterModeWakeFromLidSwitch = mContext.getResources().getBoolean(
1611                com.android.internal.R.bool.config_allowTheaterModeWakeFromLidSwitch);
1612        mAllowTheaterModeWakeFromWakeGesture = mContext.getResources().getBoolean(
1613                com.android.internal.R.bool.config_allowTheaterModeWakeFromGesture);
1614
1615        mGoToSleepOnButtonPressTheaterMode = mContext.getResources().getBoolean(
1616                com.android.internal.R.bool.config_goToSleepOnButtonPressTheaterMode);
1617
1618        mSupportLongPressPowerWhenNonInteractive = mContext.getResources().getBoolean(
1619                com.android.internal.R.bool.config_supportLongPressPowerWhenNonInteractive);
1620
1621        mLongPressOnBackBehavior = mContext.getResources().getInteger(
1622                com.android.internal.R.integer.config_longPressOnBackBehavior);
1623
1624        mShortPressOnPowerBehavior = mContext.getResources().getInteger(
1625                com.android.internal.R.integer.config_shortPressOnPowerBehavior);
1626        mLongPressOnPowerBehavior = mContext.getResources().getInteger(
1627                com.android.internal.R.integer.config_longPressOnPowerBehavior);
1628        mDoublePressOnPowerBehavior = mContext.getResources().getInteger(
1629                com.android.internal.R.integer.config_doublePressOnPowerBehavior);
1630        mTriplePressOnPowerBehavior = mContext.getResources().getInteger(
1631                com.android.internal.R.integer.config_triplePressOnPowerBehavior);
1632        mShortPressOnSleepBehavior = mContext.getResources().getInteger(
1633                com.android.internal.R.integer.config_shortPressOnSleepBehavior);
1634
1635        mUseTvRouting = AudioSystem.getPlatformType(mContext) == AudioSystem.PLATFORM_TELEVISION;
1636
1637        readConfigurationDependentBehaviors();
1638
1639        mAccessibilityManager = (AccessibilityManager) context.getSystemService(
1640                Context.ACCESSIBILITY_SERVICE);
1641
1642        // register for dock events
1643        IntentFilter filter = new IntentFilter();
1644        filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE);
1645        filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE);
1646        filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE);
1647        filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE);
1648        filter.addAction(Intent.ACTION_DOCK_EVENT);
1649        Intent intent = context.registerReceiver(mDockReceiver, filter);
1650        if (intent != null) {
1651            // Retrieve current sticky dock event broadcast.
1652            mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1653                    Intent.EXTRA_DOCK_STATE_UNDOCKED);
1654        }
1655
1656        // register for dream-related broadcasts
1657        filter = new IntentFilter();
1658        filter.addAction(Intent.ACTION_DREAMING_STARTED);
1659        filter.addAction(Intent.ACTION_DREAMING_STOPPED);
1660        context.registerReceiver(mDreamReceiver, filter);
1661
1662        // register for multiuser-relevant broadcasts
1663        filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
1664        context.registerReceiver(mMultiuserReceiver, filter);
1665
1666        // monitor for system gestures
1667        mSystemGestures = new SystemGesturesPointerEventListener(context,
1668                new SystemGesturesPointerEventListener.Callbacks() {
1669                    @Override
1670                    public void onSwipeFromTop() {
1671                        if (mStatusBar != null) {
1672                            requestTransientBars(mStatusBar);
1673                        }
1674                    }
1675                    @Override
1676                    public void onSwipeFromBottom() {
1677                        if (mNavigationBar != null && mNavigationBarOnBottom) {
1678                            requestTransientBars(mNavigationBar);
1679                        }
1680                    }
1681                    @Override
1682                    public void onSwipeFromRight() {
1683                        if (mNavigationBar != null && !mNavigationBarOnBottom) {
1684                            requestTransientBars(mNavigationBar);
1685                        }
1686                    }
1687                    @Override
1688                    public void onFling(int duration) {
1689                        if (mPowerManagerInternal != null) {
1690                            mPowerManagerInternal.powerHint(
1691                                    PowerManagerInternal.POWER_HINT_INTERACTION, duration);
1692                        }
1693                    }
1694                    @Override
1695                    public void onDebug() {
1696                        // no-op
1697                    }
1698                    @Override
1699                    public void onDown() {
1700                        mOrientationListener.onTouchStart();
1701                    }
1702                    @Override
1703                    public void onUpOrCancel() {
1704                        mOrientationListener.onTouchEnd();
1705                    }
1706                    @Override
1707                    public void onMouseHoverAtTop() {
1708                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1709                        Message msg = mHandler.obtainMessage(MSG_REQUEST_TRANSIENT_BARS);
1710                        msg.arg1 = MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS;
1711                        mHandler.sendMessageDelayed(msg, 500);
1712                    }
1713                    @Override
1714                    public void onMouseHoverAtBottom() {
1715                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1716                        Message msg = mHandler.obtainMessage(MSG_REQUEST_TRANSIENT_BARS);
1717                        msg.arg1 = MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION;
1718                        mHandler.sendMessageDelayed(msg, 500);
1719                    }
1720                    @Override
1721                    public void onMouseLeaveFromEdge() {
1722                        mHandler.removeMessages(MSG_REQUEST_TRANSIENT_BARS);
1723                    }
1724                });
1725        mImmersiveModeConfirmation = new ImmersiveModeConfirmation(mContext);
1726        mWindowManagerFuncs.registerPointerEventListener(mSystemGestures);
1727
1728        mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
1729        mLongPressVibePattern = getLongIntArray(mContext.getResources(),
1730                com.android.internal.R.array.config_longPressVibePattern);
1731        mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
1732                com.android.internal.R.array.config_virtualKeyVibePattern);
1733        mKeyboardTapVibePattern = getLongIntArray(mContext.getResources(),
1734                com.android.internal.R.array.config_keyboardTapVibePattern);
1735        mClockTickVibePattern = getLongIntArray(mContext.getResources(),
1736                com.android.internal.R.array.config_clockTickVibePattern);
1737        mCalendarDateVibePattern = getLongIntArray(mContext.getResources(),
1738                com.android.internal.R.array.config_calendarDateVibePattern);
1739        mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
1740                com.android.internal.R.array.config_safeModeDisabledVibePattern);
1741        mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
1742                com.android.internal.R.array.config_safeModeEnabledVibePattern);
1743        mContextClickVibePattern = getLongIntArray(mContext.getResources(),
1744                com.android.internal.R.array.config_contextClickVibePattern);
1745
1746        mScreenshotChordEnabled = mContext.getResources().getBoolean(
1747                com.android.internal.R.bool.config_enableScreenshotChord);
1748        mForceWindowDrawsStatusBarBackground = mContext.getResources().getBoolean(
1749                R.bool.config_forceWindowDrawsStatusBarBackground);
1750
1751        mGlobalKeyManager = new GlobalKeyManager(mContext);
1752
1753        // Controls rotation and the like.
1754        initializeHdmiState();
1755
1756        // Match current screen state.
1757        if (!mPowerManager.isInteractive()) {
1758            startedGoingToSleep(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1759            finishedGoingToSleep(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
1760        }
1761
1762        mWindowManagerInternal.registerAppTransitionListener(
1763                mStatusBarController.getAppTransitionListener());
1764    }
1765
1766    /**
1767     * Read values from config.xml that may be overridden depending on
1768     * the configuration of the device.
1769     * eg. Disable long press on home goes to recents on sw600dp.
1770     */
1771    private void readConfigurationDependentBehaviors() {
1772        final Resources res = mContext.getResources();
1773
1774        mLongPressOnHomeBehavior = res.getInteger(
1775                com.android.internal.R.integer.config_longPressOnHomeBehavior);
1776        if (mLongPressOnHomeBehavior < LONG_PRESS_HOME_NOTHING ||
1777                mLongPressOnHomeBehavior > LAST_LONG_PRESS_HOME_BEHAVIOR) {
1778            mLongPressOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
1779        }
1780
1781        mDoubleTapOnHomeBehavior = res.getInteger(
1782                com.android.internal.R.integer.config_doubleTapOnHomeBehavior);
1783        if (mDoubleTapOnHomeBehavior < DOUBLE_TAP_HOME_NOTHING ||
1784                mDoubleTapOnHomeBehavior > DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
1785            mDoubleTapOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
1786        }
1787
1788        mShortPressWindowBehavior = SHORT_PRESS_WINDOW_NOTHING;
1789        if (mContext.getPackageManager().hasSystemFeature(FEATURE_PICTURE_IN_PICTURE)) {
1790            mShortPressWindowBehavior = SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE;
1791        }
1792
1793        mNavBarOpacityMode = res.getInteger(
1794                com.android.internal.R.integer.config_navBarOpacityMode);
1795    }
1796
1797    @Override
1798    public void setInitialDisplaySize(Display display, int width, int height, int density) {
1799        // This method might be called before the policy has been fully initialized
1800        // or for other displays we don't care about.
1801        if (mContext == null || display.getDisplayId() != Display.DEFAULT_DISPLAY) {
1802            return;
1803        }
1804        mDisplay = display;
1805
1806        final Resources res = mContext.getResources();
1807        int shortSize, longSize;
1808        if (width > height) {
1809            shortSize = height;
1810            longSize = width;
1811            mLandscapeRotation = Surface.ROTATION_0;
1812            mSeascapeRotation = Surface.ROTATION_180;
1813            if (res.getBoolean(com.android.internal.R.bool.config_reverseDefaultRotation)) {
1814                mPortraitRotation = Surface.ROTATION_90;
1815                mUpsideDownRotation = Surface.ROTATION_270;
1816            } else {
1817                mPortraitRotation = Surface.ROTATION_270;
1818                mUpsideDownRotation = Surface.ROTATION_90;
1819            }
1820        } else {
1821            shortSize = width;
1822            longSize = height;
1823            mPortraitRotation = Surface.ROTATION_0;
1824            mUpsideDownRotation = Surface.ROTATION_180;
1825            if (res.getBoolean(com.android.internal.R.bool.config_reverseDefaultRotation)) {
1826                mLandscapeRotation = Surface.ROTATION_270;
1827                mSeascapeRotation = Surface.ROTATION_90;
1828            } else {
1829                mLandscapeRotation = Surface.ROTATION_90;
1830                mSeascapeRotation = Surface.ROTATION_270;
1831            }
1832        }
1833
1834        // SystemUI (status bar) layout policy
1835        int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / density;
1836        int longSizeDp = longSize * DisplayMetrics.DENSITY_DEFAULT / density;
1837
1838        // Allow the navigation bar to move on non-square small devices (phones).
1839        mNavigationBarCanMove = width != height && shortSizeDp < 600;
1840
1841        mHasNavigationBar = res.getBoolean(com.android.internal.R.bool.config_showNavigationBar);
1842
1843        // Allow a system property to override this. Used by the emulator.
1844        // See also hasNavigationBar().
1845        String navBarOverride = SystemProperties.get("qemu.hw.mainkeys");
1846        if ("1".equals(navBarOverride)) {
1847            mHasNavigationBar = false;
1848        } else if ("0".equals(navBarOverride)) {
1849            mHasNavigationBar = true;
1850        }
1851
1852        // For demo purposes, allow the rotation of the HDMI display to be controlled.
1853        // By default, HDMI locks rotation to landscape.
1854        if ("portrait".equals(SystemProperties.get("persist.demo.hdmirotation"))) {
1855            mDemoHdmiRotation = mPortraitRotation;
1856        } else {
1857            mDemoHdmiRotation = mLandscapeRotation;
1858        }
1859        mDemoHdmiRotationLock = SystemProperties.getBoolean("persist.demo.hdmirotationlock", false);
1860
1861        // For demo purposes, allow the rotation of the remote display to be controlled.
1862        // By default, remote display locks rotation to landscape.
1863        if ("portrait".equals(SystemProperties.get("persist.demo.remoterotation"))) {
1864            mDemoRotation = mPortraitRotation;
1865        } else {
1866            mDemoRotation = mLandscapeRotation;
1867        }
1868        mDemoRotationLock = SystemProperties.getBoolean(
1869                "persist.demo.rotationlock", false);
1870
1871        // Only force the default orientation if the screen is xlarge, at least 960dp x 720dp, per
1872        // http://developer.android.com/guide/practices/screens_support.html#range
1873        mForceDefaultOrientation = longSizeDp >= 960 && shortSizeDp >= 720 &&
1874                res.getBoolean(com.android.internal.R.bool.config_forceDefaultOrientation) &&
1875                // For debug purposes the next line turns this feature off with:
1876                // $ adb shell setprop config.override_forced_orient true
1877                // $ adb shell wm size reset
1878                !"true".equals(SystemProperties.get("config.override_forced_orient"));
1879    }
1880
1881    /**
1882     * @return whether the navigation bar can be hidden, e.g. the device has a
1883     *         navigation bar and touch exploration is not enabled
1884     */
1885    private boolean canHideNavigationBar() {
1886        return mHasNavigationBar;
1887    }
1888
1889    @Override
1890    public boolean isDefaultOrientationForced() {
1891        return mForceDefaultOrientation;
1892    }
1893
1894    @Override
1895    public void setDisplayOverscan(Display display, int left, int top, int right, int bottom) {
1896        if (display.getDisplayId() == Display.DEFAULT_DISPLAY) {
1897            mOverscanLeft = left;
1898            mOverscanTop = top;
1899            mOverscanRight = right;
1900            mOverscanBottom = bottom;
1901        }
1902    }
1903
1904    public void updateSettings() {
1905        ContentResolver resolver = mContext.getContentResolver();
1906        boolean updateRotation = false;
1907        synchronized (mLock) {
1908            mEndcallBehavior = Settings.System.getIntForUser(resolver,
1909                    Settings.System.END_BUTTON_BEHAVIOR,
1910                    Settings.System.END_BUTTON_BEHAVIOR_DEFAULT,
1911                    UserHandle.USER_CURRENT);
1912            mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver,
1913                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
1914                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT,
1915                    UserHandle.USER_CURRENT);
1916
1917            // Configure wake gesture.
1918            boolean wakeGestureEnabledSetting = Settings.Secure.getIntForUser(resolver,
1919                    Settings.Secure.WAKE_GESTURE_ENABLED, 0,
1920                    UserHandle.USER_CURRENT) != 0;
1921            if (mWakeGestureEnabledSetting != wakeGestureEnabledSetting) {
1922                mWakeGestureEnabledSetting = wakeGestureEnabledSetting;
1923                updateWakeGestureListenerLp();
1924            }
1925
1926            // Configure rotation lock.
1927            int userRotation = Settings.System.getIntForUser(resolver,
1928                    Settings.System.USER_ROTATION, Surface.ROTATION_0,
1929                    UserHandle.USER_CURRENT);
1930            if (mUserRotation != userRotation) {
1931                mUserRotation = userRotation;
1932                updateRotation = true;
1933            }
1934            int userRotationMode = Settings.System.getIntForUser(resolver,
1935                    Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
1936                            WindowManagerPolicy.USER_ROTATION_FREE :
1937                                    WindowManagerPolicy.USER_ROTATION_LOCKED;
1938            if (mUserRotationMode != userRotationMode) {
1939                mUserRotationMode = userRotationMode;
1940                updateRotation = true;
1941                updateOrientationListenerLp();
1942            }
1943
1944            if (mSystemReady) {
1945                int pointerLocation = Settings.System.getIntForUser(resolver,
1946                        Settings.System.POINTER_LOCATION, 0, UserHandle.USER_CURRENT);
1947                if (mPointerLocationMode != pointerLocation) {
1948                    mPointerLocationMode = pointerLocation;
1949                    mHandler.sendEmptyMessage(pointerLocation != 0 ?
1950                            MSG_ENABLE_POINTER_LOCATION : MSG_DISABLE_POINTER_LOCATION);
1951                }
1952            }
1953            // use screen off timeout setting as the timeout for the lockscreen
1954            mLockScreenTimeout = Settings.System.getIntForUser(resolver,
1955                    Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT);
1956            String imId = Settings.Secure.getStringForUser(resolver,
1957                    Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT);
1958            boolean hasSoftInput = imId != null && imId.length() > 0;
1959            if (mHasSoftInput != hasSoftInput) {
1960                mHasSoftInput = hasSoftInput;
1961                updateRotation = true;
1962            }
1963            if (mImmersiveModeConfirmation != null) {
1964                mImmersiveModeConfirmation.loadSetting(mCurrentUserId);
1965            }
1966        }
1967        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
1968            PolicyControl.reloadFromSetting(mContext);
1969        }
1970        if (updateRotation) {
1971            updateRotation(true);
1972        }
1973    }
1974
1975    private void updateWakeGestureListenerLp() {
1976        if (shouldEnableWakeGestureLp()) {
1977            mWakeGestureListener.requestWakeUpTrigger();
1978        } else {
1979            mWakeGestureListener.cancelWakeUpTrigger();
1980        }
1981    }
1982
1983    private boolean shouldEnableWakeGestureLp() {
1984        return mWakeGestureEnabledSetting && !mAwake
1985                && (!mLidControlsSleep || mLidState != LID_CLOSED)
1986                && mWakeGestureListener.isSupported();
1987    }
1988
1989    private void enablePointerLocation() {
1990        if (mPointerLocationView == null) {
1991            mPointerLocationView = new PointerLocationView(mContext);
1992            mPointerLocationView.setPrintCoords(false);
1993            WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1994                    WindowManager.LayoutParams.MATCH_PARENT,
1995                    WindowManager.LayoutParams.MATCH_PARENT);
1996            lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
1997            lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
1998                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
1999                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
2000                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
2001            if (ActivityManager.isHighEndGfx()) {
2002                lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
2003                lp.privateFlags |=
2004                        WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED;
2005            }
2006            lp.format = PixelFormat.TRANSLUCENT;
2007            lp.setTitle("PointerLocation");
2008            WindowManager wm = (WindowManager)
2009                    mContext.getSystemService(Context.WINDOW_SERVICE);
2010            lp.inputFeatures |= WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL;
2011            wm.addView(mPointerLocationView, lp);
2012            mWindowManagerFuncs.registerPointerEventListener(mPointerLocationView);
2013        }
2014    }
2015
2016    private void disablePointerLocation() {
2017        if (mPointerLocationView != null) {
2018            mWindowManagerFuncs.unregisterPointerEventListener(mPointerLocationView);
2019            WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
2020            wm.removeView(mPointerLocationView);
2021            mPointerLocationView = null;
2022        }
2023    }
2024
2025    private int readRotation(int resID) {
2026        try {
2027            int rotation = mContext.getResources().getInteger(resID);
2028            switch (rotation) {
2029                case 0:
2030                    return Surface.ROTATION_0;
2031                case 90:
2032                    return Surface.ROTATION_90;
2033                case 180:
2034                    return Surface.ROTATION_180;
2035                case 270:
2036                    return Surface.ROTATION_270;
2037            }
2038        } catch (Resources.NotFoundException e) {
2039            // fall through
2040        }
2041        return -1;
2042    }
2043
2044    /** {@inheritDoc} */
2045    @Override
2046    public int checkAddPermission(WindowManager.LayoutParams attrs, int[] outAppOp) {
2047        int type = attrs.type;
2048
2049        outAppOp[0] = AppOpsManager.OP_NONE;
2050
2051        if (!((type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW)
2052                || (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW)
2053                || (type >= FIRST_SYSTEM_WINDOW && type <= LAST_SYSTEM_WINDOW))) {
2054            return WindowManagerGlobal.ADD_INVALID_TYPE;
2055        }
2056
2057        if (type < FIRST_SYSTEM_WINDOW || type > LAST_SYSTEM_WINDOW) {
2058            // Window manager will make sure these are okay.
2059            return WindowManagerGlobal.ADD_OKAY;
2060        }
2061        String permission = null;
2062        switch (type) {
2063            case TYPE_TOAST:
2064                // XXX right now the app process has complete control over
2065                // this...  should introduce a token to let the system
2066                // monitor/control what they are doing.
2067                outAppOp[0] = AppOpsManager.OP_TOAST_WINDOW;
2068                break;
2069            case TYPE_DREAM:
2070            case TYPE_INPUT_METHOD:
2071            case TYPE_WALLPAPER:
2072            case TYPE_PRIVATE_PRESENTATION:
2073            case TYPE_VOICE_INTERACTION:
2074            case TYPE_ACCESSIBILITY_OVERLAY:
2075            case TYPE_QS_DIALOG:
2076                // The window manager will check these.
2077                break;
2078            case TYPE_PHONE:
2079            case TYPE_PRIORITY_PHONE:
2080            case TYPE_SYSTEM_ALERT:
2081            case TYPE_SYSTEM_ERROR:
2082            case TYPE_SYSTEM_OVERLAY:
2083                permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
2084                outAppOp[0] = AppOpsManager.OP_SYSTEM_ALERT_WINDOW;
2085                break;
2086            default:
2087                permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
2088        }
2089        if (permission != null) {
2090            if (android.Manifest.permission.SYSTEM_ALERT_WINDOW.equals(permission)) {
2091                final int callingUid = Binder.getCallingUid();
2092                // system processes will be automatically allowed privilege to draw
2093                if (callingUid == Process.SYSTEM_UID) {
2094                    return WindowManagerGlobal.ADD_OKAY;
2095                }
2096
2097                // check if user has enabled this operation. SecurityException will be thrown if
2098                // this app has not been allowed by the user
2099                final int mode = mAppOpsManager.checkOpNoThrow(outAppOp[0], callingUid,
2100                        attrs.packageName);
2101                switch (mode) {
2102                    case AppOpsManager.MODE_ALLOWED:
2103                    case AppOpsManager.MODE_IGNORED:
2104                        // although we return ADD_OKAY for MODE_IGNORED, the added window will
2105                        // actually be hidden in WindowManagerService
2106                        return WindowManagerGlobal.ADD_OKAY;
2107                    case AppOpsManager.MODE_ERRORED:
2108                        try {
2109                            ApplicationInfo appInfo = mContext.getPackageManager()
2110                                    .getApplicationInfo(attrs.packageName,
2111                                            UserHandle.getUserId(callingUid));
2112                            // Don't crash legacy apps
2113                            if (appInfo.targetSdkVersion < Build.VERSION_CODES.M) {
2114                                return WindowManagerGlobal.ADD_OKAY;
2115                            }
2116                        } catch (PackageManager.NameNotFoundException e) {
2117                            /* ignore */
2118                        }
2119                        return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2120                    default:
2121                        // in the default mode, we will make a decision here based on
2122                        // checkCallingPermission()
2123                        if (mContext.checkCallingPermission(permission) !=
2124                                PackageManager.PERMISSION_GRANTED) {
2125                            return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2126                        } else {
2127                            return WindowManagerGlobal.ADD_OKAY;
2128                        }
2129                }
2130            }
2131
2132            if (mContext.checkCallingOrSelfPermission(permission)
2133                    != PackageManager.PERMISSION_GRANTED) {
2134                return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2135            }
2136        }
2137        return WindowManagerGlobal.ADD_OKAY;
2138    }
2139
2140    @Override
2141    public boolean checkShowToOwnerOnly(WindowManager.LayoutParams attrs) {
2142
2143        // If this switch statement is modified, modify the comment in the declarations of
2144        // the type in {@link WindowManager.LayoutParams} as well.
2145        switch (attrs.type) {
2146            default:
2147                // These are the windows that by default are shown only to the user that created
2148                // them. If this needs to be overridden, set
2149                // {@link WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS} in
2150                // {@link WindowManager.LayoutParams}. Note that permission
2151                // {@link android.Manifest.permission.INTERNAL_SYSTEM_WINDOW} is required as well.
2152                if ((attrs.privateFlags & PRIVATE_FLAG_SHOW_FOR_ALL_USERS) == 0) {
2153                    return true;
2154                }
2155                break;
2156
2157            // These are the windows that by default are shown to all users. However, to
2158            // protect against spoofing, check permissions below.
2159            case TYPE_APPLICATION_STARTING:
2160            case TYPE_BOOT_PROGRESS:
2161            case TYPE_DISPLAY_OVERLAY:
2162            case TYPE_INPUT_CONSUMER:
2163            case TYPE_KEYGUARD_SCRIM:
2164            case TYPE_KEYGUARD_DIALOG:
2165            case TYPE_MAGNIFICATION_OVERLAY:
2166            case TYPE_NAVIGATION_BAR:
2167            case TYPE_NAVIGATION_BAR_PANEL:
2168            case TYPE_PHONE:
2169            case TYPE_POINTER:
2170            case TYPE_PRIORITY_PHONE:
2171            case TYPE_SEARCH_BAR:
2172            case TYPE_STATUS_BAR:
2173            case TYPE_STATUS_BAR_PANEL:
2174            case TYPE_STATUS_BAR_SUB_PANEL:
2175            case TYPE_SYSTEM_DIALOG:
2176            case TYPE_VOLUME_OVERLAY:
2177            case TYPE_PRIVATE_PRESENTATION:
2178            case TYPE_DOCK_DIVIDER:
2179                break;
2180        }
2181
2182        // Check if third party app has set window to system window type.
2183        return mContext.checkCallingOrSelfPermission(
2184                android.Manifest.permission.INTERNAL_SYSTEM_WINDOW)
2185                        != PackageManager.PERMISSION_GRANTED;
2186    }
2187
2188    @Override
2189    public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
2190        switch (attrs.type) {
2191            case TYPE_SYSTEM_OVERLAY:
2192            case TYPE_SECURE_SYSTEM_OVERLAY:
2193                // These types of windows can't receive input events.
2194                attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
2195                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
2196                attrs.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
2197                break;
2198            case TYPE_STATUS_BAR:
2199
2200                // If the Keyguard is in a hidden state (occluded by another window), we force to
2201                // remove the wallpaper and keyguard flag so that any change in-flight after setting
2202                // the keyguard as occluded wouldn't set these flags again.
2203                // See {@link #processKeyguardSetHiddenResultLw}.
2204                if (mKeyguardHidden) {
2205                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
2206                    attrs.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
2207                }
2208                break;
2209        }
2210
2211        if (attrs.type != TYPE_STATUS_BAR) {
2212            // The status bar is the only window allowed to exhibit keyguard behavior.
2213            attrs.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
2214        }
2215
2216        if (ActivityManager.isHighEndGfx()) {
2217            if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0) {
2218                attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
2219            }
2220            if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
2221                    || (mForceWindowDrawsStatusBarBackground
2222                            && attrs.height == MATCH_PARENT && attrs.width == MATCH_PARENT)) {
2223                attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2224            }
2225        }
2226    }
2227
2228    void readLidState() {
2229        mLidState = mWindowManagerFuncs.getLidState();
2230    }
2231
2232    private void readCameraLensCoverState() {
2233        mCameraLensCoverState = mWindowManagerFuncs.getCameraLensCoverState();
2234    }
2235
2236    private boolean isHidden(int accessibilityMode) {
2237        switch (accessibilityMode) {
2238            case 1:
2239                return mLidState == LID_CLOSED;
2240            case 2:
2241                return mLidState == LID_OPEN;
2242            default:
2243                return false;
2244        }
2245    }
2246
2247    /** {@inheritDoc} */
2248    @Override
2249    public void adjustConfigurationLw(Configuration config, int keyboardPresence,
2250            int navigationPresence) {
2251        mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
2252
2253        readConfigurationDependentBehaviors();
2254        readLidState();
2255        applyLidSwitchState();
2256
2257        if (config.keyboard == Configuration.KEYBOARD_NOKEYS
2258                || (keyboardPresence == PRESENCE_INTERNAL
2259                        && isHidden(mLidKeyboardAccessibility))) {
2260            config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
2261            if (!mHasSoftInput) {
2262                config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES;
2263            }
2264        }
2265
2266        if (config.navigation == Configuration.NAVIGATION_NONAV
2267                || (navigationPresence == PRESENCE_INTERNAL
2268                        && isHidden(mLidNavigationAccessibility))) {
2269            config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
2270        }
2271    }
2272
2273    @Override
2274    public void onConfigurationChanged() {
2275        final Resources res = mContext.getResources();
2276
2277        mStatusBarHeight =
2278                res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
2279
2280        // Height of the navigation bar when presented horizontally at bottom
2281        mNavigationBarHeightForRotationDefault[mPortraitRotation] =
2282        mNavigationBarHeightForRotationDefault[mUpsideDownRotation] =
2283                res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_height);
2284        mNavigationBarHeightForRotationDefault[mLandscapeRotation] =
2285        mNavigationBarHeightForRotationDefault[mSeascapeRotation] = res.getDimensionPixelSize(
2286                com.android.internal.R.dimen.navigation_bar_height_landscape);
2287
2288        // Width of the navigation bar when presented vertically along one side
2289        mNavigationBarWidthForRotationDefault[mPortraitRotation] =
2290        mNavigationBarWidthForRotationDefault[mUpsideDownRotation] =
2291        mNavigationBarWidthForRotationDefault[mLandscapeRotation] =
2292        mNavigationBarWidthForRotationDefault[mSeascapeRotation] =
2293                res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_width);
2294
2295        // Height of the navigation bar when presented horizontally at bottom
2296        mNavigationBarHeightForRotationInCarMode[mPortraitRotation] =
2297        mNavigationBarHeightForRotationInCarMode[mUpsideDownRotation] =
2298                res.getDimensionPixelSize(
2299                        com.android.internal.R.dimen.navigation_bar_height_car_mode);
2300        mNavigationBarHeightForRotationInCarMode[mLandscapeRotation] =
2301        mNavigationBarHeightForRotationInCarMode[mSeascapeRotation] = res.getDimensionPixelSize(
2302                com.android.internal.R.dimen.navigation_bar_height_landscape_car_mode);
2303
2304        // Width of the navigation bar when presented vertically along one side
2305        mNavigationBarWidthForRotationInCarMode[mPortraitRotation] =
2306        mNavigationBarWidthForRotationInCarMode[mUpsideDownRotation] =
2307        mNavigationBarWidthForRotationInCarMode[mLandscapeRotation] =
2308        mNavigationBarWidthForRotationInCarMode[mSeascapeRotation] =
2309                res.getDimensionPixelSize(
2310                        com.android.internal.R.dimen.navigation_bar_width_car_mode);
2311    }
2312
2313    /** {@inheritDoc} */
2314    @Override
2315    public int windowTypeToLayerLw(int type) {
2316        if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
2317            return 2;
2318        }
2319        switch (type) {
2320        case TYPE_PRIVATE_PRESENTATION:
2321            return 2;
2322        case TYPE_WALLPAPER:
2323            // wallpaper is at the bottom, though the window manager may move it.
2324            return 2;
2325        case TYPE_DOCK_DIVIDER:
2326            return 2;
2327        case TYPE_QS_DIALOG:
2328            return 2;
2329        case TYPE_PHONE:
2330            return 3;
2331        case TYPE_SEARCH_BAR:
2332        case TYPE_VOICE_INTERACTION_STARTING:
2333            return 4;
2334        case TYPE_VOICE_INTERACTION:
2335            // voice interaction layer is almost immediately above apps.
2336            return 5;
2337        case TYPE_INPUT_CONSUMER:
2338            return 6;
2339        case TYPE_SYSTEM_DIALOG:
2340            return 7;
2341        case TYPE_TOAST:
2342            // toasts and the plugged-in battery thing
2343            return 8;
2344        case TYPE_PRIORITY_PHONE:
2345            // SIM errors and unlock.  Not sure if this really should be in a high layer.
2346            return 9;
2347        case TYPE_DREAM:
2348            // used for Dreams (screensavers with TYPE_DREAM windows)
2349            return 10;
2350        case TYPE_SYSTEM_ALERT:
2351            // like the ANR / app crashed dialogs
2352            return 11;
2353        case TYPE_INPUT_METHOD:
2354            // on-screen keyboards and other such input method user interfaces go here.
2355            return 12;
2356        case TYPE_INPUT_METHOD_DIALOG:
2357            // on-screen keyboards and other such input method user interfaces go here.
2358            return 13;
2359        case TYPE_KEYGUARD_SCRIM:
2360            // the safety window that shows behind keyguard while keyguard is starting
2361            return 14;
2362        case TYPE_STATUS_BAR_SUB_PANEL:
2363            return 15;
2364        case TYPE_STATUS_BAR:
2365            return 16;
2366        case TYPE_STATUS_BAR_PANEL:
2367            return 17;
2368        case TYPE_KEYGUARD_DIALOG:
2369            return 18;
2370        case TYPE_VOLUME_OVERLAY:
2371            // the on-screen volume indicator and controller shown when the user
2372            // changes the device volume
2373            return 19;
2374        case TYPE_SYSTEM_OVERLAY:
2375            // the on-screen volume indicator and controller shown when the user
2376            // changes the device volume
2377            return 20;
2378        case TYPE_NAVIGATION_BAR:
2379            // the navigation bar, if available, shows atop most things
2380            return 21;
2381        case TYPE_NAVIGATION_BAR_PANEL:
2382            // some panels (e.g. search) need to show on top of the navigation bar
2383            return 22;
2384        case TYPE_SCREENSHOT:
2385            // screenshot selection layer shouldn't go above system error, but it should cover
2386            // navigation bars at the very least.
2387            return 23;
2388        case TYPE_SYSTEM_ERROR:
2389            // system-level error dialogs
2390            return 24;
2391        case TYPE_MAGNIFICATION_OVERLAY:
2392            // used to highlight the magnified portion of a display
2393            return 25;
2394        case TYPE_DISPLAY_OVERLAY:
2395            // used to simulate secondary display devices
2396            return 26;
2397        case TYPE_DRAG:
2398            // the drag layer: input for drag-and-drop is associated with this window,
2399            // which sits above all other focusable windows
2400            return 27;
2401        case TYPE_ACCESSIBILITY_OVERLAY:
2402            // overlay put by accessibility services to intercept user interaction
2403            return 28;
2404        case TYPE_SECURE_SYSTEM_OVERLAY:
2405            return 29;
2406        case TYPE_BOOT_PROGRESS:
2407            return 30;
2408        case TYPE_POINTER:
2409            // the (mouse) pointer layer
2410            return 31;
2411        }
2412        Log.e(TAG, "Unknown window type: " + type);
2413        return 2;
2414    }
2415
2416    /** {@inheritDoc} */
2417    @Override
2418    public int subWindowTypeToLayerLw(int type) {
2419        switch (type) {
2420        case TYPE_APPLICATION_PANEL:
2421        case TYPE_APPLICATION_ATTACHED_DIALOG:
2422            return APPLICATION_PANEL_SUBLAYER;
2423        case TYPE_APPLICATION_MEDIA:
2424            return APPLICATION_MEDIA_SUBLAYER;
2425        case TYPE_APPLICATION_MEDIA_OVERLAY:
2426            return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
2427        case TYPE_APPLICATION_SUB_PANEL:
2428            return APPLICATION_SUB_PANEL_SUBLAYER;
2429        case TYPE_APPLICATION_ABOVE_SUB_PANEL:
2430            return APPLICATION_ABOVE_SUB_PANEL_SUBLAYER;
2431        }
2432        Log.e(TAG, "Unknown sub-window type: " + type);
2433        return 0;
2434    }
2435
2436    @Override
2437    public int getMaxWallpaperLayer() {
2438        return windowTypeToLayerLw(TYPE_STATUS_BAR);
2439    }
2440
2441    private int getNavigationBarWidth(int rotation, int uiMode) {
2442        if ((uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR) {
2443            return mNavigationBarWidthForRotationInCarMode[rotation];
2444        } else {
2445            return mNavigationBarWidthForRotationDefault[rotation];
2446        }
2447    }
2448
2449    @Override
2450    public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation,
2451            int uiMode) {
2452        if (mHasNavigationBar) {
2453            // For a basic navigation bar, when we are in landscape mode we place
2454            // the navigation bar to the side.
2455            if (mNavigationBarCanMove && fullWidth > fullHeight) {
2456                return fullWidth - getNavigationBarWidth(rotation, uiMode);
2457            }
2458        }
2459        return fullWidth;
2460    }
2461
2462    private int getNavigationBarHeight(int rotation, int uiMode) {
2463        if ((uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR) {
2464            return mNavigationBarHeightForRotationInCarMode[rotation];
2465        } else {
2466            return mNavigationBarHeightForRotationDefault[rotation];
2467        }
2468    }
2469
2470    @Override
2471    public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation,
2472            int uiMode) {
2473        if (mHasNavigationBar) {
2474            // For a basic navigation bar, when we are in portrait mode we place
2475            // the navigation bar to the bottom.
2476            if (!mNavigationBarCanMove || fullWidth < fullHeight) {
2477                return fullHeight - getNavigationBarHeight(rotation, uiMode);
2478            }
2479        }
2480        return fullHeight;
2481    }
2482
2483    @Override
2484    public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation, int uiMode) {
2485        return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation, uiMode);
2486    }
2487
2488    @Override
2489    public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation, int uiMode) {
2490        // There is a separate status bar at the top of the display.  We don't count that as part
2491        // of the fixed decor, since it can hide; however, for purposes of configurations,
2492        // we do want to exclude it since applications can't generally use that part
2493        // of the screen.
2494        return getNonDecorDisplayHeight(
2495                fullWidth, fullHeight, rotation, uiMode) - mStatusBarHeight;
2496    }
2497
2498    @Override
2499    public boolean isForceHiding(WindowManager.LayoutParams attrs) {
2500        return (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 ||
2501                (isKeyguardHostWindow(attrs) &&
2502                        (mKeyguardDelegate != null && mKeyguardDelegate.isShowing())) ||
2503                (attrs.type == TYPE_KEYGUARD_SCRIM);
2504    }
2505
2506    @Override
2507    public boolean isKeyguardHostWindow(WindowManager.LayoutParams attrs) {
2508        return attrs.type == TYPE_STATUS_BAR;
2509    }
2510
2511    @Override
2512    public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
2513        switch (attrs.type) {
2514            case TYPE_STATUS_BAR:
2515            case TYPE_NAVIGATION_BAR:
2516            case TYPE_WALLPAPER:
2517            case TYPE_DREAM:
2518            case TYPE_KEYGUARD_SCRIM:
2519                return false;
2520            default:
2521                // Hide only windows below the keyguard host window.
2522                return windowTypeToLayerLw(win.getBaseType())
2523                        < windowTypeToLayerLw(TYPE_STATUS_BAR);
2524        }
2525    }
2526
2527    @Override
2528    public WindowState getWinShowWhenLockedLw() {
2529        return mWinShowWhenLocked;
2530    }
2531
2532    /** {@inheritDoc} */
2533    @Override
2534    public View addStartingWindow(IBinder appToken, String packageName, int theme,
2535            CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel, int labelRes,
2536            int icon, int logo, int windowFlags) {
2537        if (!SHOW_STARTING_ANIMATIONS) {
2538            return null;
2539        }
2540        if (packageName == null) {
2541            return null;
2542        }
2543
2544        WindowManager wm = null;
2545        View view = null;
2546
2547        try {
2548            Context context = mContext;
2549            if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow " + packageName
2550                    + ": nonLocalizedLabel=" + nonLocalizedLabel + " theme="
2551                    + Integer.toHexString(theme));
2552            if (theme != context.getThemeResId() || labelRes != 0) {
2553                try {
2554                    context = context.createPackageContext(packageName, 0);
2555                    context.setTheme(theme);
2556                } catch (PackageManager.NameNotFoundException e) {
2557                    // Ignore
2558                }
2559            }
2560
2561            PhoneWindow win = new PhoneWindow(context);
2562            win.setIsStartingWindow(true);
2563
2564            Resources r = context.getResources();
2565            win.setTitle(r.getText(labelRes, nonLocalizedLabel));
2566
2567            win.setType(
2568                WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
2569
2570            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
2571                // Assumes it's safe to show starting windows of launched apps while
2572                // the keyguard is being hidden. This is okay because starting windows never show
2573                // secret information.
2574                if (mKeyguardHidden) {
2575                    windowFlags |= FLAG_SHOW_WHEN_LOCKED;
2576                }
2577            }
2578
2579            // Force the window flags: this is a fake window, so it is not really
2580            // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
2581            // flag because we do know that the next window will take input
2582            // focus, so we want to get the IME window up on top of us right away.
2583            win.setFlags(
2584                windowFlags|
2585                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2586                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2587                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
2588                windowFlags|
2589                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2590                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2591                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
2592
2593            win.setDefaultIcon(icon);
2594            win.setDefaultLogo(logo);
2595
2596            win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
2597                    WindowManager.LayoutParams.MATCH_PARENT);
2598
2599            final WindowManager.LayoutParams params = win.getAttributes();
2600            params.token = appToken;
2601            params.packageName = packageName;
2602            params.windowAnimations = win.getWindowStyle().getResourceId(
2603                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2604            params.privateFlags |=
2605                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED;
2606            params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
2607
2608            if (!compatInfo.supportsScreen()) {
2609                params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
2610            }
2611
2612            params.setTitle("Starting " + packageName);
2613
2614            wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
2615            view = win.getDecorView();
2616
2617            if (DEBUG_STARTING_WINDOW) Slog.d(
2618                TAG, "Adding starting window for " + packageName
2619                + " / " + appToken + ": "
2620                + (view.getParent() != null ? view : null));
2621
2622            wm.addView(view, params);
2623
2624            // Only return the view if it was successfully added to the
2625            // window manager... which we can tell by it having a parent.
2626            return view.getParent() != null ? view : null;
2627        } catch (WindowManager.BadTokenException e) {
2628            // ignore
2629            Log.w(TAG, appToken + " already running, starting window not displayed. " +
2630                    e.getMessage());
2631        } catch (RuntimeException e) {
2632            // don't crash if something else bad happens, for example a
2633            // failure loading resources because we are loading from an app
2634            // on external storage that has been unmounted.
2635            Log.w(TAG, appToken + " failed creating starting window", e);
2636        } finally {
2637            if (view != null && view.getParent() == null) {
2638                Log.w(TAG, "view not successfully added to wm, removing view");
2639                wm.removeViewImmediate(view);
2640            }
2641        }
2642
2643        return null;
2644    }
2645
2646    /** {@inheritDoc} */
2647    @Override
2648    public void removeStartingWindow(IBinder appToken, View window) {
2649        if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Removing starting window for " + appToken + ": "
2650                + window + " Callers=" + Debug.getCallers(4));
2651
2652        if (window != null) {
2653            WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
2654            wm.removeView(window);
2655        }
2656    }
2657
2658    /**
2659     * Preflight adding a window to the system.
2660     *
2661     * Currently enforces that three window types are singletons:
2662     * <ul>
2663     * <li>STATUS_BAR_TYPE</li>
2664     * <li>KEYGUARD_TYPE</li>
2665     * </ul>
2666     *
2667     * @param win The window to be added
2668     * @param attrs Information about the window to be added
2669     *
2670     * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons,
2671     * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
2672     */
2673    @Override
2674    public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
2675        switch (attrs.type) {
2676            case TYPE_STATUS_BAR:
2677                mContext.enforceCallingOrSelfPermission(
2678                        android.Manifest.permission.STATUS_BAR_SERVICE,
2679                        "PhoneWindowManager");
2680                if (mStatusBar != null) {
2681                    if (mStatusBar.isAlive()) {
2682                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2683                    }
2684                }
2685                mStatusBar = win;
2686                mStatusBarController.setWindow(win);
2687                break;
2688            case TYPE_NAVIGATION_BAR:
2689                mContext.enforceCallingOrSelfPermission(
2690                        android.Manifest.permission.STATUS_BAR_SERVICE,
2691                        "PhoneWindowManager");
2692                if (mNavigationBar != null) {
2693                    if (mNavigationBar.isAlive()) {
2694                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2695                    }
2696                }
2697                mNavigationBar = win;
2698                mNavigationBarController.setWindow(win);
2699                if (DEBUG_LAYOUT) Slog.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
2700                break;
2701            case TYPE_NAVIGATION_BAR_PANEL:
2702            case TYPE_STATUS_BAR_PANEL:
2703            case TYPE_STATUS_BAR_SUB_PANEL:
2704            case TYPE_VOICE_INTERACTION_STARTING:
2705                mContext.enforceCallingOrSelfPermission(
2706                        android.Manifest.permission.STATUS_BAR_SERVICE,
2707                        "PhoneWindowManager");
2708                break;
2709            case TYPE_KEYGUARD_SCRIM:
2710                if (mKeyguardScrim != null) {
2711                    return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2712                }
2713                mKeyguardScrim = win;
2714                break;
2715        }
2716        return WindowManagerGlobal.ADD_OKAY;
2717    }
2718
2719    /** {@inheritDoc} */
2720    @Override
2721    public void removeWindowLw(WindowState win) {
2722        if (mStatusBar == win) {
2723            mStatusBar = null;
2724            mStatusBarController.setWindow(null);
2725            mKeyguardDelegate.showScrim();
2726        } else if (mKeyguardScrim == win) {
2727            Log.v(TAG, "Removing keyguard scrim");
2728            mKeyguardScrim = null;
2729        } if (mNavigationBar == win) {
2730            mNavigationBar = null;
2731            mNavigationBarController.setWindow(null);
2732        }
2733    }
2734
2735    static final boolean PRINT_ANIM = false;
2736
2737    /** {@inheritDoc} */
2738    @Override
2739    public int selectAnimationLw(WindowState win, int transit) {
2740        if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
2741              + ": transit=" + transit);
2742        if (win == mStatusBar) {
2743            boolean isKeyguard = (win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
2744            if (transit == TRANSIT_EXIT
2745                    || transit == TRANSIT_HIDE) {
2746                return isKeyguard ? -1 : R.anim.dock_top_exit;
2747            } else if (transit == TRANSIT_ENTER
2748                    || transit == TRANSIT_SHOW) {
2749                return isKeyguard ? -1 : R.anim.dock_top_enter;
2750            }
2751        } else if (win == mNavigationBar) {
2752            if (win.getAttrs().windowAnimations != 0) {
2753                return 0;
2754            }
2755            // This can be on either the bottom or the right.
2756            if (mNavigationBarOnBottom) {
2757                if (transit == TRANSIT_EXIT
2758                        || transit == TRANSIT_HIDE) {
2759                    return R.anim.dock_bottom_exit;
2760                } else if (transit == TRANSIT_ENTER
2761                        || transit == TRANSIT_SHOW) {
2762                    return R.anim.dock_bottom_enter;
2763                }
2764            } else {
2765                if (transit == TRANSIT_EXIT
2766                        || transit == TRANSIT_HIDE) {
2767                    return R.anim.dock_right_exit;
2768                } else if (transit == TRANSIT_ENTER
2769                        || transit == TRANSIT_SHOW) {
2770                    return R.anim.dock_right_enter;
2771                }
2772            }
2773        } else if (win.getAttrs().type == TYPE_DOCK_DIVIDER) {
2774            return selectDockedDividerAnimationLw(win, transit);
2775        }
2776
2777        if (transit == TRANSIT_PREVIEW_DONE) {
2778            if (win.hasAppShownWindows()) {
2779                if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
2780                return com.android.internal.R.anim.app_starting_exit;
2781            }
2782        } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
2783                && transit == TRANSIT_ENTER) {
2784            // Special case: we are animating in a dream, while the keyguard
2785            // is shown.  We don't want an animation on the dream, because
2786            // we need it shown immediately with the keyguard animating away
2787            // to reveal it.
2788            return -1;
2789        }
2790
2791        return 0;
2792    }
2793
2794    private int selectDockedDividerAnimationLw(WindowState win, int transit) {
2795        int insets = mWindowManagerFuncs.getDockedDividerInsetsLw();
2796
2797        // If the divider is behind the navigation bar, don't animate.
2798        final Rect frame = win.getFrameLw();
2799        final boolean behindNavBar = mNavigationBar != null
2800                && ((mNavigationBarOnBottom
2801                        && frame.top + insets >= mNavigationBar.getFrameLw().top)
2802                || (!mNavigationBarOnBottom
2803                        && frame.left + insets >= mNavigationBar.getFrameLw().left));
2804        final boolean landscape = frame.height() > frame.width();
2805        final boolean offscreenLandscape = landscape && (frame.right - insets <= 0
2806                || frame.left + insets >= win.getDisplayFrameLw().right);
2807        final boolean offscreenPortrait = !landscape && (frame.top - insets <= 0
2808                || frame.bottom + insets >= win.getDisplayFrameLw().bottom);
2809        final boolean offscreen = offscreenLandscape || offscreenPortrait;
2810        if (behindNavBar || offscreen) {
2811            return 0;
2812        }
2813        if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) {
2814            return R.anim.fade_in;
2815        } else if (transit == TRANSIT_EXIT) {
2816            return R.anim.fade_out;
2817        } else {
2818            return 0;
2819        }
2820    }
2821
2822    @Override
2823    public void selectRotationAnimationLw(int anim[]) {
2824        if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
2825                + mTopFullscreenOpaqueWindowState + " rotationAnimation="
2826                + (mTopFullscreenOpaqueWindowState == null ?
2827                        "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
2828        if (mTopFullscreenOpaqueWindowState != null && mTopIsFullscreen) {
2829            switch (mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation) {
2830                case ROTATION_ANIMATION_CROSSFADE:
2831                    anim[0] = R.anim.rotation_animation_xfade_exit;
2832                    anim[1] = R.anim.rotation_animation_enter;
2833                    break;
2834                case ROTATION_ANIMATION_JUMPCUT:
2835                    anim[0] = R.anim.rotation_animation_jump_exit;
2836                    anim[1] = R.anim.rotation_animation_enter;
2837                    break;
2838                case ROTATION_ANIMATION_ROTATE:
2839                default:
2840                    anim[0] = anim[1] = 0;
2841                    break;
2842            }
2843        } else {
2844            anim[0] = anim[1] = 0;
2845        }
2846    }
2847
2848    @Override
2849    public boolean validateRotationAnimationLw(int exitAnimId, int enterAnimId,
2850            boolean forceDefault) {
2851        switch (exitAnimId) {
2852            case R.anim.rotation_animation_xfade_exit:
2853            case R.anim.rotation_animation_jump_exit:
2854                // These are the only cases that matter.
2855                if (forceDefault) {
2856                    return false;
2857                }
2858                int anim[] = new int[2];
2859                selectRotationAnimationLw(anim);
2860                return (exitAnimId == anim[0] && enterAnimId == anim[1]);
2861            default:
2862                return true;
2863        }
2864    }
2865
2866    @Override
2867    public Animation createForceHideEnterAnimation(boolean onWallpaper,
2868            boolean goingToNotificationShade) {
2869        if (goingToNotificationShade) {
2870            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_behind_enter_fade_in);
2871        }
2872
2873        AnimationSet set = (AnimationSet) AnimationUtils.loadAnimation(mContext, onWallpaper ?
2874                    R.anim.lock_screen_behind_enter_wallpaper :
2875                    R.anim.lock_screen_behind_enter);
2876
2877        // TODO: Use XML interpolators when we have log interpolators available in XML.
2878        final List<Animation> animations = set.getAnimations();
2879        for (int i = animations.size() - 1; i >= 0; --i) {
2880            animations.get(i).setInterpolator(mLogDecelerateInterpolator);
2881        }
2882
2883        return set;
2884    }
2885
2886
2887    @Override
2888    public Animation createForceHideWallpaperExitAnimation(boolean goingToNotificationShade) {
2889        if (goingToNotificationShade) {
2890            return null;
2891        } else {
2892            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_wallpaper_exit);
2893        }
2894    }
2895
2896    private static void awakenDreams() {
2897        IDreamManager dreamManager = getDreamManager();
2898        if (dreamManager != null) {
2899            try {
2900                dreamManager.awaken();
2901            } catch (RemoteException e) {
2902                // fine, stay asleep then
2903            }
2904        }
2905    }
2906
2907    static IDreamManager getDreamManager() {
2908        return IDreamManager.Stub.asInterface(
2909                ServiceManager.checkService(DreamService.DREAM_SERVICE));
2910    }
2911
2912    TelecomManager getTelecommService() {
2913        return (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2914    }
2915
2916    static IAudioService getAudioService() {
2917        IAudioService audioService = IAudioService.Stub.asInterface(
2918                ServiceManager.checkService(Context.AUDIO_SERVICE));
2919        if (audioService == null) {
2920            Log.w(TAG, "Unable to find IAudioService interface.");
2921        }
2922        return audioService;
2923    }
2924
2925    boolean keyguardOn() {
2926        return isKeyguardShowingAndNotOccluded() || inKeyguardRestrictedKeyInputMode();
2927    }
2928
2929    private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
2930            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
2931            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
2932        };
2933
2934    /** {@inheritDoc} */
2935    @Override
2936    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
2937        final boolean keyguardOn = keyguardOn();
2938        final int keyCode = event.getKeyCode();
2939        final int repeatCount = event.getRepeatCount();
2940        final int metaState = event.getMetaState();
2941        final int flags = event.getFlags();
2942        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
2943        final boolean canceled = event.isCanceled();
2944
2945        if (DEBUG_INPUT) {
2946            Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
2947                    + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
2948                    + " canceled=" + canceled);
2949        }
2950
2951        // If we think we might have a volume down & power key chord on the way
2952        // but we're not sure, then tell the dispatcher to wait a little while and
2953        // try again later before dispatching.
2954        if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
2955            if (mScreenshotChordVolumeDownKeyTriggered && !mScreenshotChordPowerKeyTriggered) {
2956                final long now = SystemClock.uptimeMillis();
2957                final long timeoutTime = mScreenshotChordVolumeDownKeyTime
2958                        + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
2959                if (now < timeoutTime) {
2960                    return timeoutTime - now;
2961                }
2962            }
2963            if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
2964                    && mScreenshotChordVolumeDownKeyConsumed) {
2965                if (!down) {
2966                    mScreenshotChordVolumeDownKeyConsumed = false;
2967                }
2968                return -1;
2969            }
2970        }
2971
2972        // Cancel any pending meta actions if we see any other keys being pressed between the down
2973        // of the meta key and its corresponding up.
2974        if (mPendingMetaAction && !KeyEvent.isMetaKey(keyCode)) {
2975            mPendingMetaAction = false;
2976        }
2977        // Any key that is not Alt or Meta cancels Caps Lock combo tracking.
2978        if (mPendingCapsLockToggle && !KeyEvent.isMetaKey(keyCode) && !KeyEvent.isAltKey(keyCode)) {
2979            mPendingCapsLockToggle = false;
2980        }
2981
2982        // First we always handle the home key here, so applications
2983        // can never break it, although if keyguard is on, we do let
2984        // it handle it, because that gives us the correct 5 second
2985        // timeout.
2986        if (keyCode == KeyEvent.KEYCODE_HOME) {
2987
2988            // If we have released the home key, and didn't do anything else
2989            // while it was pressed, then it is time to go home!
2990            if (!down) {
2991                cancelPreloadRecentApps();
2992
2993                mHomePressed = false;
2994                if (mHomeConsumed) {
2995                    mHomeConsumed = false;
2996                    return -1;
2997                }
2998
2999                if (canceled) {
3000                    Log.i(TAG, "Ignoring HOME; event canceled.");
3001                    return -1;
3002                }
3003
3004                // If an incoming call is ringing, HOME is totally disabled.
3005                // (The user is already on the InCallUI at this point,
3006                // and his ONLY options are to answer or reject the call.)
3007                TelecomManager telecomManager = getTelecommService();
3008                if (telecomManager != null && telecomManager.isRinging()) {
3009                    Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
3010                    return -1;
3011                }
3012
3013                // Delay handling home if a double-tap is possible.
3014                if (mDoubleTapOnHomeBehavior != DOUBLE_TAP_HOME_NOTHING) {
3015                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable); // just in case
3016                    mHomeDoubleTapPending = true;
3017                    mHandler.postDelayed(mHomeDoubleTapTimeoutRunnable,
3018                            ViewConfiguration.getDoubleTapTimeout());
3019                    return -1;
3020                }
3021
3022                handleShortPressOnHome();
3023                return -1;
3024            }
3025
3026            // If a system window has focus, then it doesn't make sense
3027            // right now to interact with applications.
3028            WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
3029            if (attrs != null) {
3030                final int type = attrs.type;
3031                if (type == WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM
3032                        || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
3033                        || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
3034                    // the "app" is keyguard, so give it the key
3035                    return 0;
3036                }
3037                final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
3038                for (int i=0; i<typeCount; i++) {
3039                    if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
3040                        // don't do anything, but also don't pass it to the app
3041                        return -1;
3042                    }
3043                }
3044            }
3045
3046            // Remember that home is pressed and handle special actions.
3047            if (repeatCount == 0) {
3048                mHomePressed = true;
3049                if (mHomeDoubleTapPending) {
3050                    mHomeDoubleTapPending = false;
3051                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable);
3052                    handleDoubleTapOnHome();
3053                } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI
3054                        || mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
3055                    preloadRecentApps();
3056                }
3057            } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
3058                if (!keyguardOn) {
3059                    handleLongPressOnHome(event.getDeviceId());
3060                }
3061            }
3062            return -1;
3063        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
3064            // Hijack modified menu keys for debugging features
3065            final int chordBug = KeyEvent.META_SHIFT_ON;
3066
3067            if (down && repeatCount == 0) {
3068                if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
3069                    Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
3070                    mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
3071                            null, null, null, 0, null, null);
3072                    return -1;
3073                } else if (SHOW_PROCESSES_ON_ALT_MENU &&
3074                        (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
3075                    Intent service = new Intent();
3076                    service.setClassName(mContext, "com.android.server.LoadAverageService");
3077                    ContentResolver res = mContext.getContentResolver();
3078                    boolean shown = Settings.Global.getInt(
3079                            res, Settings.Global.SHOW_PROCESSES, 0) != 0;
3080                    if (!shown) {
3081                        mContext.startService(service);
3082                    } else {
3083                        mContext.stopService(service);
3084                    }
3085                    Settings.Global.putInt(
3086                            res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
3087                    return -1;
3088                }
3089            }
3090        } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
3091            if (down) {
3092                if (repeatCount == 0) {
3093                    mSearchKeyShortcutPending = true;
3094                    mConsumeSearchKeyUp = false;
3095                }
3096            } else {
3097                mSearchKeyShortcutPending = false;
3098                if (mConsumeSearchKeyUp) {
3099                    mConsumeSearchKeyUp = false;
3100                    return -1;
3101                }
3102            }
3103            return 0;
3104        } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
3105            if (!keyguardOn) {
3106                if (down && repeatCount == 0) {
3107                    preloadRecentApps();
3108                } else if (!down) {
3109                    toggleRecentApps();
3110                }
3111            }
3112            return -1;
3113        } else if (keyCode == KeyEvent.KEYCODE_N && event.isMetaPressed()) {
3114            if (down) {
3115                IStatusBarService service = getStatusBarService();
3116                if (service != null) {
3117                    try {
3118                        service.expandNotificationsPanel();
3119                    } catch (RemoteException e) {
3120                        // do nothing.
3121                    }
3122                }
3123            }
3124        } else if (keyCode == KeyEvent.KEYCODE_S && event.isMetaPressed()
3125                && event.isCtrlPressed()) {
3126            if (down && repeatCount == 0) {
3127                int type = event.isShiftPressed() ? TAKE_SCREENSHOT_SELECTED_REGION
3128                        : TAKE_SCREENSHOT_FULLSCREEN;
3129                mScreenshotRunnable.setScreenshotType(type);
3130                mHandler.post(mScreenshotRunnable);
3131                return -1;
3132            }
3133        } else if (keyCode == KeyEvent.KEYCODE_SLASH && event.isMetaPressed()) {
3134            if (down && repeatCount == 0 && !isKeyguardLocked()) {
3135                toggleKeyboardShortcutsMenu(event.getDeviceId());
3136            }
3137        } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
3138            if (down) {
3139                if (repeatCount == 0) {
3140                    mAssistKeyLongPressed = false;
3141                } else if (repeatCount == 1) {
3142                    mAssistKeyLongPressed = true;
3143                    if (!keyguardOn) {
3144                         launchAssistLongPressAction();
3145                    }
3146                }
3147            } else {
3148                if (mAssistKeyLongPressed) {
3149                    mAssistKeyLongPressed = false;
3150                } else {
3151                    if (!keyguardOn) {
3152                        launchAssistAction(null, event.getDeviceId());
3153                    }
3154                }
3155            }
3156            return -1;
3157        } else if (keyCode == KeyEvent.KEYCODE_VOICE_ASSIST) {
3158            if (!down) {
3159                Intent voiceIntent;
3160                if (!keyguardOn) {
3161                    voiceIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3162                } else {
3163                    IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
3164                            ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
3165                    if (dic != null) {
3166                        try {
3167                            dic.exitIdle("voice-search");
3168                        } catch (RemoteException e) {
3169                        }
3170                    }
3171                    voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
3172                    voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, true);
3173                }
3174                startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
3175            }
3176        } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
3177            if (down && repeatCount == 0) {
3178                mScreenshotRunnable.setScreenshotType(TAKE_SCREENSHOT_FULLSCREEN);
3179                mHandler.post(mScreenshotRunnable);
3180            }
3181            return -1;
3182        } else if (keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP
3183                || keyCode == KeyEvent.KEYCODE_BRIGHTNESS_DOWN) {
3184            if (down) {
3185                int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1;
3186
3187                // Disable autobrightness if it's on
3188                int auto = Settings.System.getIntForUser(
3189                        mContext.getContentResolver(),
3190                        Settings.System.SCREEN_BRIGHTNESS_MODE,
3191                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3192                        UserHandle.USER_CURRENT_OR_SELF);
3193                if (auto != 0) {
3194                    Settings.System.putIntForUser(mContext.getContentResolver(),
3195                            Settings.System.SCREEN_BRIGHTNESS_MODE,
3196                            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3197                            UserHandle.USER_CURRENT_OR_SELF);
3198                }
3199
3200                int min = mPowerManager.getMinimumScreenBrightnessSetting();
3201                int max = mPowerManager.getMaximumScreenBrightnessSetting();
3202                int step = (max - min + BRIGHTNESS_STEPS - 1) / BRIGHTNESS_STEPS * direction;
3203                int brightness = Settings.System.getIntForUser(mContext.getContentResolver(),
3204                        Settings.System.SCREEN_BRIGHTNESS,
3205                        mPowerManager.getDefaultScreenBrightnessSetting(),
3206                        UserHandle.USER_CURRENT_OR_SELF);
3207                brightness += step;
3208                // Make sure we don't go beyond the limits.
3209                brightness = Math.min(max, brightness);
3210                brightness = Math.max(min, brightness);
3211
3212                Settings.System.putIntForUser(mContext.getContentResolver(),
3213                        Settings.System.SCREEN_BRIGHTNESS, brightness,
3214                        UserHandle.USER_CURRENT_OR_SELF);
3215                startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG),
3216                        UserHandle.CURRENT_OR_SELF);
3217            }
3218            return -1;
3219        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP
3220                || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
3221                || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
3222            if (mUseTvRouting) {
3223                // On TVs volume keys never go to the foreground app.
3224                dispatchDirectAudioEvent(event);
3225                return -1;
3226            }
3227        }
3228
3229        // Toggle Caps Lock on META-ALT.
3230        boolean actionTriggered = false;
3231        if (KeyEvent.isModifierKey(keyCode)) {
3232            if (!mPendingCapsLockToggle) {
3233                // Start tracking meta state for combo.
3234                mInitialMetaState = mMetaState;
3235                mPendingCapsLockToggle = true;
3236            } else if (event.getAction() == KeyEvent.ACTION_UP) {
3237                int altOnMask = mMetaState & KeyEvent.META_ALT_MASK;
3238                int metaOnMask = mMetaState & KeyEvent.META_META_MASK;
3239
3240                // Check for Caps Lock toggle
3241                if ((metaOnMask != 0) && (altOnMask != 0)) {
3242                    // Check if nothing else is pressed
3243                    if (mInitialMetaState == (mMetaState ^ (altOnMask | metaOnMask))) {
3244                        // Handle Caps Lock Toggle
3245                        mInputManagerInternal.toggleCapsLock(event.getDeviceId());
3246                        actionTriggered = true;
3247                    }
3248                }
3249
3250                // Always stop tracking when key goes up.
3251                mPendingCapsLockToggle = false;
3252            }
3253        }
3254        // Store current meta state to be able to evaluate it later.
3255        mMetaState = metaState;
3256
3257        if (actionTriggered) {
3258            return -1;
3259        }
3260
3261        if (KeyEvent.isMetaKey(keyCode)) {
3262            if (down) {
3263                mPendingMetaAction = true;
3264            } else if (mPendingMetaAction) {
3265                launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, event.getDeviceId());
3266            }
3267            return -1;
3268        }
3269
3270        // Shortcuts are invoked through Search+key, so intercept those here
3271        // Any printing key that is chorded with Search should be consumed
3272        // even if no shortcut was invoked.  This prevents text from being
3273        // inadvertently inserted when using a keyboard that has built-in macro
3274        // shortcut keys (that emit Search+x) and some of them are not registered.
3275        if (mSearchKeyShortcutPending) {
3276            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3277            if (kcm.isPrintingKey(keyCode)) {
3278                mConsumeSearchKeyUp = true;
3279                mSearchKeyShortcutPending = false;
3280                if (down && repeatCount == 0 && !keyguardOn) {
3281                    Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
3282                    if (shortcutIntent != null) {
3283                        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3284                        try {
3285                            startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3286                        } catch (ActivityNotFoundException ex) {
3287                            Slog.w(TAG, "Dropping shortcut key combination because "
3288                                    + "the activity to which it is registered was not found: "
3289                                    + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
3290                        }
3291                    } else {
3292                        Slog.i(TAG, "Dropping unregistered shortcut key combination: "
3293                                + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
3294                    }
3295                }
3296                return -1;
3297            }
3298        }
3299
3300        // Invoke shortcuts using Meta.
3301        if (down && repeatCount == 0 && !keyguardOn
3302                && (metaState & KeyEvent.META_META_ON) != 0) {
3303            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3304            if (kcm.isPrintingKey(keyCode)) {
3305                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
3306                        metaState & ~(KeyEvent.META_META_ON
3307                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
3308                if (shortcutIntent != null) {
3309                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3310                    try {
3311                        startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3312                    } catch (ActivityNotFoundException ex) {
3313                        Slog.w(TAG, "Dropping shortcut key combination because "
3314                                + "the activity to which it is registered was not found: "
3315                                + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
3316                    }
3317                    return -1;
3318                }
3319            }
3320        }
3321
3322        // Handle application launch keys.
3323        if (down && repeatCount == 0 && !keyguardOn) {
3324            String category = sApplicationLaunchKeyCategories.get(keyCode);
3325            if (category != null) {
3326                Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
3327                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3328                try {
3329                    startActivityAsUser(intent, UserHandle.CURRENT);
3330                } catch (ActivityNotFoundException ex) {
3331                    Slog.w(TAG, "Dropping application launch key because "
3332                            + "the activity to which it is registered was not found: "
3333                            + "keyCode=" + keyCode + ", category=" + category, ex);
3334                }
3335                return -1;
3336            }
3337        }
3338
3339        // Display task switcher for ALT-TAB.
3340        if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
3341            if (mRecentAppsHeldModifiers == 0 && !keyguardOn && isUserSetupComplete()) {
3342                final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
3343                if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)) {
3344                    mRecentAppsHeldModifiers = shiftlessModifiers;
3345                    showRecentApps(true);
3346                    return -1;
3347                }
3348            }
3349        } else if (!down && mRecentAppsHeldModifiers != 0
3350                && (metaState & mRecentAppsHeldModifiers) == 0) {
3351            mRecentAppsHeldModifiers = 0;
3352            hideRecentApps(true, false);
3353        }
3354
3355        // Handle input method switching.
3356        if (down && repeatCount == 0
3357                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3358                        || (keyCode == KeyEvent.KEYCODE_SPACE
3359                                && (metaState & KeyEvent.META_META_MASK) != 0))) {
3360            final boolean forwardDirection = (metaState & KeyEvent.META_SHIFT_MASK) == 0;
3361            mWindowManagerFuncs.switchInputMethod(forwardDirection);
3362            return -1;
3363        }
3364        if (mLanguageSwitchKeyPressed && !down
3365                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3366                        || keyCode == KeyEvent.KEYCODE_SPACE)) {
3367            mLanguageSwitchKeyPressed = false;
3368            return -1;
3369        }
3370
3371        if (isValidGlobalKey(keyCode)
3372                && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
3373            return -1;
3374        }
3375
3376        if (down) {
3377            long shortcutCode = (long) keyCode;
3378            if (event.isCtrlPressed()) {
3379                shortcutCode |= ((long) KeyEvent.META_CTRL_ON) << Integer.SIZE;
3380            }
3381
3382            if (event.isAltPressed()) {
3383                shortcutCode |= ((long) KeyEvent.META_ALT_ON) << Integer.SIZE;
3384            }
3385
3386            if (event.isShiftPressed()) {
3387                shortcutCode |= ((long) KeyEvent.META_SHIFT_ON) << Integer.SIZE;
3388            }
3389
3390            if (event.isMetaPressed()) {
3391                shortcutCode |= ((long) KeyEvent.META_META_ON) << Integer.SIZE;
3392            }
3393
3394            IShortcutService shortcutService = mShortcutKeyServices.get(shortcutCode);
3395            if (shortcutService != null) {
3396                try {
3397                    shortcutService.notifyShortcutKeyPressed(shortcutCode);
3398                } catch (RemoteException e) {
3399                    mShortcutKeyServices.delete(shortcutCode);
3400                }
3401                return -1;
3402            }
3403        }
3404
3405        // Reserve all the META modifier combos for system behavior
3406        if ((metaState & KeyEvent.META_META_ON) != 0) {
3407            return -1;
3408        }
3409
3410        // Let the application handle the key.
3411        return 0;
3412    }
3413
3414    /** {@inheritDoc} */
3415    @Override
3416    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
3417        // Note: This method is only called if the initial down was unhandled.
3418        if (DEBUG_INPUT) {
3419            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
3420                    + ", flags=" + event.getFlags()
3421                    + ", keyCode=" + event.getKeyCode()
3422                    + ", scanCode=" + event.getScanCode()
3423                    + ", metaState=" + event.getMetaState()
3424                    + ", repeatCount=" + event.getRepeatCount()
3425                    + ", policyFlags=" + policyFlags);
3426        }
3427
3428        KeyEvent fallbackEvent = null;
3429        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3430            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3431            final int keyCode = event.getKeyCode();
3432            final int metaState = event.getMetaState();
3433            final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
3434                    && event.getRepeatCount() == 0;
3435
3436            // Check for fallback actions specified by the key character map.
3437            final FallbackAction fallbackAction;
3438            if (initialDown) {
3439                fallbackAction = kcm.getFallbackAction(keyCode, metaState);
3440            } else {
3441                fallbackAction = mFallbackActions.get(keyCode);
3442            }
3443
3444            if (fallbackAction != null) {
3445                if (DEBUG_INPUT) {
3446                    Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
3447                            + " metaState=" + Integer.toHexString(fallbackAction.metaState));
3448                }
3449
3450                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
3451                fallbackEvent = KeyEvent.obtain(
3452                        event.getDownTime(), event.getEventTime(),
3453                        event.getAction(), fallbackAction.keyCode,
3454                        event.getRepeatCount(), fallbackAction.metaState,
3455                        event.getDeviceId(), event.getScanCode(),
3456                        flags, event.getSource(), null);
3457
3458                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
3459                    fallbackEvent.recycle();
3460                    fallbackEvent = null;
3461                }
3462
3463                if (initialDown) {
3464                    mFallbackActions.put(keyCode, fallbackAction);
3465                } else if (event.getAction() == KeyEvent.ACTION_UP) {
3466                    mFallbackActions.remove(keyCode);
3467                    fallbackAction.recycle();
3468                }
3469            }
3470        }
3471
3472        if (DEBUG_INPUT) {
3473            if (fallbackEvent == null) {
3474                Slog.d(TAG, "No fallback.");
3475            } else {
3476                Slog.d(TAG, "Performing fallback: " + fallbackEvent);
3477            }
3478        }
3479        return fallbackEvent;
3480    }
3481
3482    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
3483        int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
3484        if ((actions & ACTION_PASS_TO_USER) != 0) {
3485            long delayMillis = interceptKeyBeforeDispatching(
3486                    win, fallbackEvent, policyFlags);
3487            if (delayMillis == 0) {
3488                return true;
3489            }
3490        }
3491        return false;
3492    }
3493
3494    public void registerShortcutKey(long shortcutCode, IShortcutService shortcutService)
3495            throws RemoteException {
3496        synchronized (mLock) {
3497            IShortcutService service = mShortcutKeyServices.get(shortcutCode);
3498            if (service != null && service.asBinder().pingBinder()) {
3499                throw new RemoteException("Key already exists.");
3500            }
3501
3502            mShortcutKeyServices.put(shortcutCode, shortcutService);
3503        }
3504    }
3505
3506    private void launchAssistLongPressAction() {
3507        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3508        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3509
3510        // launch the search activity
3511        Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
3512        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3513        try {
3514            // TODO: This only stops the factory-installed search manager.
3515            // Need to formalize an API to handle others
3516            SearchManager searchManager = getSearchManager();
3517            if (searchManager != null) {
3518                searchManager.stopSearch();
3519            }
3520            startActivityAsUser(intent, UserHandle.CURRENT);
3521        } catch (ActivityNotFoundException e) {
3522            Slog.w(TAG, "No activity to handle assist long press action.", e);
3523        }
3524    }
3525
3526    private void launchAssistAction(String hint, int deviceId) {
3527        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3528        if (!isUserSetupComplete()) {
3529            // Disable opening assist window during setup
3530            return;
3531        }
3532        Bundle args = null;
3533        if (deviceId > Integer.MIN_VALUE) {
3534            args = new Bundle();
3535            args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
3536        }
3537        if ((mContext.getResources().getConfiguration().uiMode
3538                & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
3539            // On TV, use legacy handling until assistants are implemented in the proper way.
3540            ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
3541                    .launchLegacyAssist(hint, UserHandle.myUserId(), args);
3542        } else {
3543            try {
3544                if (hint != null) {
3545                    if (args == null) {
3546                        args = new Bundle();
3547                    }
3548                    args.putBoolean(hint, true);
3549                }
3550                IStatusBarService statusbar = getStatusBarService();
3551                if (statusbar != null) {
3552                    statusbar.startAssist(args);
3553                }
3554            } catch (RemoteException e) {
3555                Slog.e(TAG, "RemoteException when starting assist", e);
3556                // re-acquire status bar service next time it is needed.
3557                mStatusBarService = null;
3558            }
3559        }
3560    }
3561
3562    private void startActivityAsUser(Intent intent, UserHandle handle) {
3563        if (isUserSetupComplete()) {
3564            mContext.startActivityAsUser(intent, handle);
3565        } else {
3566            Slog.i(TAG, "Not starting activity because user setup is in progress: " + intent);
3567        }
3568    }
3569
3570    private SearchManager getSearchManager() {
3571        if (mSearchManager == null) {
3572            mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
3573        }
3574        return mSearchManager;
3575    }
3576
3577    private void preloadRecentApps() {
3578        mPreloadedRecentApps = true;
3579        try {
3580            IStatusBarService statusbar = getStatusBarService();
3581            if (statusbar != null) {
3582                statusbar.preloadRecentApps();
3583            }
3584        } catch (RemoteException e) {
3585            Slog.e(TAG, "RemoteException when preloading recent apps", e);
3586            // re-acquire status bar service next time it is needed.
3587            mStatusBarService = null;
3588        }
3589    }
3590
3591    private void cancelPreloadRecentApps() {
3592        if (mPreloadedRecentApps) {
3593            mPreloadedRecentApps = false;
3594            try {
3595                IStatusBarService statusbar = getStatusBarService();
3596                if (statusbar != null) {
3597                    statusbar.cancelPreloadRecentApps();
3598                }
3599            } catch (RemoteException e) {
3600                Slog.e(TAG, "RemoteException when cancelling recent apps preload", e);
3601                // re-acquire status bar service next time it is needed.
3602                mStatusBarService = null;
3603            }
3604        }
3605    }
3606
3607    private void toggleRecentApps() {
3608        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3609        try {
3610            IStatusBarService statusbar = getStatusBarService();
3611            if (statusbar != null) {
3612                statusbar.toggleRecentApps();
3613            }
3614        } catch (RemoteException e) {
3615            Slog.e(TAG, "RemoteException when toggling recent apps", e);
3616            // re-acquire status bar service next time it is needed.
3617            mStatusBarService = null;
3618        }
3619    }
3620
3621    @Override
3622    public void showRecentApps() {
3623        mHandler.removeMessages(MSG_DISPATCH_SHOW_RECENTS);
3624        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_RECENTS);
3625    }
3626
3627    private void showRecentApps(boolean triggeredFromAltTab) {
3628        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3629        try {
3630            IStatusBarService statusbar = getStatusBarService();
3631            if (statusbar != null) {
3632                statusbar.showRecentApps(triggeredFromAltTab);
3633            }
3634        } catch (RemoteException e) {
3635            Slog.e(TAG, "RemoteException when showing recent apps", e);
3636            // re-acquire status bar service next time it is needed.
3637            mStatusBarService = null;
3638        }
3639    }
3640
3641    private void toggleKeyboardShortcutsMenu(int deviceId) {
3642        try {
3643            IStatusBarService statusbar = getStatusBarService();
3644            if (statusbar != null) {
3645                statusbar.toggleKeyboardShortcutsMenu(deviceId);
3646            }
3647        } catch (RemoteException e) {
3648            Slog.e(TAG, "RemoteException when showing keyboard shortcuts menu", e);
3649        }
3650    }
3651
3652    private void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHome) {
3653        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3654        try {
3655            IStatusBarService statusbar = getStatusBarService();
3656            if (statusbar != null) {
3657                statusbar.hideRecentApps(triggeredFromAltTab, triggeredFromHome);
3658            }
3659        } catch (RemoteException e) {
3660            Slog.e(TAG, "RemoteException when closing recent apps", e);
3661            // re-acquire status bar service next time it is needed.
3662            mStatusBarService = null;
3663        }
3664    }
3665
3666    void launchHomeFromHotKey() {
3667        launchHomeFromHotKey(true /* awakenFromDreams */, true /*respectKeyguard*/);
3668    }
3669
3670    /**
3671     * A home key -> launch home action was detected.  Take the appropriate action
3672     * given the situation with the keyguard.
3673     */
3674    void launchHomeFromHotKey(final boolean awakenFromDreams, final boolean respectKeyguard) {
3675        if (respectKeyguard) {
3676            if (isKeyguardShowingAndNotOccluded()) {
3677                // don't launch home if keyguard showing
3678                return;
3679            }
3680
3681            if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
3682                // when in keyguard restricted mode, must first verify unlock
3683                // before launching home
3684                mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
3685                    @Override
3686                    public void onKeyguardExitResult(boolean success) {
3687                        if (success) {
3688                            try {
3689                                ActivityManagerNative.getDefault().stopAppSwitches();
3690                            } catch (RemoteException e) {
3691                            }
3692                            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3693                            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3694                        }
3695                    }
3696                });
3697                return;
3698            }
3699        }
3700
3701        // no keyguard stuff to worry about, just launch home!
3702        try {
3703            ActivityManagerNative.getDefault().stopAppSwitches();
3704        } catch (RemoteException e) {
3705        }
3706        if (mRecentsVisible) {
3707            // Hide Recents and notify it to launch Home
3708            if (awakenFromDreams) {
3709                awakenDreams();
3710            }
3711            hideRecentApps(false, true);
3712        } else {
3713            // Otherwise, just launch Home
3714            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3715            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3716        }
3717    }
3718
3719    private final Runnable mClearHideNavigationFlag = new Runnable() {
3720        @Override
3721        public void run() {
3722            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3723                // Clear flags.
3724                mForceClearedSystemUiFlags &=
3725                        ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3726            }
3727            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3728        }
3729    };
3730
3731    /**
3732     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
3733     * to determine when the nav bar should be shown and prevent applications from
3734     * receiving those touches.
3735     */
3736    final class HideNavInputEventReceiver extends InputEventReceiver {
3737        public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
3738            super(inputChannel, looper);
3739        }
3740
3741        @Override
3742        public void onInputEvent(InputEvent event) {
3743            boolean handled = false;
3744            try {
3745                if (event instanceof MotionEvent
3746                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3747                    final MotionEvent motionEvent = (MotionEvent)event;
3748                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
3749                        // When the user taps down, we re-show the nav bar.
3750                        boolean changed = false;
3751                        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3752                            // Any user activity always causes us to show the
3753                            // navigation controls, if they had been hidden.
3754                            // We also clear the low profile and only content
3755                            // flags so that tapping on the screen will atomically
3756                            // restore all currently hidden screen decorations.
3757                            int newVal = mResettingSystemUiFlags |
3758                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3759                                    View.SYSTEM_UI_FLAG_LOW_PROFILE |
3760                                    View.SYSTEM_UI_FLAG_FULLSCREEN;
3761                            if (mResettingSystemUiFlags != newVal) {
3762                                mResettingSystemUiFlags = newVal;
3763                                changed = true;
3764                            }
3765                            // We don't allow the system's nav bar to be hidden
3766                            // again for 1 second, to prevent applications from
3767                            // spamming us and keeping it from being shown.
3768                            newVal = mForceClearedSystemUiFlags |
3769                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3770                            if (mForceClearedSystemUiFlags != newVal) {
3771                                mForceClearedSystemUiFlags = newVal;
3772                                changed = true;
3773                                mHandler.postDelayed(mClearHideNavigationFlag, 1000);
3774                            }
3775                        }
3776                        if (changed) {
3777                            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3778                        }
3779                    }
3780                }
3781            } finally {
3782                finishInputEvent(event, handled);
3783            }
3784        }
3785    }
3786    final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
3787            new InputEventReceiver.Factory() {
3788        @Override
3789        public InputEventReceiver createInputEventReceiver(
3790                InputChannel inputChannel, Looper looper) {
3791            return new HideNavInputEventReceiver(inputChannel, looper);
3792        }
3793    };
3794
3795    @Override
3796    public int adjustSystemUiVisibilityLw(int visibility) {
3797        mStatusBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3798        mNavigationBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3799        mRecentsVisible = (visibility & View.RECENT_APPS_VISIBLE) > 0;
3800
3801        // Reset any bits in mForceClearingStatusBarVisibility that
3802        // are now clear.
3803        mResettingSystemUiFlags &= visibility;
3804        // Clear any bits in the new visibility that are currently being
3805        // force cleared, before reporting it.
3806        return visibility & ~mResettingSystemUiFlags
3807                & ~mForceClearedSystemUiFlags;
3808    }
3809
3810    @Override
3811    public boolean getInsetHintLw(WindowManager.LayoutParams attrs, int displayRotation,
3812            Rect outContentInsets, Rect outStableInsets, Rect outOutsets) {
3813        final int fl = PolicyControl.getWindowFlags(null, attrs);
3814        final int sysuiVis = PolicyControl.getSystemUiVisibility(null, attrs);
3815        final int systemUiVisibility = (sysuiVis | attrs.subtreeSystemUiVisibility);
3816
3817        final boolean useOutsets = outOutsets != null && shouldUseOutsets(attrs, fl);
3818        if (useOutsets) {
3819            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
3820            if (outset > 0) {
3821                if (displayRotation == Surface.ROTATION_0) {
3822                    outOutsets.bottom += outset;
3823                } else if (displayRotation == Surface.ROTATION_90) {
3824                    outOutsets.right += outset;
3825                } else if (displayRotation == Surface.ROTATION_180) {
3826                    outOutsets.top += outset;
3827                } else if (displayRotation == Surface.ROTATION_270) {
3828                    outOutsets.left += outset;
3829                }
3830            }
3831        }
3832
3833        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3834                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3835            int availRight, availBottom;
3836            if (canHideNavigationBar() &&
3837                    (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
3838                availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3839                availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3840            } else {
3841                availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
3842                availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3843            }
3844            if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3845                if ((fl & FLAG_FULLSCREEN) != 0) {
3846                    outContentInsets.set(mStableFullscreenLeft, mStableFullscreenTop,
3847                            availRight - mStableFullscreenRight,
3848                            availBottom - mStableFullscreenBottom);
3849                } else {
3850                    outContentInsets.set(mStableLeft, mStableTop,
3851                            availRight - mStableRight, availBottom - mStableBottom);
3852                }
3853            } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
3854                outContentInsets.setEmpty();
3855            } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
3856                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
3857                outContentInsets.set(mCurLeft, mCurTop,
3858                        availRight - mCurRight, availBottom - mCurBottom);
3859            } else {
3860                outContentInsets.set(mCurLeft, mCurTop,
3861                        availRight - mCurRight, availBottom - mCurBottom);
3862            }
3863
3864            outStableInsets.set(mStableLeft, mStableTop,
3865                    availRight - mStableRight, availBottom - mStableBottom);
3866            return mForceShowSystemBars;
3867        }
3868        outContentInsets.setEmpty();
3869        outStableInsets.setEmpty();
3870        return mForceShowSystemBars;
3871    }
3872
3873    private boolean shouldUseOutsets(WindowManager.LayoutParams attrs, int fl) {
3874        return attrs.type == TYPE_WALLPAPER || (fl & (WindowManager.LayoutParams.FLAG_FULLSCREEN
3875                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN)) != 0;
3876    }
3877
3878    /** {@inheritDoc} */
3879    @Override
3880    public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
3881                              int displayRotation, int uiMode) {
3882        mDisplayRotation = displayRotation;
3883        final int overscanLeft, overscanTop, overscanRight, overscanBottom;
3884        if (isDefaultDisplay) {
3885            switch (displayRotation) {
3886                case Surface.ROTATION_90:
3887                    overscanLeft = mOverscanTop;
3888                    overscanTop = mOverscanRight;
3889                    overscanRight = mOverscanBottom;
3890                    overscanBottom = mOverscanLeft;
3891                    break;
3892                case Surface.ROTATION_180:
3893                    overscanLeft = mOverscanRight;
3894                    overscanTop = mOverscanBottom;
3895                    overscanRight = mOverscanLeft;
3896                    overscanBottom = mOverscanTop;
3897                    break;
3898                case Surface.ROTATION_270:
3899                    overscanLeft = mOverscanBottom;
3900                    overscanTop = mOverscanLeft;
3901                    overscanRight = mOverscanTop;
3902                    overscanBottom = mOverscanRight;
3903                    break;
3904                default:
3905                    overscanLeft = mOverscanLeft;
3906                    overscanTop = mOverscanTop;
3907                    overscanRight = mOverscanRight;
3908                    overscanBottom = mOverscanBottom;
3909                    break;
3910            }
3911        } else {
3912            overscanLeft = 0;
3913            overscanTop = 0;
3914            overscanRight = 0;
3915            overscanBottom = 0;
3916        }
3917        mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
3918        mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
3919        mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
3920        mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
3921        mSystemLeft = 0;
3922        mSystemTop = 0;
3923        mSystemRight = displayWidth;
3924        mSystemBottom = displayHeight;
3925        mUnrestrictedScreenLeft = overscanLeft;
3926        mUnrestrictedScreenTop = overscanTop;
3927        mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
3928        mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
3929        mRestrictedScreenLeft = mUnrestrictedScreenLeft;
3930        mRestrictedScreenTop = mUnrestrictedScreenTop;
3931        mRestrictedScreenWidth = mSystemGestures.screenWidth = mUnrestrictedScreenWidth;
3932        mRestrictedScreenHeight = mSystemGestures.screenHeight = mUnrestrictedScreenHeight;
3933        mDockLeft = mContentLeft = mVoiceContentLeft = mStableLeft = mStableFullscreenLeft
3934                = mCurLeft = mUnrestrictedScreenLeft;
3935        mDockTop = mContentTop = mVoiceContentTop = mStableTop = mStableFullscreenTop
3936                = mCurTop = mUnrestrictedScreenTop;
3937        mDockRight = mContentRight = mVoiceContentRight = mStableRight = mStableFullscreenRight
3938                = mCurRight = displayWidth - overscanRight;
3939        mDockBottom = mContentBottom = mVoiceContentBottom = mStableBottom = mStableFullscreenBottom
3940                = mCurBottom = displayHeight - overscanBottom;
3941        mDockLayer = 0x10000000;
3942        mStatusBarLayer = -1;
3943
3944        // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
3945        final Rect pf = mTmpParentFrame;
3946        final Rect df = mTmpDisplayFrame;
3947        final Rect of = mTmpOverscanFrame;
3948        final Rect vf = mTmpVisibleFrame;
3949        final Rect dcf = mTmpDecorFrame;
3950        pf.left = df.left = of.left = vf.left = mDockLeft;
3951        pf.top = df.top = of.top = vf.top = mDockTop;
3952        pf.right = df.right = of.right = vf.right = mDockRight;
3953        pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
3954        dcf.setEmpty();  // Decor frame N/A for system bars.
3955
3956        if (isDefaultDisplay) {
3957            // For purposes of putting out fake window up to steal focus, we will
3958            // drive nav being hidden only by whether it is requested.
3959            final int sysui = mLastSystemUiFlags;
3960            boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
3961            boolean navTranslucent = (sysui
3962                    & (View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT)) != 0;
3963            boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
3964            boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
3965            boolean navAllowedHidden = immersive || immersiveSticky;
3966            navTranslucent &= !immersiveSticky;  // transient trumps translucent
3967            boolean isKeyguardShowing = isStatusBarKeyguard() && !mHideLockScreen;
3968            if (!isKeyguardShowing) {
3969                navTranslucent &= areTranslucentBarsAllowed();
3970            }
3971
3972            // When the navigation bar isn't visible, we put up a fake
3973            // input window to catch all touch events.  This way we can
3974            // detect when the user presses anywhere to bring back the nav
3975            // bar and ensure the application doesn't see the event.
3976            if (navVisible || navAllowedHidden) {
3977                if (mInputConsumer != null) {
3978                    mInputConsumer.dismiss();
3979                    mInputConsumer = null;
3980                }
3981            } else if (mInputConsumer == null) {
3982                mInputConsumer = mWindowManagerFuncs.addInputConsumer(mHandler.getLooper(),
3983                        mHideNavInputEventReceiverFactory);
3984            }
3985
3986            // For purposes of positioning and showing the nav bar, if we have
3987            // decided that it can't be hidden (because of the screen aspect ratio),
3988            // then take that into account.
3989            navVisible |= !canHideNavigationBar();
3990
3991            boolean updateSysUiVisibility = layoutNavigationBar(displayWidth, displayHeight,
3992                    displayRotation, uiMode, overscanRight, overscanBottom, dcf, navVisible, navTranslucent,
3993                    navAllowedHidden);
3994            if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
3995                    mDockLeft, mDockTop, mDockRight, mDockBottom));
3996            updateSysUiVisibility |= layoutStatusBar(pf, df, of, vf, dcf, sysui, isKeyguardShowing);
3997            if (updateSysUiVisibility) {
3998                updateSystemUiVisibilityLw();
3999            }
4000        }
4001    }
4002
4003    private boolean layoutStatusBar(Rect pf, Rect df, Rect of, Rect vf, Rect dcf, int sysui,
4004            boolean isKeyguardShowing) {
4005        // decide where the status bar goes ahead of time
4006        if (mStatusBar != null) {
4007            // apply any navigation bar insets
4008            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4009            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4010            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
4011            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
4012                    + mUnrestrictedScreenTop;
4013            vf.left = mStableLeft;
4014            vf.top = mStableTop;
4015            vf.right = mStableRight;
4016            vf.bottom = mStableBottom;
4017
4018            mStatusBarLayer = mStatusBar.getSurfaceLayer();
4019
4020            // Let the status bar determine its size.
4021            mStatusBar.computeFrameLw(pf /* parentFrame */, df /* displayFrame */,
4022                    vf /* overlayFrame */, vf /* contentFrame */, vf /* visibleFrame */,
4023                    dcf /* decorFrame */, vf /* stableFrame */, vf /* outsetFrame */);
4024
4025            // For layout, the status bar is always at the top with our fixed height.
4026            mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
4027
4028            boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
4029            boolean statusBarTranslucent = (sysui
4030                    & (View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT)) != 0;
4031            if (!isKeyguardShowing) {
4032                statusBarTranslucent &= areTranslucentBarsAllowed();
4033            }
4034
4035            // If the status bar is hidden, we don't want to cause
4036            // windows behind it to scroll.
4037            if (mStatusBar.isVisibleLw() && !statusBarTransient) {
4038                // Status bar may go away, so the screen area it occupies
4039                // is available to apps but just covering them when the
4040                // status bar is visible.
4041                mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
4042
4043                mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4044                mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4045                mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4046                mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4047
4048                if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
4049                        String.format(
4050                                "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
4051                                mDockLeft, mDockTop, mDockRight, mDockBottom,
4052                                mContentLeft, mContentTop, mContentRight, mContentBottom,
4053                                mCurLeft, mCurTop, mCurRight, mCurBottom));
4054            }
4055            if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
4056                    && !statusBarTransient && !statusBarTranslucent
4057                    && !mStatusBarController.wasRecentlyTranslucent()) {
4058                // If the opaque status bar is currently requested to be visible,
4059                // and not in the process of animating on or off, then
4060                // we can tell the app that it is covered by it.
4061                mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
4062            }
4063            if (mStatusBarController.checkHiddenLw()) {
4064                return true;
4065            }
4066        }
4067        return false;
4068    }
4069
4070    private boolean layoutNavigationBar(int displayWidth, int displayHeight, int displayRotation,
4071            int uiMode, int overscanRight, int overscanBottom, Rect dcf, boolean navVisible,
4072            boolean navTranslucent, boolean navAllowedHidden) {
4073        if (mNavigationBar != null) {
4074            boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
4075            // Force the navigation bar to its appropriate place and
4076            // size.  We need to do this directly, instead of relying on
4077            // it to bubble up from the nav bar, because this needs to
4078            // change atomically with screen rotations.
4079            mNavigationBarOnBottom = isNavigationBarOnBottom(displayWidth, displayHeight);
4080            if (mNavigationBarOnBottom) {
4081                // It's a system nav bar or a portrait screen; nav bar goes on bottom.
4082                int top = displayHeight - overscanBottom
4083                        - getNavigationBarHeight(displayRotation, uiMode);
4084                mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
4085                mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
4086                if (transientNavBarShowing) {
4087                    mNavigationBarController.setBarShowingLw(true);
4088                } else if (navVisible) {
4089                    mNavigationBarController.setBarShowingLw(true);
4090                    mDockBottom = mTmpNavigationFrame.top;
4091                    mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
4092                    mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
4093                } else {
4094                    // We currently want to hide the navigation UI.
4095                    mNavigationBarController.setBarShowingLw(false);
4096                }
4097                if (navVisible && !navTranslucent && !navAllowedHidden
4098                        && !mNavigationBar.isAnimatingLw()
4099                        && !mNavigationBarController.wasRecentlyTranslucent()) {
4100                    // If the opaque nav bar is currently requested to be visible,
4101                    // and not in the process of animating on or off, then
4102                    // we can tell the app that it is covered by it.
4103                    mSystemBottom = mTmpNavigationFrame.top;
4104                }
4105            } else {
4106                // Landscape screen; nav bar goes to the right.
4107                int left = displayWidth - overscanRight
4108                        - getNavigationBarWidth(displayRotation, uiMode);
4109                mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
4110                mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
4111                if (transientNavBarShowing) {
4112                    mNavigationBarController.setBarShowingLw(true);
4113                } else if (navVisible) {
4114                    mNavigationBarController.setBarShowingLw(true);
4115                    mDockRight = mTmpNavigationFrame.left;
4116                    mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
4117                    mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
4118                } else {
4119                    // We currently want to hide the navigation UI.
4120                    mNavigationBarController.setBarShowingLw(false);
4121                }
4122                if (navVisible && !navTranslucent && !navAllowedHidden
4123                        && !mNavigationBar.isAnimatingLw()
4124                        && !mNavigationBarController.wasRecentlyTranslucent()) {
4125                    // If the nav bar is currently requested to be visible,
4126                    // and not in the process of animating on or off, then
4127                    // we can tell the app that it is covered by it.
4128                    mSystemRight = mTmpNavigationFrame.left;
4129                }
4130            }
4131            // Make sure the content and current rectangles are updated to
4132            // account for the restrictions from the navigation bar.
4133            mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4134            mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4135            mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4136            mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4137            mStatusBarLayer = mNavigationBar.getSurfaceLayer();
4138            // And compute the final frame.
4139            mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
4140                    mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf,
4141                    mTmpNavigationFrame, mTmpNavigationFrame);
4142            if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
4143            if (mNavigationBarController.checkHiddenLw()) {
4144                return true;
4145            }
4146        }
4147        return false;
4148    }
4149
4150    private boolean isNavigationBarOnBottom(int displayWidth, int displayHeight) {
4151        return !mNavigationBarCanMove || displayWidth < displayHeight;
4152    }
4153
4154    /** {@inheritDoc} */
4155    @Override
4156    public int getSystemDecorLayerLw() {
4157        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
4158            return mStatusBar.getSurfaceLayer();
4159        }
4160
4161        if (mNavigationBar != null && mNavigationBar.isVisibleLw()) {
4162            return mNavigationBar.getSurfaceLayer();
4163        }
4164
4165        return 0;
4166    }
4167
4168    @Override
4169    public void getContentRectLw(Rect r) {
4170        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
4171    }
4172
4173    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
4174            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
4175        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
4176            // Here's a special case: if this attached window is a panel that is
4177            // above the dock window, and the window it is attached to is below
4178            // the dock window, then the frames we computed for the window it is
4179            // attached to can not be used because the dock is effectively part
4180            // of the underlying window and the attached window is floating on top
4181            // of the whole thing.  So, we ignore the attached window and explicitly
4182            // compute the frames that would be appropriate without the dock.
4183            df.left = of.left = cf.left = vf.left = mDockLeft;
4184            df.top = of.top = cf.top = vf.top = mDockTop;
4185            df.right = of.right = cf.right = vf.right = mDockRight;
4186            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
4187        } else {
4188            // The effective display frame of the attached window depends on
4189            // whether it is taking care of insetting its content.  If not,
4190            // we need to use the parent's content frame so that the entire
4191            // window is positioned within that content.  Otherwise we can use
4192            // the overscan frame and let the attached window take care of
4193            // positioning its content appropriately.
4194            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4195                // Set the content frame of the attached window to the parent's decor frame
4196                // (same as content frame when IME isn't present) if specifically requested by
4197                // setting {@link WindowManager.LayoutParams#FLAG_LAYOUT_ATTACHED_IN_DECOR} flag.
4198                // Otherwise, use the overscan frame.
4199                cf.set((fl & FLAG_LAYOUT_ATTACHED_IN_DECOR) != 0
4200                        ? attached.getContentFrameLw() : attached.getOverscanFrameLw());
4201            } else {
4202                // If the window is resizing, then we want to base the content
4203                // frame on our attached content frame to resize...  however,
4204                // things can be tricky if the attached window is NOT in resize
4205                // mode, in which case its content frame will be larger.
4206                // Ungh.  So to deal with that, make sure the content frame
4207                // we end up using is not covering the IM dock.
4208                cf.set(attached.getContentFrameLw());
4209                if (attached.isVoiceInteraction()) {
4210                    if (cf.left < mVoiceContentLeft) cf.left = mVoiceContentLeft;
4211                    if (cf.top < mVoiceContentTop) cf.top = mVoiceContentTop;
4212                    if (cf.right > mVoiceContentRight) cf.right = mVoiceContentRight;
4213                    if (cf.bottom > mVoiceContentBottom) cf.bottom = mVoiceContentBottom;
4214                } else if (attached.getSurfaceLayer() < mDockLayer) {
4215                    if (cf.left < mContentLeft) cf.left = mContentLeft;
4216                    if (cf.top < mContentTop) cf.top = mContentTop;
4217                    if (cf.right > mContentRight) cf.right = mContentRight;
4218                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
4219                }
4220            }
4221            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
4222            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
4223            vf.set(attached.getVisibleFrameLw());
4224        }
4225        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
4226        // window should be positioned relative to its parent or the entire
4227        // screen.
4228        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
4229                ? attached.getFrameLw() : df);
4230    }
4231
4232    private void applyStableConstraints(int sysui, int fl, Rect r) {
4233        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
4234            // If app is requesting a stable layout, don't let the
4235            // content insets go below the stable values.
4236            if ((fl & FLAG_FULLSCREEN) != 0) {
4237                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
4238                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
4239                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
4240                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
4241            } else {
4242                if (r.left < mStableLeft) r.left = mStableLeft;
4243                if (r.top < mStableTop) r.top = mStableTop;
4244                if (r.right > mStableRight) r.right = mStableRight;
4245                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
4246            }
4247        }
4248    }
4249
4250    private boolean canReceiveInput(WindowState win) {
4251        boolean notFocusable =
4252                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0;
4253        boolean altFocusableIm =
4254                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0;
4255        boolean notFocusableForIm = notFocusable ^ altFocusableIm;
4256        return !notFocusableForIm;
4257    }
4258
4259    /** {@inheritDoc} */
4260    @Override
4261    public void layoutWindowLw(WindowState win, WindowState attached) {
4262        // We've already done the navigation bar and status bar. If the status bar can receive
4263        // input, we need to layout it again to accomodate for the IME window.
4264        if ((win == mStatusBar && !canReceiveInput(win)) || win == mNavigationBar) {
4265            return;
4266        }
4267        final WindowManager.LayoutParams attrs = win.getAttrs();
4268        final boolean isDefaultDisplay = win.isDefaultDisplay();
4269        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
4270                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
4271        if (needsToOffsetInputMethodTarget) {
4272            if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
4273            offsetInputMethodWindowLw(mLastInputMethodWindow);
4274        }
4275
4276        final int fl = PolicyControl.getWindowFlags(win, attrs);
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                        && !mForceWindowDrawsStatusBarBackground) {
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 int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
7247        final boolean dockedStackVisible = mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID);
7248        final boolean freeformStackVisible =
7249                mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID);
7250        final boolean resizing = mWindowManagerInternal.isDockedDividerResizing();
7251
7252        // We need to force system bars when the docked stack is visible, when the freeform stack
7253        // is visible but also when we are resizing for the transitions when docked stack
7254        // visibility changes.
7255        mForceShowSystemBars = dockedStackVisible || freeformStackVisible || resizing;
7256        final boolean forceOpaqueStatusBar = mForceShowSystemBars && !mForceStatusBarFromKeyguard;
7257
7258        // apply translucent bar vis flags
7259        WindowState transWin = isStatusBarKeyguard() && !mHideLockScreen
7260                ? mStatusBar
7261                : mTopFullscreenOpaqueWindowState;
7262        vis = mStatusBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
7263        vis = mNavigationBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
7264
7265        // prevent status bar interaction from clearing certain flags
7266        int type = win.getAttrs().type;
7267        boolean statusBarHasFocus = type == TYPE_STATUS_BAR;
7268        if (statusBarHasFocus && !isStatusBarKeyguard()) {
7269            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
7270                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
7271                    | View.SYSTEM_UI_FLAG_IMMERSIVE
7272                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
7273                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7274            if (mHideLockScreen) {
7275                flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
7276            }
7277            vis = (vis & ~flags) | (oldVis & flags);
7278        }
7279
7280        if ((!areTranslucentBarsAllowed() && transWin != mStatusBar)
7281                || forceOpaqueStatusBar) {
7282            vis &= ~(View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT);
7283        }
7284
7285        vis = configureNavBarOpacity(vis, dockedStackVisible, freeformStackVisible, resizing);
7286
7287        if (mForceWindowDrawsStatusBarBackground) {
7288            vis |= View.STATUS_BAR_TRANSPARENT;
7289            vis &= ~View.STATUS_BAR_TRANSLUCENT;
7290        }
7291
7292        // update status bar
7293        boolean immersiveSticky =
7294                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7295        final boolean hideStatusBarWM =
7296                mTopFullscreenOpaqueWindowState != null
7297                && (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
7298                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
7299        final boolean hideStatusBarSysui =
7300                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
7301        final boolean hideNavBarSysui =
7302                (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
7303
7304        final boolean transientStatusBarAllowed = mStatusBar != null
7305                && (statusBarHasFocus || (!mForceShowSystemBars
7306                        && (hideStatusBarWM || (hideStatusBarSysui && immersiveSticky))));
7307
7308        final boolean transientNavBarAllowed = mNavigationBar != null
7309                && !mForceShowSystemBars && hideNavBarSysui && immersiveSticky;
7310
7311        final long now = SystemClock.uptimeMillis();
7312        final boolean pendingPanic = mPendingPanicGestureUptime != 0
7313                && now - mPendingPanicGestureUptime <= PANIC_GESTURE_EXPIRATION;
7314        if (pendingPanic && hideNavBarSysui && !isStatusBarKeyguard() && mKeyguardDrawComplete) {
7315            // The user performed the panic gesture recently, we're about to hide the bars,
7316            // we're no longer on the Keyguard and the screen is ready. We can now request the bars.
7317            mPendingPanicGestureUptime = 0;
7318            mStatusBarController.showTransient();
7319            mNavigationBarController.showTransient();
7320        }
7321
7322        final boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
7323                && !transientStatusBarAllowed && hideStatusBarSysui;
7324        final boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
7325                && !transientNavBarAllowed;
7326        if (denyTransientStatus || denyTransientNav || mForceShowSystemBars) {
7327            // clear the clearable flags instead
7328            clearClearableFlagsLw();
7329            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
7330        }
7331
7332        final boolean immersive = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
7333        immersiveSticky = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7334        final boolean navAllowedHidden = immersive || immersiveSticky;
7335
7336        if (hideNavBarSysui && !navAllowedHidden && windowTypeToLayerLw(win.getBaseType())
7337                > windowTypeToLayerLw(TYPE_INPUT_CONSUMER)) {
7338            // We can't hide the navbar from this window otherwise the input consumer would not get
7339            // the input events.
7340            vis = (vis & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
7341        }
7342
7343        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
7344
7345        // update navigation bar
7346        boolean oldImmersiveMode = isImmersiveMode(oldVis);
7347        boolean newImmersiveMode = isImmersiveMode(vis);
7348        if (win != null && oldImmersiveMode != newImmersiveMode) {
7349            final String pkg = win.getOwningPackage();
7350            mImmersiveModeConfirmation.immersiveModeChanged(pkg, newImmersiveMode,
7351                    isUserSetupComplete());
7352        }
7353
7354        vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
7355
7356        return vis;
7357    }
7358
7359    /**
7360     * @return the current visibility flags with the nav-bar opacity related flags toggled based
7361     *         on the nav bar opacity rules chosen by {@link #mNavBarOpacityMode}.
7362     */
7363    private int configureNavBarOpacity(int visibility, boolean dockedStackVisible,
7364            boolean freeformStackVisible, boolean isDockedDividerResizing) {
7365        if (mNavBarOpacityMode == NAV_BAR_OPAQUE_WHEN_FREEFORM_OR_DOCKED) {
7366            if (dockedStackVisible || freeformStackVisible || isDockedDividerResizing) {
7367                visibility = setNavBarOpaqueFlag(visibility);
7368            }
7369        } else if (mNavBarOpacityMode == NAV_BAR_TRANSLUCENT_WHEN_FREEFORM_OPAQUE_OTHERWISE) {
7370            if (isDockedDividerResizing) {
7371                visibility = setNavBarOpaqueFlag(visibility);
7372            } else if (freeformStackVisible) {
7373                visibility = setNavBarTranslucentFlag(visibility);
7374            } else {
7375                visibility = setNavBarOpaqueFlag(visibility);
7376            }
7377        }
7378
7379        if (!areTranslucentBarsAllowed()) {
7380            visibility &= ~View.NAVIGATION_BAR_TRANSLUCENT;
7381        }
7382        return visibility;
7383    }
7384
7385    private int setNavBarOpaqueFlag(int visibility) {
7386        return visibility &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT);
7387    }
7388
7389    private int setNavBarTranslucentFlag(int visibility) {
7390        visibility &= ~View.NAVIGATION_BAR_TRANSPARENT;
7391        return visibility |= View.NAVIGATION_BAR_TRANSLUCENT;
7392    }
7393
7394    private void clearClearableFlagsLw() {
7395        int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
7396        if (newVal != mResettingSystemUiFlags) {
7397            mResettingSystemUiFlags = newVal;
7398            mWindowManagerFuncs.reevaluateStatusBarVisibility();
7399        }
7400    }
7401
7402    private boolean isImmersiveMode(int vis) {
7403        final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
7404        return mNavigationBar != null
7405                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
7406                && (vis & flags) != 0
7407                && canHideNavigationBar();
7408    }
7409
7410    /**
7411     * @return whether the navigation or status bar can be made translucent
7412     *
7413     * This should return true unless touch exploration is not enabled or
7414     * R.boolean.config_enableTranslucentDecor is false.
7415     */
7416    private boolean areTranslucentBarsAllowed() {
7417        return mTranslucentDecorEnabled;
7418    }
7419
7420    // Use this instead of checking config_showNavigationBar so that it can be consistently
7421    // overridden by qemu.hw.mainkeys in the emulator.
7422    @Override
7423    public boolean hasNavigationBar() {
7424        return mHasNavigationBar;
7425    }
7426
7427    @Override
7428    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
7429        mLastInputMethodWindow = ime;
7430        mLastInputMethodTargetWindow = target;
7431    }
7432
7433    @Override
7434    public int getInputMethodWindowVisibleHeightLw() {
7435        return mDockBottom - mCurBottom;
7436    }
7437
7438    @Override
7439    public void setCurrentUserLw(int newUserId) {
7440        mCurrentUserId = newUserId;
7441        if (mKeyguardDelegate != null) {
7442            mKeyguardDelegate.setCurrentUser(newUserId);
7443        }
7444        if (mStatusBarService != null) {
7445            try {
7446                mStatusBarService.setCurrentUser(newUserId);
7447            } catch (RemoteException e) {
7448                // oh well
7449            }
7450        }
7451        setLastInputMethodWindowLw(null, null);
7452    }
7453
7454    @Override
7455    public boolean canMagnifyWindow(int windowType) {
7456        switch (windowType) {
7457            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
7458            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
7459            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
7460            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
7461                return false;
7462            }
7463        }
7464        return true;
7465    }
7466
7467    @Override
7468    public boolean isTopLevelWindow(int windowType) {
7469        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
7470                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
7471            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
7472        }
7473        return true;
7474    }
7475
7476    @Override
7477    public void dump(String prefix, PrintWriter pw, String[] args) {
7478        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
7479                pw.print(" mSystemReady="); pw.print(mSystemReady);
7480                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
7481        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
7482                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
7483                pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
7484                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
7485        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
7486                || mForceClearedSystemUiFlags != 0) {
7487            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
7488                    pw.print(Integer.toHexString(mLastSystemUiFlags));
7489                    pw.print(" mResettingSystemUiFlags=0x");
7490                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
7491                    pw.print(" mForceClearedSystemUiFlags=0x");
7492                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
7493        }
7494        if (mLastFocusNeedsMenu) {
7495            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
7496                    pw.println(mLastFocusNeedsMenu);
7497        }
7498        pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
7499                pw.println(mWakeGestureEnabledSetting);
7500
7501        pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
7502        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
7503                pw.print(" mDockMode="); pw.print(mDockMode);
7504                pw.print(" mEnableCarDockHomeCapture="); pw.print(mEnableCarDockHomeCapture);
7505                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
7506                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
7507        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
7508                pw.print(" mUserRotation="); pw.print(mUserRotation);
7509                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
7510        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
7511        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
7512                pw.print(mCarDockEnablesAccelerometer);
7513                pw.print(" mDeskDockEnablesAccelerometer=");
7514                pw.println(mDeskDockEnablesAccelerometer);
7515        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
7516                pw.print(mLidKeyboardAccessibility);
7517                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
7518                pw.print(" mLidControlsScreenLock="); pw.println(mLidControlsScreenLock);
7519                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
7520        pw.print(prefix);
7521                pw.print(" mLongPressOnBackBehavior="); pw.println(mLongPressOnBackBehavior);
7522        pw.print(prefix);
7523                pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
7524                pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
7525        pw.print(prefix);
7526                pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
7527                pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
7528        pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
7529        pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
7530        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
7531                pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
7532        pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
7533                pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
7534        pw.print(prefix); pw.print("mOrientationSensorEnabled=");
7535                pw.println(mOrientationSensorEnabled);
7536        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
7537                pw.print(","); pw.print(mOverscanScreenTop);
7538                pw.print(") "); pw.print(mOverscanScreenWidth);
7539                pw.print("x"); pw.println(mOverscanScreenHeight);
7540        if (mOverscanLeft != 0 || mOverscanTop != 0
7541                || mOverscanRight != 0 || mOverscanBottom != 0) {
7542            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
7543                    pw.print(" top="); pw.print(mOverscanTop);
7544                    pw.print(" right="); pw.print(mOverscanRight);
7545                    pw.print(" bottom="); pw.println(mOverscanBottom);
7546        }
7547        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
7548                pw.print(mRestrictedOverscanScreenLeft);
7549                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
7550                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
7551                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
7552        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
7553                pw.print(","); pw.print(mUnrestrictedScreenTop);
7554                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
7555                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
7556        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
7557                pw.print(","); pw.print(mRestrictedScreenTop);
7558                pw.print(") "); pw.print(mRestrictedScreenWidth);
7559                pw.print("x"); pw.println(mRestrictedScreenHeight);
7560        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
7561                pw.print(","); pw.print(mStableFullscreenTop);
7562                pw.print(")-("); pw.print(mStableFullscreenRight);
7563                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
7564        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
7565                pw.print(","); pw.print(mStableTop);
7566                pw.print(")-("); pw.print(mStableRight);
7567                pw.print(","); pw.print(mStableBottom); pw.println(")");
7568        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
7569                pw.print(","); pw.print(mSystemTop);
7570                pw.print(")-("); pw.print(mSystemRight);
7571                pw.print(","); pw.print(mSystemBottom); pw.println(")");
7572        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
7573                pw.print(","); pw.print(mCurTop);
7574                pw.print(")-("); pw.print(mCurRight);
7575                pw.print(","); pw.print(mCurBottom); pw.println(")");
7576        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
7577                pw.print(","); pw.print(mContentTop);
7578                pw.print(")-("); pw.print(mContentRight);
7579                pw.print(","); pw.print(mContentBottom); pw.println(")");
7580        pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
7581                pw.print(","); pw.print(mVoiceContentTop);
7582                pw.print(")-("); pw.print(mVoiceContentRight);
7583                pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
7584        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
7585                pw.print(","); pw.print(mDockTop);
7586                pw.print(")-("); pw.print(mDockRight);
7587                pw.print(","); pw.print(mDockBottom); pw.println(")");
7588        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
7589                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
7590        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
7591                pw.print(" mShowingDream="); pw.print(mShowingDream);
7592                pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
7593                pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
7594        if (mLastInputMethodWindow != null) {
7595            pw.print(prefix); pw.print("mLastInputMethodWindow=");
7596                    pw.println(mLastInputMethodWindow);
7597        }
7598        if (mLastInputMethodTargetWindow != null) {
7599            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
7600                    pw.println(mLastInputMethodTargetWindow);
7601        }
7602        if (mStatusBar != null) {
7603            pw.print(prefix); pw.print("mStatusBar=");
7604                    pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
7605                    pw.println(isStatusBarKeyguard());
7606        }
7607        if (mNavigationBar != null) {
7608            pw.print(prefix); pw.print("mNavigationBar=");
7609                    pw.println(mNavigationBar);
7610        }
7611        if (mFocusedWindow != null) {
7612            pw.print(prefix); pw.print("mFocusedWindow=");
7613                    pw.println(mFocusedWindow);
7614        }
7615        if (mFocusedApp != null) {
7616            pw.print(prefix); pw.print("mFocusedApp=");
7617                    pw.println(mFocusedApp);
7618        }
7619        if (mWinDismissingKeyguard != null) {
7620            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
7621                    pw.println(mWinDismissingKeyguard);
7622        }
7623        if (mTopFullscreenOpaqueWindowState != null) {
7624            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
7625                    pw.println(mTopFullscreenOpaqueWindowState);
7626        }
7627        if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
7628            pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
7629                    pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
7630        }
7631        if (mForcingShowNavBar) {
7632            pw.print(prefix); pw.print("mForcingShowNavBar=");
7633                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
7634                    pw.println(mForcingShowNavBarLayer);
7635        }
7636        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
7637                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
7638        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
7639                pw.print(" mForceStatusBarFromKeyguard=");
7640                pw.println(mForceStatusBarFromKeyguard);
7641        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
7642                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
7643                pw.print(" mHomePressed="); pw.println(mHomePressed);
7644        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
7645                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
7646                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
7647        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
7648                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
7649                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
7650        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
7651                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
7652        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
7653                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
7654        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
7655                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
7656        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
7657
7658        mGlobalKeyManager.dump(prefix, pw);
7659        mStatusBarController.dump(pw, prefix);
7660        mNavigationBarController.dump(pw, prefix);
7661        PolicyControl.dump(prefix, pw);
7662
7663        if (mWakeGestureListener != null) {
7664            mWakeGestureListener.dump(pw, prefix);
7665        }
7666        if (mOrientationListener != null) {
7667            mOrientationListener.dump(pw, prefix);
7668        }
7669        if (mBurnInProtectionHelper != null) {
7670            mBurnInProtectionHelper.dump(prefix, pw);
7671        }
7672        if (mKeyguardDelegate != null) {
7673            mKeyguardDelegate.dump(prefix, pw);
7674        }
7675    }
7676}
7677