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