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