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