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