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