PhoneWindowManager.java revision 347bb9a3cf53595b8beed17574cec9c0072aa819
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        // SystemUI (status bar) layout policy
1829        int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / density;
1830        int longSizeDp = longSize * DisplayMetrics.DENSITY_DEFAULT / density;
1831
1832        // Allow the navigation bar to move on non-square small devices (phones).
1833        mNavigationBarCanMove = width != height && shortSizeDp < 600;
1834
1835        mHasNavigationBar = res.getBoolean(com.android.internal.R.bool.config_showNavigationBar);
1836
1837        // Allow a system property to override this. Used by the emulator.
1838        // See also hasNavigationBar().
1839        String navBarOverride = SystemProperties.get("qemu.hw.mainkeys");
1840        if ("1".equals(navBarOverride)) {
1841            mHasNavigationBar = false;
1842        } else if ("0".equals(navBarOverride)) {
1843            mHasNavigationBar = true;
1844        }
1845
1846        // For demo purposes, allow the rotation of the HDMI display to be controlled.
1847        // By default, HDMI locks rotation to landscape.
1848        if ("portrait".equals(SystemProperties.get("persist.demo.hdmirotation"))) {
1849            mDemoHdmiRotation = mPortraitRotation;
1850        } else {
1851            mDemoHdmiRotation = mLandscapeRotation;
1852        }
1853        mDemoHdmiRotationLock = SystemProperties.getBoolean("persist.demo.hdmirotationlock", false);
1854
1855        // For demo purposes, allow the rotation of the remote display to be controlled.
1856        // By default, remote display locks rotation to landscape.
1857        if ("portrait".equals(SystemProperties.get("persist.demo.remoterotation"))) {
1858            mDemoRotation = mPortraitRotation;
1859        } else {
1860            mDemoRotation = mLandscapeRotation;
1861        }
1862        mDemoRotationLock = SystemProperties.getBoolean(
1863                "persist.demo.rotationlock", false);
1864
1865        // Only force the default orientation if the screen is xlarge, at least 960dp x 720dp, per
1866        // http://developer.android.com/guide/practices/screens_support.html#range
1867        mForceDefaultOrientation = longSizeDp >= 960 && shortSizeDp >= 720 &&
1868                res.getBoolean(com.android.internal.R.bool.config_forceDefaultOrientation) &&
1869                // For debug purposes the next line turns this feature off with:
1870                // $ adb shell setprop config.override_forced_orient true
1871                // $ adb shell wm size reset
1872                !"true".equals(SystemProperties.get("config.override_forced_orient"));
1873    }
1874
1875    /**
1876     * @return whether the navigation bar can be hidden, e.g. the device has a
1877     *         navigation bar and touch exploration is not enabled
1878     */
1879    private boolean canHideNavigationBar() {
1880        return mHasNavigationBar;
1881    }
1882
1883    @Override
1884    public boolean isDefaultOrientationForced() {
1885        return mForceDefaultOrientation;
1886    }
1887
1888    @Override
1889    public void setDisplayOverscan(Display display, int left, int top, int right, int bottom) {
1890        if (display.getDisplayId() == Display.DEFAULT_DISPLAY) {
1891            mOverscanLeft = left;
1892            mOverscanTop = top;
1893            mOverscanRight = right;
1894            mOverscanBottom = bottom;
1895        }
1896    }
1897
1898    public void updateSettings() {
1899        ContentResolver resolver = mContext.getContentResolver();
1900        boolean updateRotation = false;
1901        synchronized (mLock) {
1902            mEndcallBehavior = Settings.System.getIntForUser(resolver,
1903                    Settings.System.END_BUTTON_BEHAVIOR,
1904                    Settings.System.END_BUTTON_BEHAVIOR_DEFAULT,
1905                    UserHandle.USER_CURRENT);
1906            mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver,
1907                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
1908                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT,
1909                    UserHandle.USER_CURRENT);
1910
1911            // Configure wake gesture.
1912            boolean wakeGestureEnabledSetting = Settings.Secure.getIntForUser(resolver,
1913                    Settings.Secure.WAKE_GESTURE_ENABLED, 0,
1914                    UserHandle.USER_CURRENT) != 0;
1915            if (mWakeGestureEnabledSetting != wakeGestureEnabledSetting) {
1916                mWakeGestureEnabledSetting = wakeGestureEnabledSetting;
1917                updateWakeGestureListenerLp();
1918            }
1919
1920            // Configure rotation lock.
1921            int userRotation = Settings.System.getIntForUser(resolver,
1922                    Settings.System.USER_ROTATION, Surface.ROTATION_0,
1923                    UserHandle.USER_CURRENT);
1924            if (mUserRotation != userRotation) {
1925                mUserRotation = userRotation;
1926                updateRotation = true;
1927            }
1928            int userRotationMode = Settings.System.getIntForUser(resolver,
1929                    Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
1930                            WindowManagerPolicy.USER_ROTATION_FREE :
1931                                    WindowManagerPolicy.USER_ROTATION_LOCKED;
1932            if (mUserRotationMode != userRotationMode) {
1933                mUserRotationMode = userRotationMode;
1934                updateRotation = true;
1935                updateOrientationListenerLp();
1936            }
1937
1938            if (mSystemReady) {
1939                int pointerLocation = Settings.System.getIntForUser(resolver,
1940                        Settings.System.POINTER_LOCATION, 0, UserHandle.USER_CURRENT);
1941                if (mPointerLocationMode != pointerLocation) {
1942                    mPointerLocationMode = pointerLocation;
1943                    mHandler.sendEmptyMessage(pointerLocation != 0 ?
1944                            MSG_ENABLE_POINTER_LOCATION : MSG_DISABLE_POINTER_LOCATION);
1945                }
1946            }
1947            // use screen off timeout setting as the timeout for the lockscreen
1948            mLockScreenTimeout = Settings.System.getIntForUser(resolver,
1949                    Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT);
1950            String imId = Settings.Secure.getStringForUser(resolver,
1951                    Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT);
1952            boolean hasSoftInput = imId != null && imId.length() > 0;
1953            if (mHasSoftInput != hasSoftInput) {
1954                mHasSoftInput = hasSoftInput;
1955                updateRotation = true;
1956            }
1957            if (mImmersiveModeConfirmation != null) {
1958                mImmersiveModeConfirmation.loadSetting(mCurrentUserId);
1959            }
1960        }
1961        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
1962            PolicyControl.reloadFromSetting(mContext);
1963        }
1964        if (updateRotation) {
1965            updateRotation(true);
1966        }
1967    }
1968
1969    private void updateWakeGestureListenerLp() {
1970        if (shouldEnableWakeGestureLp()) {
1971            mWakeGestureListener.requestWakeUpTrigger();
1972        } else {
1973            mWakeGestureListener.cancelWakeUpTrigger();
1974        }
1975    }
1976
1977    private boolean shouldEnableWakeGestureLp() {
1978        return mWakeGestureEnabledSetting && !mAwake
1979                && (!mLidControlsSleep || mLidState != LID_CLOSED)
1980                && mWakeGestureListener.isSupported();
1981    }
1982
1983    private void enablePointerLocation() {
1984        if (mPointerLocationView == null) {
1985            mPointerLocationView = new PointerLocationView(mContext);
1986            mPointerLocationView.setPrintCoords(false);
1987            WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1988                    WindowManager.LayoutParams.MATCH_PARENT,
1989                    WindowManager.LayoutParams.MATCH_PARENT);
1990            lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
1991            lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
1992                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
1993                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1994                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
1995            if (ActivityManager.isHighEndGfx()) {
1996                lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1997                lp.privateFlags |=
1998                        WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED;
1999            }
2000            lp.format = PixelFormat.TRANSLUCENT;
2001            lp.setTitle("PointerLocation");
2002            WindowManager wm = (WindowManager)
2003                    mContext.getSystemService(Context.WINDOW_SERVICE);
2004            lp.inputFeatures |= WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL;
2005            wm.addView(mPointerLocationView, lp);
2006            mWindowManagerFuncs.registerPointerEventListener(mPointerLocationView);
2007        }
2008    }
2009
2010    private void disablePointerLocation() {
2011        if (mPointerLocationView != null) {
2012            mWindowManagerFuncs.unregisterPointerEventListener(mPointerLocationView);
2013            WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
2014            wm.removeView(mPointerLocationView);
2015            mPointerLocationView = null;
2016        }
2017    }
2018
2019    private int readRotation(int resID) {
2020        try {
2021            int rotation = mContext.getResources().getInteger(resID);
2022            switch (rotation) {
2023                case 0:
2024                    return Surface.ROTATION_0;
2025                case 90:
2026                    return Surface.ROTATION_90;
2027                case 180:
2028                    return Surface.ROTATION_180;
2029                case 270:
2030                    return Surface.ROTATION_270;
2031            }
2032        } catch (Resources.NotFoundException e) {
2033            // fall through
2034        }
2035        return -1;
2036    }
2037
2038    /** {@inheritDoc} */
2039    @Override
2040    public int checkAddPermission(WindowManager.LayoutParams attrs, int[] outAppOp) {
2041        int type = attrs.type;
2042
2043        outAppOp[0] = AppOpsManager.OP_NONE;
2044
2045        if (!((type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW)
2046                || (type >= FIRST_SUB_WINDOW && type <= LAST_SUB_WINDOW)
2047                || (type >= FIRST_SYSTEM_WINDOW && type <= LAST_SYSTEM_WINDOW))) {
2048            return WindowManagerGlobal.ADD_INVALID_TYPE;
2049        }
2050
2051        if (type < FIRST_SYSTEM_WINDOW || type > LAST_SYSTEM_WINDOW) {
2052            // Window manager will make sure these are okay.
2053            return WindowManagerGlobal.ADD_OKAY;
2054        }
2055        String permission = null;
2056        switch (type) {
2057            case TYPE_TOAST:
2058                // XXX right now the app process has complete control over
2059                // this...  should introduce a token to let the system
2060                // monitor/control what they are doing.
2061                outAppOp[0] = AppOpsManager.OP_TOAST_WINDOW;
2062                break;
2063            case TYPE_DREAM:
2064            case TYPE_INPUT_METHOD:
2065            case TYPE_WALLPAPER:
2066            case TYPE_PRIVATE_PRESENTATION:
2067            case TYPE_VOICE_INTERACTION:
2068            case TYPE_ACCESSIBILITY_OVERLAY:
2069            case TYPE_QS_DIALOG:
2070                // The window manager will check these.
2071                break;
2072            case TYPE_PHONE:
2073            case TYPE_PRIORITY_PHONE:
2074            case TYPE_SYSTEM_ALERT:
2075            case TYPE_SYSTEM_ERROR:
2076            case TYPE_SYSTEM_OVERLAY:
2077                permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
2078                outAppOp[0] = AppOpsManager.OP_SYSTEM_ALERT_WINDOW;
2079                break;
2080            default:
2081                permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
2082        }
2083        if (permission != null) {
2084            if (android.Manifest.permission.SYSTEM_ALERT_WINDOW.equals(permission)) {
2085                final int callingUid = Binder.getCallingUid();
2086                // system processes will be automatically allowed privilege to draw
2087                if (callingUid == Process.SYSTEM_UID) {
2088                    return WindowManagerGlobal.ADD_OKAY;
2089                }
2090
2091                // check if user has enabled this operation. SecurityException will be thrown if
2092                // this app has not been allowed by the user
2093                final int mode = mAppOpsManager.checkOpNoThrow(outAppOp[0], callingUid,
2094                        attrs.packageName);
2095                switch (mode) {
2096                    case AppOpsManager.MODE_ALLOWED:
2097                    case AppOpsManager.MODE_IGNORED:
2098                        // although we return ADD_OKAY for MODE_IGNORED, the added window will
2099                        // actually be hidden in WindowManagerService
2100                        return WindowManagerGlobal.ADD_OKAY;
2101                    case AppOpsManager.MODE_ERRORED:
2102                        try {
2103                            ApplicationInfo appInfo = mContext.getPackageManager()
2104                                    .getApplicationInfo(attrs.packageName,
2105                                            UserHandle.getUserId(callingUid));
2106                            // Don't crash legacy apps
2107                            if (appInfo.targetSdkVersion < Build.VERSION_CODES.M) {
2108                                return WindowManagerGlobal.ADD_OKAY;
2109                            }
2110                        } catch (PackageManager.NameNotFoundException e) {
2111                            /* ignore */
2112                        }
2113                        return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2114                    default:
2115                        // in the default mode, we will make a decision here based on
2116                        // checkCallingPermission()
2117                        if (mContext.checkCallingPermission(permission) !=
2118                                PackageManager.PERMISSION_GRANTED) {
2119                            return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2120                        } else {
2121                            return WindowManagerGlobal.ADD_OKAY;
2122                        }
2123                }
2124            }
2125
2126            if (mContext.checkCallingOrSelfPermission(permission)
2127                    != PackageManager.PERMISSION_GRANTED) {
2128                return WindowManagerGlobal.ADD_PERMISSION_DENIED;
2129            }
2130        }
2131        return WindowManagerGlobal.ADD_OKAY;
2132    }
2133
2134    @Override
2135    public boolean checkShowToOwnerOnly(WindowManager.LayoutParams attrs) {
2136
2137        // If this switch statement is modified, modify the comment in the declarations of
2138        // the type in {@link WindowManager.LayoutParams} as well.
2139        switch (attrs.type) {
2140            default:
2141                // These are the windows that by default are shown only to the user that created
2142                // them. If this needs to be overridden, set
2143                // {@link WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS} in
2144                // {@link WindowManager.LayoutParams}. Note that permission
2145                // {@link android.Manifest.permission.INTERNAL_SYSTEM_WINDOW} is required as well.
2146                if ((attrs.privateFlags & PRIVATE_FLAG_SHOW_FOR_ALL_USERS) == 0) {
2147                    return true;
2148                }
2149                break;
2150
2151            // These are the windows that by default are shown to all users. However, to
2152            // protect against spoofing, check permissions below.
2153            case TYPE_APPLICATION_STARTING:
2154            case TYPE_BOOT_PROGRESS:
2155            case TYPE_DISPLAY_OVERLAY:
2156            case TYPE_INPUT_CONSUMER:
2157            case TYPE_KEYGUARD_SCRIM:
2158            case TYPE_KEYGUARD_DIALOG:
2159            case TYPE_MAGNIFICATION_OVERLAY:
2160            case TYPE_NAVIGATION_BAR:
2161            case TYPE_NAVIGATION_BAR_PANEL:
2162            case TYPE_PHONE:
2163            case TYPE_POINTER:
2164            case TYPE_PRIORITY_PHONE:
2165            case TYPE_SEARCH_BAR:
2166            case TYPE_STATUS_BAR:
2167            case TYPE_STATUS_BAR_PANEL:
2168            case TYPE_STATUS_BAR_SUB_PANEL:
2169            case TYPE_SYSTEM_DIALOG:
2170            case TYPE_VOLUME_OVERLAY:
2171            case TYPE_PRIVATE_PRESENTATION:
2172            case TYPE_DOCK_DIVIDER:
2173                break;
2174        }
2175
2176        // Check if third party app has set window to system window type.
2177        return mContext.checkCallingOrSelfPermission(
2178                android.Manifest.permission.INTERNAL_SYSTEM_WINDOW)
2179                        != PackageManager.PERMISSION_GRANTED;
2180    }
2181
2182    @Override
2183    public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
2184        switch (attrs.type) {
2185            case TYPE_SYSTEM_OVERLAY:
2186            case TYPE_SECURE_SYSTEM_OVERLAY:
2187                // These types of windows can't receive input events.
2188                attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
2189                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
2190                attrs.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
2191                break;
2192            case TYPE_STATUS_BAR:
2193
2194                // If the Keyguard is in a hidden state (occluded by another window), we force to
2195                // remove the wallpaper and keyguard flag so that any change in-flight after setting
2196                // the keyguard as occluded wouldn't set these flags again.
2197                // See {@link #processKeyguardSetHiddenResultLw}.
2198                if (mKeyguardHidden) {
2199                    attrs.flags &= ~WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
2200                    attrs.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
2201                }
2202                break;
2203        }
2204
2205        if (attrs.type != TYPE_STATUS_BAR) {
2206            // The status bar is the only window allowed to exhibit keyguard behavior.
2207            attrs.privateFlags &= ~WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
2208        }
2209
2210        if (ActivityManager.isHighEndGfx()) {
2211            if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0) {
2212                attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
2213            }
2214            if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
2215                    || (mForceWindowDrawsStatusBarBackground
2216                            && attrs.height == MATCH_PARENT && attrs.width == MATCH_PARENT)) {
2217                attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2218            }
2219        }
2220    }
2221
2222    void readLidState() {
2223        mLidState = mWindowManagerFuncs.getLidState();
2224    }
2225
2226    private void readCameraLensCoverState() {
2227        mCameraLensCoverState = mWindowManagerFuncs.getCameraLensCoverState();
2228    }
2229
2230    private boolean isHidden(int accessibilityMode) {
2231        switch (accessibilityMode) {
2232            case 1:
2233                return mLidState == LID_CLOSED;
2234            case 2:
2235                return mLidState == LID_OPEN;
2236            default:
2237                return false;
2238        }
2239    }
2240
2241    /** {@inheritDoc} */
2242    @Override
2243    public void adjustConfigurationLw(Configuration config, int keyboardPresence,
2244            int navigationPresence) {
2245        mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
2246
2247        readConfigurationDependentBehaviors();
2248        readLidState();
2249        applyLidSwitchState();
2250
2251        if (config.keyboard == Configuration.KEYBOARD_NOKEYS
2252                || (keyboardPresence == PRESENCE_INTERNAL
2253                        && isHidden(mLidKeyboardAccessibility))) {
2254            config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
2255            if (!mHasSoftInput) {
2256                config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES;
2257            }
2258        }
2259
2260        if (config.navigation == Configuration.NAVIGATION_NONAV
2261                || (navigationPresence == PRESENCE_INTERNAL
2262                        && isHidden(mLidNavigationAccessibility))) {
2263            config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
2264        }
2265    }
2266
2267    @Override
2268    public void onConfigurationChanged() {
2269        final Resources res = mContext.getResources();
2270
2271        mStatusBarHeight =
2272                res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
2273
2274        // Height of the navigation bar when presented horizontally at bottom
2275        mNavigationBarHeightForRotationDefault[mPortraitRotation] =
2276        mNavigationBarHeightForRotationDefault[mUpsideDownRotation] =
2277                res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_height);
2278        mNavigationBarHeightForRotationDefault[mLandscapeRotation] =
2279        mNavigationBarHeightForRotationDefault[mSeascapeRotation] = res.getDimensionPixelSize(
2280                com.android.internal.R.dimen.navigation_bar_height_landscape);
2281
2282        // Width of the navigation bar when presented vertically along one side
2283        mNavigationBarWidthForRotationDefault[mPortraitRotation] =
2284        mNavigationBarWidthForRotationDefault[mUpsideDownRotation] =
2285        mNavigationBarWidthForRotationDefault[mLandscapeRotation] =
2286        mNavigationBarWidthForRotationDefault[mSeascapeRotation] =
2287                res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_width);
2288
2289        // Height of the navigation bar when presented horizontally at bottom
2290        mNavigationBarHeightForRotationInCarMode[mPortraitRotation] =
2291        mNavigationBarHeightForRotationInCarMode[mUpsideDownRotation] =
2292                res.getDimensionPixelSize(
2293                        com.android.internal.R.dimen.navigation_bar_height_car_mode);
2294        mNavigationBarHeightForRotationInCarMode[mLandscapeRotation] =
2295        mNavigationBarHeightForRotationInCarMode[mSeascapeRotation] = res.getDimensionPixelSize(
2296                com.android.internal.R.dimen.navigation_bar_height_landscape_car_mode);
2297
2298        // Width of the navigation bar when presented vertically along one side
2299        mNavigationBarWidthForRotationInCarMode[mPortraitRotation] =
2300        mNavigationBarWidthForRotationInCarMode[mUpsideDownRotation] =
2301        mNavigationBarWidthForRotationInCarMode[mLandscapeRotation] =
2302        mNavigationBarWidthForRotationInCarMode[mSeascapeRotation] =
2303                res.getDimensionPixelSize(
2304                        com.android.internal.R.dimen.navigation_bar_width_car_mode);
2305    }
2306
2307    /** {@inheritDoc} */
2308    @Override
2309    public int windowTypeToLayerLw(int type) {
2310        if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
2311            return 2;
2312        }
2313        switch (type) {
2314        case TYPE_PRIVATE_PRESENTATION:
2315            return 2;
2316        case TYPE_WALLPAPER:
2317            // wallpaper is at the bottom, though the window manager may move it.
2318            return 2;
2319        case TYPE_DOCK_DIVIDER:
2320            return 2;
2321        case TYPE_QS_DIALOG:
2322            return 2;
2323        case TYPE_PHONE:
2324            return 3;
2325        case TYPE_SEARCH_BAR:
2326        case TYPE_VOICE_INTERACTION_STARTING:
2327            return 4;
2328        case TYPE_VOICE_INTERACTION:
2329            // voice interaction layer is almost immediately above apps.
2330            return 5;
2331        case TYPE_INPUT_CONSUMER:
2332            return 6;
2333        case TYPE_SYSTEM_DIALOG:
2334            return 7;
2335        case TYPE_TOAST:
2336            // toasts and the plugged-in battery thing
2337            return 8;
2338        case TYPE_PRIORITY_PHONE:
2339            // SIM errors and unlock.  Not sure if this really should be in a high layer.
2340            return 9;
2341        case TYPE_DREAM:
2342            // used for Dreams (screensavers with TYPE_DREAM windows)
2343            return 10;
2344        case TYPE_SYSTEM_ALERT:
2345            // like the ANR / app crashed dialogs
2346            return 11;
2347        case TYPE_INPUT_METHOD:
2348            // on-screen keyboards and other such input method user interfaces go here.
2349            return 12;
2350        case TYPE_INPUT_METHOD_DIALOG:
2351            // on-screen keyboards and other such input method user interfaces go here.
2352            return 13;
2353        case TYPE_KEYGUARD_SCRIM:
2354            // the safety window that shows behind keyguard while keyguard is starting
2355            return 14;
2356        case TYPE_STATUS_BAR_SUB_PANEL:
2357            return 15;
2358        case TYPE_STATUS_BAR:
2359            return 16;
2360        case TYPE_STATUS_BAR_PANEL:
2361            return 17;
2362        case TYPE_KEYGUARD_DIALOG:
2363            return 18;
2364        case TYPE_VOLUME_OVERLAY:
2365            // the on-screen volume indicator and controller shown when the user
2366            // changes the device volume
2367            return 19;
2368        case TYPE_SYSTEM_OVERLAY:
2369            // the on-screen volume indicator and controller shown when the user
2370            // changes the device volume
2371            return 20;
2372        case TYPE_NAVIGATION_BAR:
2373            // the navigation bar, if available, shows atop most things
2374            return 21;
2375        case TYPE_NAVIGATION_BAR_PANEL:
2376            // some panels (e.g. search) need to show on top of the navigation bar
2377            return 22;
2378        case TYPE_SCREENSHOT:
2379            // screenshot selection layer shouldn't go above system error, but it should cover
2380            // navigation bars at the very least.
2381            return 23;
2382        case TYPE_SYSTEM_ERROR:
2383            // system-level error dialogs
2384            return 24;
2385        case TYPE_MAGNIFICATION_OVERLAY:
2386            // used to highlight the magnified portion of a display
2387            return 25;
2388        case TYPE_DISPLAY_OVERLAY:
2389            // used to simulate secondary display devices
2390            return 26;
2391        case TYPE_DRAG:
2392            // the drag layer: input for drag-and-drop is associated with this window,
2393            // which sits above all other focusable windows
2394            return 27;
2395        case TYPE_ACCESSIBILITY_OVERLAY:
2396            // overlay put by accessibility services to intercept user interaction
2397            return 28;
2398        case TYPE_SECURE_SYSTEM_OVERLAY:
2399            return 29;
2400        case TYPE_BOOT_PROGRESS:
2401            return 30;
2402        case TYPE_POINTER:
2403            // the (mouse) pointer layer
2404            return 31;
2405        }
2406        Log.e(TAG, "Unknown window type: " + type);
2407        return 2;
2408    }
2409
2410    /** {@inheritDoc} */
2411    @Override
2412    public int subWindowTypeToLayerLw(int type) {
2413        switch (type) {
2414        case TYPE_APPLICATION_PANEL:
2415        case TYPE_APPLICATION_ATTACHED_DIALOG:
2416            return APPLICATION_PANEL_SUBLAYER;
2417        case TYPE_APPLICATION_MEDIA:
2418            return APPLICATION_MEDIA_SUBLAYER;
2419        case TYPE_APPLICATION_MEDIA_OVERLAY:
2420            return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
2421        case TYPE_APPLICATION_SUB_PANEL:
2422            return APPLICATION_SUB_PANEL_SUBLAYER;
2423        case TYPE_APPLICATION_ABOVE_SUB_PANEL:
2424            return APPLICATION_ABOVE_SUB_PANEL_SUBLAYER;
2425        }
2426        Log.e(TAG, "Unknown sub-window type: " + type);
2427        return 0;
2428    }
2429
2430    @Override
2431    public int getMaxWallpaperLayer() {
2432        return windowTypeToLayerLw(TYPE_STATUS_BAR);
2433    }
2434
2435    private int getNavigationBarWidth(int rotation, int uiMode) {
2436        if ((uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR) {
2437            return mNavigationBarWidthForRotationInCarMode[rotation];
2438        } else {
2439            return mNavigationBarWidthForRotationDefault[rotation];
2440        }
2441    }
2442
2443    @Override
2444    public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation,
2445            int uiMode) {
2446        if (mHasNavigationBar) {
2447            // For a basic navigation bar, when we are in landscape mode we place
2448            // the navigation bar to the side.
2449            if (mNavigationBarCanMove && fullWidth > fullHeight) {
2450                return fullWidth - getNavigationBarWidth(rotation, uiMode);
2451            }
2452        }
2453        return fullWidth;
2454    }
2455
2456    private int getNavigationBarHeight(int rotation, int uiMode) {
2457        if ((uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR) {
2458            return mNavigationBarHeightForRotationInCarMode[rotation];
2459        } else {
2460            return mNavigationBarHeightForRotationDefault[rotation];
2461        }
2462    }
2463
2464    @Override
2465    public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation,
2466            int uiMode) {
2467        if (mHasNavigationBar) {
2468            // For a basic navigation bar, when we are in portrait mode we place
2469            // the navigation bar to the bottom.
2470            if (!mNavigationBarCanMove || fullWidth < fullHeight) {
2471                return fullHeight - getNavigationBarHeight(rotation, uiMode);
2472            }
2473        }
2474        return fullHeight;
2475    }
2476
2477    @Override
2478    public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation, int uiMode) {
2479        return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation, uiMode);
2480    }
2481
2482    @Override
2483    public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation, int uiMode) {
2484        // There is a separate status bar at the top of the display.  We don't count that as part
2485        // of the fixed decor, since it can hide; however, for purposes of configurations,
2486        // we do want to exclude it since applications can't generally use that part
2487        // of the screen.
2488        return getNonDecorDisplayHeight(
2489                fullWidth, fullHeight, rotation, uiMode) - mStatusBarHeight;
2490    }
2491
2492    @Override
2493    public boolean isForceHiding(WindowManager.LayoutParams attrs) {
2494        return (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 ||
2495                (isKeyguardHostWindow(attrs) &&
2496                        (mKeyguardDelegate != null && mKeyguardDelegate.isShowing())) ||
2497                (attrs.type == TYPE_KEYGUARD_SCRIM);
2498    }
2499
2500    @Override
2501    public boolean isKeyguardHostWindow(WindowManager.LayoutParams attrs) {
2502        return attrs.type == TYPE_STATUS_BAR;
2503    }
2504
2505    @Override
2506    public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
2507        switch (attrs.type) {
2508            case TYPE_STATUS_BAR:
2509            case TYPE_NAVIGATION_BAR:
2510            case TYPE_WALLPAPER:
2511            case TYPE_DREAM:
2512            case TYPE_KEYGUARD_SCRIM:
2513                return false;
2514            default:
2515                // Hide only windows below the keyguard host window.
2516                return windowTypeToLayerLw(win.getBaseType())
2517                        < windowTypeToLayerLw(TYPE_STATUS_BAR);
2518        }
2519    }
2520
2521    @Override
2522    public WindowState getWinShowWhenLockedLw() {
2523        return mWinShowWhenLocked;
2524    }
2525
2526    /** {@inheritDoc} */
2527    @Override
2528    public View addStartingWindow(IBinder appToken, String packageName, int theme,
2529            CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel, int labelRes,
2530            int icon, int logo, int windowFlags) {
2531        if (!SHOW_STARTING_ANIMATIONS) {
2532            return null;
2533        }
2534        if (packageName == null) {
2535            return null;
2536        }
2537
2538        WindowManager wm = null;
2539        View view = null;
2540
2541        try {
2542            Context context = mContext;
2543            if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow " + packageName
2544                    + ": nonLocalizedLabel=" + nonLocalizedLabel + " theme="
2545                    + Integer.toHexString(theme));
2546            if (theme != context.getThemeResId() || labelRes != 0) {
2547                try {
2548                    context = context.createPackageContext(packageName, 0);
2549                    context.setTheme(theme);
2550                } catch (PackageManager.NameNotFoundException e) {
2551                    // Ignore
2552                }
2553            }
2554
2555            PhoneWindow win = new PhoneWindow(context);
2556            win.setIsStartingWindow(true);
2557
2558            Resources r = context.getResources();
2559            win.setTitle(r.getText(labelRes, nonLocalizedLabel));
2560
2561            win.setType(
2562                WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
2563
2564            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
2565                // Assumes it's safe to show starting windows of launched apps while
2566                // the keyguard is being hidden. This is okay because starting windows never show
2567                // secret information.
2568                if (mKeyguardHidden) {
2569                    windowFlags |= FLAG_SHOW_WHEN_LOCKED;
2570                }
2571            }
2572
2573            // Force the window flags: this is a fake window, so it is not really
2574            // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
2575            // flag because we do know that the next window will take input
2576            // focus, so we want to get the IME window up on top of us right away.
2577            win.setFlags(
2578                windowFlags|
2579                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2580                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2581                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
2582                windowFlags|
2583                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2584                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2585                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
2586
2587            win.setDefaultIcon(icon);
2588            win.setDefaultLogo(logo);
2589
2590            win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
2591                    WindowManager.LayoutParams.MATCH_PARENT);
2592
2593            final WindowManager.LayoutParams params = win.getAttributes();
2594            params.token = appToken;
2595            params.packageName = packageName;
2596            params.windowAnimations = win.getWindowStyle().getResourceId(
2597                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2598            params.privateFlags |=
2599                    WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED;
2600            params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
2601
2602            if (!compatInfo.supportsScreen()) {
2603                params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
2604            }
2605
2606            params.setTitle("Starting " + packageName);
2607
2608            wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
2609            view = win.getDecorView();
2610
2611            if (DEBUG_STARTING_WINDOW) Slog.d(
2612                TAG, "Adding starting window for " + packageName
2613                + " / " + appToken + ": "
2614                + (view.getParent() != null ? view : null));
2615
2616            wm.addView(view, params);
2617
2618            // Only return the view if it was successfully added to the
2619            // window manager... which we can tell by it having a parent.
2620            return view.getParent() != null ? view : null;
2621        } catch (WindowManager.BadTokenException e) {
2622            // ignore
2623            Log.w(TAG, appToken + " already running, starting window not displayed. " +
2624                    e.getMessage());
2625        } catch (RuntimeException e) {
2626            // don't crash if something else bad happens, for example a
2627            // failure loading resources because we are loading from an app
2628            // on external storage that has been unmounted.
2629            Log.w(TAG, appToken + " failed creating starting window", e);
2630        } finally {
2631            if (view != null && view.getParent() == null) {
2632                Log.w(TAG, "view not successfully added to wm, removing view");
2633                wm.removeViewImmediate(view);
2634            }
2635        }
2636
2637        return null;
2638    }
2639
2640    /** {@inheritDoc} */
2641    @Override
2642    public void removeStartingWindow(IBinder appToken, View window) {
2643        if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Removing starting window for " + appToken + ": "
2644                + window + " Callers=" + Debug.getCallers(4));
2645
2646        if (window != null) {
2647            WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
2648            wm.removeView(window);
2649        }
2650    }
2651
2652    /**
2653     * Preflight adding a window to the system.
2654     *
2655     * Currently enforces that three window types are singletons:
2656     * <ul>
2657     * <li>STATUS_BAR_TYPE</li>
2658     * <li>KEYGUARD_TYPE</li>
2659     * </ul>
2660     *
2661     * @param win The window to be added
2662     * @param attrs Information about the window to be added
2663     *
2664     * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons,
2665     * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
2666     */
2667    @Override
2668    public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
2669        switch (attrs.type) {
2670            case TYPE_STATUS_BAR:
2671                mContext.enforceCallingOrSelfPermission(
2672                        android.Manifest.permission.STATUS_BAR_SERVICE,
2673                        "PhoneWindowManager");
2674                if (mStatusBar != null) {
2675                    if (mStatusBar.isAlive()) {
2676                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2677                    }
2678                }
2679                mStatusBar = win;
2680                mStatusBarController.setWindow(win);
2681                break;
2682            case TYPE_NAVIGATION_BAR:
2683                mContext.enforceCallingOrSelfPermission(
2684                        android.Manifest.permission.STATUS_BAR_SERVICE,
2685                        "PhoneWindowManager");
2686                if (mNavigationBar != null) {
2687                    if (mNavigationBar.isAlive()) {
2688                        return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2689                    }
2690                }
2691                mNavigationBar = win;
2692                mNavigationBarController.setWindow(win);
2693                if (DEBUG_LAYOUT) Slog.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
2694                break;
2695            case TYPE_NAVIGATION_BAR_PANEL:
2696            case TYPE_STATUS_BAR_PANEL:
2697            case TYPE_STATUS_BAR_SUB_PANEL:
2698            case TYPE_VOICE_INTERACTION_STARTING:
2699                mContext.enforceCallingOrSelfPermission(
2700                        android.Manifest.permission.STATUS_BAR_SERVICE,
2701                        "PhoneWindowManager");
2702                break;
2703            case TYPE_KEYGUARD_SCRIM:
2704                if (mKeyguardScrim != null) {
2705                    return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2706                }
2707                mKeyguardScrim = win;
2708                break;
2709        }
2710        return WindowManagerGlobal.ADD_OKAY;
2711    }
2712
2713    /** {@inheritDoc} */
2714    @Override
2715    public void removeWindowLw(WindowState win) {
2716        if (mStatusBar == win) {
2717            mStatusBar = null;
2718            mStatusBarController.setWindow(null);
2719            mKeyguardDelegate.showScrim();
2720        } else if (mKeyguardScrim == win) {
2721            Log.v(TAG, "Removing keyguard scrim");
2722            mKeyguardScrim = null;
2723        } if (mNavigationBar == win) {
2724            mNavigationBar = null;
2725            mNavigationBarController.setWindow(null);
2726        }
2727    }
2728
2729    static final boolean PRINT_ANIM = false;
2730
2731    /** {@inheritDoc} */
2732    @Override
2733    public int selectAnimationLw(WindowState win, int transit) {
2734        if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
2735              + ": transit=" + transit);
2736        if (win == mStatusBar) {
2737            boolean isKeyguard = (win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
2738            if (transit == TRANSIT_EXIT
2739                    || transit == TRANSIT_HIDE) {
2740                return isKeyguard ? -1 : R.anim.dock_top_exit;
2741            } else if (transit == TRANSIT_ENTER
2742                    || transit == TRANSIT_SHOW) {
2743                return isKeyguard ? -1 : R.anim.dock_top_enter;
2744            }
2745        } else if (win == mNavigationBar) {
2746            if (win.getAttrs().windowAnimations != 0) {
2747                return 0;
2748            }
2749            // This can be on either the bottom or the right.
2750            if (mNavigationBarOnBottom) {
2751                if (transit == TRANSIT_EXIT
2752                        || transit == TRANSIT_HIDE) {
2753                    return R.anim.dock_bottom_exit;
2754                } else if (transit == TRANSIT_ENTER
2755                        || transit == TRANSIT_SHOW) {
2756                    return R.anim.dock_bottom_enter;
2757                }
2758            } else {
2759                if (transit == TRANSIT_EXIT
2760                        || transit == TRANSIT_HIDE) {
2761                    return R.anim.dock_right_exit;
2762                } else if (transit == TRANSIT_ENTER
2763                        || transit == TRANSIT_SHOW) {
2764                    return R.anim.dock_right_enter;
2765                }
2766            }
2767        } else if (win.getAttrs().type == TYPE_DOCK_DIVIDER) {
2768            return selectDockedDividerAnimationLw(win, transit);
2769        }
2770
2771        if (transit == TRANSIT_PREVIEW_DONE) {
2772            if (win.hasAppShownWindows()) {
2773                if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
2774                return com.android.internal.R.anim.app_starting_exit;
2775            }
2776        } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
2777                && transit == TRANSIT_ENTER) {
2778            // Special case: we are animating in a dream, while the keyguard
2779            // is shown.  We don't want an animation on the dream, because
2780            // we need it shown immediately with the keyguard animating away
2781            // to reveal it.
2782            return -1;
2783        }
2784
2785        return 0;
2786    }
2787
2788    private int selectDockedDividerAnimationLw(WindowState win, int transit) {
2789        int insets = mWindowManagerFuncs.getDockedDividerInsetsLw();
2790
2791        // If the divider is behind the navigation bar, don't animate.
2792        final Rect frame = win.getFrameLw();
2793        final boolean behindNavBar = mNavigationBar != null
2794                && ((mNavigationBarOnBottom
2795                        && frame.top + insets >= mNavigationBar.getFrameLw().top)
2796                || (!mNavigationBarOnBottom
2797                        && frame.left + insets >= mNavigationBar.getFrameLw().left));
2798        final boolean landscape = frame.height() > frame.width();
2799        final boolean offscreenLandscape = landscape && (frame.right - insets <= 0
2800                || frame.left + insets >= win.getDisplayFrameLw().right);
2801        final boolean offscreenPortrait = !landscape && (frame.top - insets <= 0
2802                || frame.bottom + insets >= win.getDisplayFrameLw().bottom);
2803        final boolean offscreen = offscreenLandscape || offscreenPortrait;
2804        if (behindNavBar || offscreen) {
2805            return 0;
2806        }
2807        if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) {
2808            return R.anim.fade_in;
2809        } else if (transit == TRANSIT_EXIT) {
2810            return R.anim.fade_out;
2811        } else {
2812            return 0;
2813        }
2814    }
2815
2816    @Override
2817    public void selectRotationAnimationLw(int anim[]) {
2818        if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
2819                + mTopFullscreenOpaqueWindowState + " rotationAnimation="
2820                + (mTopFullscreenOpaqueWindowState == null ?
2821                        "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
2822        if (mTopFullscreenOpaqueWindowState != null && mTopIsFullscreen) {
2823            switch (mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation) {
2824                case ROTATION_ANIMATION_CROSSFADE:
2825                    anim[0] = R.anim.rotation_animation_xfade_exit;
2826                    anim[1] = R.anim.rotation_animation_enter;
2827                    break;
2828                case ROTATION_ANIMATION_JUMPCUT:
2829                    anim[0] = R.anim.rotation_animation_jump_exit;
2830                    anim[1] = R.anim.rotation_animation_enter;
2831                    break;
2832                case ROTATION_ANIMATION_ROTATE:
2833                default:
2834                    anim[0] = anim[1] = 0;
2835                    break;
2836            }
2837        } else {
2838            anim[0] = anim[1] = 0;
2839        }
2840    }
2841
2842    @Override
2843    public boolean validateRotationAnimationLw(int exitAnimId, int enterAnimId,
2844            boolean forceDefault) {
2845        switch (exitAnimId) {
2846            case R.anim.rotation_animation_xfade_exit:
2847            case R.anim.rotation_animation_jump_exit:
2848                // These are the only cases that matter.
2849                if (forceDefault) {
2850                    return false;
2851                }
2852                int anim[] = new int[2];
2853                selectRotationAnimationLw(anim);
2854                return (exitAnimId == anim[0] && enterAnimId == anim[1]);
2855            default:
2856                return true;
2857        }
2858    }
2859
2860    @Override
2861    public Animation createForceHideEnterAnimation(boolean onWallpaper,
2862            boolean goingToNotificationShade) {
2863        if (goingToNotificationShade) {
2864            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_behind_enter_fade_in);
2865        }
2866
2867        AnimationSet set = (AnimationSet) AnimationUtils.loadAnimation(mContext, onWallpaper ?
2868                    R.anim.lock_screen_behind_enter_wallpaper :
2869                    R.anim.lock_screen_behind_enter);
2870
2871        // TODO: Use XML interpolators when we have log interpolators available in XML.
2872        final List<Animation> animations = set.getAnimations();
2873        for (int i = animations.size() - 1; i >= 0; --i) {
2874            animations.get(i).setInterpolator(mLogDecelerateInterpolator);
2875        }
2876
2877        return set;
2878    }
2879
2880
2881    @Override
2882    public Animation createForceHideWallpaperExitAnimation(boolean goingToNotificationShade) {
2883        if (goingToNotificationShade) {
2884            return null;
2885        } else {
2886            return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_wallpaper_exit);
2887        }
2888    }
2889
2890    private static void awakenDreams() {
2891        IDreamManager dreamManager = getDreamManager();
2892        if (dreamManager != null) {
2893            try {
2894                dreamManager.awaken();
2895            } catch (RemoteException e) {
2896                // fine, stay asleep then
2897            }
2898        }
2899    }
2900
2901    static IDreamManager getDreamManager() {
2902        return IDreamManager.Stub.asInterface(
2903                ServiceManager.checkService(DreamService.DREAM_SERVICE));
2904    }
2905
2906    TelecomManager getTelecommService() {
2907        return (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
2908    }
2909
2910    static IAudioService getAudioService() {
2911        IAudioService audioService = IAudioService.Stub.asInterface(
2912                ServiceManager.checkService(Context.AUDIO_SERVICE));
2913        if (audioService == null) {
2914            Log.w(TAG, "Unable to find IAudioService interface.");
2915        }
2916        return audioService;
2917    }
2918
2919    boolean keyguardOn() {
2920        return isKeyguardShowingAndNotOccluded() || inKeyguardRestrictedKeyInputMode();
2921    }
2922
2923    private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
2924            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
2925            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
2926        };
2927
2928    /** {@inheritDoc} */
2929    @Override
2930    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
2931        final boolean keyguardOn = keyguardOn();
2932        final int keyCode = event.getKeyCode();
2933        final int repeatCount = event.getRepeatCount();
2934        final int metaState = event.getMetaState();
2935        final int flags = event.getFlags();
2936        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
2937        final boolean canceled = event.isCanceled();
2938
2939        if (DEBUG_INPUT) {
2940            Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
2941                    + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
2942                    + " canceled=" + canceled);
2943        }
2944
2945        // If we think we might have a volume down & power key chord on the way
2946        // but we're not sure, then tell the dispatcher to wait a little while and
2947        // try again later before dispatching.
2948        if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
2949            if (mScreenshotChordVolumeDownKeyTriggered && !mScreenshotChordPowerKeyTriggered) {
2950                final long now = SystemClock.uptimeMillis();
2951                final long timeoutTime = mScreenshotChordVolumeDownKeyTime
2952                        + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
2953                if (now < timeoutTime) {
2954                    return timeoutTime - now;
2955                }
2956            }
2957            if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
2958                    && mScreenshotChordVolumeDownKeyConsumed) {
2959                if (!down) {
2960                    mScreenshotChordVolumeDownKeyConsumed = false;
2961                }
2962                return -1;
2963            }
2964        }
2965
2966        // Cancel any pending meta actions if we see any other keys being pressed between the down
2967        // of the meta key and its corresponding up.
2968        if (mPendingMetaAction && !KeyEvent.isMetaKey(keyCode)) {
2969            mPendingMetaAction = false;
2970        }
2971
2972        // First we always handle the home key here, so applications
2973        // can never break it, although if keyguard is on, we do let
2974        // it handle it, because that gives us the correct 5 second
2975        // timeout.
2976        if (keyCode == KeyEvent.KEYCODE_HOME) {
2977
2978            // If we have released the home key, and didn't do anything else
2979            // while it was pressed, then it is time to go home!
2980            if (!down) {
2981                cancelPreloadRecentApps();
2982
2983                mHomePressed = false;
2984                if (mHomeConsumed) {
2985                    mHomeConsumed = false;
2986                    return -1;
2987                }
2988
2989                if (canceled) {
2990                    Log.i(TAG, "Ignoring HOME; event canceled.");
2991                    return -1;
2992                }
2993
2994                // If an incoming call is ringing, HOME is totally disabled.
2995                // (The user is already on the InCallUI at this point,
2996                // and his ONLY options are to answer or reject the call.)
2997                TelecomManager telecomManager = getTelecommService();
2998                if (telecomManager != null && telecomManager.isRinging()) {
2999                    Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
3000                    return -1;
3001                }
3002
3003                // Delay handling home if a double-tap is possible.
3004                if (mDoubleTapOnHomeBehavior != DOUBLE_TAP_HOME_NOTHING) {
3005                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable); // just in case
3006                    mHomeDoubleTapPending = true;
3007                    mHandler.postDelayed(mHomeDoubleTapTimeoutRunnable,
3008                            ViewConfiguration.getDoubleTapTimeout());
3009                    return -1;
3010                }
3011
3012                handleShortPressOnHome();
3013                return -1;
3014            }
3015
3016            // If a system window has focus, then it doesn't make sense
3017            // right now to interact with applications.
3018            WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
3019            if (attrs != null) {
3020                final int type = attrs.type;
3021                if (type == WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM
3022                        || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
3023                        || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
3024                    // the "app" is keyguard, so give it the key
3025                    return 0;
3026                }
3027                final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
3028                for (int i=0; i<typeCount; i++) {
3029                    if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
3030                        // don't do anything, but also don't pass it to the app
3031                        return -1;
3032                    }
3033                }
3034            }
3035
3036            // Remember that home is pressed and handle special actions.
3037            if (repeatCount == 0) {
3038                mHomePressed = true;
3039                if (mHomeDoubleTapPending) {
3040                    mHomeDoubleTapPending = false;
3041                    mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable);
3042                    handleDoubleTapOnHome();
3043                } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI
3044                        || mDoubleTapOnHomeBehavior == DOUBLE_TAP_HOME_RECENT_SYSTEM_UI) {
3045                    preloadRecentApps();
3046                }
3047            } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
3048                if (!keyguardOn) {
3049                    handleLongPressOnHome(event.getDeviceId());
3050                }
3051            }
3052            return -1;
3053        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
3054            // Hijack modified menu keys for debugging features
3055            final int chordBug = KeyEvent.META_SHIFT_ON;
3056
3057            if (down && repeatCount == 0) {
3058                if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
3059                    Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
3060                    mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
3061                            null, null, null, 0, null, null);
3062                    return -1;
3063                } else if (SHOW_PROCESSES_ON_ALT_MENU &&
3064                        (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
3065                    Intent service = new Intent();
3066                    service.setClassName(mContext, "com.android.server.LoadAverageService");
3067                    ContentResolver res = mContext.getContentResolver();
3068                    boolean shown = Settings.Global.getInt(
3069                            res, Settings.Global.SHOW_PROCESSES, 0) != 0;
3070                    if (!shown) {
3071                        mContext.startService(service);
3072                    } else {
3073                        mContext.stopService(service);
3074                    }
3075                    Settings.Global.putInt(
3076                            res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
3077                    return -1;
3078                }
3079            }
3080        } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
3081            if (down) {
3082                if (repeatCount == 0) {
3083                    mSearchKeyShortcutPending = true;
3084                    mConsumeSearchKeyUp = false;
3085                }
3086            } else {
3087                mSearchKeyShortcutPending = false;
3088                if (mConsumeSearchKeyUp) {
3089                    mConsumeSearchKeyUp = false;
3090                    return -1;
3091                }
3092            }
3093            return 0;
3094        } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
3095            if (!keyguardOn) {
3096                if (down && repeatCount == 0) {
3097                    preloadRecentApps();
3098                } else if (!down) {
3099                    toggleRecentApps();
3100                }
3101            }
3102            return -1;
3103        } else if (keyCode == KeyEvent.KEYCODE_N && event.isMetaPressed()) {
3104            if (down) {
3105                IStatusBarService service = getStatusBarService();
3106                if (service != null) {
3107                    try {
3108                        service.expandNotificationsPanel();
3109                    } catch (RemoteException e) {
3110                        // do nothing.
3111                    }
3112                }
3113            }
3114        } else if (keyCode == KeyEvent.KEYCODE_S && event.isMetaPressed()
3115                && event.isCtrlPressed()) {
3116            if (down && repeatCount == 0) {
3117                int type = event.isShiftPressed() ? TAKE_SCREENSHOT_SELECTED_REGION
3118                        : TAKE_SCREENSHOT_FULLSCREEN;
3119                mScreenshotRunnable.setScreenshotType(type);
3120                mHandler.post(mScreenshotRunnable);
3121                return -1;
3122            }
3123        } else if (keyCode == KeyEvent.KEYCODE_SLASH && event.isMetaPressed()) {
3124            if (down && repeatCount == 0 && !isKeyguardLocked()) {
3125                toggleKeyboardShortcutsMenu(event.getDeviceId());
3126            }
3127        } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
3128            if (down) {
3129                if (repeatCount == 0) {
3130                    mAssistKeyLongPressed = false;
3131                } else if (repeatCount == 1) {
3132                    mAssistKeyLongPressed = true;
3133                    if (!keyguardOn) {
3134                         launchAssistLongPressAction();
3135                    }
3136                }
3137            } else {
3138                if (mAssistKeyLongPressed) {
3139                    mAssistKeyLongPressed = false;
3140                } else {
3141                    if (!keyguardOn) {
3142                        launchAssistAction(null, event.getDeviceId());
3143                    }
3144                }
3145            }
3146            return -1;
3147        } else if (keyCode == KeyEvent.KEYCODE_VOICE_ASSIST) {
3148            if (!down) {
3149                Intent voiceIntent;
3150                if (!keyguardOn) {
3151                    voiceIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3152                } else {
3153                    IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
3154                            ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
3155                    if (dic != null) {
3156                        try {
3157                            dic.exitIdle("voice-search");
3158                        } catch (RemoteException e) {
3159                        }
3160                    }
3161                    voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
3162                    voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, true);
3163                }
3164                startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
3165            }
3166        } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
3167            if (down && repeatCount == 0) {
3168                mScreenshotRunnable.setScreenshotType(TAKE_SCREENSHOT_FULLSCREEN);
3169                mHandler.post(mScreenshotRunnable);
3170            }
3171            return -1;
3172        } else if (keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP
3173                || keyCode == KeyEvent.KEYCODE_BRIGHTNESS_DOWN) {
3174            if (down) {
3175                int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1;
3176
3177                // Disable autobrightness if it's on
3178                int auto = Settings.System.getIntForUser(
3179                        mContext.getContentResolver(),
3180                        Settings.System.SCREEN_BRIGHTNESS_MODE,
3181                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3182                        UserHandle.USER_CURRENT_OR_SELF);
3183                if (auto != 0) {
3184                    Settings.System.putIntForUser(mContext.getContentResolver(),
3185                            Settings.System.SCREEN_BRIGHTNESS_MODE,
3186                            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3187                            UserHandle.USER_CURRENT_OR_SELF);
3188                }
3189
3190                int min = mPowerManager.getMinimumScreenBrightnessSetting();
3191                int max = mPowerManager.getMaximumScreenBrightnessSetting();
3192                int step = (max - min + BRIGHTNESS_STEPS - 1) / BRIGHTNESS_STEPS * direction;
3193                int brightness = Settings.System.getIntForUser(mContext.getContentResolver(),
3194                        Settings.System.SCREEN_BRIGHTNESS,
3195                        mPowerManager.getDefaultScreenBrightnessSetting(),
3196                        UserHandle.USER_CURRENT_OR_SELF);
3197                brightness += step;
3198                // Make sure we don't go beyond the limits.
3199                brightness = Math.min(max, brightness);
3200                brightness = Math.max(min, brightness);
3201
3202                Settings.System.putIntForUser(mContext.getContentResolver(),
3203                        Settings.System.SCREEN_BRIGHTNESS, brightness,
3204                        UserHandle.USER_CURRENT_OR_SELF);
3205                startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG),
3206                        UserHandle.CURRENT_OR_SELF);
3207            }
3208            return -1;
3209        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP
3210                || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
3211                || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
3212            if (mUseTvRouting) {
3213                // On TVs volume keys never go to the foreground app.
3214                dispatchDirectAudioEvent(event);
3215                return -1;
3216            }
3217        }
3218
3219        if (KeyEvent.isMetaKey(keyCode)) {
3220            if (down) {
3221                mPendingMetaAction = true;
3222            } else if (mPendingMetaAction) {
3223                launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, event.getDeviceId());
3224            }
3225            return -1;
3226        }
3227
3228        // Shortcuts are invoked through Search+key, so intercept those here
3229        // Any printing key that is chorded with Search should be consumed
3230        // even if no shortcut was invoked.  This prevents text from being
3231        // inadvertently inserted when using a keyboard that has built-in macro
3232        // shortcut keys (that emit Search+x) and some of them are not registered.
3233        if (mSearchKeyShortcutPending) {
3234            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3235            if (kcm.isPrintingKey(keyCode)) {
3236                mConsumeSearchKeyUp = true;
3237                mSearchKeyShortcutPending = false;
3238                if (down && repeatCount == 0 && !keyguardOn) {
3239                    Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
3240                    if (shortcutIntent != null) {
3241                        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3242                        try {
3243                            startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3244                        } catch (ActivityNotFoundException ex) {
3245                            Slog.w(TAG, "Dropping shortcut key combination because "
3246                                    + "the activity to which it is registered was not found: "
3247                                    + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
3248                        }
3249                    } else {
3250                        Slog.i(TAG, "Dropping unregistered shortcut key combination: "
3251                                + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
3252                    }
3253                }
3254                return -1;
3255            }
3256        }
3257
3258        // Invoke shortcuts using Meta.
3259        if (down && repeatCount == 0 && !keyguardOn
3260                && (metaState & KeyEvent.META_META_ON) != 0) {
3261            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3262            if (kcm.isPrintingKey(keyCode)) {
3263                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
3264                        metaState & ~(KeyEvent.META_META_ON
3265                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
3266                if (shortcutIntent != null) {
3267                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3268                    try {
3269                        startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3270                    } catch (ActivityNotFoundException ex) {
3271                        Slog.w(TAG, "Dropping shortcut key combination because "
3272                                + "the activity to which it is registered was not found: "
3273                                + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
3274                    }
3275                    return -1;
3276                }
3277            }
3278        }
3279
3280        // Handle application launch keys.
3281        if (down && repeatCount == 0 && !keyguardOn) {
3282            String category = sApplicationLaunchKeyCategories.get(keyCode);
3283            if (category != null) {
3284                Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
3285                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3286                try {
3287                    startActivityAsUser(intent, UserHandle.CURRENT);
3288                } catch (ActivityNotFoundException ex) {
3289                    Slog.w(TAG, "Dropping application launch key because "
3290                            + "the activity to which it is registered was not found: "
3291                            + "keyCode=" + keyCode + ", category=" + category, ex);
3292                }
3293                return -1;
3294            }
3295        }
3296
3297        // Display task switcher for ALT-TAB.
3298        if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
3299            if (mRecentAppsHeldModifiers == 0 && !keyguardOn && isUserSetupComplete()) {
3300                final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
3301                if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)) {
3302                    mRecentAppsHeldModifiers = shiftlessModifiers;
3303                    showRecentApps(true);
3304                    return -1;
3305                }
3306            }
3307        } else if (!down && mRecentAppsHeldModifiers != 0
3308                && (metaState & mRecentAppsHeldModifiers) == 0) {
3309            mRecentAppsHeldModifiers = 0;
3310            hideRecentApps(true, false);
3311        }
3312
3313        // Handle input method switching.
3314        if (down && repeatCount == 0
3315                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3316                        || (keyCode == KeyEvent.KEYCODE_SPACE
3317                                && (metaState & KeyEvent.META_META_MASK) != 0))) {
3318            final boolean forwardDirection = (metaState & KeyEvent.META_SHIFT_MASK) == 0;
3319            mWindowManagerFuncs.switchInputMethod(forwardDirection);
3320            return -1;
3321        }
3322        if (mLanguageSwitchKeyPressed && !down
3323                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3324                        || keyCode == KeyEvent.KEYCODE_SPACE)) {
3325            mLanguageSwitchKeyPressed = false;
3326            return -1;
3327        }
3328
3329        if (isValidGlobalKey(keyCode)
3330                && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
3331            return -1;
3332        }
3333
3334        if (down) {
3335            long shortcutCode = (long) keyCode;
3336            if (event.isCtrlPressed()) {
3337                shortcutCode |= ((long) KeyEvent.META_CTRL_ON) << Integer.SIZE;
3338            }
3339
3340            if (event.isAltPressed()) {
3341                shortcutCode |= ((long) KeyEvent.META_ALT_ON) << Integer.SIZE;
3342            }
3343
3344            if (event.isShiftPressed()) {
3345                shortcutCode |= ((long) KeyEvent.META_SHIFT_ON) << Integer.SIZE;
3346            }
3347
3348            if (event.isMetaPressed()) {
3349                shortcutCode |= ((long) KeyEvent.META_META_ON) << Integer.SIZE;
3350            }
3351
3352            IShortcutService shortcutService = mShortcutKeyServices.get(shortcutCode);
3353            if (shortcutService != null) {
3354                try {
3355                    shortcutService.notifyShortcutKeyPressed(shortcutCode);
3356                } catch (RemoteException e) {
3357                    mShortcutKeyServices.delete(shortcutCode);
3358                }
3359                return -1;
3360            }
3361        }
3362
3363        // Reserve all the META modifier combos for system behavior
3364        if ((metaState & KeyEvent.META_META_ON) != 0) {
3365            return -1;
3366        }
3367
3368        // Let the application handle the key.
3369        return 0;
3370    }
3371
3372    /** {@inheritDoc} */
3373    @Override
3374    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
3375        // Note: This method is only called if the initial down was unhandled.
3376        if (DEBUG_INPUT) {
3377            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
3378                    + ", flags=" + event.getFlags()
3379                    + ", keyCode=" + event.getKeyCode()
3380                    + ", scanCode=" + event.getScanCode()
3381                    + ", metaState=" + event.getMetaState()
3382                    + ", repeatCount=" + event.getRepeatCount()
3383                    + ", policyFlags=" + policyFlags);
3384        }
3385
3386        KeyEvent fallbackEvent = null;
3387        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3388            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3389            final int keyCode = event.getKeyCode();
3390            final int metaState = event.getMetaState();
3391            final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
3392                    && event.getRepeatCount() == 0;
3393
3394            // Check for fallback actions specified by the key character map.
3395            final FallbackAction fallbackAction;
3396            if (initialDown) {
3397                fallbackAction = kcm.getFallbackAction(keyCode, metaState);
3398            } else {
3399                fallbackAction = mFallbackActions.get(keyCode);
3400            }
3401
3402            if (fallbackAction != null) {
3403                if (DEBUG_INPUT) {
3404                    Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
3405                            + " metaState=" + Integer.toHexString(fallbackAction.metaState));
3406                }
3407
3408                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
3409                fallbackEvent = KeyEvent.obtain(
3410                        event.getDownTime(), event.getEventTime(),
3411                        event.getAction(), fallbackAction.keyCode,
3412                        event.getRepeatCount(), fallbackAction.metaState,
3413                        event.getDeviceId(), event.getScanCode(),
3414                        flags, event.getSource(), null);
3415
3416                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
3417                    fallbackEvent.recycle();
3418                    fallbackEvent = null;
3419                }
3420
3421                if (initialDown) {
3422                    mFallbackActions.put(keyCode, fallbackAction);
3423                } else if (event.getAction() == KeyEvent.ACTION_UP) {
3424                    mFallbackActions.remove(keyCode);
3425                    fallbackAction.recycle();
3426                }
3427            }
3428        }
3429
3430        if (DEBUG_INPUT) {
3431            if (fallbackEvent == null) {
3432                Slog.d(TAG, "No fallback.");
3433            } else {
3434                Slog.d(TAG, "Performing fallback: " + fallbackEvent);
3435            }
3436        }
3437        return fallbackEvent;
3438    }
3439
3440    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
3441        int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
3442        if ((actions & ACTION_PASS_TO_USER) != 0) {
3443            long delayMillis = interceptKeyBeforeDispatching(
3444                    win, fallbackEvent, policyFlags);
3445            if (delayMillis == 0) {
3446                return true;
3447            }
3448        }
3449        return false;
3450    }
3451
3452    public void registerShortcutKey(long shortcutCode, IShortcutService shortcutService)
3453            throws RemoteException {
3454        synchronized (mLock) {
3455            IShortcutService service = mShortcutKeyServices.get(shortcutCode);
3456            if (service != null && service.asBinder().pingBinder()) {
3457                throw new RemoteException("Key already exists.");
3458            }
3459
3460            mShortcutKeyServices.put(shortcutCode, shortcutService);
3461        }
3462    }
3463
3464    private void launchAssistLongPressAction() {
3465        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3466        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3467
3468        // launch the search activity
3469        Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
3470        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3471        try {
3472            // TODO: This only stops the factory-installed search manager.
3473            // Need to formalize an API to handle others
3474            SearchManager searchManager = getSearchManager();
3475            if (searchManager != null) {
3476                searchManager.stopSearch();
3477            }
3478            startActivityAsUser(intent, UserHandle.CURRENT);
3479        } catch (ActivityNotFoundException e) {
3480            Slog.w(TAG, "No activity to handle assist long press action.", e);
3481        }
3482    }
3483
3484    private void launchAssistAction(String hint, int deviceId) {
3485        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3486        if (!isUserSetupComplete()) {
3487            // Disable opening assist window during setup
3488            return;
3489        }
3490        Bundle args = null;
3491        if (deviceId > Integer.MIN_VALUE) {
3492            args = new Bundle();
3493            args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
3494        }
3495        if ((mContext.getResources().getConfiguration().uiMode
3496                & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
3497            // On TV, use legacy handling until assistants are implemented in the proper way.
3498            ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
3499                    .launchLegacyAssist(hint, UserHandle.myUserId(), args);
3500        } else {
3501            try {
3502                if (hint != null) {
3503                    if (args == null) {
3504                        args = new Bundle();
3505                    }
3506                    args.putBoolean(hint, true);
3507                }
3508                IStatusBarService statusbar = getStatusBarService();
3509                if (statusbar != null) {
3510                    statusbar.startAssist(args);
3511                }
3512            } catch (RemoteException e) {
3513                Slog.e(TAG, "RemoteException when starting assist", e);
3514                // re-acquire status bar service next time it is needed.
3515                mStatusBarService = null;
3516            }
3517        }
3518    }
3519
3520    private void startActivityAsUser(Intent intent, UserHandle handle) {
3521        if (isUserSetupComplete()) {
3522            mContext.startActivityAsUser(intent, handle);
3523        } else {
3524            Slog.i(TAG, "Not starting activity because user setup is in progress: " + intent);
3525        }
3526    }
3527
3528    private SearchManager getSearchManager() {
3529        if (mSearchManager == null) {
3530            mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
3531        }
3532        return mSearchManager;
3533    }
3534
3535    private void preloadRecentApps() {
3536        mPreloadedRecentApps = true;
3537        try {
3538            IStatusBarService statusbar = getStatusBarService();
3539            if (statusbar != null) {
3540                statusbar.preloadRecentApps();
3541            }
3542        } catch (RemoteException e) {
3543            Slog.e(TAG, "RemoteException when preloading recent apps", e);
3544            // re-acquire status bar service next time it is needed.
3545            mStatusBarService = null;
3546        }
3547    }
3548
3549    private void cancelPreloadRecentApps() {
3550        if (mPreloadedRecentApps) {
3551            mPreloadedRecentApps = false;
3552            try {
3553                IStatusBarService statusbar = getStatusBarService();
3554                if (statusbar != null) {
3555                    statusbar.cancelPreloadRecentApps();
3556                }
3557            } catch (RemoteException e) {
3558                Slog.e(TAG, "RemoteException when cancelling recent apps preload", e);
3559                // re-acquire status bar service next time it is needed.
3560                mStatusBarService = null;
3561            }
3562        }
3563    }
3564
3565    private void toggleRecentApps() {
3566        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3567        try {
3568            IStatusBarService statusbar = getStatusBarService();
3569            if (statusbar != null) {
3570                statusbar.toggleRecentApps();
3571            }
3572        } catch (RemoteException e) {
3573            Slog.e(TAG, "RemoteException when toggling recent apps", e);
3574            // re-acquire status bar service next time it is needed.
3575            mStatusBarService = null;
3576        }
3577    }
3578
3579    @Override
3580    public void showRecentApps() {
3581        mHandler.removeMessages(MSG_DISPATCH_SHOW_RECENTS);
3582        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_RECENTS);
3583    }
3584
3585    private void showRecentApps(boolean triggeredFromAltTab) {
3586        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3587        try {
3588            IStatusBarService statusbar = getStatusBarService();
3589            if (statusbar != null) {
3590                statusbar.showRecentApps(triggeredFromAltTab);
3591            }
3592        } catch (RemoteException e) {
3593            Slog.e(TAG, "RemoteException when showing recent apps", e);
3594            // re-acquire status bar service next time it is needed.
3595            mStatusBarService = null;
3596        }
3597    }
3598
3599    private void toggleKeyboardShortcutsMenu(int deviceId) {
3600        try {
3601            IStatusBarService statusbar = getStatusBarService();
3602            if (statusbar != null) {
3603                statusbar.toggleKeyboardShortcutsMenu(deviceId);
3604            }
3605        } catch (RemoteException e) {
3606            Slog.e(TAG, "RemoteException when showing keyboard shortcuts menu", e);
3607        }
3608    }
3609
3610    private void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHome) {
3611        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3612        try {
3613            IStatusBarService statusbar = getStatusBarService();
3614            if (statusbar != null) {
3615                statusbar.hideRecentApps(triggeredFromAltTab, triggeredFromHome);
3616            }
3617        } catch (RemoteException e) {
3618            Slog.e(TAG, "RemoteException when closing recent apps", e);
3619            // re-acquire status bar service next time it is needed.
3620            mStatusBarService = null;
3621        }
3622    }
3623
3624    void launchHomeFromHotKey() {
3625        launchHomeFromHotKey(true /* awakenFromDreams */, true /*respectKeyguard*/);
3626    }
3627
3628    /**
3629     * A home key -> launch home action was detected.  Take the appropriate action
3630     * given the situation with the keyguard.
3631     */
3632    void launchHomeFromHotKey(final boolean awakenFromDreams, final boolean respectKeyguard) {
3633        if (respectKeyguard) {
3634            if (isKeyguardShowingAndNotOccluded()) {
3635                // don't launch home if keyguard showing
3636                return;
3637            }
3638
3639            if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
3640                // when in keyguard restricted mode, must first verify unlock
3641                // before launching home
3642                mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
3643                    @Override
3644                    public void onKeyguardExitResult(boolean success) {
3645                        if (success) {
3646                            try {
3647                                ActivityManagerNative.getDefault().stopAppSwitches();
3648                            } catch (RemoteException e) {
3649                            }
3650                            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3651                            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3652                        }
3653                    }
3654                });
3655                return;
3656            }
3657        }
3658
3659        // no keyguard stuff to worry about, just launch home!
3660        try {
3661            ActivityManagerNative.getDefault().stopAppSwitches();
3662        } catch (RemoteException e) {
3663        }
3664        if (mRecentsVisible) {
3665            // Hide Recents and notify it to launch Home
3666            if (awakenFromDreams) {
3667                awakenDreams();
3668            }
3669            hideRecentApps(false, true);
3670        } else {
3671            // Otherwise, just launch Home
3672            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3673            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3674        }
3675    }
3676
3677    private final Runnable mClearHideNavigationFlag = new Runnable() {
3678        @Override
3679        public void run() {
3680            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3681                // Clear flags.
3682                mForceClearedSystemUiFlags &=
3683                        ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3684            }
3685            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3686        }
3687    };
3688
3689    /**
3690     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
3691     * to determine when the nav bar should be shown and prevent applications from
3692     * receiving those touches.
3693     */
3694    final class HideNavInputEventReceiver extends InputEventReceiver {
3695        public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
3696            super(inputChannel, looper);
3697        }
3698
3699        @Override
3700        public void onInputEvent(InputEvent event) {
3701            boolean handled = false;
3702            try {
3703                if (event instanceof MotionEvent
3704                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3705                    final MotionEvent motionEvent = (MotionEvent)event;
3706                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
3707                        // When the user taps down, we re-show the nav bar.
3708                        boolean changed = false;
3709                        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3710                            // Any user activity always causes us to show the
3711                            // navigation controls, if they had been hidden.
3712                            // We also clear the low profile and only content
3713                            // flags so that tapping on the screen will atomically
3714                            // restore all currently hidden screen decorations.
3715                            int newVal = mResettingSystemUiFlags |
3716                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3717                                    View.SYSTEM_UI_FLAG_LOW_PROFILE |
3718                                    View.SYSTEM_UI_FLAG_FULLSCREEN;
3719                            if (mResettingSystemUiFlags != newVal) {
3720                                mResettingSystemUiFlags = newVal;
3721                                changed = true;
3722                            }
3723                            // We don't allow the system's nav bar to be hidden
3724                            // again for 1 second, to prevent applications from
3725                            // spamming us and keeping it from being shown.
3726                            newVal = mForceClearedSystemUiFlags |
3727                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3728                            if (mForceClearedSystemUiFlags != newVal) {
3729                                mForceClearedSystemUiFlags = newVal;
3730                                changed = true;
3731                                mHandler.postDelayed(mClearHideNavigationFlag, 1000);
3732                            }
3733                        }
3734                        if (changed) {
3735                            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3736                        }
3737                    }
3738                }
3739            } finally {
3740                finishInputEvent(event, handled);
3741            }
3742        }
3743    }
3744    final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
3745            new InputEventReceiver.Factory() {
3746        @Override
3747        public InputEventReceiver createInputEventReceiver(
3748                InputChannel inputChannel, Looper looper) {
3749            return new HideNavInputEventReceiver(inputChannel, looper);
3750        }
3751    };
3752
3753    @Override
3754    public int adjustSystemUiVisibilityLw(int visibility) {
3755        mStatusBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3756        mNavigationBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3757        mRecentsVisible = (visibility & View.RECENT_APPS_VISIBLE) > 0;
3758
3759        // Reset any bits in mForceClearingStatusBarVisibility that
3760        // are now clear.
3761        mResettingSystemUiFlags &= visibility;
3762        // Clear any bits in the new visibility that are currently being
3763        // force cleared, before reporting it.
3764        return visibility & ~mResettingSystemUiFlags
3765                & ~mForceClearedSystemUiFlags;
3766    }
3767
3768    @Override
3769    public boolean getInsetHintLw(WindowManager.LayoutParams attrs, int displayRotation,
3770            Rect outContentInsets, Rect outStableInsets, Rect outOutsets) {
3771        final int fl = PolicyControl.getWindowFlags(null, attrs);
3772        final int sysuiVis = PolicyControl.getSystemUiVisibility(null, attrs);
3773        final int systemUiVisibility = (sysuiVis | attrs.subtreeSystemUiVisibility);
3774
3775        final boolean useOutsets = outOutsets != null && shouldUseOutsets(attrs, fl);
3776        if (useOutsets) {
3777            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
3778            if (outset > 0) {
3779                if (displayRotation == Surface.ROTATION_0) {
3780                    outOutsets.bottom += outset;
3781                } else if (displayRotation == Surface.ROTATION_90) {
3782                    outOutsets.right += outset;
3783                } else if (displayRotation == Surface.ROTATION_180) {
3784                    outOutsets.top += outset;
3785                } else if (displayRotation == Surface.ROTATION_270) {
3786                    outOutsets.left += outset;
3787                }
3788            }
3789        }
3790
3791        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3792                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3793            int availRight, availBottom;
3794            if (canHideNavigationBar() &&
3795                    (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
3796                availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3797                availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3798            } else {
3799                availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
3800                availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3801            }
3802            if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3803                if ((fl & FLAG_FULLSCREEN) != 0) {
3804                    outContentInsets.set(mStableFullscreenLeft, mStableFullscreenTop,
3805                            availRight - mStableFullscreenRight,
3806                            availBottom - mStableFullscreenBottom);
3807                } else {
3808                    outContentInsets.set(mStableLeft, mStableTop,
3809                            availRight - mStableRight, availBottom - mStableBottom);
3810                }
3811            } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
3812                outContentInsets.setEmpty();
3813            } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
3814                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
3815                outContentInsets.set(mCurLeft, mCurTop,
3816                        availRight - mCurRight, availBottom - mCurBottom);
3817            } else {
3818                outContentInsets.set(mCurLeft, mCurTop,
3819                        availRight - mCurRight, availBottom - mCurBottom);
3820            }
3821
3822            outStableInsets.set(mStableLeft, mStableTop,
3823                    availRight - mStableRight, availBottom - mStableBottom);
3824            return mForceShowSystemBars;
3825        }
3826        outContentInsets.setEmpty();
3827        outStableInsets.setEmpty();
3828        return mForceShowSystemBars;
3829    }
3830
3831    private boolean shouldUseOutsets(WindowManager.LayoutParams attrs, int fl) {
3832        return attrs.type == TYPE_WALLPAPER || (fl & (WindowManager.LayoutParams.FLAG_FULLSCREEN
3833                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN)) != 0;
3834    }
3835
3836    /** {@inheritDoc} */
3837    @Override
3838    public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
3839                              int displayRotation, int uiMode) {
3840        mDisplayRotation = displayRotation;
3841        final int overscanLeft, overscanTop, overscanRight, overscanBottom;
3842        if (isDefaultDisplay) {
3843            switch (displayRotation) {
3844                case Surface.ROTATION_90:
3845                    overscanLeft = mOverscanTop;
3846                    overscanTop = mOverscanRight;
3847                    overscanRight = mOverscanBottom;
3848                    overscanBottom = mOverscanLeft;
3849                    break;
3850                case Surface.ROTATION_180:
3851                    overscanLeft = mOverscanRight;
3852                    overscanTop = mOverscanBottom;
3853                    overscanRight = mOverscanLeft;
3854                    overscanBottom = mOverscanTop;
3855                    break;
3856                case Surface.ROTATION_270:
3857                    overscanLeft = mOverscanBottom;
3858                    overscanTop = mOverscanLeft;
3859                    overscanRight = mOverscanTop;
3860                    overscanBottom = mOverscanRight;
3861                    break;
3862                default:
3863                    overscanLeft = mOverscanLeft;
3864                    overscanTop = mOverscanTop;
3865                    overscanRight = mOverscanRight;
3866                    overscanBottom = mOverscanBottom;
3867                    break;
3868            }
3869        } else {
3870            overscanLeft = 0;
3871            overscanTop = 0;
3872            overscanRight = 0;
3873            overscanBottom = 0;
3874        }
3875        mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
3876        mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
3877        mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
3878        mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
3879        mSystemLeft = 0;
3880        mSystemTop = 0;
3881        mSystemRight = displayWidth;
3882        mSystemBottom = displayHeight;
3883        mUnrestrictedScreenLeft = overscanLeft;
3884        mUnrestrictedScreenTop = overscanTop;
3885        mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
3886        mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
3887        mRestrictedScreenLeft = mUnrestrictedScreenLeft;
3888        mRestrictedScreenTop = mUnrestrictedScreenTop;
3889        mRestrictedScreenWidth = mSystemGestures.screenWidth = mUnrestrictedScreenWidth;
3890        mRestrictedScreenHeight = mSystemGestures.screenHeight = mUnrestrictedScreenHeight;
3891        mDockLeft = mContentLeft = mVoiceContentLeft = mStableLeft = mStableFullscreenLeft
3892                = mCurLeft = mUnrestrictedScreenLeft;
3893        mDockTop = mContentTop = mVoiceContentTop = mStableTop = mStableFullscreenTop
3894                = mCurTop = mUnrestrictedScreenTop;
3895        mDockRight = mContentRight = mVoiceContentRight = mStableRight = mStableFullscreenRight
3896                = mCurRight = displayWidth - overscanRight;
3897        mDockBottom = mContentBottom = mVoiceContentBottom = mStableBottom = mStableFullscreenBottom
3898                = mCurBottom = displayHeight - overscanBottom;
3899        mDockLayer = 0x10000000;
3900        mStatusBarLayer = -1;
3901
3902        // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
3903        final Rect pf = mTmpParentFrame;
3904        final Rect df = mTmpDisplayFrame;
3905        final Rect of = mTmpOverscanFrame;
3906        final Rect vf = mTmpVisibleFrame;
3907        final Rect dcf = mTmpDecorFrame;
3908        pf.left = df.left = of.left = vf.left = mDockLeft;
3909        pf.top = df.top = of.top = vf.top = mDockTop;
3910        pf.right = df.right = of.right = vf.right = mDockRight;
3911        pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
3912        dcf.setEmpty();  // Decor frame N/A for system bars.
3913
3914        if (isDefaultDisplay) {
3915            // For purposes of putting out fake window up to steal focus, we will
3916            // drive nav being hidden only by whether it is requested.
3917            final int sysui = mLastSystemUiFlags;
3918            boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
3919            boolean navTranslucent = (sysui
3920                    & (View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT)) != 0;
3921            boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
3922            boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
3923            boolean navAllowedHidden = immersive || immersiveSticky;
3924            navTranslucent &= !immersiveSticky;  // transient trumps translucent
3925            boolean isKeyguardShowing = isStatusBarKeyguard() && !mHideLockScreen;
3926            if (!isKeyguardShowing) {
3927                navTranslucent &= areTranslucentBarsAllowed();
3928            }
3929
3930            // When the navigation bar isn't visible, we put up a fake
3931            // input window to catch all touch events.  This way we can
3932            // detect when the user presses anywhere to bring back the nav
3933            // bar and ensure the application doesn't see the event.
3934            if (navVisible || navAllowedHidden) {
3935                if (mInputConsumer != null) {
3936                    mInputConsumer.dismiss();
3937                    mInputConsumer = null;
3938                }
3939            } else if (mInputConsumer == null) {
3940                mInputConsumer = mWindowManagerFuncs.addInputConsumer(mHandler.getLooper(),
3941                        mHideNavInputEventReceiverFactory);
3942            }
3943
3944            // For purposes of positioning and showing the nav bar, if we have
3945            // decided that it can't be hidden (because of the screen aspect ratio),
3946            // then take that into account.
3947            navVisible |= !canHideNavigationBar();
3948
3949            boolean updateSysUiVisibility = layoutNavigationBar(displayWidth, displayHeight,
3950                    displayRotation, uiMode, overscanRight, overscanBottom, dcf, navVisible, navTranslucent,
3951                    navAllowedHidden);
3952            if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
3953                    mDockLeft, mDockTop, mDockRight, mDockBottom));
3954            updateSysUiVisibility |= layoutStatusBar(pf, df, of, vf, dcf, sysui, isKeyguardShowing);
3955            if (updateSysUiVisibility) {
3956                updateSystemUiVisibilityLw();
3957            }
3958        }
3959    }
3960
3961    private boolean layoutStatusBar(Rect pf, Rect df, Rect of, Rect vf, Rect dcf, int sysui,
3962            boolean isKeyguardShowing) {
3963        // decide where the status bar goes ahead of time
3964        if (mStatusBar != null) {
3965            // apply any navigation bar insets
3966            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3967            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3968            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
3969            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
3970                    + mUnrestrictedScreenTop;
3971            vf.left = mStableLeft;
3972            vf.top = mStableTop;
3973            vf.right = mStableRight;
3974            vf.bottom = mStableBottom;
3975
3976            mStatusBarLayer = mStatusBar.getSurfaceLayer();
3977
3978            // Let the status bar determine its size.
3979            mStatusBar.computeFrameLw(pf /* parentFrame */, df /* displayFrame */,
3980                    vf /* overlayFrame */, vf /* contentFrame */, vf /* visibleFrame */,
3981                    dcf /* decorFrame */, vf /* stableFrame */, vf /* outsetFrame */);
3982
3983            // For layout, the status bar is always at the top with our fixed height.
3984            mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
3985
3986            boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
3987            boolean statusBarTranslucent = (sysui
3988                    & (View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT)) != 0;
3989            if (!isKeyguardShowing) {
3990                statusBarTranslucent &= areTranslucentBarsAllowed();
3991            }
3992
3993            // If the status bar is hidden, we don't want to cause
3994            // windows behind it to scroll.
3995            if (mStatusBar.isVisibleLw() && !statusBarTransient) {
3996                // Status bar may go away, so the screen area it occupies
3997                // is available to apps but just covering them when the
3998                // status bar is visible.
3999                mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
4000
4001                mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4002                mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4003                mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4004                mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4005
4006                if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
4007                        String.format(
4008                                "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
4009                                mDockLeft, mDockTop, mDockRight, mDockBottom,
4010                                mContentLeft, mContentTop, mContentRight, mContentBottom,
4011                                mCurLeft, mCurTop, mCurRight, mCurBottom));
4012            }
4013            if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
4014                    && !statusBarTransient && !statusBarTranslucent
4015                    && !mStatusBarController.wasRecentlyTranslucent()) {
4016                // If the opaque status bar is currently requested to be visible,
4017                // and not in the process of animating on or off, then
4018                // we can tell the app that it is covered by it.
4019                mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
4020            }
4021            if (mStatusBarController.checkHiddenLw()) {
4022                return true;
4023            }
4024        }
4025        return false;
4026    }
4027
4028    private boolean layoutNavigationBar(int displayWidth, int displayHeight, int displayRotation,
4029            int uiMode, int overscanRight, int overscanBottom, Rect dcf, boolean navVisible,
4030            boolean navTranslucent, boolean navAllowedHidden) {
4031        if (mNavigationBar != null) {
4032            boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
4033            // Force the navigation bar to its appropriate place and
4034            // size.  We need to do this directly, instead of relying on
4035            // it to bubble up from the nav bar, because this needs to
4036            // change atomically with screen rotations.
4037            mNavigationBarOnBottom = isNavigationBarOnBottom(displayWidth, displayHeight);
4038            if (mNavigationBarOnBottom) {
4039                // It's a system nav bar or a portrait screen; nav bar goes on bottom.
4040                int top = displayHeight - overscanBottom
4041                        - getNavigationBarHeight(displayRotation, uiMode);
4042                mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
4043                mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
4044                if (transientNavBarShowing) {
4045                    mNavigationBarController.setBarShowingLw(true);
4046                } else if (navVisible) {
4047                    mNavigationBarController.setBarShowingLw(true);
4048                    mDockBottom = mTmpNavigationFrame.top;
4049                    mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
4050                    mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
4051                } else {
4052                    // We currently want to hide the navigation UI.
4053                    mNavigationBarController.setBarShowingLw(false);
4054                }
4055                if (navVisible && !navTranslucent && !navAllowedHidden
4056                        && !mNavigationBar.isAnimatingLw()
4057                        && !mNavigationBarController.wasRecentlyTranslucent()) {
4058                    // If the opaque nav bar is currently requested to be visible,
4059                    // and not in the process of animating on or off, then
4060                    // we can tell the app that it is covered by it.
4061                    mSystemBottom = mTmpNavigationFrame.top;
4062                }
4063            } else {
4064                // Landscape screen; nav bar goes to the right.
4065                int left = displayWidth - overscanRight
4066                        - getNavigationBarWidth(displayRotation, uiMode);
4067                mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
4068                mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
4069                if (transientNavBarShowing) {
4070                    mNavigationBarController.setBarShowingLw(true);
4071                } else if (navVisible) {
4072                    mNavigationBarController.setBarShowingLw(true);
4073                    mDockRight = mTmpNavigationFrame.left;
4074                    mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
4075                    mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
4076                } else {
4077                    // We currently want to hide the navigation UI.
4078                    mNavigationBarController.setBarShowingLw(false);
4079                }
4080                if (navVisible && !navTranslucent && !navAllowedHidden
4081                        && !mNavigationBar.isAnimatingLw()
4082                        && !mNavigationBarController.wasRecentlyTranslucent()) {
4083                    // If the nav bar is currently requested to be visible,
4084                    // and not in the process of animating on or off, then
4085                    // we can tell the app that it is covered by it.
4086                    mSystemRight = mTmpNavigationFrame.left;
4087                }
4088            }
4089            // Make sure the content and current rectangles are updated to
4090            // account for the restrictions from the navigation bar.
4091            mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4092            mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4093            mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4094            mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4095            mStatusBarLayer = mNavigationBar.getSurfaceLayer();
4096            // And compute the final frame.
4097            mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
4098                    mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf,
4099                    mTmpNavigationFrame, mTmpNavigationFrame);
4100            if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
4101            if (mNavigationBarController.checkHiddenLw()) {
4102                return true;
4103            }
4104        }
4105        return false;
4106    }
4107
4108    private boolean isNavigationBarOnBottom(int displayWidth, int displayHeight) {
4109        return !mNavigationBarCanMove || displayWidth < displayHeight;
4110    }
4111
4112    /** {@inheritDoc} */
4113    @Override
4114    public int getSystemDecorLayerLw() {
4115        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
4116            return mStatusBar.getSurfaceLayer();
4117        }
4118
4119        if (mNavigationBar != null && mNavigationBar.isVisibleLw()) {
4120            return mNavigationBar.getSurfaceLayer();
4121        }
4122
4123        return 0;
4124    }
4125
4126    @Override
4127    public void getContentRectLw(Rect r) {
4128        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
4129    }
4130
4131    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
4132            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
4133        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
4134            // Here's a special case: if this attached window is a panel that is
4135            // above the dock window, and the window it is attached to is below
4136            // the dock window, then the frames we computed for the window it is
4137            // attached to can not be used because the dock is effectively part
4138            // of the underlying window and the attached window is floating on top
4139            // of the whole thing.  So, we ignore the attached window and explicitly
4140            // compute the frames that would be appropriate without the dock.
4141            df.left = of.left = cf.left = vf.left = mDockLeft;
4142            df.top = of.top = cf.top = vf.top = mDockTop;
4143            df.right = of.right = cf.right = vf.right = mDockRight;
4144            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
4145        } else {
4146            // The effective display frame of the attached window depends on
4147            // whether it is taking care of insetting its content.  If not,
4148            // we need to use the parent's content frame so that the entire
4149            // window is positioned within that content.  Otherwise we can use
4150            // the overscan frame and let the attached window take care of
4151            // positioning its content appropriately.
4152            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4153                // Set the content frame of the attached window to the parent's decor frame
4154                // (same as content frame when IME isn't present) if specifically requested by
4155                // setting {@link WindowManager.LayoutParams#FLAG_LAYOUT_ATTACHED_IN_DECOR} flag.
4156                // Otherwise, use the overscan frame.
4157                cf.set((fl & FLAG_LAYOUT_ATTACHED_IN_DECOR) != 0
4158                        ? attached.getContentFrameLw() : attached.getOverscanFrameLw());
4159            } else {
4160                // If the window is resizing, then we want to base the content
4161                // frame on our attached content frame to resize...  however,
4162                // things can be tricky if the attached window is NOT in resize
4163                // mode, in which case its content frame will be larger.
4164                // Ungh.  So to deal with that, make sure the content frame
4165                // we end up using is not covering the IM dock.
4166                cf.set(attached.getContentFrameLw());
4167                if (attached.isVoiceInteraction()) {
4168                    if (cf.left < mVoiceContentLeft) cf.left = mVoiceContentLeft;
4169                    if (cf.top < mVoiceContentTop) cf.top = mVoiceContentTop;
4170                    if (cf.right > mVoiceContentRight) cf.right = mVoiceContentRight;
4171                    if (cf.bottom > mVoiceContentBottom) cf.bottom = mVoiceContentBottom;
4172                } else if (attached.getSurfaceLayer() < mDockLayer) {
4173                    if (cf.left < mContentLeft) cf.left = mContentLeft;
4174                    if (cf.top < mContentTop) cf.top = mContentTop;
4175                    if (cf.right > mContentRight) cf.right = mContentRight;
4176                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
4177                }
4178            }
4179            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
4180            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
4181            vf.set(attached.getVisibleFrameLw());
4182        }
4183        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
4184        // window should be positioned relative to its parent or the entire
4185        // screen.
4186        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
4187                ? attached.getFrameLw() : df);
4188    }
4189
4190    private void applyStableConstraints(int sysui, int fl, Rect r) {
4191        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
4192            // If app is requesting a stable layout, don't let the
4193            // content insets go below the stable values.
4194            if ((fl & FLAG_FULLSCREEN) != 0) {
4195                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
4196                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
4197                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
4198                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
4199            } else {
4200                if (r.left < mStableLeft) r.left = mStableLeft;
4201                if (r.top < mStableTop) r.top = mStableTop;
4202                if (r.right > mStableRight) r.right = mStableRight;
4203                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
4204            }
4205        }
4206    }
4207
4208    private boolean canReceiveInput(WindowState win) {
4209        boolean notFocusable =
4210                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0;
4211        boolean altFocusableIm =
4212                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0;
4213        boolean notFocusableForIm = notFocusable ^ altFocusableIm;
4214        return !notFocusableForIm;
4215    }
4216
4217    /** {@inheritDoc} */
4218    @Override
4219    public void layoutWindowLw(WindowState win, WindowState attached) {
4220        // We've already done the navigation bar and status bar. If the status bar can receive
4221        // input, we need to layout it again to accomodate for the IME window.
4222        if ((win == mStatusBar && !canReceiveInput(win)) || win == mNavigationBar) {
4223            return;
4224        }
4225        final WindowManager.LayoutParams attrs = win.getAttrs();
4226        final boolean isDefaultDisplay = win.isDefaultDisplay();
4227        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
4228                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
4229        if (needsToOffsetInputMethodTarget) {
4230            if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
4231            offsetInputMethodWindowLw(mLastInputMethodWindow);
4232        }
4233
4234        final int fl = PolicyControl.getWindowFlags(win, attrs);
4235        final int sim = attrs.softInputMode;
4236        final int sysUiFl = PolicyControl.getSystemUiVisibility(win, null);
4237
4238        final Rect pf = mTmpParentFrame;
4239        final Rect df = mTmpDisplayFrame;
4240        final Rect of = mTmpOverscanFrame;
4241        final Rect cf = mTmpContentFrame;
4242        final Rect vf = mTmpVisibleFrame;
4243        final Rect dcf = mTmpDecorFrame;
4244        final Rect sf = mTmpStableFrame;
4245        Rect osf = null;
4246        dcf.setEmpty();
4247
4248        final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
4249                && mNavigationBar != null && mNavigationBar.isVisibleLw());
4250
4251        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
4252
4253        if (isDefaultDisplay) {
4254            sf.set(mStableLeft, mStableTop, mStableRight, mStableBottom);
4255        } else {
4256            sf.set(mOverscanLeft, mOverscanTop, mOverscanRight, mOverscanBottom);
4257        }
4258
4259        if (!isDefaultDisplay) {
4260            if (attached != null) {
4261                // If this window is attached to another, our display
4262                // frame is the same as the one we are attached to.
4263                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4264            } else {
4265                // Give the window full screen.
4266                pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4267                pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4268                pf.right = df.right = of.right = cf.right
4269                        = mOverscanScreenLeft + mOverscanScreenWidth;
4270                pf.bottom = df.bottom = of.bottom = cf.bottom
4271                        = mOverscanScreenTop + mOverscanScreenHeight;
4272            }
4273        } else if (attrs.type == TYPE_INPUT_METHOD) {
4274            pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
4275            pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
4276            pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
4277            // IM dock windows layout below the nav bar...
4278            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4279            // ...with content insets above the nav bar
4280            cf.bottom = vf.bottom = mStableBottom;
4281            // IM dock windows always go to the bottom of the screen.
4282            attrs.gravity = Gravity.BOTTOM;
4283            mDockLayer = win.getSurfaceLayer();
4284        } else if (attrs.type == TYPE_VOICE_INTERACTION) {
4285            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4286            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4287            pf.right = df.right = of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4288            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4289            cf.bottom = vf.bottom = mStableBottom;
4290            // Note: In Phone landscape mode, the button bar should also be excluded.
4291            cf.right = vf.right = mStableRight;
4292            cf.left = vf.left = mStableLeft;
4293            cf.top = vf.top = mStableTop;
4294        } else if (win == mStatusBar) {
4295            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4296            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4297            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
4298            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight + mUnrestrictedScreenTop;
4299            cf.left = vf.left = mStableLeft;
4300            cf.top = vf.top = mStableTop;
4301            cf.right = vf.right = mStableRight;
4302            vf.bottom = mStableBottom;
4303
4304            if (adjust == SOFT_INPUT_ADJUST_RESIZE) {
4305                cf.bottom = mContentBottom;
4306            } else {
4307                cf.bottom = mDockBottom;
4308                vf.bottom = mContentBottom;
4309            }
4310        } else {
4311
4312            // Default policy decor for the default display
4313            dcf.left = mSystemLeft;
4314            dcf.top = mSystemTop;
4315            dcf.right = mSystemRight;
4316            dcf.bottom = mSystemBottom;
4317            final boolean inheritTranslucentDecor = (attrs.privateFlags
4318                    & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
4319            final boolean isAppWindow =
4320                    attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
4321                    attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
4322            final boolean topAtRest =
4323                    win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
4324            if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
4325                if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
4326                        && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
4327                        && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0
4328                        && (fl & WindowManager.LayoutParams.
4329                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0
4330                        && !mForceWindowDrawsStatusBarBackground) {
4331                    // Ensure policy decor includes status bar
4332                    dcf.top = mStableTop;
4333                }
4334                if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
4335                        && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
4336                        && (fl & WindowManager.LayoutParams.
4337                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
4338                    // Ensure policy decor includes navigation bar
4339                    dcf.bottom = mStableBottom;
4340                    dcf.right = mStableRight;
4341                }
4342            }
4343
4344            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
4345                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
4346                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
4347                            + "): IN_SCREEN, INSET_DECOR");
4348                // This is the case for a normal activity window: we want it
4349                // to cover all of the screen space, and it can take care of
4350                // moving its contents to account for screen decorations that
4351                // intrude into that space.
4352                if (attached != null) {
4353                    // If this window is attached to another, our display
4354                    // frame is the same as the one we are attached to.
4355                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4356                } else {
4357                    if (attrs.type == TYPE_STATUS_BAR_PANEL
4358                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
4359                        // Status bar panels are the only windows who can go on top of
4360                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
4361                        // permission, so they have the same privileges as the status
4362                        // bar itself.
4363                        //
4364                        // However, they should still dodge the navigation bar if it exists.
4365
4366                        pf.left = df.left = of.left = hasNavBar
4367                                ? mDockLeft : mUnrestrictedScreenLeft;
4368                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
4369                        pf.right = df.right = of.right = hasNavBar
4370                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
4371                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4372                        pf.bottom = df.bottom = of.bottom = hasNavBar
4373                                ? mRestrictedScreenTop+mRestrictedScreenHeight
4374                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4375
4376                        if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4377                                        "Laying out status bar window: (%d,%d - %d,%d)",
4378                                        pf.left, pf.top, pf.right, pf.bottom));
4379                    } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4380                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4381                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4382                        // Asking to layout into the overscan region, so give it that pure
4383                        // unrestricted area.
4384                        pf.left = df.left = of.left = mOverscanScreenLeft;
4385                        pf.top = df.top = of.top = mOverscanScreenTop;
4386                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
4387                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
4388                                + mOverscanScreenHeight;
4389                    } else if (canHideNavigationBar()
4390                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4391                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4392                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4393                        // Asking for layout as if the nav bar is hidden, lets the
4394                        // application extend into the unrestricted overscan screen area.  We
4395                        // only do this for application windows to ensure no window that
4396                        // can be above the nav bar can do this.
4397                        pf.left = df.left = mOverscanScreenLeft;
4398                        pf.top = df.top = mOverscanScreenTop;
4399                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4400                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4401                        // We need to tell the app about where the frame inside the overscan
4402                        // is, so it can inset its content by that amount -- it didn't ask
4403                        // to actually extend itself into the overscan region.
4404                        of.left = mUnrestrictedScreenLeft;
4405                        of.top = mUnrestrictedScreenTop;
4406                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4407                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4408                    } else {
4409                        pf.left = df.left = mRestrictedOverscanScreenLeft;
4410                        pf.top = df.top = mRestrictedOverscanScreenTop;
4411                        pf.right = df.right = mRestrictedOverscanScreenLeft
4412                                + mRestrictedOverscanScreenWidth;
4413                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
4414                                + mRestrictedOverscanScreenHeight;
4415                        // We need to tell the app about where the frame inside the overscan
4416                        // is, so it can inset its content by that amount -- it didn't ask
4417                        // to actually extend itself into the overscan region.
4418                        of.left = mUnrestrictedScreenLeft;
4419                        of.top = mUnrestrictedScreenTop;
4420                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4421                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4422                    }
4423
4424                    if ((fl & FLAG_FULLSCREEN) == 0) {
4425                        if (win.isVoiceInteraction()) {
4426                            cf.left = mVoiceContentLeft;
4427                            cf.top = mVoiceContentTop;
4428                            cf.right = mVoiceContentRight;
4429                            cf.bottom = mVoiceContentBottom;
4430                        } else {
4431                            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4432                                cf.left = mDockLeft;
4433                                cf.top = mDockTop;
4434                                cf.right = mDockRight;
4435                                cf.bottom = mDockBottom;
4436                            } else {
4437                                cf.left = mContentLeft;
4438                                cf.top = mContentTop;
4439                                cf.right = mContentRight;
4440                                cf.bottom = mContentBottom;
4441                            }
4442                        }
4443                    } else {
4444                        // Full screen windows are always given a layout that is as if the
4445                        // status bar and other transient decors are gone.  This is to avoid
4446                        // bad states when moving from a window that is not hding the
4447                        // status bar to one that is.
4448                        cf.left = mRestrictedScreenLeft;
4449                        cf.top = mRestrictedScreenTop;
4450                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4451                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
4452                    }
4453                    applyStableConstraints(sysUiFl, fl, cf);
4454                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4455                        vf.left = mCurLeft;
4456                        vf.top = mCurTop;
4457                        vf.right = mCurRight;
4458                        vf.bottom = mCurBottom;
4459                    } else {
4460                        vf.set(cf);
4461                    }
4462                }
4463            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
4464                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
4465                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
4466                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4467                        "): IN_SCREEN");
4468                // A window that has requested to fill the entire screen just
4469                // gets everything, period.
4470                if (attrs.type == TYPE_STATUS_BAR_PANEL
4471                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL
4472                        || attrs.type == TYPE_VOLUME_OVERLAY) {
4473                    pf.left = df.left = of.left = cf.left = hasNavBar
4474                            ? mDockLeft : mUnrestrictedScreenLeft;
4475                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4476                    pf.right = df.right = of.right = cf.right = hasNavBar
4477                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
4478                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4479                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
4480                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
4481                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4482                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4483                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
4484                                    pf.left, pf.top, pf.right, pf.bottom));
4485                } else if (attrs.type == TYPE_NAVIGATION_BAR
4486                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
4487                    // The navigation bar has Real Ultimate Power.
4488                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4489                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
4490                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
4491                            + mUnrestrictedScreenWidth;
4492                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
4493                            + mUnrestrictedScreenHeight;
4494                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4495                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
4496                                    pf.left, pf.top, pf.right, pf.bottom));
4497                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
4498                                || attrs.type == TYPE_BOOT_PROGRESS
4499                                || attrs.type == TYPE_SCREENSHOT)
4500                        && ((fl & FLAG_FULLSCREEN) != 0)) {
4501                    // Fullscreen secure system overlays get what they ask for. Screenshot region
4502                    // selection overlay should also expand to full screen.
4503                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4504                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4505                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4506                            + mOverscanScreenWidth;
4507                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4508                            + mOverscanScreenHeight;
4509                } else if (attrs.type == TYPE_BOOT_PROGRESS) {
4510                    // Boot progress screen always covers entire display.
4511                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4512                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4513                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4514                            + mOverscanScreenWidth;
4515                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4516                            + mOverscanScreenHeight;
4517                } else if (attrs.type == TYPE_WALLPAPER) {
4518                    // The wallpaper also has Real Ultimate Power, but we want to tell
4519                    // it about the overscan area.
4520                    pf.left = df.left = mOverscanScreenLeft;
4521                    pf.top = df.top = mOverscanScreenTop;
4522                    pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4523                    pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4524                    of.left = cf.left = mUnrestrictedScreenLeft;
4525                    of.top = cf.top = mUnrestrictedScreenTop;
4526                    of.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4527                    of.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4528                } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4529                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4530                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4531                    // Asking to layout into the overscan region, so give it that pure
4532                    // unrestricted area.
4533                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4534                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4535                    pf.right = df.right = of.right = cf.right
4536                            = mOverscanScreenLeft + mOverscanScreenWidth;
4537                    pf.bottom = df.bottom = of.bottom = cf.bottom
4538                            = mOverscanScreenTop + mOverscanScreenHeight;
4539                } else if (canHideNavigationBar()
4540                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4541                        && (attrs.type == TYPE_STATUS_BAR
4542                            || attrs.type == TYPE_TOAST
4543                            || attrs.type == TYPE_DOCK_DIVIDER
4544                            || attrs.type == TYPE_VOICE_INTERACTION_STARTING
4545                            || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4546                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
4547                    // Asking for layout as if the nav bar is hidden, lets the
4548                    // application extend into the unrestricted screen area.  We
4549                    // only do this for application windows (or toasts) to ensure no window that
4550                    // can be above the nav bar can do this.
4551                    // XXX This assumes that an app asking for this will also
4552                    // ask for layout in only content.  We can't currently figure out
4553                    // what the screen would be if only laying out to hide the nav bar.
4554                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
4555                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4556                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
4557                            + mUnrestrictedScreenWidth;
4558                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
4559                            + mUnrestrictedScreenHeight;
4560                } else if ((sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0) {
4561                    pf.left = df.left = of.left = mRestrictedScreenLeft;
4562                    pf.top = df.top = of.top  = mRestrictedScreenTop;
4563                    pf.right = df.right = of.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4564                    pf.bottom = df.bottom = of.bottom = mRestrictedScreenTop
4565                            + mRestrictedScreenHeight;
4566                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4567                        cf.left = mDockLeft;
4568                        cf.top = mDockTop;
4569                        cf.right = mDockRight;
4570                        cf.bottom = mDockBottom;
4571                    } else {
4572                        cf.left = mContentLeft;
4573                        cf.top = mContentTop;
4574                        cf.right = mContentRight;
4575                        cf.bottom = mContentBottom;
4576                    }
4577                } else {
4578                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4579                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4580                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4581                            + mRestrictedScreenWidth;
4582                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4583                            + mRestrictedScreenHeight;
4584                }
4585
4586                applyStableConstraints(sysUiFl, fl, cf);
4587
4588                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4589                    vf.left = mCurLeft;
4590                    vf.top = mCurTop;
4591                    vf.right = mCurRight;
4592                    vf.bottom = mCurBottom;
4593                } else {
4594                    vf.set(cf);
4595                }
4596            } else if (attached != null) {
4597                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4598                        "): attached to " + attached);
4599                // A child window should be placed inside of the same visible
4600                // frame that its parent had.
4601                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
4602            } else {
4603                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4604                        "): normal window");
4605                // Otherwise, a normal window must be placed inside the content
4606                // of all screen decorations.
4607                if (attrs.type == TYPE_STATUS_BAR_PANEL || attrs.type == TYPE_VOLUME_OVERLAY) {
4608                    // Status bar panels and the volume dialog are the only windows who can go on
4609                    // top of the status bar.  They are protected by the STATUS_BAR_SERVICE
4610                    // permission, so they have the same privileges as the status
4611                    // bar itself.
4612                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4613                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4614                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4615                            + mRestrictedScreenWidth;
4616                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4617                            + mRestrictedScreenHeight;
4618                } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT) {
4619                    // These dialogs are stable to interim decor changes.
4620                    pf.left = df.left = of.left = cf.left = mStableLeft;
4621                    pf.top = df.top = of.top = cf.top = mStableTop;
4622                    pf.right = df.right = of.right = cf.right = mStableRight;
4623                    pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
4624                } else {
4625                    pf.left = mContentLeft;
4626                    pf.top = mContentTop;
4627                    pf.right = mContentRight;
4628                    pf.bottom = mContentBottom;
4629                    if (win.isVoiceInteraction()) {
4630                        df.left = of.left = cf.left = mVoiceContentLeft;
4631                        df.top = of.top = cf.top = mVoiceContentTop;
4632                        df.right = of.right = cf.right = mVoiceContentRight;
4633                        df.bottom = of.bottom = cf.bottom = mVoiceContentBottom;
4634                    } else if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4635                        df.left = of.left = cf.left = mDockLeft;
4636                        df.top = of.top = cf.top = mDockTop;
4637                        df.right = of.right = cf.right = mDockRight;
4638                        df.bottom = of.bottom = cf.bottom = mDockBottom;
4639                    } else {
4640                        df.left = of.left = cf.left = mContentLeft;
4641                        df.top = of.top = cf.top = mContentTop;
4642                        df.right = of.right = cf.right = mContentRight;
4643                        df.bottom = of.bottom = cf.bottom = mContentBottom;
4644                    }
4645                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4646                        vf.left = mCurLeft;
4647                        vf.top = mCurTop;
4648                        vf.right = mCurRight;
4649                        vf.bottom = mCurBottom;
4650                    } else {
4651                        vf.set(cf);
4652                    }
4653                }
4654            }
4655        }
4656
4657        // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
4658        // Also, we don't allow windows in multi-window mode to extend out of the screen.
4659        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR
4660                && !win.isInMultiWindowMode()) {
4661            df.left = df.top = -10000;
4662            df.right = df.bottom = 10000;
4663            if (attrs.type != TYPE_WALLPAPER) {
4664                of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
4665                of.right = of.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
4666            }
4667        }
4668
4669        // If the device has a chin (e.g. some watches), a dead area at the bottom of the screen we
4670        // need to provide information to the clients that want to pretend that you can draw there.
4671        // We only want to apply outsets to certain types of windows. For example, we never want to
4672        // apply the outsets to floating dialogs, because they wouldn't make sense there.
4673        final boolean useOutsets = shouldUseOutsets(attrs, fl);
4674        if (isDefaultDisplay && useOutsets) {
4675            osf = mTmpOutsetFrame;
4676            osf.set(cf.left, cf.top, cf.right, cf.bottom);
4677            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
4678            if (outset > 0) {
4679                int rotation = mDisplayRotation;
4680                if (rotation == Surface.ROTATION_0) {
4681                    osf.bottom += outset;
4682                } else if (rotation == Surface.ROTATION_90) {
4683                    osf.right += outset;
4684                } else if (rotation == Surface.ROTATION_180) {
4685                    osf.top -= outset;
4686                } else if (rotation == Surface.ROTATION_270) {
4687                    osf.left -= outset;
4688                }
4689                if (DEBUG_LAYOUT) Slog.v(TAG, "applying bottom outset of " + outset
4690                        + " with rotation " + rotation + ", result: " + osf);
4691            }
4692        }
4693
4694        if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
4695                + ": sim=#" + Integer.toHexString(sim)
4696                + " attach=" + attached + " type=" + attrs.type
4697                + String.format(" flags=0x%08x", fl)
4698                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
4699                + " of=" + of.toShortString()
4700                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
4701                + " dcf=" + dcf.toShortString()
4702                + " sf=" + sf.toShortString()
4703                + " osf=" + (osf == null ? "null" : osf.toShortString()));
4704
4705        win.computeFrameLw(pf, df, of, cf, vf, dcf, sf, osf);
4706
4707        // Dock windows carve out the bottom of the screen, so normal windows
4708        // can't appear underneath them.
4709        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
4710                && !win.getGivenInsetsPendingLw()) {
4711            setLastInputMethodWindowLw(null, null);
4712            offsetInputMethodWindowLw(win);
4713        }
4714        if (attrs.type == TYPE_VOICE_INTERACTION && win.isVisibleOrBehindKeyguardLw()
4715                && !win.getGivenInsetsPendingLw()) {
4716            offsetVoiceInputWindowLw(win);
4717        }
4718    }
4719
4720    private void offsetInputMethodWindowLw(WindowState win) {
4721        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4722        top += win.getGivenContentInsetsLw().top;
4723        if (mContentBottom > top) {
4724            mContentBottom = top;
4725        }
4726        if (mVoiceContentBottom > top) {
4727            mVoiceContentBottom = top;
4728        }
4729        top = win.getVisibleFrameLw().top;
4730        top += win.getGivenVisibleInsetsLw().top;
4731        if (mCurBottom > top) {
4732            mCurBottom = top;
4733        }
4734        if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
4735                + mDockBottom + " mContentBottom="
4736                + mContentBottom + " mCurBottom=" + mCurBottom);
4737    }
4738
4739    private void offsetVoiceInputWindowLw(WindowState win) {
4740        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4741        top += win.getGivenContentInsetsLw().top;
4742        if (mVoiceContentBottom > top) {
4743            mVoiceContentBottom = top;
4744        }
4745    }
4746
4747    /** {@inheritDoc} */
4748    @Override
4749    public void finishLayoutLw() {
4750        return;
4751    }
4752
4753    /** {@inheritDoc} */
4754    @Override
4755    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
4756        mTopFullscreenOpaqueWindowState = null;
4757        mTopFullscreenOpaqueOrDimmingWindowState = null;
4758        mTopDockedOpaqueWindowState = null;
4759        mTopDockedOpaqueOrDimmingWindowState = null;
4760        mAppsToBeHidden.clear();
4761        mAppsThatDismissKeyguard.clear();
4762        mForceStatusBar = false;
4763        mForceStatusBarFromKeyguard = false;
4764        mForceStatusBarTransparent = false;
4765        mForcingShowNavBar = false;
4766        mForcingShowNavBarLayer = -1;
4767
4768        mHideLockScreen = false;
4769        mAllowLockscreenWhenOn = false;
4770        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
4771        mShowingLockscreen = false;
4772        mShowingDream = false;
4773        mWinShowWhenLocked = null;
4774        mKeyguardSecure = isKeyguardSecure();
4775        mKeyguardSecureIncludingHidden = mKeyguardSecure
4776                && (mKeyguardDelegate != null && mKeyguardDelegate.isShowing());
4777    }
4778
4779    /** {@inheritDoc} */
4780    @Override
4781    public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs,
4782            WindowState attached) {
4783        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
4784                + win.isVisibleOrBehindKeyguardLw());
4785        final int fl = PolicyControl.getWindowFlags(win, attrs);
4786        if (mTopFullscreenOpaqueWindowState == null
4787                && win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD) {
4788            mForcingShowNavBar = true;
4789            mForcingShowNavBarLayer = win.getSurfaceLayer();
4790        }
4791        if (attrs.type == TYPE_STATUS_BAR) {
4792            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4793                mForceStatusBarFromKeyguard = true;
4794                mShowingLockscreen = true;
4795            }
4796            if ((attrs.privateFlags & PRIVATE_FLAG_FORCE_STATUS_BAR_VISIBLE_TRANSPARENT) != 0) {
4797                mForceStatusBarTransparent = true;
4798            }
4799        }
4800
4801        boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
4802                && attrs.type < FIRST_SYSTEM_WINDOW;
4803        final boolean showWhenLocked = (fl & FLAG_SHOW_WHEN_LOCKED) != 0;
4804        final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
4805        final int stackId = win.getStackId();
4806        if (mTopFullscreenOpaqueWindowState == null &&
4807                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
4808            if ((fl & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
4809                if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4810                    mForceStatusBarFromKeyguard = true;
4811                } else {
4812                    mForceStatusBar = true;
4813                }
4814            }
4815            if (attrs.type == TYPE_DREAM) {
4816                // If the lockscreen was showing when the dream started then wait
4817                // for the dream to draw before hiding the lockscreen.
4818                if (!mDreamingLockscreen
4819                        || (win.isVisibleLw() && win.hasDrawnLw())) {
4820                    mShowingDream = true;
4821                    appWindow = true;
4822                }
4823            }
4824
4825            final IApplicationToken appToken = win.getAppToken();
4826
4827            // For app windows that are not attached, we decide if all windows in the app they
4828            // represent should be hidden or if we should hide the lockscreen. For attached app
4829            // windows we defer the decision to the window it is attached to.
4830            if (appWindow && attached == null) {
4831                if (showWhenLocked) {
4832                    // Remove any previous windows with the same appToken.
4833                    mAppsToBeHidden.remove(appToken);
4834                    mAppsThatDismissKeyguard.remove(appToken);
4835                    if (mAppsToBeHidden.isEmpty()) {
4836                        if (dismissKeyguard && !mKeyguardSecure) {
4837                            mAppsThatDismissKeyguard.add(appToken);
4838                        } else if (win.isDrawnLw() || win.hasAppShownWindows()) {
4839                            mWinShowWhenLocked = win;
4840                            mHideLockScreen = true;
4841                            mForceStatusBarFromKeyguard = false;
4842                        }
4843                    }
4844                } else if (dismissKeyguard) {
4845                    if (mKeyguardSecure) {
4846                        mAppsToBeHidden.add(appToken);
4847                    } else {
4848                        mAppsToBeHidden.remove(appToken);
4849                    }
4850                    mAppsThatDismissKeyguard.add(appToken);
4851                } else {
4852                    mAppsToBeHidden.add(appToken);
4853                }
4854                if (isFullscreen(attrs) && StackId.normallyFullscreenWindows(stackId)) {
4855                    if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
4856                    mTopFullscreenOpaqueWindowState = win;
4857                    if (mTopFullscreenOpaqueOrDimmingWindowState == null) {
4858                        mTopFullscreenOpaqueOrDimmingWindowState = win;
4859                    }
4860                    if (!mAppsThatDismissKeyguard.isEmpty() &&
4861                            mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
4862                        if (DEBUG_LAYOUT) Slog.v(TAG,
4863                                "Setting mDismissKeyguard true by win " + win);
4864                        mDismissKeyguard = (mWinDismissingKeyguard == win
4865                                && mSecureDismissingKeyguard == mKeyguardSecure)
4866                                ? DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
4867                        mWinDismissingKeyguard = win;
4868                        mSecureDismissingKeyguard = mKeyguardSecure;
4869                        mForceStatusBarFromKeyguard = mShowingLockscreen && mKeyguardSecure;
4870                    } else if (mAppsToBeHidden.isEmpty() && showWhenLocked
4871                            && (win.isDrawnLw() || win.hasAppShownWindows())) {
4872                        if (DEBUG_LAYOUT) Slog.v(TAG,
4873                                "Setting mHideLockScreen to true by win " + win);
4874                        mHideLockScreen = true;
4875                        mForceStatusBarFromKeyguard = false;
4876                    }
4877                    if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
4878                        mAllowLockscreenWhenOn = true;
4879                    }
4880                }
4881
4882                if (mWinShowWhenLocked != null &&
4883                        mWinShowWhenLocked.getAppToken() != win.getAppToken() &&
4884                        (attrs.flags & FLAG_SHOW_WHEN_LOCKED) == 0) {
4885                    win.hideLw(false);
4886                }
4887            }
4888        } else if (mTopFullscreenOpaqueWindowState == null && mWinShowWhenLocked == null) {
4889            // No TopFullscreenOpaqueWindow is showing, but we found a SHOW_WHEN_LOCKED window
4890            // that is being hidden in an animation - keep the
4891            // keyguard hidden until the new window shows up and
4892            // we know whether to show the keyguard or not.
4893            if (win.isAnimatingLw() && appWindow && showWhenLocked && mKeyguardHidden) {
4894                mHideLockScreen = true;
4895                mWinShowWhenLocked = win;
4896            }
4897        }
4898
4899        // Keep track of the window if it's dimming but not necessarily fullscreen.
4900        final boolean reallyVisible = win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw();
4901        if (mTopFullscreenOpaqueOrDimmingWindowState == null &&  reallyVisible
4902                && win.isDimming() && StackId.normallyFullscreenWindows(stackId)) {
4903            mTopFullscreenOpaqueOrDimmingWindowState = win;
4904        }
4905
4906        // We need to keep track of the top "fullscreen" opaque window for the docked stack
4907        // separately, because both the "real fullscreen" opaque window and the one for the docked
4908        // stack can control View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.
4909        if (mTopDockedOpaqueWindowState == null && reallyVisible && appWindow && attached == null
4910                && isFullscreen(attrs) && stackId == DOCKED_STACK_ID) {
4911            mTopDockedOpaqueWindowState = win;
4912            if (mTopDockedOpaqueOrDimmingWindowState == null) {
4913                mTopDockedOpaqueOrDimmingWindowState = win;
4914            }
4915        }
4916
4917        // Also keep track of any windows that are dimming but not necessarily fullscreen in the
4918        // docked stack.
4919        if (mTopDockedOpaqueOrDimmingWindowState == null && reallyVisible && win.isDimming()
4920                && stackId == DOCKED_STACK_ID) {
4921            mTopDockedOpaqueOrDimmingWindowState = win;
4922        }
4923    }
4924
4925    private boolean isFullscreen(WindowManager.LayoutParams attrs) {
4926        return attrs.x == 0 && attrs.y == 0
4927                && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
4928                && attrs.height == WindowManager.LayoutParams.MATCH_PARENT;
4929    }
4930
4931    /** {@inheritDoc} */
4932    @Override
4933    public int finishPostLayoutPolicyLw() {
4934        if (mWinShowWhenLocked != null && mTopFullscreenOpaqueWindowState != null &&
4935                mWinShowWhenLocked.getAppToken() != mTopFullscreenOpaqueWindowState.getAppToken()
4936                && isKeyguardLocked()) {
4937            // A dialog is dismissing the keyguard. Put the wallpaper behind it and hide the
4938            // fullscreen window.
4939            // TODO: Make sure FLAG_SHOW_WALLPAPER is restored when dialog is dismissed. Or not.
4940            mWinShowWhenLocked.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4941            mTopFullscreenOpaqueWindowState.hideLw(false);
4942            mTopFullscreenOpaqueWindowState = mWinShowWhenLocked;
4943        }
4944
4945        int changes = 0;
4946        boolean topIsFullscreen = false;
4947
4948        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
4949                ? mTopFullscreenOpaqueWindowState.getAttrs()
4950                : null;
4951
4952        // If we are not currently showing a dream then remember the current
4953        // lockscreen state.  We will use this to determine whether the dream
4954        // started while the lockscreen was showing and remember this state
4955        // while the dream is showing.
4956        if (!mShowingDream) {
4957            mDreamingLockscreen = mShowingLockscreen;
4958            if (mDreamingSleepTokenNeeded) {
4959                mDreamingSleepTokenNeeded = false;
4960                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 0, 1).sendToTarget();
4961            }
4962        } else {
4963            if (!mDreamingSleepTokenNeeded) {
4964                mDreamingSleepTokenNeeded = true;
4965                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 1, 1).sendToTarget();
4966            }
4967        }
4968
4969        if (mStatusBar != null) {
4970            if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
4971                    + " forcefkg=" + mForceStatusBarFromKeyguard
4972                    + " top=" + mTopFullscreenOpaqueWindowState);
4973            boolean shouldBeTransparent = mForceStatusBarTransparent
4974                    && !mForceStatusBar
4975                    && !mForceStatusBarFromKeyguard;
4976            if (!shouldBeTransparent) {
4977                mStatusBarController.setShowTransparent(false /* transparent */);
4978            } else if (!mStatusBar.isVisibleLw()) {
4979                mStatusBarController.setShowTransparent(true /* transparent */);
4980            }
4981            if (mForceStatusBar || mForceStatusBarFromKeyguard || mForceStatusBarTransparent) {
4982                if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
4983                if (mStatusBarController.setBarShowingLw(true)) {
4984                    changes |= FINISH_LAYOUT_REDO_LAYOUT;
4985                }
4986                // Maintain fullscreen layout until incoming animation is complete.
4987                topIsFullscreen = mTopIsFullscreen && mStatusBar.isAnimatingLw();
4988                // Transient status bar on the lockscreen is not allowed
4989                if (mForceStatusBarFromKeyguard && mStatusBarController.isTransientShowing()) {
4990                    mStatusBarController.updateVisibilityLw(false /*transientAllowed*/,
4991                            mLastSystemUiFlags, mLastSystemUiFlags);
4992                }
4993            } else if (mTopFullscreenOpaqueWindowState != null) {
4994                final int fl = PolicyControl.getWindowFlags(null, lp);
4995                if (localLOGV) {
4996                    Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
4997                            + " shown position: "
4998                            + mTopFullscreenOpaqueWindowState.getShownPositionLw());
4999                    Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
5000                            + " lp.flags=0x" + Integer.toHexString(fl));
5001                }
5002                topIsFullscreen = (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
5003                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
5004                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
5005                // and mTopIsFullscreen is that mTopIsFullscreen is set only if the window
5006                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
5007                // case though.
5008                if (mStatusBarController.isTransientShowing()) {
5009                    if (mStatusBarController.setBarShowingLw(true)) {
5010                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
5011                    }
5012                } else if (topIsFullscreen
5013                        && !mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID)
5014                        && !mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID)) {
5015                    if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
5016                    if (mStatusBarController.setBarShowingLw(false)) {
5017                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
5018                    } else {
5019                        if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
5020                    }
5021                } else {
5022                    if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
5023                    if (mStatusBarController.setBarShowingLw(true)) {
5024                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
5025                    }
5026                }
5027            }
5028        }
5029
5030        if (mTopIsFullscreen != topIsFullscreen) {
5031            if (!topIsFullscreen) {
5032                // Force another layout when status bar becomes fully shown.
5033                changes |= FINISH_LAYOUT_REDO_LAYOUT;
5034            }
5035            mTopIsFullscreen = topIsFullscreen;
5036        }
5037
5038        // Hide the key guard if a visible window explicitly specifies that it wants to be
5039        // displayed when the screen is locked.
5040        if (mKeyguardDelegate != null && mStatusBar != null) {
5041            if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
5042                    + mHideLockScreen);
5043            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardSecure) {
5044                mKeyguardHidden = true;
5045                if (setKeyguardOccludedLw(true)) {
5046                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5047                            | FINISH_LAYOUT_REDO_CONFIG
5048                            | FINISH_LAYOUT_REDO_WALLPAPER;
5049                }
5050                if (mKeyguardDelegate.isShowing()) {
5051                    mHandler.post(new Runnable() {
5052                        @Override
5053                        public void run() {
5054                            mKeyguardDelegate.keyguardDone(false, false);
5055                        }
5056                    });
5057                }
5058            } else if (mHideLockScreen) {
5059                mKeyguardHidden = true;
5060                mWinDismissingKeyguard = null;
5061                if (setKeyguardOccludedLw(true)) {
5062                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5063                            | FINISH_LAYOUT_REDO_CONFIG
5064                            | FINISH_LAYOUT_REDO_WALLPAPER;
5065                }
5066            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
5067                mKeyguardHidden = false;
5068                if (setKeyguardOccludedLw(false)) {
5069                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5070                            | FINISH_LAYOUT_REDO_CONFIG
5071                            | FINISH_LAYOUT_REDO_WALLPAPER;
5072                }
5073                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
5074                    // Only launch the next keyguard unlock window once per window.
5075                    mHandler.post(new Runnable() {
5076                        @Override
5077                        public void run() {
5078                            mKeyguardDelegate.dismiss();
5079                        }
5080                    });
5081                }
5082            } else {
5083                mWinDismissingKeyguard = null;
5084                mSecureDismissingKeyguard = false;
5085                mKeyguardHidden = false;
5086                if (setKeyguardOccludedLw(false)) {
5087                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5088                            | FINISH_LAYOUT_REDO_CONFIG
5089                            | FINISH_LAYOUT_REDO_WALLPAPER;
5090                }
5091            }
5092        }
5093
5094        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
5095            // If the navigation bar has been hidden or shown, we need to do another
5096            // layout pass to update that window.
5097            changes |= FINISH_LAYOUT_REDO_LAYOUT;
5098        }
5099
5100        // update since mAllowLockscreenWhenOn might have changed
5101        updateLockScreenTimeout();
5102        return changes;
5103    }
5104
5105    /**
5106     * Updates the occluded state of the Keyguard.
5107     *
5108     * @return Whether the flags have changed and we have to redo the layout.
5109     */
5110    private boolean setKeyguardOccludedLw(boolean isOccluded) {
5111        boolean wasOccluded = mKeyguardOccluded;
5112        boolean showing = mKeyguardDelegate.isShowing();
5113        if (wasOccluded && !isOccluded && showing) {
5114            mKeyguardOccluded = false;
5115            mKeyguardDelegate.setOccluded(false);
5116            mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
5117            mStatusBar.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
5118            return true;
5119        } else if (!wasOccluded && isOccluded && showing) {
5120            mKeyguardOccluded = true;
5121            mKeyguardDelegate.setOccluded(true);
5122            mStatusBar.getAttrs().privateFlags &= ~PRIVATE_FLAG_KEYGUARD;
5123            mStatusBar.getAttrs().flags &= ~FLAG_SHOW_WALLPAPER;
5124            return true;
5125        } else {
5126            return false;
5127        }
5128    }
5129
5130    private boolean isStatusBarKeyguard() {
5131        return mStatusBar != null
5132                && (mStatusBar.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
5133    }
5134
5135    @Override
5136    public boolean allowAppAnimationsLw() {
5137        if (isStatusBarKeyguard() || mShowingDream) {
5138            // If keyguard or dreams is currently visible, no reason to animate behind it.
5139            return false;
5140        }
5141        return true;
5142    }
5143
5144    @Override
5145    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
5146        mFocusedWindow = newFocus;
5147        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
5148            // If the navigation bar has been hidden or shown, we need to do another
5149            // layout pass to update that window.
5150            return FINISH_LAYOUT_REDO_LAYOUT;
5151        }
5152        return 0;
5153    }
5154
5155    /** {@inheritDoc} */
5156    @Override
5157    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
5158        // lid changed state
5159        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
5160        if (newLidState == mLidState) {
5161            return;
5162        }
5163
5164        mLidState = newLidState;
5165        applyLidSwitchState();
5166        updateRotation(true);
5167
5168        if (lidOpen) {
5169            wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromLidSwitch,
5170                    "android.policy:LID");
5171        } else if (!mLidControlsSleep) {
5172            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5173        }
5174    }
5175
5176    @Override
5177    public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered) {
5178        int lensCoverState = lensCovered ? CAMERA_LENS_COVERED : CAMERA_LENS_UNCOVERED;
5179        if (mCameraLensCoverState == lensCoverState) {
5180            return;
5181        }
5182        if (mCameraLensCoverState == CAMERA_LENS_COVERED &&
5183                lensCoverState == CAMERA_LENS_UNCOVERED) {
5184            Intent intent;
5185            final boolean keyguardActive = mKeyguardDelegate == null ? false :
5186                    mKeyguardDelegate.isShowing();
5187            if (keyguardActive) {
5188                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
5189            } else {
5190                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
5191            }
5192            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromCameraLens,
5193                    "android.policy:CAMERA_COVER");
5194            startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
5195        }
5196        mCameraLensCoverState = lensCoverState;
5197    }
5198
5199    void setHdmiPlugged(boolean plugged) {
5200        if (mHdmiPlugged != plugged) {
5201            mHdmiPlugged = plugged;
5202            updateRotation(true, true);
5203            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
5204            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5205            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
5206            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
5207        }
5208    }
5209
5210    void initializeHdmiState() {
5211        boolean plugged = false;
5212        // watch for HDMI plug messages if the hdmi switch exists
5213        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
5214            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
5215
5216            final String filename = "/sys/class/switch/hdmi/state";
5217            FileReader reader = null;
5218            try {
5219                reader = new FileReader(filename);
5220                char[] buf = new char[15];
5221                int n = reader.read(buf);
5222                if (n > 1) {
5223                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
5224                }
5225            } catch (IOException ex) {
5226                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
5227            } catch (NumberFormatException ex) {
5228                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
5229            } finally {
5230                if (reader != null) {
5231                    try {
5232                        reader.close();
5233                    } catch (IOException ex) {
5234                    }
5235                }
5236            }
5237        }
5238        // This dance forces the code in setHdmiPlugged to run.
5239        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
5240        mHdmiPlugged = !plugged;
5241        setHdmiPlugged(!mHdmiPlugged);
5242    }
5243
5244    final Object mScreenshotLock = new Object();
5245    ServiceConnection mScreenshotConnection = null;
5246
5247    final Runnable mScreenshotTimeout = new Runnable() {
5248        @Override public void run() {
5249            synchronized (mScreenshotLock) {
5250                if (mScreenshotConnection != null) {
5251                    mContext.unbindService(mScreenshotConnection);
5252                    mScreenshotConnection = null;
5253                    notifyScreenshotError();
5254                }
5255            }
5256        }
5257    };
5258
5259    // Assume this is called from the Handler thread.
5260    private void takeScreenshot(final int screenshotType) {
5261        synchronized (mScreenshotLock) {
5262            if (mScreenshotConnection != null) {
5263                return;
5264            }
5265            final ComponentName serviceComponent = new ComponentName(SYSUI_PACKAGE,
5266                    SYSUI_SCREENSHOT_SERVICE);
5267            final Intent serviceIntent = new Intent();
5268            serviceIntent.setComponent(serviceComponent);
5269            ServiceConnection conn = new ServiceConnection() {
5270                @Override
5271                public void onServiceConnected(ComponentName name, IBinder service) {
5272                    synchronized (mScreenshotLock) {
5273                        if (mScreenshotConnection != this) {
5274                            return;
5275                        }
5276                        Messenger messenger = new Messenger(service);
5277                        Message msg = Message.obtain(null, screenshotType);
5278                        final ServiceConnection myConn = this;
5279                        Handler h = new Handler(mHandler.getLooper()) {
5280                            @Override
5281                            public void handleMessage(Message msg) {
5282                                synchronized (mScreenshotLock) {
5283                                    if (mScreenshotConnection == myConn) {
5284                                        mContext.unbindService(mScreenshotConnection);
5285                                        mScreenshotConnection = null;
5286                                        mHandler.removeCallbacks(mScreenshotTimeout);
5287                                    }
5288                                }
5289                            }
5290                        };
5291                        msg.replyTo = new Messenger(h);
5292                        msg.arg1 = msg.arg2 = 0;
5293                        if (mStatusBar != null && mStatusBar.isVisibleLw())
5294                            msg.arg1 = 1;
5295                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
5296                            msg.arg2 = 1;
5297                        try {
5298                            messenger.send(msg);
5299                        } catch (RemoteException e) {
5300                        }
5301                    }
5302                }
5303
5304                @Override
5305                public void onServiceDisconnected(ComponentName name) {
5306                    notifyScreenshotError();
5307                }
5308            };
5309            if (mContext.bindServiceAsUser(serviceIntent, conn,
5310                    Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE,
5311                    UserHandle.CURRENT)) {
5312                mScreenshotConnection = conn;
5313                mHandler.postDelayed(mScreenshotTimeout, 10000);
5314            }
5315        }
5316    }
5317
5318    /**
5319     * Notifies the screenshot service to show an error.
5320     */
5321    private void notifyScreenshotError() {
5322        // If the service process is killed, then ask it to clean up after itself
5323        final ComponentName errorComponent = new ComponentName(SYSUI_PACKAGE,
5324                SYSUI_SCREENSHOT_ERROR_RECEIVER);
5325        Intent errorIntent = new Intent();
5326        errorIntent.setComponent(errorComponent);
5327        errorIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
5328                Intent.FLAG_RECEIVER_FOREGROUND);
5329        mContext.sendBroadcastAsUser(errorIntent, UserHandle.ALL);
5330    }
5331
5332    /** {@inheritDoc} */
5333    @Override
5334    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
5335        if (!mSystemBooted) {
5336            // If we have not yet booted, don't let key events do anything.
5337            return 0;
5338        }
5339
5340        final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;
5341        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
5342        final boolean canceled = event.isCanceled();
5343        final int keyCode = event.getKeyCode();
5344
5345        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
5346
5347        // If screen is off then we treat the case where the keyguard is open but hidden
5348        // the same as if it were open and in front.
5349        // This will prevent any keys other than the power button from waking the screen
5350        // when the keyguard is hidden by another activity.
5351        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
5352                                            (interactive ?
5353                                                isKeyguardShowingAndNotOccluded() :
5354                                                mKeyguardDelegate.isShowing()));
5355
5356        if (DEBUG_INPUT) {
5357            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
5358                    + " interactive=" + interactive + " keyguardActive=" + keyguardActive
5359                    + " policyFlags=" + Integer.toHexString(policyFlags));
5360        }
5361
5362        // Basic policy based on interactive state.
5363        int result;
5364        boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
5365                || event.isWakeKey();
5366        if (interactive || (isInjected && !isWakeKey)) {
5367            // When the device is interactive or the key is injected pass the
5368            // key to the application.
5369            result = ACTION_PASS_TO_USER;
5370            isWakeKey = false;
5371        } else if (!interactive && shouldDispatchInputWhenNonInteractive()) {
5372            // If we're currently dozing with the screen on and the keyguard showing, pass the key
5373            // to the application but preserve its wake key status to make sure we still move
5374            // from dozing to fully interactive if we would normally go from off to fully
5375            // interactive.
5376            result = ACTION_PASS_TO_USER;
5377        } else {
5378            // When the screen is off and the key is not injected, determine whether
5379            // to wake the device but don't pass the key to the application.
5380            result = 0;
5381            if (isWakeKey && (!down || !isWakeKeyWhenScreenOff(keyCode))) {
5382                isWakeKey = false;
5383            }
5384        }
5385
5386        // If the key would be handled globally, just return the result, don't worry about special
5387        // key processing.
5388        if (isValidGlobalKey(keyCode)
5389                && mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
5390            if (isWakeKey) {
5391                wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5392            }
5393            return result;
5394        }
5395
5396        boolean useHapticFeedback = down
5397                && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
5398                && event.getRepeatCount() == 0;
5399
5400        // Handle special keys.
5401        switch (keyCode) {
5402            case KeyEvent.KEYCODE_BACK: {
5403                if (down) {
5404                    mBackKeyHandled = false;
5405                    if (hasLongPressOnBackBehavior()) {
5406                        Message msg = mHandler.obtainMessage(MSG_BACK_LONG_PRESS);
5407                        msg.setAsynchronous(true);
5408                        mHandler.sendMessageDelayed(msg,
5409                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5410                    }
5411                } else {
5412                    boolean handled = mBackKeyHandled;
5413
5414                    // Reset back key state
5415                    cancelPendingBackKeyAction();
5416
5417                    // Don't pass back press to app if we've already handled it
5418                    if (handled) {
5419                        result &= ~ACTION_PASS_TO_USER;
5420                    }
5421                }
5422                break;
5423            }
5424
5425            case KeyEvent.KEYCODE_VOLUME_DOWN:
5426            case KeyEvent.KEYCODE_VOLUME_UP:
5427            case KeyEvent.KEYCODE_VOLUME_MUTE: {
5428                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
5429                    if (down) {
5430                        if (interactive && !mScreenshotChordVolumeDownKeyTriggered
5431                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5432                            mScreenshotChordVolumeDownKeyTriggered = true;
5433                            mScreenshotChordVolumeDownKeyTime = event.getDownTime();
5434                            mScreenshotChordVolumeDownKeyConsumed = false;
5435                            cancelPendingPowerKeyAction();
5436                            interceptScreenshotChord();
5437                        }
5438                    } else {
5439                        mScreenshotChordVolumeDownKeyTriggered = false;
5440                        cancelPendingScreenshotChordAction();
5441                    }
5442                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
5443                    if (down) {
5444                        if (interactive && !mScreenshotChordVolumeUpKeyTriggered
5445                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5446                            mScreenshotChordVolumeUpKeyTriggered = true;
5447                            cancelPendingPowerKeyAction();
5448                            cancelPendingScreenshotChordAction();
5449                        }
5450                    } else {
5451                        mScreenshotChordVolumeUpKeyTriggered = false;
5452                        cancelPendingScreenshotChordAction();
5453                    }
5454                }
5455                if (down) {
5456                    TelecomManager telecomManager = getTelecommService();
5457                    if (telecomManager != null) {
5458                        if (telecomManager.isRinging()) {
5459                            // If an incoming call is ringing, either VOLUME key means
5460                            // "silence ringer".  We handle these keys here, rather than
5461                            // in the InCallScreen, to make sure we'll respond to them
5462                            // even if the InCallScreen hasn't come to the foreground yet.
5463                            // Look for the DOWN event here, to agree with the "fallback"
5464                            // behavior in the InCallScreen.
5465                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5466                                  + " VOLUME key-down while ringing: Silence ringer!");
5467
5468                            // Silence the ringer.  (It's safe to call this
5469                            // even if the ringer has already been silenced.)
5470                            telecomManager.silenceRinger();
5471
5472                            // And *don't* pass this key thru to the current activity
5473                            // (which is probably the InCallScreen.)
5474                            result &= ~ACTION_PASS_TO_USER;
5475                            break;
5476                        }
5477                        if (telecomManager.isInCall()
5478                                && (result & ACTION_PASS_TO_USER) == 0) {
5479                            // If we are in call but we decided not to pass the key to
5480                            // the application, just pass it to the session service.
5481
5482                            MediaSessionLegacyHelper.getHelper(mContext)
5483                                    .sendVolumeKeyEvent(event, false);
5484                            break;
5485                        }
5486                    }
5487                }
5488                if (mUseTvRouting) {
5489                    // On TVs, defer special key handlings to
5490                    // {@link interceptKeyBeforeDispatching()}.
5491                    result |= ACTION_PASS_TO_USER;
5492                } else if ((result & ACTION_PASS_TO_USER) == 0) {
5493                    // If we aren't passing to the user and no one else
5494                    // handled it send it to the session manager to
5495                    // figure out.
5496                    MediaSessionLegacyHelper.getHelper(mContext)
5497                            .sendVolumeKeyEvent(event, true);
5498                }
5499                break;
5500            }
5501
5502            case KeyEvent.KEYCODE_ENDCALL: {
5503                result &= ~ACTION_PASS_TO_USER;
5504                if (down) {
5505                    TelecomManager telecomManager = getTelecommService();
5506                    boolean hungUp = false;
5507                    if (telecomManager != null) {
5508                        hungUp = telecomManager.endCall();
5509                    }
5510                    if (interactive && !hungUp) {
5511                        mEndCallKeyHandled = false;
5512                        mHandler.postDelayed(mEndCallLongPress,
5513                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5514                    } else {
5515                        mEndCallKeyHandled = true;
5516                    }
5517                } else {
5518                    if (!mEndCallKeyHandled) {
5519                        mHandler.removeCallbacks(mEndCallLongPress);
5520                        if (!canceled) {
5521                            if ((mEndcallBehavior
5522                                    & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
5523                                if (goHome()) {
5524                                    break;
5525                                }
5526                            }
5527                            if ((mEndcallBehavior
5528                                    & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
5529                                mPowerManager.goToSleep(event.getEventTime(),
5530                                        PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
5531                                isWakeKey = false;
5532                            }
5533                        }
5534                    }
5535                }
5536                break;
5537            }
5538
5539            case KeyEvent.KEYCODE_POWER: {
5540                result &= ~ACTION_PASS_TO_USER;
5541                isWakeKey = false; // wake-up will be handled separately
5542                if (down) {
5543                    interceptPowerKeyDown(event, interactive);
5544                } else {
5545                    interceptPowerKeyUp(event, interactive, canceled);
5546                }
5547                break;
5548            }
5549
5550            case KeyEvent.KEYCODE_SLEEP: {
5551                result &= ~ACTION_PASS_TO_USER;
5552                isWakeKey = false;
5553                if (!mPowerManager.isInteractive()) {
5554                    useHapticFeedback = false; // suppress feedback if already non-interactive
5555                }
5556                if (down) {
5557                    sleepPress(event.getEventTime());
5558                } else {
5559                    sleepRelease(event.getEventTime());
5560                }
5561                break;
5562            }
5563
5564            case KeyEvent.KEYCODE_SOFT_SLEEP: {
5565                result &= ~ACTION_PASS_TO_USER;
5566                isWakeKey = false;
5567                if (!down) {
5568                    mPowerManagerInternal.setUserInactiveOverrideFromWindowManager();
5569                }
5570                break;
5571            }
5572
5573            case KeyEvent.KEYCODE_WAKEUP: {
5574                result &= ~ACTION_PASS_TO_USER;
5575                isWakeKey = true;
5576                break;
5577            }
5578
5579            case KeyEvent.KEYCODE_MEDIA_PLAY:
5580            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5581            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5582            case KeyEvent.KEYCODE_HEADSETHOOK:
5583            case KeyEvent.KEYCODE_MUTE:
5584            case KeyEvent.KEYCODE_MEDIA_STOP:
5585            case KeyEvent.KEYCODE_MEDIA_NEXT:
5586            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5587            case KeyEvent.KEYCODE_MEDIA_REWIND:
5588            case KeyEvent.KEYCODE_MEDIA_RECORD:
5589            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5590            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
5591                if (MediaSessionLegacyHelper.getHelper(mContext).isGlobalPriorityActive()) {
5592                    // If the global session is active pass all media keys to it
5593                    // instead of the active window.
5594                    result &= ~ACTION_PASS_TO_USER;
5595                }
5596                if ((result & ACTION_PASS_TO_USER) == 0) {
5597                    // Only do this if we would otherwise not pass it to the user. In that
5598                    // case, the PhoneWindow class will do the same thing, except it will
5599                    // only do it if the showing app doesn't process the key on its own.
5600                    // Note that we need to make a copy of the key event here because the
5601                    // original key event will be recycled when we return.
5602                    mBroadcastWakeLock.acquire();
5603                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
5604                            new KeyEvent(event));
5605                    msg.setAsynchronous(true);
5606                    msg.sendToTarget();
5607                }
5608                break;
5609            }
5610
5611            case KeyEvent.KEYCODE_CALL: {
5612                if (down) {
5613                    TelecomManager telecomManager = getTelecommService();
5614                    if (telecomManager != null) {
5615                        if (telecomManager.isRinging()) {
5616                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5617                                  + " CALL key-down while ringing: Answer the call!");
5618                            telecomManager.acceptRingingCall();
5619
5620                            // And *don't* pass this key thru to the current activity
5621                            // (which is presumably the InCallScreen.)
5622                            result &= ~ACTION_PASS_TO_USER;
5623                        }
5624                    }
5625                }
5626                break;
5627            }
5628            case KeyEvent.KEYCODE_VOICE_ASSIST: {
5629                // Only do this if we would otherwise not pass it to the user. In that case,
5630                // interceptKeyBeforeDispatching would apply a similar but different policy in
5631                // order to invoke voice assist actions. Note that we need to make a copy of the
5632                // key event here because the original key event will be recycled when we return.
5633                if ((result & ACTION_PASS_TO_USER) == 0 && !down) {
5634                    mBroadcastWakeLock.acquire();
5635                    Message msg = mHandler.obtainMessage(MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK,
5636                            keyguardActive ? 1 : 0, 0);
5637                    msg.setAsynchronous(true);
5638                    msg.sendToTarget();
5639                }
5640                break;
5641            }
5642            case KeyEvent.KEYCODE_WINDOW: {
5643                if (mShortPressWindowBehavior == SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE) {
5644                    if (!down) {
5645                        requestTvPictureInPicture(event);
5646                    }
5647                    result &= ~ACTION_PASS_TO_USER;
5648                }
5649                break;
5650            }
5651        }
5652
5653        if (useHapticFeedback) {
5654            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
5655        }
5656
5657        if (isWakeKey) {
5658            wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5659        }
5660
5661        return result;
5662    }
5663
5664    /**
5665     * Returns true if the key can have global actions attached to it.
5666     * We reserve all power management keys for the system since they require
5667     * very careful handling.
5668     */
5669    private static boolean isValidGlobalKey(int keyCode) {
5670        switch (keyCode) {
5671            case KeyEvent.KEYCODE_POWER:
5672            case KeyEvent.KEYCODE_WAKEUP:
5673            case KeyEvent.KEYCODE_SLEEP:
5674                return false;
5675            default:
5676                return true;
5677        }
5678    }
5679
5680    /**
5681     * When the screen is off we ignore some keys that might otherwise typically
5682     * be considered wake keys.  We filter them out here.
5683     *
5684     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
5685     * is always considered a wake key.
5686     */
5687    private boolean isWakeKeyWhenScreenOff(int keyCode) {
5688        switch (keyCode) {
5689            // ignore volume keys unless docked
5690            case KeyEvent.KEYCODE_VOLUME_UP:
5691            case KeyEvent.KEYCODE_VOLUME_DOWN:
5692            case KeyEvent.KEYCODE_VOLUME_MUTE:
5693                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
5694
5695            // ignore media and camera keys
5696            case KeyEvent.KEYCODE_MUTE:
5697            case KeyEvent.KEYCODE_HEADSETHOOK:
5698            case KeyEvent.KEYCODE_MEDIA_PLAY:
5699            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5700            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5701            case KeyEvent.KEYCODE_MEDIA_STOP:
5702            case KeyEvent.KEYCODE_MEDIA_NEXT:
5703            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5704            case KeyEvent.KEYCODE_MEDIA_REWIND:
5705            case KeyEvent.KEYCODE_MEDIA_RECORD:
5706            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5707            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
5708            case KeyEvent.KEYCODE_CAMERA:
5709                return false;
5710        }
5711        return true;
5712    }
5713
5714
5715    /** {@inheritDoc} */
5716    @Override
5717    public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
5718        if ((policyFlags & FLAG_WAKE) != 0) {
5719            if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion,
5720                    "android.policy:MOTION")) {
5721                return 0;
5722            }
5723        }
5724
5725        if (shouldDispatchInputWhenNonInteractive()) {
5726            return ACTION_PASS_TO_USER;
5727        }
5728
5729        // If we have not passed the action up and we are in theater mode without dreaming,
5730        // there will be no dream to intercept the touch and wake into ambient.  The device should
5731        // wake up in this case.
5732        if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
5733            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotionWhenNotDreaming,
5734                    "android.policy:MOTION");
5735        }
5736
5737        return 0;
5738    }
5739
5740    private boolean shouldDispatchInputWhenNonInteractive() {
5741        // Send events to keyguard while the screen is on.
5742        if (isKeyguardShowingAndNotOccluded() && mDisplay != null
5743                && mDisplay.getState() != Display.STATE_OFF) {
5744            return true;
5745        }
5746
5747        // Send events to a dozing dream even if the screen is off since the dream
5748        // is in control of the state of the screen.
5749        IDreamManager dreamManager = getDreamManager();
5750
5751        try {
5752            if (dreamManager != null && dreamManager.isDreaming()) {
5753                return true;
5754            }
5755        } catch (RemoteException e) {
5756            Slog.e(TAG, "RemoteException when checking if dreaming", e);
5757        }
5758
5759        // Otherwise, consume events since the user can't see what is being
5760        // interacted with.
5761        return false;
5762    }
5763
5764    private void dispatchDirectAudioEvent(KeyEvent event) {
5765        if (event.getAction() != KeyEvent.ACTION_DOWN) {
5766            return;
5767        }
5768        int keyCode = event.getKeyCode();
5769        int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
5770                | AudioManager.FLAG_FROM_KEY;
5771        String pkgName = mContext.getOpPackageName();
5772        switch (keyCode) {
5773            case KeyEvent.KEYCODE_VOLUME_UP:
5774                try {
5775                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
5776                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5777                } catch (RemoteException e) {
5778                    Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
5779                }
5780                break;
5781            case KeyEvent.KEYCODE_VOLUME_DOWN:
5782                try {
5783                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
5784                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5785                } catch (RemoteException e) {
5786                    Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
5787                }
5788                break;
5789            case KeyEvent.KEYCODE_VOLUME_MUTE:
5790                try {
5791                    if (event.getRepeatCount() == 0) {
5792                        getAudioService().adjustSuggestedStreamVolume(
5793                                AudioManager.ADJUST_TOGGLE_MUTE,
5794                                AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5795                    }
5796                } catch (RemoteException e) {
5797                    Log.e(TAG, "Error dispatching mute in dispatchTvAudioEvent.", e);
5798                }
5799                break;
5800        }
5801    }
5802
5803    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
5804        if (DEBUG_INPUT) {
5805            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
5806        }
5807
5808        if (mHavePendingMediaKeyRepeatWithWakeLock) {
5809            if (DEBUG_INPUT) {
5810                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
5811            }
5812
5813            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
5814            mHavePendingMediaKeyRepeatWithWakeLock = false;
5815            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
5816        }
5817
5818        dispatchMediaKeyWithWakeLockToAudioService(event);
5819
5820        if (event.getAction() == KeyEvent.ACTION_DOWN
5821                && event.getRepeatCount() == 0) {
5822            mHavePendingMediaKeyRepeatWithWakeLock = true;
5823
5824            Message msg = mHandler.obtainMessage(
5825                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
5826            msg.setAsynchronous(true);
5827            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
5828        } else {
5829            mBroadcastWakeLock.release();
5830        }
5831    }
5832
5833    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
5834        mHavePendingMediaKeyRepeatWithWakeLock = false;
5835
5836        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
5837                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
5838        if (DEBUG_INPUT) {
5839            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
5840        }
5841
5842        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
5843        mBroadcastWakeLock.release();
5844    }
5845
5846    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
5847        if (ActivityManagerNative.isSystemReady()) {
5848            MediaSessionLegacyHelper.getHelper(mContext).sendMediaButtonEvent(event, true);
5849        }
5850    }
5851
5852    void launchVoiceAssistWithWakeLock(boolean keyguardActive) {
5853        IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
5854                ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
5855        if (dic != null) {
5856            try {
5857                dic.exitIdle("voice-search");
5858            } catch (RemoteException e) {
5859            }
5860        }
5861        Intent voiceIntent =
5862            new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
5863        voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, keyguardActive);
5864        startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
5865        mBroadcastWakeLock.release();
5866    }
5867
5868    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
5869        @Override
5870        public void onReceive(Context context, Intent intent) {
5871            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
5872                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
5873                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
5874            } else {
5875                try {
5876                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
5877                            ServiceManager.getService(Context.UI_MODE_SERVICE));
5878                    mUiMode = uiModeService.getCurrentModeType();
5879                } catch (RemoteException e) {
5880                }
5881            }
5882            updateRotation(true);
5883            synchronized (mLock) {
5884                updateOrientationListenerLp();
5885            }
5886        }
5887    };
5888
5889    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
5890        @Override
5891        public void onReceive(Context context, Intent intent) {
5892            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
5893                if (mKeyguardDelegate != null) {
5894                    mKeyguardDelegate.onDreamingStarted();
5895                }
5896            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
5897                if (mKeyguardDelegate != null) {
5898                    mKeyguardDelegate.onDreamingStopped();
5899                }
5900            }
5901        }
5902    };
5903
5904    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
5905        @Override
5906        public void onReceive(Context context, Intent intent) {
5907            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
5908                // tickle the settings observer: this first ensures that we're
5909                // observing the relevant settings for the newly-active user,
5910                // and then updates our own bookkeeping based on the now-
5911                // current user.
5912                mSettingsObserver.onChange(false);
5913
5914                // force a re-application of focused window sysui visibility.
5915                // the window may never have been shown for this user
5916                // e.g. the keyguard when going through the new-user setup flow
5917                synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5918                    mLastSystemUiFlags = 0;
5919                    updateSystemUiVisibilityLw();
5920                }
5921            }
5922        }
5923    };
5924
5925    private final Runnable mHiddenNavPanic = new Runnable() {
5926        @Override
5927        public void run() {
5928            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5929                if (!isUserSetupComplete()) {
5930                    // Swipe-up for navigation bar is disabled during setup
5931                    return;
5932                }
5933                mPendingPanicGestureUptime = SystemClock.uptimeMillis();
5934                mNavigationBarController.showTransient();
5935            }
5936        }
5937    };
5938
5939    private void requestTransientBars(WindowState swipeTarget) {
5940        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5941            if (!isUserSetupComplete()) {
5942                // Swipe-up for navigation bar is disabled during setup
5943                return;
5944            }
5945            boolean sb = mStatusBarController.checkShowTransientBarLw();
5946            boolean nb = mNavigationBarController.checkShowTransientBarLw();
5947            if (sb || nb) {
5948                // Don't show status bar when swiping on already visible navigation bar
5949                if (!nb && swipeTarget == mNavigationBar) {
5950                    if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
5951                    return;
5952                }
5953                if (sb) mStatusBarController.showTransient();
5954                if (nb) mNavigationBarController.showTransient();
5955                mImmersiveModeConfirmation.confirmCurrentPrompt();
5956                updateSystemUiVisibilityLw();
5957            }
5958        }
5959    }
5960
5961    // Called on the PowerManager's Notifier thread.
5962    @Override
5963    public void startedGoingToSleep(int why) {
5964        if (DEBUG_WAKEUP) Slog.i(TAG, "Started going to sleep... (why=" + why + ")");
5965        mCameraGestureTriggeredDuringGoingToSleep = false;
5966        mGoingToSleep = true;
5967        if (mKeyguardDelegate != null) {
5968            mKeyguardDelegate.onStartedGoingToSleep(why);
5969        }
5970    }
5971
5972    // Called on the PowerManager's Notifier thread.
5973    @Override
5974    public void finishedGoingToSleep(int why) {
5975        EventLog.writeEvent(70000, 0);
5976        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished going to sleep... (why=" + why + ")");
5977        MetricsLogger.histogram(mContext, "screen_timeout", mLockScreenTimeout / 1000);
5978
5979        mGoingToSleep = false;
5980
5981        // We must get this work done here because the power manager will drop
5982        // the wake lock and let the system suspend once this function returns.
5983        synchronized (mLock) {
5984            mAwake = false;
5985            updateWakeGestureListenerLp();
5986            updateOrientationListenerLp();
5987            updateLockScreenTimeout();
5988        }
5989        if (mKeyguardDelegate != null) {
5990            mKeyguardDelegate.onFinishedGoingToSleep(why,
5991                    mCameraGestureTriggeredDuringGoingToSleep);
5992        }
5993        mCameraGestureTriggeredDuringGoingToSleep = false;
5994    }
5995
5996    // Called on the PowerManager's Notifier thread.
5997    @Override
5998    public void startedWakingUp() {
5999        EventLog.writeEvent(70000, 1);
6000        if (DEBUG_WAKEUP) Slog.i(TAG, "Started waking up...");
6001
6002        // Since goToSleep performs these functions synchronously, we must
6003        // do the same here.  We cannot post this work to a handler because
6004        // that might cause it to become reordered with respect to what
6005        // may happen in a future call to goToSleep.
6006        synchronized (mLock) {
6007            mAwake = true;
6008
6009            updateWakeGestureListenerLp();
6010            updateOrientationListenerLp();
6011            updateLockScreenTimeout();
6012        }
6013
6014        if (mKeyguardDelegate != null) {
6015            mKeyguardDelegate.onStartedWakingUp();
6016        }
6017    }
6018
6019    // Called on the PowerManager's Notifier thread.
6020    @Override
6021    public void finishedWakingUp() {
6022        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");
6023    }
6024
6025    private void wakeUpFromPowerKey(long eventTime) {
6026        wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey, "android.policy:POWER");
6027    }
6028
6029    private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode, String reason) {
6030        final boolean theaterModeEnabled = isTheaterModeEnabled();
6031        if (!wakeInTheaterMode && theaterModeEnabled) {
6032            return false;
6033        }
6034
6035        if (theaterModeEnabled) {
6036            Settings.Global.putInt(mContext.getContentResolver(),
6037                    Settings.Global.THEATER_MODE_ON, 0);
6038        }
6039
6040        mPowerManager.wakeUp(wakeTime, reason);
6041        return true;
6042    }
6043
6044    private void finishKeyguardDrawn() {
6045        synchronized (mLock) {
6046            if (!mScreenOnEarly || mKeyguardDrawComplete) {
6047                return; // We are not awake yet or we have already informed of this event.
6048            }
6049
6050            mKeyguardDrawComplete = true;
6051            if (mKeyguardDelegate != null) {
6052                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
6053            }
6054            mWindowManagerDrawComplete = false;
6055        }
6056
6057        // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
6058        // as well as enabling the orientation change logic/sensor.
6059        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
6060                WAITING_FOR_DRAWN_TIMEOUT);
6061    }
6062
6063    // Called on the DisplayManager's DisplayPowerController thread.
6064    @Override
6065    public void screenTurnedOff() {
6066        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turned off...");
6067
6068        updateScreenOffSleepToken(true);
6069        synchronized (mLock) {
6070            mScreenOnEarly = false;
6071            mScreenOnFully = false;
6072            mKeyguardDrawComplete = false;
6073            mWindowManagerDrawComplete = false;
6074            mScreenOnListener = null;
6075            updateOrientationListenerLp();
6076
6077            if (mKeyguardDelegate != null) {
6078                mKeyguardDelegate.onScreenTurnedOff();
6079            }
6080        }
6081    }
6082
6083    // Called on the DisplayManager's DisplayPowerController thread.
6084    @Override
6085    public void screenTurningOn(final ScreenOnListener screenOnListener) {
6086        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
6087
6088        updateScreenOffSleepToken(false);
6089        synchronized (mLock) {
6090            mScreenOnEarly = true;
6091            mScreenOnFully = false;
6092            mKeyguardDrawComplete = false;
6093            mWindowManagerDrawComplete = false;
6094            mScreenOnListener = screenOnListener;
6095
6096            if (mKeyguardDelegate != null) {
6097                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
6098                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
6099                mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
6100            } else {
6101                if (DEBUG_WAKEUP) Slog.d(TAG,
6102                        "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
6103                finishKeyguardDrawn();
6104            }
6105        }
6106    }
6107
6108    // Called on the DisplayManager's DisplayPowerController thread.
6109    @Override
6110    public void screenTurnedOn() {
6111        synchronized (mLock) {
6112            if (mKeyguardDelegate != null) {
6113                mKeyguardDelegate.onScreenTurnedOn();
6114            }
6115        }
6116    }
6117
6118    private void finishWindowsDrawn() {
6119        synchronized (mLock) {
6120            if (!mScreenOnEarly || mWindowManagerDrawComplete) {
6121                return; // Screen is not turned on or we did already handle this case earlier.
6122            }
6123
6124            mWindowManagerDrawComplete = true;
6125        }
6126
6127        finishScreenTurningOn();
6128    }
6129
6130    private void finishScreenTurningOn() {
6131        synchronized (mLock) {
6132            // We have just finished drawing screen content. Since the orientation listener
6133            // gets only installed when all windows are drawn, we try to install it again.
6134            updateOrientationListenerLp();
6135        }
6136        final ScreenOnListener listener;
6137        final boolean enableScreen;
6138        synchronized (mLock) {
6139            if (DEBUG_WAKEUP) Slog.d(TAG,
6140                    "finishScreenTurningOn: mAwake=" + mAwake
6141                            + ", mScreenOnEarly=" + mScreenOnEarly
6142                            + ", mScreenOnFully=" + mScreenOnFully
6143                            + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
6144                            + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
6145
6146            if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
6147                    || (mAwake && !mKeyguardDrawComplete)) {
6148                return; // spurious or not ready yet
6149            }
6150
6151            if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
6152            listener = mScreenOnListener;
6153            mScreenOnListener = null;
6154            mScreenOnFully = true;
6155
6156            // Remember the first time we draw the keyguard so we know when we're done with
6157            // the main part of booting and can enable the screen and hide boot messages.
6158            if (!mKeyguardDrawnOnce && mAwake) {
6159                mKeyguardDrawnOnce = true;
6160                enableScreen = true;
6161                if (mBootMessageNeedsHiding) {
6162                    mBootMessageNeedsHiding = false;
6163                    hideBootMessages();
6164                }
6165            } else {
6166                enableScreen = false;
6167            }
6168        }
6169
6170        if (listener != null) {
6171            listener.onScreenOn();
6172        }
6173
6174        if (enableScreen) {
6175            try {
6176                mWindowManager.enableScreenIfNeeded();
6177            } catch (RemoteException unhandled) {
6178            }
6179        }
6180    }
6181
6182    private void handleHideBootMessage() {
6183        synchronized (mLock) {
6184            if (!mKeyguardDrawnOnce) {
6185                mBootMessageNeedsHiding = true;
6186                return; // keyguard hasn't drawn the first time yet, not done booting
6187            }
6188        }
6189
6190        if (mBootMsgDialog != null) {
6191            if (DEBUG_WAKEUP) Slog.d(TAG, "handleHideBootMessage: dismissing");
6192            mBootMsgDialog.dismiss();
6193            mBootMsgDialog = null;
6194        }
6195    }
6196
6197    @Override
6198    public boolean isScreenOn() {
6199        return mScreenOnFully;
6200    }
6201
6202    /** {@inheritDoc} */
6203    @Override
6204    public void enableKeyguard(boolean enabled) {
6205        if (mKeyguardDelegate != null) {
6206            mKeyguardDelegate.setKeyguardEnabled(enabled);
6207        }
6208    }
6209
6210    /** {@inheritDoc} */
6211    @Override
6212    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
6213        if (mKeyguardDelegate != null) {
6214            mKeyguardDelegate.verifyUnlock(callback);
6215        }
6216    }
6217
6218    private boolean isKeyguardShowingAndNotOccluded() {
6219        if (mKeyguardDelegate == null) return false;
6220        return mKeyguardDelegate.isShowing() && !mKeyguardOccluded;
6221    }
6222
6223    /** {@inheritDoc} */
6224    @Override
6225    public boolean isKeyguardLocked() {
6226        return keyguardOn();
6227    }
6228
6229    /** {@inheritDoc} */
6230    @Override
6231    public boolean isKeyguardSecure() {
6232        if (mKeyguardDelegate == null) return false;
6233        return mKeyguardDelegate.isSecure();
6234    }
6235
6236    /** {@inheritDoc} */
6237    @Override
6238    public boolean isKeyguardShowingOrOccluded() {
6239        return mKeyguardDelegate == null ? false : mKeyguardDelegate.isShowing();
6240    }
6241
6242    /** {@inheritDoc} */
6243    @Override
6244    public boolean inKeyguardRestrictedKeyInputMode() {
6245        if (mKeyguardDelegate == null) return false;
6246        return mKeyguardDelegate.isInputRestricted();
6247    }
6248
6249    @Override
6250    public void dismissKeyguardLw() {
6251        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
6252            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.dismissKeyguardLw");
6253            mHandler.post(new Runnable() {
6254                @Override
6255                public void run() {
6256                    // ask the keyguard to prompt the user to authenticate if necessary
6257                    mKeyguardDelegate.dismiss();
6258                }
6259            });
6260        }
6261    }
6262
6263    public void notifyActivityDrawnForKeyguardLw() {
6264        if (mKeyguardDelegate != null) {
6265            mHandler.post(new Runnable() {
6266                @Override
6267                public void run() {
6268                    mKeyguardDelegate.onActivityDrawn();
6269                }
6270            });
6271        }
6272    }
6273
6274    @Override
6275    public boolean isKeyguardDrawnLw() {
6276        synchronized (mLock) {
6277            return mKeyguardDrawnOnce;
6278        }
6279    }
6280
6281    @Override
6282    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
6283        if (mKeyguardDelegate != null) {
6284            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation");
6285            mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration);
6286        }
6287    }
6288
6289    @Override
6290    public void getStableInsetsLw(int displayRotation, int displayWidth, int displayHeight,
6291            Rect outInsets) {
6292        outInsets.setEmpty();
6293
6294        // Navigation bar and status bar.
6295        getNonDecorInsetsLw(displayRotation, displayWidth, displayHeight, outInsets);
6296        if (mStatusBar != null) {
6297            outInsets.top = mStatusBarHeight;
6298        }
6299    }
6300
6301    @Override
6302    public void getNonDecorInsetsLw(int displayRotation, int displayWidth, int displayHeight,
6303            Rect outInsets) {
6304        outInsets.setEmpty();
6305
6306        // Only navigation bar
6307        if (mNavigationBar != null) {
6308            if (isNavigationBarOnBottom(displayWidth, displayHeight)) {
6309                outInsets.bottom = getNavigationBarHeight(displayRotation, mUiMode);
6310            } else {
6311                outInsets.right = getNavigationBarWidth(displayRotation, mUiMode);
6312            }
6313        }
6314    }
6315
6316    @Override
6317    public boolean isNavBarForcedShownLw(WindowState windowState) {
6318        return mForceShowSystemBars;
6319    }
6320
6321    @Override
6322    public boolean isDockSideAllowed(int dockSide) {
6323
6324        // We do not allow all dock sides at which the navigation bar touches the docked stack.
6325        if (!mNavigationBarCanMove) {
6326            return dockSide == DOCKED_TOP || dockSide == DOCKED_LEFT || dockSide == DOCKED_RIGHT;
6327        } else {
6328            return dockSide == DOCKED_TOP || dockSide == DOCKED_LEFT;
6329        }
6330    }
6331
6332    void sendCloseSystemWindows() {
6333        PhoneWindow.sendCloseSystemWindows(mContext, null);
6334    }
6335
6336    void sendCloseSystemWindows(String reason) {
6337        PhoneWindow.sendCloseSystemWindows(mContext, reason);
6338    }
6339
6340    @Override
6341    public int rotationForOrientationLw(int orientation, int lastRotation) {
6342        if (false) {
6343            Slog.v(TAG, "rotationForOrientationLw(orient="
6344                        + orientation + ", last=" + lastRotation
6345                        + "); user=" + mUserRotation + " "
6346                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
6347                            ? "USER_ROTATION_LOCKED" : "")
6348                        );
6349        }
6350
6351        if (mForceDefaultOrientation) {
6352            return Surface.ROTATION_0;
6353        }
6354
6355        synchronized (mLock) {
6356            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
6357            if (sensorRotation < 0) {
6358                sensorRotation = lastRotation;
6359            }
6360
6361            final int preferredRotation;
6362            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
6363                // Ignore sensor when lid switch is open and rotation is forced.
6364                preferredRotation = mLidOpenRotation;
6365            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
6366                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
6367                // Ignore sensor when in car dock unless explicitly enabled.
6368                // This case can override the behavior of NOSENSOR, and can also
6369                // enable 180 degree rotation while docked.
6370                preferredRotation = mCarDockEnablesAccelerometer
6371                        ? sensorRotation : mCarDockRotation;
6372            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6373                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
6374                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
6375                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
6376                // Ignore sensor when in desk dock unless explicitly enabled.
6377                // This case can override the behavior of NOSENSOR, and can also
6378                // enable 180 degree rotation while docked.
6379                preferredRotation = mDeskDockEnablesAccelerometer
6380                        ? sensorRotation : mDeskDockRotation;
6381            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
6382                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
6383                // Note that the dock orientation overrides the HDMI orientation.
6384                preferredRotation = mDemoHdmiRotation;
6385            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
6386                    && mUndockedHdmiRotation >= 0) {
6387                // Ignore sensor when plugged into HDMI and an undocked orientation has
6388                // been specified in the configuration (only for legacy devices without
6389                // full multi-display support).
6390                // Note that the dock orientation overrides the HDMI orientation.
6391                preferredRotation = mUndockedHdmiRotation;
6392            } else if (mDemoRotationLock) {
6393                // Ignore sensor when demo rotation lock is enabled.
6394                // Note that the dock orientation and HDMI rotation lock override this.
6395                preferredRotation = mDemoRotation;
6396            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
6397                // Application just wants to remain locked in the last rotation.
6398                preferredRotation = lastRotation;
6399            } else if (!mSupportAutoRotation) {
6400                // If we don't support auto-rotation then bail out here and ignore
6401                // the sensor and any rotation lock settings.
6402                preferredRotation = -1;
6403            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
6404                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
6405                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
6406                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
6407                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
6408                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
6409                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
6410                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6411                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
6412                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
6413                // Otherwise, use sensor only if requested by the application or enabled
6414                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
6415                if (mAllowAllRotations < 0) {
6416                    // Can't read this during init() because the context doesn't
6417                    // have display metrics at that time so we cannot determine
6418                    // tablet vs. phone then.
6419                    mAllowAllRotations = mContext.getResources().getBoolean(
6420                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
6421                }
6422                if (sensorRotation != Surface.ROTATION_180
6423                        || mAllowAllRotations == 1
6424                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6425                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
6426                    preferredRotation = sensorRotation;
6427                } else {
6428                    preferredRotation = lastRotation;
6429                }
6430            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
6431                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
6432                // Apply rotation lock.  Does not apply to NOSENSOR.
6433                // The idea is that the user rotation expresses a weak preference for the direction
6434                // of gravity and as NOSENSOR is never affected by gravity, then neither should
6435                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
6436                preferredRotation = mUserRotation;
6437            } else {
6438                // No overriding preference.
6439                // We will do exactly what the application asked us to do.
6440                preferredRotation = -1;
6441            }
6442
6443            switch (orientation) {
6444                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6445                    // Return portrait unless overridden.
6446                    if (isAnyPortrait(preferredRotation)) {
6447                        return preferredRotation;
6448                    }
6449                    return mPortraitRotation;
6450
6451                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6452                    // Return landscape unless overridden.
6453                    if (isLandscapeOrSeascape(preferredRotation)) {
6454                        return preferredRotation;
6455                    }
6456                    return mLandscapeRotation;
6457
6458                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6459                    // Return reverse portrait unless overridden.
6460                    if (isAnyPortrait(preferredRotation)) {
6461                        return preferredRotation;
6462                    }
6463                    return mUpsideDownRotation;
6464
6465                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6466                    // Return seascape unless overridden.
6467                    if (isLandscapeOrSeascape(preferredRotation)) {
6468                        return preferredRotation;
6469                    }
6470                    return mSeascapeRotation;
6471
6472                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6473                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
6474                    // Return either landscape rotation.
6475                    if (isLandscapeOrSeascape(preferredRotation)) {
6476                        return preferredRotation;
6477                    }
6478                    if (isLandscapeOrSeascape(lastRotation)) {
6479                        return lastRotation;
6480                    }
6481                    return mLandscapeRotation;
6482
6483                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6484                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
6485                    // Return either portrait rotation.
6486                    if (isAnyPortrait(preferredRotation)) {
6487                        return preferredRotation;
6488                    }
6489                    if (isAnyPortrait(lastRotation)) {
6490                        return lastRotation;
6491                    }
6492                    return mPortraitRotation;
6493
6494                default:
6495                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
6496                    // just return the preferred orientation we already calculated.
6497                    if (preferredRotation >= 0) {
6498                        return preferredRotation;
6499                    }
6500                    return Surface.ROTATION_0;
6501            }
6502        }
6503    }
6504
6505    @Override
6506    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
6507        switch (orientation) {
6508            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6509            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6510            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6511                return isAnyPortrait(rotation);
6512
6513            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6514            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6515            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6516                return isLandscapeOrSeascape(rotation);
6517
6518            default:
6519                return true;
6520        }
6521    }
6522
6523    @Override
6524    public void setRotationLw(int rotation) {
6525        mOrientationListener.setCurrentRotation(rotation);
6526    }
6527
6528    private boolean isLandscapeOrSeascape(int rotation) {
6529        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
6530    }
6531
6532    private boolean isAnyPortrait(int rotation) {
6533        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
6534    }
6535
6536    @Override
6537    public int getUserRotationMode() {
6538        return Settings.System.getIntForUser(mContext.getContentResolver(),
6539                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
6540                        WindowManagerPolicy.USER_ROTATION_FREE :
6541                                WindowManagerPolicy.USER_ROTATION_LOCKED;
6542    }
6543
6544    // User rotation: to be used when all else fails in assigning an orientation to the device
6545    @Override
6546    public void setUserRotationMode(int mode, int rot) {
6547        ContentResolver res = mContext.getContentResolver();
6548
6549        // mUserRotationMode and mUserRotation will be assigned by the content observer
6550        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
6551            Settings.System.putIntForUser(res,
6552                    Settings.System.USER_ROTATION,
6553                    rot,
6554                    UserHandle.USER_CURRENT);
6555            Settings.System.putIntForUser(res,
6556                    Settings.System.ACCELEROMETER_ROTATION,
6557                    0,
6558                    UserHandle.USER_CURRENT);
6559        } else {
6560            Settings.System.putIntForUser(res,
6561                    Settings.System.ACCELEROMETER_ROTATION,
6562                    1,
6563                    UserHandle.USER_CURRENT);
6564        }
6565    }
6566
6567    @Override
6568    public void setSafeMode(boolean safeMode) {
6569        mSafeMode = safeMode;
6570        performHapticFeedbackLw(null, safeMode
6571                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
6572                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
6573    }
6574
6575    static long[] getLongIntArray(Resources r, int resid) {
6576        int[] ar = r.getIntArray(resid);
6577        if (ar == null) {
6578            return null;
6579        }
6580        long[] out = new long[ar.length];
6581        for (int i=0; i<ar.length; i++) {
6582            out[i] = ar[i];
6583        }
6584        return out;
6585    }
6586
6587    /** {@inheritDoc} */
6588    @Override
6589    public void systemReady() {
6590        mKeyguardDelegate = new KeyguardServiceDelegate(mContext);
6591        mKeyguardDelegate.onSystemReady();
6592
6593        readCameraLensCoverState();
6594        updateUiMode();
6595        boolean bindKeyguardNow;
6596        synchronized (mLock) {
6597            updateOrientationListenerLp();
6598            mSystemReady = true;
6599            mHandler.post(new Runnable() {
6600                @Override
6601                public void run() {
6602                    updateSettings();
6603                }
6604            });
6605
6606            bindKeyguardNow = mDeferBindKeyguard;
6607            if (bindKeyguardNow) {
6608                // systemBooted ran but wasn't able to bind to the Keyguard, we'll do it now.
6609                mDeferBindKeyguard = false;
6610            }
6611        }
6612
6613        if (bindKeyguardNow) {
6614            mKeyguardDelegate.bindService(mContext);
6615            mKeyguardDelegate.onBootCompleted();
6616        }
6617        mSystemGestures.systemReady();
6618    }
6619
6620    /** {@inheritDoc} */
6621    @Override
6622    public void systemBooted() {
6623        boolean bindKeyguardNow = false;
6624        synchronized (mLock) {
6625            // Time to bind Keyguard; take care to only bind it once, either here if ready or
6626            // in systemReady if not.
6627            if (mKeyguardDelegate != null) {
6628                bindKeyguardNow = true;
6629            } else {
6630                // Because mKeyguardDelegate is null, we know that the synchronized block in
6631                // systemReady didn't run yet and setting this will actually have an effect.
6632                mDeferBindKeyguard = true;
6633            }
6634        }
6635        if (bindKeyguardNow) {
6636            mKeyguardDelegate.bindService(mContext);
6637            mKeyguardDelegate.onBootCompleted();
6638        }
6639        synchronized (mLock) {
6640            mSystemBooted = true;
6641        }
6642        startedWakingUp();
6643        screenTurningOn(null);
6644        screenTurnedOn();
6645    }
6646
6647    ProgressDialog mBootMsgDialog = null;
6648
6649    /** {@inheritDoc} */
6650    @Override
6651    public void showBootMessage(final CharSequence msg, final boolean always) {
6652        mHandler.post(new Runnable() {
6653            @Override public void run() {
6654                if (mBootMsgDialog == null) {
6655                    int theme;
6656                    if (mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
6657                        theme = com.android.internal.R.style.Theme_Micro_Dialog_Alert;
6658                    } else if (mContext.getPackageManager().hasSystemFeature(FEATURE_TELEVISION)) {
6659                        theme = com.android.internal.R.style.Theme_Leanback_Dialog_Alert;
6660                    } else {
6661                        theme = 0;
6662                    }
6663
6664                    mBootMsgDialog = new ProgressDialog(mContext, theme) {
6665                        // This dialog will consume all events coming in to
6666                        // it, to avoid it trying to do things too early in boot.
6667                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
6668                            return true;
6669                        }
6670                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6671                            return true;
6672                        }
6673                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
6674                            return true;
6675                        }
6676                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
6677                            return true;
6678                        }
6679                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
6680                            return true;
6681                        }
6682                        @Override public boolean dispatchPopulateAccessibilityEvent(
6683                                AccessibilityEvent event) {
6684                            return true;
6685                        }
6686                    };
6687                    if (mContext.getPackageManager().isUpgrade()) {
6688                        mBootMsgDialog.setTitle(R.string.android_upgrading_title);
6689                    } else {
6690                        mBootMsgDialog.setTitle(R.string.android_start_title);
6691                    }
6692                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
6693                    mBootMsgDialog.setIndeterminate(true);
6694                    mBootMsgDialog.getWindow().setType(
6695                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
6696                    mBootMsgDialog.getWindow().addFlags(
6697                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
6698                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
6699                    mBootMsgDialog.getWindow().setDimAmount(1);
6700                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
6701                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
6702                    mBootMsgDialog.getWindow().setAttributes(lp);
6703                    mBootMsgDialog.setCancelable(false);
6704                    mBootMsgDialog.show();
6705                }
6706                mBootMsgDialog.setMessage(msg);
6707            }
6708        });
6709    }
6710
6711    /** {@inheritDoc} */
6712    @Override
6713    public void hideBootMessages() {
6714        mHandler.sendEmptyMessage(MSG_HIDE_BOOT_MESSAGE);
6715    }
6716
6717    /** {@inheritDoc} */
6718    @Override
6719    public void userActivity() {
6720        // ***************************************
6721        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
6722        // ***************************************
6723        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
6724        // WITH ITS LOCKS HELD.
6725        //
6726        // This code must be VERY careful about the locks
6727        // it acquires.
6728        // In fact, the current code acquires way too many,
6729        // and probably has lurking deadlocks.
6730
6731        synchronized (mScreenLockTimeout) {
6732            if (mLockScreenTimerActive) {
6733                // reset the timer
6734                mHandler.removeCallbacks(mScreenLockTimeout);
6735                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6736            }
6737        }
6738    }
6739
6740    class ScreenLockTimeout implements Runnable {
6741        Bundle options;
6742
6743        @Override
6744        public void run() {
6745            synchronized (this) {
6746                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
6747                if (mKeyguardDelegate != null) {
6748                    mKeyguardDelegate.doKeyguardTimeout(options);
6749                }
6750                mLockScreenTimerActive = false;
6751                options = null;
6752            }
6753        }
6754
6755        public void setLockOptions(Bundle options) {
6756            this.options = options;
6757        }
6758    }
6759
6760    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
6761
6762    @Override
6763    public void lockNow(Bundle options) {
6764        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
6765        mHandler.removeCallbacks(mScreenLockTimeout);
6766        if (options != null) {
6767            // In case multiple calls are made to lockNow, we don't wipe out the options
6768            // until the runnable actually executes.
6769            mScreenLockTimeout.setLockOptions(options);
6770        }
6771        mHandler.post(mScreenLockTimeout);
6772    }
6773
6774    private void updateLockScreenTimeout() {
6775        synchronized (mScreenLockTimeout) {
6776            boolean enable = (mAllowLockscreenWhenOn && mAwake &&
6777                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
6778            if (mLockScreenTimerActive != enable) {
6779                if (enable) {
6780                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
6781                    mHandler.removeCallbacks(mScreenLockTimeout); // remove any pending requests
6782                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6783                } else {
6784                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
6785                    mHandler.removeCallbacks(mScreenLockTimeout);
6786                }
6787                mLockScreenTimerActive = enable;
6788            }
6789        }
6790    }
6791
6792    private void updateDreamingSleepToken(boolean acquire) {
6793        if (acquire) {
6794            if (mDreamingSleepToken == null) {
6795                mDreamingSleepToken = mActivityManagerInternal.acquireSleepToken("Dream");
6796            }
6797        } else {
6798            if (mDreamingSleepToken != null) {
6799                mDreamingSleepToken.release();
6800                mDreamingSleepToken = null;
6801            }
6802        }
6803    }
6804
6805    private void updateScreenOffSleepToken(boolean acquire) {
6806        if (acquire) {
6807            if (mScreenOffSleepToken == null) {
6808                mScreenOffSleepToken = mActivityManagerInternal.acquireSleepToken("ScreenOff");
6809            }
6810        } else {
6811            if (mScreenOffSleepToken != null) {
6812                mScreenOffSleepToken.release();
6813                mScreenOffSleepToken = null;
6814            }
6815        }
6816    }
6817
6818    /** {@inheritDoc} */
6819    @Override
6820    public void enableScreenAfterBoot() {
6821        readLidState();
6822        applyLidSwitchState();
6823        updateRotation(true);
6824    }
6825
6826    private void applyLidSwitchState() {
6827        if (mLidState == LID_CLOSED && mLidControlsSleep) {
6828            mPowerManager.goToSleep(SystemClock.uptimeMillis(),
6829                    PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
6830                    PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
6831        } else if (mLidState == LID_CLOSED && mLidControlsScreenLock) {
6832            mWindowManagerFuncs.lockDeviceNow();
6833        }
6834
6835        synchronized (mLock) {
6836            updateWakeGestureListenerLp();
6837        }
6838    }
6839
6840    void updateUiMode() {
6841        if (mUiModeManager == null) {
6842            mUiModeManager = IUiModeManager.Stub.asInterface(
6843                    ServiceManager.getService(Context.UI_MODE_SERVICE));
6844        }
6845        try {
6846            mUiMode = mUiModeManager.getCurrentModeType();
6847        } catch (RemoteException e) {
6848        }
6849    }
6850
6851    void updateRotation(boolean alwaysSendConfiguration) {
6852        try {
6853            //set orientation on WindowManager
6854            mWindowManager.updateRotation(alwaysSendConfiguration, false);
6855        } catch (RemoteException e) {
6856            // Ignore
6857        }
6858    }
6859
6860    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
6861        try {
6862            //set orientation on WindowManager
6863            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
6864        } catch (RemoteException e) {
6865            // Ignore
6866        }
6867    }
6868
6869    /**
6870     * Return an Intent to launch the currently active dock app as home.  Returns
6871     * null if the standard home should be launched, which is the case if any of the following is
6872     * true:
6873     * <ul>
6874     *  <li>The device is not in either car mode or desk mode
6875     *  <li>The device is in car mode but mEnableCarDockHomeCapture is false
6876     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
6877     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
6878     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
6879     * </ul>
6880     * @return A dock intent.
6881     */
6882    Intent createHomeDockIntent() {
6883        Intent intent = null;
6884
6885        // What home does is based on the mode, not the dock state.  That
6886        // is, when in car mode you should be taken to car home regardless
6887        // of whether we are actually in a car dock.
6888        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
6889            if (mEnableCarDockHomeCapture) {
6890                intent = mCarDockIntent;
6891            }
6892        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
6893            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
6894                intent = mDeskDockIntent;
6895            }
6896        } else if (mUiMode == Configuration.UI_MODE_TYPE_WATCH
6897                && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6898                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK
6899                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK)) {
6900            // Always launch dock home from home when watch is docked, if it exists.
6901            intent = mDeskDockIntent;
6902        }
6903
6904        if (intent == null) {
6905            return null;
6906        }
6907
6908        ActivityInfo ai = null;
6909        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
6910                intent,
6911                PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
6912                mCurrentUserId);
6913        if (info != null) {
6914            ai = info.activityInfo;
6915        }
6916        if (ai != null
6917                && ai.metaData != null
6918                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
6919            intent = new Intent(intent);
6920            intent.setClassName(ai.packageName, ai.name);
6921            return intent;
6922        }
6923
6924        return null;
6925    }
6926
6927    void startDockOrHome(boolean fromHomeKey, boolean awakenFromDreams) {
6928        if (awakenFromDreams) {
6929            awakenDreams();
6930        }
6931
6932        Intent dock = createHomeDockIntent();
6933        if (dock != null) {
6934            try {
6935                if (fromHomeKey) {
6936                    dock.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6937                }
6938                startActivityAsUser(dock, UserHandle.CURRENT);
6939                return;
6940            } catch (ActivityNotFoundException e) {
6941            }
6942        }
6943
6944        Intent intent;
6945
6946        if (fromHomeKey) {
6947            intent = new Intent(mHomeIntent);
6948            intent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6949        } else {
6950            intent = mHomeIntent;
6951        }
6952
6953        startActivityAsUser(intent, UserHandle.CURRENT);
6954    }
6955
6956    /**
6957     * goes to the home screen
6958     * @return whether it did anything
6959     */
6960    boolean goHome() {
6961        if (!isUserSetupComplete()) {
6962            Slog.i(TAG, "Not going home because user setup is in progress.");
6963            return false;
6964        }
6965        if (false) {
6966            // This code always brings home to the front.
6967            try {
6968                ActivityManagerNative.getDefault().stopAppSwitches();
6969            } catch (RemoteException e) {
6970            }
6971            sendCloseSystemWindows();
6972            startDockOrHome(false /*fromHomeKey*/, true /* awakenFromDreams */);
6973        } else {
6974            // This code brings home to the front or, if it is already
6975            // at the front, puts the device to sleep.
6976            try {
6977                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
6978                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
6979                    Log.d(TAG, "UTS-TEST-MODE");
6980                } else {
6981                    ActivityManagerNative.getDefault().stopAppSwitches();
6982                    sendCloseSystemWindows();
6983                    Intent dock = createHomeDockIntent();
6984                    if (dock != null) {
6985                        int result = ActivityManagerNative.getDefault()
6986                                .startActivityAsUser(null, null, dock,
6987                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
6988                                        null, null, 0,
6989                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6990                                        null, null, UserHandle.USER_CURRENT);
6991                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6992                            return false;
6993                        }
6994                    }
6995                }
6996                int result = ActivityManagerNative.getDefault()
6997                        .startActivityAsUser(null, null, mHomeIntent,
6998                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
6999                                null, null, 0,
7000                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
7001                                null, null, UserHandle.USER_CURRENT);
7002                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
7003                    return false;
7004                }
7005            } catch (RemoteException ex) {
7006                // bummer, the activity manager, which is in this process, is dead
7007            }
7008        }
7009        return true;
7010    }
7011
7012    @Override
7013    public void setCurrentOrientationLw(int newOrientation) {
7014        synchronized (mLock) {
7015            if (newOrientation != mCurrentAppOrientation) {
7016                mCurrentAppOrientation = newOrientation;
7017                updateOrientationListenerLp();
7018            }
7019        }
7020    }
7021
7022    private void performAuditoryFeedbackForAccessibilityIfNeed() {
7023        if (!isGlobalAccessibilityGestureEnabled()) {
7024            return;
7025        }
7026        AudioManager audioManager = (AudioManager) mContext.getSystemService(
7027                Context.AUDIO_SERVICE);
7028        if (audioManager.isSilentMode()) {
7029            return;
7030        }
7031        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
7032                Settings.System.DEFAULT_NOTIFICATION_URI);
7033        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
7034        ringTone.play();
7035    }
7036
7037    private boolean isTheaterModeEnabled() {
7038        return Settings.Global.getInt(mContext.getContentResolver(),
7039                Settings.Global.THEATER_MODE_ON, 0) == 1;
7040    }
7041
7042    private boolean isGlobalAccessibilityGestureEnabled() {
7043        return Settings.Global.getInt(mContext.getContentResolver(),
7044                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
7045    }
7046
7047    @Override
7048    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
7049        if (!mVibrator.hasVibrator()) {
7050            return false;
7051        }
7052        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
7053                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
7054        if (hapticsDisabled && !always) {
7055            return false;
7056        }
7057        long[] pattern = null;
7058        switch (effectId) {
7059            case HapticFeedbackConstants.LONG_PRESS:
7060                pattern = mLongPressVibePattern;
7061                break;
7062            case HapticFeedbackConstants.VIRTUAL_KEY:
7063                pattern = mVirtualKeyVibePattern;
7064                break;
7065            case HapticFeedbackConstants.KEYBOARD_TAP:
7066                pattern = mKeyboardTapVibePattern;
7067                break;
7068            case HapticFeedbackConstants.CLOCK_TICK:
7069                pattern = mClockTickVibePattern;
7070                break;
7071            case HapticFeedbackConstants.CALENDAR_DATE:
7072                pattern = mCalendarDateVibePattern;
7073                break;
7074            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
7075                pattern = mSafeModeDisabledVibePattern;
7076                break;
7077            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
7078                pattern = mSafeModeEnabledVibePattern;
7079                break;
7080            case HapticFeedbackConstants.CONTEXT_CLICK:
7081                pattern = mContextClickVibePattern;
7082                break;
7083            default:
7084                return false;
7085        }
7086        int owningUid;
7087        String owningPackage;
7088        if (win != null) {
7089            owningUid = win.getOwningUid();
7090            owningPackage = win.getOwningPackage();
7091        } else {
7092            owningUid = android.os.Process.myUid();
7093            owningPackage = mContext.getOpPackageName();
7094        }
7095        if (pattern.length == 1) {
7096            // One-shot vibration
7097            mVibrator.vibrate(owningUid, owningPackage, pattern[0], VIBRATION_ATTRIBUTES);
7098        } else {
7099            // Pattern vibration
7100            mVibrator.vibrate(owningUid, owningPackage, pattern, -1, VIBRATION_ATTRIBUTES);
7101        }
7102        return true;
7103    }
7104
7105    @Override
7106    public void keepScreenOnStartedLw() {
7107    }
7108
7109    @Override
7110    public void keepScreenOnStoppedLw() {
7111        if (isKeyguardShowingAndNotOccluded()) {
7112            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
7113        }
7114    }
7115
7116    private int updateSystemUiVisibilityLw() {
7117        // If there is no window focused, there will be nobody to handle the events
7118        // anyway, so just hang on in whatever state we're in until things settle down.
7119        final WindowState win = mFocusedWindow != null ? mFocusedWindow
7120                : mTopFullscreenOpaqueWindowState;
7121        if (win == null) {
7122            return 0;
7123        }
7124        if ((win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 && mHideLockScreen == true) {
7125            // We are updating at a point where the keyguard has gotten
7126            // focus, but we were last in a state where the top window is
7127            // hiding it.  This is probably because the keyguard as been
7128            // shown while the top window was displayed, so we want to ignore
7129            // it here because this is just a very transient change and it
7130            // will quickly lose focus once it correctly gets hidden.
7131            return 0;
7132        }
7133
7134        int tmpVisibility = PolicyControl.getSystemUiVisibility(win, null)
7135                & ~mResettingSystemUiFlags
7136                & ~mForceClearedSystemUiFlags;
7137        if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
7138            tmpVisibility &= ~PolicyControl.adjustClearableFlags(win, View.SYSTEM_UI_CLEARABLE_FLAGS);
7139        }
7140
7141        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
7142            tmpVisibility |= StatusBarManager.DISABLE_RECENT;
7143        }
7144
7145        final int fullscreenVisibility = updateLightStatusBarLw(0 /* vis */,
7146                mTopFullscreenOpaqueWindowState, mTopFullscreenOpaqueOrDimmingWindowState);
7147        final int dockedVisibility = updateLightStatusBarLw(0 /* vis */,
7148                mTopDockedOpaqueWindowState, mTopDockedOpaqueOrDimmingWindowState);
7149        mWindowManagerFuncs.getStackBounds(HOME_STACK_ID, mNonDockedStackBounds);
7150        mWindowManagerFuncs.getStackBounds(DOCKED_STACK_ID, mDockedStackBounds);
7151        final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
7152        final int diff = visibility ^ mLastSystemUiFlags;
7153        final int fullscreenDiff = fullscreenVisibility ^ mLastFullscreenStackSysUiFlags;
7154        final int dockedDiff = dockedVisibility ^ mLastDockedStackSysUiFlags;
7155        final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
7156        if (diff == 0 && fullscreenDiff == 0 && dockedDiff == 0 && mLastFocusNeedsMenu == needsMenu
7157                && mFocusedApp == win.getAppToken()
7158                && mLastNonDockedStackBounds.equals(mNonDockedStackBounds)
7159                && mLastDockedStackBounds.equals(mDockedStackBounds)) {
7160            return 0;
7161        }
7162        mLastSystemUiFlags = visibility;
7163        mLastFullscreenStackSysUiFlags = fullscreenVisibility;
7164        mLastDockedStackSysUiFlags = dockedVisibility;
7165        mLastFocusNeedsMenu = needsMenu;
7166        mFocusedApp = win.getAppToken();
7167        final Rect fullscreenStackBounds = new Rect(mNonDockedStackBounds);
7168        final Rect dockedStackBounds = new Rect(mDockedStackBounds);
7169        mHandler.post(new Runnable() {
7170                @Override
7171                public void run() {
7172                    StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
7173                    if (statusbar != null) {
7174                        statusbar.setSystemUiVisibility(visibility, fullscreenVisibility,
7175                                dockedVisibility, 0xffffffff, fullscreenStackBounds,
7176                                dockedStackBounds, win.toString());
7177                        statusbar.topAppWindowChanged(needsMenu);
7178                    }
7179                }
7180            });
7181        return diff;
7182    }
7183
7184    private int updateLightStatusBarLw(int vis, WindowState opaque, WindowState opaqueOrDimming) {
7185        WindowState statusColorWin = isStatusBarKeyguard() && !mHideLockScreen
7186                ? mStatusBar
7187                : opaqueOrDimming;
7188
7189        if (statusColorWin != null) {
7190            if (statusColorWin == opaque) {
7191                // If the top fullscreen-or-dimming window is also the top fullscreen, respect
7192                // its light flag.
7193                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7194                vis |= PolicyControl.getSystemUiVisibility(statusColorWin, null)
7195                        & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7196            } else if (statusColorWin != null && statusColorWin.isDimming()) {
7197                // Otherwise if it's dimming, clear the light flag.
7198                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7199            }
7200        }
7201        return vis;
7202    }
7203
7204    private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
7205        final boolean dockedStackVisible = mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID);
7206        final boolean freeformStackVisible =
7207                mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID);
7208        final boolean resizing = mWindowManagerInternal.isDockedDividerResizing();
7209
7210        // We need to force system bars when the docked stack is visible, when the freeform stack
7211        // is visible but also when we are resizing for the transitions when docked stack
7212        // visibility changes.
7213        mForceShowSystemBars = dockedStackVisible || freeformStackVisible || resizing;
7214        final boolean forceOpaqueStatusBar = mForceShowSystemBars && !mForceStatusBarFromKeyguard;
7215
7216        // apply translucent bar vis flags
7217        WindowState transWin = isStatusBarKeyguard() && !mHideLockScreen
7218                ? mStatusBar
7219                : mTopFullscreenOpaqueWindowState;
7220        vis = mStatusBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
7221        vis = mNavigationBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
7222
7223        // prevent status bar interaction from clearing certain flags
7224        int type = win.getAttrs().type;
7225        boolean statusBarHasFocus = type == TYPE_STATUS_BAR;
7226        if (statusBarHasFocus && !isStatusBarKeyguard()) {
7227            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
7228                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
7229                    | View.SYSTEM_UI_FLAG_IMMERSIVE
7230                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
7231                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7232            if (mHideLockScreen) {
7233                flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
7234            }
7235            vis = (vis & ~flags) | (oldVis & flags);
7236        }
7237
7238        if ((!areTranslucentBarsAllowed() && transWin != mStatusBar)
7239                || forceOpaqueStatusBar) {
7240            vis &= ~(View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT);
7241        }
7242
7243        vis = configureNavBarOpacity(vis, dockedStackVisible, freeformStackVisible, resizing);
7244
7245        if (mForceWindowDrawsStatusBarBackground) {
7246            vis |= View.STATUS_BAR_TRANSPARENT;
7247            vis &= ~View.STATUS_BAR_TRANSLUCENT;
7248        }
7249
7250        // update status bar
7251        boolean immersiveSticky =
7252                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7253        final boolean hideStatusBarWM =
7254                mTopFullscreenOpaqueWindowState != null
7255                && (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
7256                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
7257        final boolean hideStatusBarSysui =
7258                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
7259        final boolean hideNavBarSysui =
7260                (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
7261
7262        final boolean transientStatusBarAllowed = mStatusBar != null
7263                && (statusBarHasFocus || (!mForceShowSystemBars
7264                        && (hideStatusBarWM || (hideStatusBarSysui && immersiveSticky))));
7265
7266        final boolean transientNavBarAllowed = mNavigationBar != null
7267                && !mForceShowSystemBars && hideNavBarSysui && immersiveSticky;
7268
7269        final long now = SystemClock.uptimeMillis();
7270        final boolean pendingPanic = mPendingPanicGestureUptime != 0
7271                && now - mPendingPanicGestureUptime <= PANIC_GESTURE_EXPIRATION;
7272        if (pendingPanic && hideNavBarSysui && !isStatusBarKeyguard() && mKeyguardDrawComplete) {
7273            // The user performed the panic gesture recently, we're about to hide the bars,
7274            // we're no longer on the Keyguard and the screen is ready. We can now request the bars.
7275            mPendingPanicGestureUptime = 0;
7276            mStatusBarController.showTransient();
7277            mNavigationBarController.showTransient();
7278        }
7279
7280        final boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
7281                && !transientStatusBarAllowed && hideStatusBarSysui;
7282        final boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
7283                && !transientNavBarAllowed;
7284        if (denyTransientStatus || denyTransientNav || mForceShowSystemBars) {
7285            // clear the clearable flags instead
7286            clearClearableFlagsLw();
7287            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
7288        }
7289
7290        final boolean immersive = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
7291        immersiveSticky = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7292        final boolean navAllowedHidden = immersive || immersiveSticky;
7293
7294        if (hideNavBarSysui && !navAllowedHidden && windowTypeToLayerLw(win.getBaseType())
7295                > windowTypeToLayerLw(TYPE_INPUT_CONSUMER)) {
7296            // We can't hide the navbar from this window otherwise the input consumer would not get
7297            // the input events.
7298            vis = (vis & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
7299        }
7300
7301        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
7302
7303        // update navigation bar
7304        boolean oldImmersiveMode = isImmersiveMode(oldVis);
7305        boolean newImmersiveMode = isImmersiveMode(vis);
7306        if (win != null && oldImmersiveMode != newImmersiveMode) {
7307            final String pkg = win.getOwningPackage();
7308            mImmersiveModeConfirmation.immersiveModeChanged(pkg, newImmersiveMode,
7309                    isUserSetupComplete());
7310        }
7311
7312        vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
7313
7314        return vis;
7315    }
7316
7317    /**
7318     * @return the current visibility flags with the nav-bar opacity related flags toggled based
7319     *         on the nav bar opacity rules chosen by {@link #mNavBarOpacityMode}.
7320     */
7321    private int configureNavBarOpacity(int visibility, boolean dockedStackVisible,
7322            boolean freeformStackVisible, boolean isDockedDividerResizing) {
7323        if (mNavBarOpacityMode == NAV_BAR_OPAQUE_WHEN_FREEFORM_OR_DOCKED) {
7324            if (dockedStackVisible || freeformStackVisible || isDockedDividerResizing) {
7325                visibility = setNavBarOpaqueFlag(visibility);
7326            }
7327        } else if (mNavBarOpacityMode == NAV_BAR_TRANSLUCENT_WHEN_FREEFORM_OPAQUE_OTHERWISE) {
7328            if (isDockedDividerResizing) {
7329                visibility = setNavBarOpaqueFlag(visibility);
7330            } else if (freeformStackVisible) {
7331                visibility = setNavBarTranslucentFlag(visibility);
7332            } else {
7333                visibility = setNavBarOpaqueFlag(visibility);
7334            }
7335        }
7336
7337        if (!areTranslucentBarsAllowed()) {
7338            visibility &= ~View.NAVIGATION_BAR_TRANSLUCENT;
7339        }
7340        return visibility;
7341    }
7342
7343    private int setNavBarOpaqueFlag(int visibility) {
7344        return visibility &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT);
7345    }
7346
7347    private int setNavBarTranslucentFlag(int visibility) {
7348        visibility &= ~View.NAVIGATION_BAR_TRANSPARENT;
7349        return visibility |= View.NAVIGATION_BAR_TRANSLUCENT;
7350    }
7351
7352    private void clearClearableFlagsLw() {
7353        int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
7354        if (newVal != mResettingSystemUiFlags) {
7355            mResettingSystemUiFlags = newVal;
7356            mWindowManagerFuncs.reevaluateStatusBarVisibility();
7357        }
7358    }
7359
7360    private boolean isImmersiveMode(int vis) {
7361        final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
7362        return mNavigationBar != null
7363                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
7364                && (vis & flags) != 0
7365                && canHideNavigationBar();
7366    }
7367
7368    /**
7369     * @return whether the navigation or status bar can be made translucent
7370     *
7371     * This should return true unless touch exploration is not enabled or
7372     * R.boolean.config_enableTranslucentDecor is false.
7373     */
7374    private boolean areTranslucentBarsAllowed() {
7375        return mTranslucentDecorEnabled;
7376    }
7377
7378    // Use this instead of checking config_showNavigationBar so that it can be consistently
7379    // overridden by qemu.hw.mainkeys in the emulator.
7380    @Override
7381    public boolean hasNavigationBar() {
7382        return mHasNavigationBar;
7383    }
7384
7385    @Override
7386    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
7387        mLastInputMethodWindow = ime;
7388        mLastInputMethodTargetWindow = target;
7389    }
7390
7391    @Override
7392    public int getInputMethodWindowVisibleHeightLw() {
7393        return mDockBottom - mCurBottom;
7394    }
7395
7396    @Override
7397    public void setCurrentUserLw(int newUserId) {
7398        mCurrentUserId = newUserId;
7399        if (mKeyguardDelegate != null) {
7400            mKeyguardDelegate.setCurrentUser(newUserId);
7401        }
7402        if (mStatusBarService != null) {
7403            try {
7404                mStatusBarService.setCurrentUser(newUserId);
7405            } catch (RemoteException e) {
7406                // oh well
7407            }
7408        }
7409        setLastInputMethodWindowLw(null, null);
7410    }
7411
7412    @Override
7413    public boolean canMagnifyWindow(int windowType) {
7414        switch (windowType) {
7415            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
7416            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
7417            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
7418            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
7419                return false;
7420            }
7421        }
7422        return true;
7423    }
7424
7425    @Override
7426    public boolean isTopLevelWindow(int windowType) {
7427        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
7428                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
7429            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
7430        }
7431        return true;
7432    }
7433
7434    @Override
7435    public void dump(String prefix, PrintWriter pw, String[] args) {
7436        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
7437                pw.print(" mSystemReady="); pw.print(mSystemReady);
7438                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
7439        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
7440                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
7441                pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
7442                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
7443        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
7444                || mForceClearedSystemUiFlags != 0) {
7445            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
7446                    pw.print(Integer.toHexString(mLastSystemUiFlags));
7447                    pw.print(" mResettingSystemUiFlags=0x");
7448                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
7449                    pw.print(" mForceClearedSystemUiFlags=0x");
7450                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
7451        }
7452        if (mLastFocusNeedsMenu) {
7453            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
7454                    pw.println(mLastFocusNeedsMenu);
7455        }
7456        pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
7457                pw.println(mWakeGestureEnabledSetting);
7458
7459        pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
7460        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
7461                pw.print(" mDockMode="); pw.print(mDockMode);
7462                pw.print(" mEnableCarDockHomeCapture="); pw.print(mEnableCarDockHomeCapture);
7463                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
7464                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
7465        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
7466                pw.print(" mUserRotation="); pw.print(mUserRotation);
7467                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
7468        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
7469        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
7470                pw.print(mCarDockEnablesAccelerometer);
7471                pw.print(" mDeskDockEnablesAccelerometer=");
7472                pw.println(mDeskDockEnablesAccelerometer);
7473        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
7474                pw.print(mLidKeyboardAccessibility);
7475                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
7476                pw.print(" mLidControlsScreenLock="); pw.println(mLidControlsScreenLock);
7477                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
7478        pw.print(prefix);
7479                pw.print(" mLongPressOnBackBehavior="); pw.println(mLongPressOnBackBehavior);
7480        pw.print(prefix);
7481                pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
7482                pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
7483        pw.print(prefix);
7484                pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
7485                pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
7486        pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
7487        pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
7488        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
7489                pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
7490        pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
7491                pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
7492        pw.print(prefix); pw.print("mOrientationSensorEnabled=");
7493                pw.println(mOrientationSensorEnabled);
7494        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
7495                pw.print(","); pw.print(mOverscanScreenTop);
7496                pw.print(") "); pw.print(mOverscanScreenWidth);
7497                pw.print("x"); pw.println(mOverscanScreenHeight);
7498        if (mOverscanLeft != 0 || mOverscanTop != 0
7499                || mOverscanRight != 0 || mOverscanBottom != 0) {
7500            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
7501                    pw.print(" top="); pw.print(mOverscanTop);
7502                    pw.print(" right="); pw.print(mOverscanRight);
7503                    pw.print(" bottom="); pw.println(mOverscanBottom);
7504        }
7505        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
7506                pw.print(mRestrictedOverscanScreenLeft);
7507                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
7508                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
7509                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
7510        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
7511                pw.print(","); pw.print(mUnrestrictedScreenTop);
7512                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
7513                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
7514        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
7515                pw.print(","); pw.print(mRestrictedScreenTop);
7516                pw.print(") "); pw.print(mRestrictedScreenWidth);
7517                pw.print("x"); pw.println(mRestrictedScreenHeight);
7518        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
7519                pw.print(","); pw.print(mStableFullscreenTop);
7520                pw.print(")-("); pw.print(mStableFullscreenRight);
7521                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
7522        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
7523                pw.print(","); pw.print(mStableTop);
7524                pw.print(")-("); pw.print(mStableRight);
7525                pw.print(","); pw.print(mStableBottom); pw.println(")");
7526        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
7527                pw.print(","); pw.print(mSystemTop);
7528                pw.print(")-("); pw.print(mSystemRight);
7529                pw.print(","); pw.print(mSystemBottom); pw.println(")");
7530        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
7531                pw.print(","); pw.print(mCurTop);
7532                pw.print(")-("); pw.print(mCurRight);
7533                pw.print(","); pw.print(mCurBottom); pw.println(")");
7534        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
7535                pw.print(","); pw.print(mContentTop);
7536                pw.print(")-("); pw.print(mContentRight);
7537                pw.print(","); pw.print(mContentBottom); pw.println(")");
7538        pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
7539                pw.print(","); pw.print(mVoiceContentTop);
7540                pw.print(")-("); pw.print(mVoiceContentRight);
7541                pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
7542        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
7543                pw.print(","); pw.print(mDockTop);
7544                pw.print(")-("); pw.print(mDockRight);
7545                pw.print(","); pw.print(mDockBottom); pw.println(")");
7546        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
7547                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
7548        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
7549                pw.print(" mShowingDream="); pw.print(mShowingDream);
7550                pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
7551                pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
7552        if (mLastInputMethodWindow != null) {
7553            pw.print(prefix); pw.print("mLastInputMethodWindow=");
7554                    pw.println(mLastInputMethodWindow);
7555        }
7556        if (mLastInputMethodTargetWindow != null) {
7557            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
7558                    pw.println(mLastInputMethodTargetWindow);
7559        }
7560        if (mStatusBar != null) {
7561            pw.print(prefix); pw.print("mStatusBar=");
7562                    pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
7563                    pw.println(isStatusBarKeyguard());
7564        }
7565        if (mNavigationBar != null) {
7566            pw.print(prefix); pw.print("mNavigationBar=");
7567                    pw.println(mNavigationBar);
7568        }
7569        if (mFocusedWindow != null) {
7570            pw.print(prefix); pw.print("mFocusedWindow=");
7571                    pw.println(mFocusedWindow);
7572        }
7573        if (mFocusedApp != null) {
7574            pw.print(prefix); pw.print("mFocusedApp=");
7575                    pw.println(mFocusedApp);
7576        }
7577        if (mWinDismissingKeyguard != null) {
7578            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
7579                    pw.println(mWinDismissingKeyguard);
7580        }
7581        if (mTopFullscreenOpaqueWindowState != null) {
7582            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
7583                    pw.println(mTopFullscreenOpaqueWindowState);
7584        }
7585        if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
7586            pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
7587                    pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
7588        }
7589        if (mForcingShowNavBar) {
7590            pw.print(prefix); pw.print("mForcingShowNavBar=");
7591                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
7592                    pw.println(mForcingShowNavBarLayer);
7593        }
7594        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
7595                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
7596        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
7597                pw.print(" mForceStatusBarFromKeyguard=");
7598                pw.println(mForceStatusBarFromKeyguard);
7599        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
7600                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
7601                pw.print(" mHomePressed="); pw.println(mHomePressed);
7602        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
7603                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
7604                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
7605        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
7606                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
7607                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
7608        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
7609                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
7610        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
7611                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
7612        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
7613                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
7614        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
7615
7616        mGlobalKeyManager.dump(prefix, pw);
7617        mStatusBarController.dump(pw, prefix);
7618        mNavigationBarController.dump(pw, prefix);
7619        PolicyControl.dump(prefix, pw);
7620
7621        if (mWakeGestureListener != null) {
7622            mWakeGestureListener.dump(pw, prefix);
7623        }
7624        if (mOrientationListener != null) {
7625            mOrientationListener.dump(pw, prefix);
7626        }
7627        if (mBurnInProtectionHelper != null) {
7628            mBurnInProtectionHelper.dump(prefix, pw);
7629        }
7630        if (mKeyguardDelegate != null) {
7631            mKeyguardDelegate.dump(prefix, pw);
7632        }
7633    }
7634}
7635