PhoneWindowManager.java revision 933076d80561751618f462b26309ce9e4c3ff3bf
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) {
3111                if (repeatCount == 0) {
3112                    toggleKeyboardShortcutsMenu(event.getDeviceId());
3113                }
3114            }
3115        } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
3116            if (down) {
3117                if (repeatCount == 0) {
3118                    mAssistKeyLongPressed = false;
3119                } else if (repeatCount == 1) {
3120                    mAssistKeyLongPressed = true;
3121                    if (!keyguardOn) {
3122                         launchAssistLongPressAction();
3123                    }
3124                }
3125            } else {
3126                if (mAssistKeyLongPressed) {
3127                    mAssistKeyLongPressed = false;
3128                } else {
3129                    if (!keyguardOn) {
3130                        launchAssistAction(null, event.getDeviceId());
3131                    }
3132                }
3133            }
3134            return -1;
3135        } else if (keyCode == KeyEvent.KEYCODE_VOICE_ASSIST) {
3136            if (!down) {
3137                Intent voiceIntent;
3138                if (!keyguardOn) {
3139                    voiceIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3140                } else {
3141                    IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
3142                            ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
3143                    if (dic != null) {
3144                        try {
3145                            dic.exitIdle("voice-search");
3146                        } catch (RemoteException e) {
3147                        }
3148                    }
3149                    voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
3150                    voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, true);
3151                }
3152                startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
3153            }
3154        } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
3155            if (down && repeatCount == 0) {
3156                mScreenshotRunnable.setScreenshotType(TAKE_SCREENSHOT_FULLSCREEN);
3157                mHandler.post(mScreenshotRunnable);
3158            }
3159            return -1;
3160        } else if (keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP
3161                || keyCode == KeyEvent.KEYCODE_BRIGHTNESS_DOWN) {
3162            if (down) {
3163                int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1;
3164
3165                // Disable autobrightness if it's on
3166                int auto = Settings.System.getIntForUser(
3167                        mContext.getContentResolver(),
3168                        Settings.System.SCREEN_BRIGHTNESS_MODE,
3169                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3170                        UserHandle.USER_CURRENT_OR_SELF);
3171                if (auto != 0) {
3172                    Settings.System.putIntForUser(mContext.getContentResolver(),
3173                            Settings.System.SCREEN_BRIGHTNESS_MODE,
3174                            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3175                            UserHandle.USER_CURRENT_OR_SELF);
3176                }
3177
3178                int min = mPowerManager.getMinimumScreenBrightnessSetting();
3179                int max = mPowerManager.getMaximumScreenBrightnessSetting();
3180                int step = (max - min + BRIGHTNESS_STEPS - 1) / BRIGHTNESS_STEPS * direction;
3181                int brightness = Settings.System.getIntForUser(mContext.getContentResolver(),
3182                        Settings.System.SCREEN_BRIGHTNESS,
3183                        mPowerManager.getDefaultScreenBrightnessSetting(),
3184                        UserHandle.USER_CURRENT_OR_SELF);
3185                brightness += step;
3186                // Make sure we don't go beyond the limits.
3187                brightness = Math.min(max, brightness);
3188                brightness = Math.max(min, brightness);
3189
3190                Settings.System.putIntForUser(mContext.getContentResolver(),
3191                        Settings.System.SCREEN_BRIGHTNESS, brightness,
3192                        UserHandle.USER_CURRENT_OR_SELF);
3193                startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG),
3194                        UserHandle.CURRENT_OR_SELF);
3195            }
3196            return -1;
3197        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP
3198                || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
3199                || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
3200            if (mUseTvRouting) {
3201                // On TVs volume keys never go to the foreground app.
3202                dispatchDirectAudioEvent(event);
3203                return -1;
3204            }
3205        }
3206
3207        if (KeyEvent.isMetaKey(keyCode)) {
3208            if (down) {
3209                mPendingMetaAction = true;
3210            } else if (mPendingMetaAction) {
3211                launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, event.getDeviceId());
3212            }
3213            return -1;
3214        }
3215
3216        // Shortcuts are invoked through Search+key, so intercept those here
3217        // Any printing key that is chorded with Search should be consumed
3218        // even if no shortcut was invoked.  This prevents text from being
3219        // inadvertently inserted when using a keyboard that has built-in macro
3220        // shortcut keys (that emit Search+x) and some of them are not registered.
3221        if (mSearchKeyShortcutPending) {
3222            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3223            if (kcm.isPrintingKey(keyCode)) {
3224                mConsumeSearchKeyUp = true;
3225                mSearchKeyShortcutPending = false;
3226                if (down && repeatCount == 0 && !keyguardOn) {
3227                    Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
3228                    if (shortcutIntent != null) {
3229                        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3230                        try {
3231                            startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3232                        } catch (ActivityNotFoundException ex) {
3233                            Slog.w(TAG, "Dropping shortcut key combination because "
3234                                    + "the activity to which it is registered was not found: "
3235                                    + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
3236                        }
3237                    } else {
3238                        Slog.i(TAG, "Dropping unregistered shortcut key combination: "
3239                                + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
3240                    }
3241                }
3242                return -1;
3243            }
3244        }
3245
3246        // Invoke shortcuts using Meta.
3247        if (down && repeatCount == 0 && !keyguardOn
3248                && (metaState & KeyEvent.META_META_ON) != 0) {
3249            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3250            if (kcm.isPrintingKey(keyCode)) {
3251                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
3252                        metaState & ~(KeyEvent.META_META_ON
3253                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
3254                if (shortcutIntent != null) {
3255                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3256                    try {
3257                        startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3258                    } catch (ActivityNotFoundException ex) {
3259                        Slog.w(TAG, "Dropping shortcut key combination because "
3260                                + "the activity to which it is registered was not found: "
3261                                + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
3262                    }
3263                    return -1;
3264                }
3265            }
3266        }
3267
3268        // Handle application launch keys.
3269        if (down && repeatCount == 0 && !keyguardOn) {
3270            String category = sApplicationLaunchKeyCategories.get(keyCode);
3271            if (category != null) {
3272                Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
3273                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3274                try {
3275                    startActivityAsUser(intent, UserHandle.CURRENT);
3276                } catch (ActivityNotFoundException ex) {
3277                    Slog.w(TAG, "Dropping application launch key because "
3278                            + "the activity to which it is registered was not found: "
3279                            + "keyCode=" + keyCode + ", category=" + category, ex);
3280                }
3281                return -1;
3282            }
3283        }
3284
3285        // Display task switcher for ALT-TAB.
3286        if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
3287            if (mRecentAppsHeldModifiers == 0 && !keyguardOn && isUserSetupComplete()) {
3288                final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
3289                if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)) {
3290                    mRecentAppsHeldModifiers = shiftlessModifiers;
3291                    showRecentApps(true);
3292                    return -1;
3293                }
3294            }
3295        } else if (!down && mRecentAppsHeldModifiers != 0
3296                && (metaState & mRecentAppsHeldModifiers) == 0) {
3297            mRecentAppsHeldModifiers = 0;
3298            hideRecentApps(true, false);
3299        }
3300
3301        // Handle input method switching.
3302        if (down && repeatCount == 0
3303                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3304                        || (keyCode == KeyEvent.KEYCODE_SPACE
3305                                && (metaState & KeyEvent.META_META_MASK) != 0))) {
3306            final boolean forwardDirection = (metaState & KeyEvent.META_SHIFT_MASK) == 0;
3307            mWindowManagerFuncs.switchInputMethod(forwardDirection);
3308            return -1;
3309        }
3310        if (mLanguageSwitchKeyPressed && !down
3311                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3312                        || keyCode == KeyEvent.KEYCODE_SPACE)) {
3313            mLanguageSwitchKeyPressed = false;
3314            return -1;
3315        }
3316
3317        if (isValidGlobalKey(keyCode)
3318                && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
3319            return -1;
3320        }
3321
3322        if (down) {
3323            long shortcutCode = (long) keyCode;
3324            if (event.isCtrlPressed()) {
3325                shortcutCode |= ((long) KeyEvent.META_CTRL_ON) << Integer.SIZE;
3326            }
3327
3328            if (event.isAltPressed()) {
3329                shortcutCode |= ((long) KeyEvent.META_ALT_ON) << Integer.SIZE;
3330            }
3331
3332            if (event.isShiftPressed()) {
3333                shortcutCode |= ((long) KeyEvent.META_SHIFT_ON) << Integer.SIZE;
3334            }
3335
3336            if (event.isMetaPressed()) {
3337                shortcutCode |= ((long) KeyEvent.META_META_ON) << Integer.SIZE;
3338            }
3339
3340            IShortcutService shortcutService = mShortcutKeyServices.get(shortcutCode);
3341            if (shortcutService != null) {
3342                try {
3343                    shortcutService.notifyShortcutKeyPressed(shortcutCode);
3344                } catch (RemoteException e) {
3345                    mShortcutKeyServices.delete(shortcutCode);
3346                }
3347                return -1;
3348            }
3349        }
3350
3351        // Reserve all the META modifier combos for system behavior
3352        if ((metaState & KeyEvent.META_META_ON) != 0) {
3353            return -1;
3354        }
3355
3356        // Let the application handle the key.
3357        return 0;
3358    }
3359
3360    /** {@inheritDoc} */
3361    @Override
3362    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
3363        // Note: This method is only called if the initial down was unhandled.
3364        if (DEBUG_INPUT) {
3365            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
3366                    + ", flags=" + event.getFlags()
3367                    + ", keyCode=" + event.getKeyCode()
3368                    + ", scanCode=" + event.getScanCode()
3369                    + ", metaState=" + event.getMetaState()
3370                    + ", repeatCount=" + event.getRepeatCount()
3371                    + ", policyFlags=" + policyFlags);
3372        }
3373
3374        KeyEvent fallbackEvent = null;
3375        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3376            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3377            final int keyCode = event.getKeyCode();
3378            final int metaState = event.getMetaState();
3379            final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
3380                    && event.getRepeatCount() == 0;
3381
3382            // Check for fallback actions specified by the key character map.
3383            final FallbackAction fallbackAction;
3384            if (initialDown) {
3385                fallbackAction = kcm.getFallbackAction(keyCode, metaState);
3386            } else {
3387                fallbackAction = mFallbackActions.get(keyCode);
3388            }
3389
3390            if (fallbackAction != null) {
3391                if (DEBUG_INPUT) {
3392                    Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
3393                            + " metaState=" + Integer.toHexString(fallbackAction.metaState));
3394                }
3395
3396                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
3397                fallbackEvent = KeyEvent.obtain(
3398                        event.getDownTime(), event.getEventTime(),
3399                        event.getAction(), fallbackAction.keyCode,
3400                        event.getRepeatCount(), fallbackAction.metaState,
3401                        event.getDeviceId(), event.getScanCode(),
3402                        flags, event.getSource(), null);
3403
3404                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
3405                    fallbackEvent.recycle();
3406                    fallbackEvent = null;
3407                }
3408
3409                if (initialDown) {
3410                    mFallbackActions.put(keyCode, fallbackAction);
3411                } else if (event.getAction() == KeyEvent.ACTION_UP) {
3412                    mFallbackActions.remove(keyCode);
3413                    fallbackAction.recycle();
3414                }
3415            }
3416        }
3417
3418        if (DEBUG_INPUT) {
3419            if (fallbackEvent == null) {
3420                Slog.d(TAG, "No fallback.");
3421            } else {
3422                Slog.d(TAG, "Performing fallback: " + fallbackEvent);
3423            }
3424        }
3425        return fallbackEvent;
3426    }
3427
3428    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
3429        int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
3430        if ((actions & ACTION_PASS_TO_USER) != 0) {
3431            long delayMillis = interceptKeyBeforeDispatching(
3432                    win, fallbackEvent, policyFlags);
3433            if (delayMillis == 0) {
3434                return true;
3435            }
3436        }
3437        return false;
3438    }
3439
3440    public void registerShortcutKey(long shortcutCode, IShortcutService shortcutService)
3441            throws RemoteException {
3442        synchronized (mLock) {
3443            IShortcutService service = mShortcutKeyServices.get(shortcutCode);
3444            if (service != null && service.asBinder().pingBinder()) {
3445                throw new RemoteException("Key already exists.");
3446            }
3447
3448            mShortcutKeyServices.put(shortcutCode, shortcutService);
3449        }
3450    }
3451
3452    private void launchAssistLongPressAction() {
3453        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3454        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3455
3456        // launch the search activity
3457        Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
3458        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3459        try {
3460            // TODO: This only stops the factory-installed search manager.
3461            // Need to formalize an API to handle others
3462            SearchManager searchManager = getSearchManager();
3463            if (searchManager != null) {
3464                searchManager.stopSearch();
3465            }
3466            startActivityAsUser(intent, UserHandle.CURRENT);
3467        } catch (ActivityNotFoundException e) {
3468            Slog.w(TAG, "No activity to handle assist long press action.", e);
3469        }
3470    }
3471
3472    private void launchAssistAction(String hint, int deviceId) {
3473        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3474        if (!isUserSetupComplete()) {
3475            // Disable opening assist window during setup
3476            return;
3477        }
3478        Bundle args = null;
3479        if (deviceId > Integer.MIN_VALUE) {
3480            args = new Bundle();
3481            args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
3482        }
3483        if ((mContext.getResources().getConfiguration().uiMode
3484                & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
3485            // On TV, use legacy handling until assistants are implemented in the proper way.
3486            ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
3487                    .launchLegacyAssist(hint, UserHandle.myUserId(), args);
3488        } else {
3489            try {
3490                if (hint != null) {
3491                    if (args == null) {
3492                        args = new Bundle();
3493                    }
3494                    args.putBoolean(hint, true);
3495                }
3496                IStatusBarService statusbar = getStatusBarService();
3497                if (statusbar != null) {
3498                    statusbar.startAssist(args);
3499                }
3500            } catch (RemoteException e) {
3501                Slog.e(TAG, "RemoteException when starting assist", e);
3502                // re-acquire status bar service next time it is needed.
3503                mStatusBarService = null;
3504            }
3505        }
3506    }
3507
3508    private void startActivityAsUser(Intent intent, UserHandle handle) {
3509        if (isUserSetupComplete()) {
3510            mContext.startActivityAsUser(intent, handle);
3511        } else {
3512            Slog.i(TAG, "Not starting activity because user setup is in progress: " + intent);
3513        }
3514    }
3515
3516    private SearchManager getSearchManager() {
3517        if (mSearchManager == null) {
3518            mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
3519        }
3520        return mSearchManager;
3521    }
3522
3523    private void preloadRecentApps() {
3524        mPreloadedRecentApps = true;
3525        try {
3526            IStatusBarService statusbar = getStatusBarService();
3527            if (statusbar != null) {
3528                statusbar.preloadRecentApps();
3529            }
3530        } catch (RemoteException e) {
3531            Slog.e(TAG, "RemoteException when preloading recent apps", e);
3532            // re-acquire status bar service next time it is needed.
3533            mStatusBarService = null;
3534        }
3535    }
3536
3537    private void cancelPreloadRecentApps() {
3538        if (mPreloadedRecentApps) {
3539            mPreloadedRecentApps = false;
3540            try {
3541                IStatusBarService statusbar = getStatusBarService();
3542                if (statusbar != null) {
3543                    statusbar.cancelPreloadRecentApps();
3544                }
3545            } catch (RemoteException e) {
3546                Slog.e(TAG, "RemoteException when cancelling recent apps preload", e);
3547                // re-acquire status bar service next time it is needed.
3548                mStatusBarService = null;
3549            }
3550        }
3551    }
3552
3553    private void toggleRecentApps() {
3554        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3555        try {
3556            IStatusBarService statusbar = getStatusBarService();
3557            if (statusbar != null) {
3558                statusbar.toggleRecentApps();
3559            }
3560        } catch (RemoteException e) {
3561            Slog.e(TAG, "RemoteException when toggling recent apps", e);
3562            // re-acquire status bar service next time it is needed.
3563            mStatusBarService = null;
3564        }
3565    }
3566
3567    @Override
3568    public void showRecentApps() {
3569        mHandler.removeMessages(MSG_DISPATCH_SHOW_RECENTS);
3570        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_RECENTS);
3571    }
3572
3573    private void showRecentApps(boolean triggeredFromAltTab) {
3574        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3575        try {
3576            IStatusBarService statusbar = getStatusBarService();
3577            if (statusbar != null) {
3578                statusbar.showRecentApps(triggeredFromAltTab);
3579            }
3580        } catch (RemoteException e) {
3581            Slog.e(TAG, "RemoteException when showing recent apps", e);
3582            // re-acquire status bar service next time it is needed.
3583            mStatusBarService = null;
3584        }
3585    }
3586
3587    private void toggleKeyboardShortcutsMenu(int deviceId) {
3588        try {
3589            IStatusBarService statusbar = getStatusBarService();
3590            if (statusbar != null) {
3591                statusbar.toggleKeyboardShortcutsMenu(deviceId);
3592            }
3593        } catch (RemoteException e) {
3594            Slog.e(TAG, "RemoteException when showing keyboard shortcuts menu", e);
3595        }
3596    }
3597
3598    private void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHome) {
3599        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3600        try {
3601            IStatusBarService statusbar = getStatusBarService();
3602            if (statusbar != null) {
3603                statusbar.hideRecentApps(triggeredFromAltTab, triggeredFromHome);
3604            }
3605        } catch (RemoteException e) {
3606            Slog.e(TAG, "RemoteException when closing recent apps", e);
3607            // re-acquire status bar service next time it is needed.
3608            mStatusBarService = null;
3609        }
3610    }
3611
3612    void launchHomeFromHotKey() {
3613        launchHomeFromHotKey(true /* awakenFromDreams */, true /*respectKeyguard*/);
3614    }
3615
3616    /**
3617     * A home key -> launch home action was detected.  Take the appropriate action
3618     * given the situation with the keyguard.
3619     */
3620    void launchHomeFromHotKey(final boolean awakenFromDreams, final boolean respectKeyguard) {
3621        if (respectKeyguard) {
3622            if (isKeyguardShowingAndNotOccluded()) {
3623                // don't launch home if keyguard showing
3624                return;
3625            }
3626
3627            if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
3628                // when in keyguard restricted mode, must first verify unlock
3629                // before launching home
3630                mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
3631                    @Override
3632                    public void onKeyguardExitResult(boolean success) {
3633                        if (success) {
3634                            try {
3635                                ActivityManagerNative.getDefault().stopAppSwitches();
3636                            } catch (RemoteException e) {
3637                            }
3638                            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3639                            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3640                        }
3641                    }
3642                });
3643                return;
3644            }
3645        }
3646
3647        // no keyguard stuff to worry about, just launch home!
3648        try {
3649            ActivityManagerNative.getDefault().stopAppSwitches();
3650        } catch (RemoteException e) {
3651        }
3652        if (mRecentsVisible) {
3653            // Hide Recents and notify it to launch Home
3654            if (awakenFromDreams) {
3655                awakenDreams();
3656            }
3657            hideRecentApps(false, true);
3658        } else {
3659            // Otherwise, just launch Home
3660            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3661            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3662        }
3663    }
3664
3665    private final Runnable mClearHideNavigationFlag = new Runnable() {
3666        @Override
3667        public void run() {
3668            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3669                // Clear flags.
3670                mForceClearedSystemUiFlags &=
3671                        ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3672            }
3673            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3674        }
3675    };
3676
3677    /**
3678     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
3679     * to determine when the nav bar should be shown and prevent applications from
3680     * receiving those touches.
3681     */
3682    final class HideNavInputEventReceiver extends InputEventReceiver {
3683        public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
3684            super(inputChannel, looper);
3685        }
3686
3687        @Override
3688        public void onInputEvent(InputEvent event) {
3689            boolean handled = false;
3690            try {
3691                if (event instanceof MotionEvent
3692                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3693                    final MotionEvent motionEvent = (MotionEvent)event;
3694                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
3695                        // When the user taps down, we re-show the nav bar.
3696                        boolean changed = false;
3697                        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3698                            // Any user activity always causes us to show the
3699                            // navigation controls, if they had been hidden.
3700                            // We also clear the low profile and only content
3701                            // flags so that tapping on the screen will atomically
3702                            // restore all currently hidden screen decorations.
3703                            int newVal = mResettingSystemUiFlags |
3704                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3705                                    View.SYSTEM_UI_FLAG_LOW_PROFILE |
3706                                    View.SYSTEM_UI_FLAG_FULLSCREEN;
3707                            if (mResettingSystemUiFlags != newVal) {
3708                                mResettingSystemUiFlags = newVal;
3709                                changed = true;
3710                            }
3711                            // We don't allow the system's nav bar to be hidden
3712                            // again for 1 second, to prevent applications from
3713                            // spamming us and keeping it from being shown.
3714                            newVal = mForceClearedSystemUiFlags |
3715                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3716                            if (mForceClearedSystemUiFlags != newVal) {
3717                                mForceClearedSystemUiFlags = newVal;
3718                                changed = true;
3719                                mHandler.postDelayed(mClearHideNavigationFlag, 1000);
3720                            }
3721                        }
3722                        if (changed) {
3723                            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3724                        }
3725                    }
3726                }
3727            } finally {
3728                finishInputEvent(event, handled);
3729            }
3730        }
3731    }
3732    final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
3733            new InputEventReceiver.Factory() {
3734        @Override
3735        public InputEventReceiver createInputEventReceiver(
3736                InputChannel inputChannel, Looper looper) {
3737            return new HideNavInputEventReceiver(inputChannel, looper);
3738        }
3739    };
3740
3741    @Override
3742    public int adjustSystemUiVisibilityLw(int visibility) {
3743        mStatusBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3744        mNavigationBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3745        mRecentsVisible = (visibility & View.RECENT_APPS_VISIBLE) > 0;
3746
3747        // Reset any bits in mForceClearingStatusBarVisibility that
3748        // are now clear.
3749        mResettingSystemUiFlags &= visibility;
3750        // Clear any bits in the new visibility that are currently being
3751        // force cleared, before reporting it.
3752        return visibility & ~mResettingSystemUiFlags
3753                & ~mForceClearedSystemUiFlags;
3754    }
3755
3756    @Override
3757    public boolean getInsetHintLw(WindowManager.LayoutParams attrs, int displayRotation,
3758            Rect outContentInsets, Rect outStableInsets, Rect outOutsets) {
3759        final int fl = PolicyControl.getWindowFlags(null, attrs);
3760        final int sysuiVis = PolicyControl.getSystemUiVisibility(null, attrs);
3761        final int systemUiVisibility = (sysuiVis | attrs.subtreeSystemUiVisibility);
3762
3763        final boolean useOutsets = outOutsets != null && shouldUseOutsets(attrs, fl);
3764        if (useOutsets) {
3765            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
3766            if (outset > 0) {
3767                if (displayRotation == Surface.ROTATION_0) {
3768                    outOutsets.bottom += outset;
3769                } else if (displayRotation == Surface.ROTATION_90) {
3770                    outOutsets.right += outset;
3771                } else if (displayRotation == Surface.ROTATION_180) {
3772                    outOutsets.top += outset;
3773                } else if (displayRotation == Surface.ROTATION_270) {
3774                    outOutsets.left += outset;
3775                }
3776            }
3777        }
3778
3779        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3780                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3781            int availRight, availBottom;
3782            if (canHideNavigationBar() &&
3783                    (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
3784                availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3785                availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3786            } else {
3787                availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
3788                availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3789            }
3790            if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3791                if ((fl & FLAG_FULLSCREEN) != 0) {
3792                    outContentInsets.set(mStableFullscreenLeft, mStableFullscreenTop,
3793                            availRight - mStableFullscreenRight,
3794                            availBottom - mStableFullscreenBottom);
3795                } else {
3796                    outContentInsets.set(mStableLeft, mStableTop,
3797                            availRight - mStableRight, availBottom - mStableBottom);
3798                }
3799            } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
3800                outContentInsets.setEmpty();
3801            } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
3802                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
3803                outContentInsets.set(mCurLeft, mCurTop,
3804                        availRight - mCurRight, availBottom - mCurBottom);
3805            } else {
3806                outContentInsets.set(mCurLeft, mCurTop,
3807                        availRight - mCurRight, availBottom - mCurBottom);
3808            }
3809
3810            outStableInsets.set(mStableLeft, mStableTop,
3811                    availRight - mStableRight, availBottom - mStableBottom);
3812            return mForceShowSystemBars;
3813        }
3814        outContentInsets.setEmpty();
3815        outStableInsets.setEmpty();
3816        return mForceShowSystemBars;
3817    }
3818
3819    private boolean shouldUseOutsets(WindowManager.LayoutParams attrs, int fl) {
3820        return attrs.type == TYPE_WALLPAPER || (fl & (WindowManager.LayoutParams.FLAG_FULLSCREEN
3821                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN)) != 0;
3822    }
3823
3824    /** {@inheritDoc} */
3825    @Override
3826    public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
3827                              int displayRotation, int uiMode) {
3828        mDisplayRotation = displayRotation;
3829        final int overscanLeft, overscanTop, overscanRight, overscanBottom;
3830        if (isDefaultDisplay) {
3831            switch (displayRotation) {
3832                case Surface.ROTATION_90:
3833                    overscanLeft = mOverscanTop;
3834                    overscanTop = mOverscanRight;
3835                    overscanRight = mOverscanBottom;
3836                    overscanBottom = mOverscanLeft;
3837                    break;
3838                case Surface.ROTATION_180:
3839                    overscanLeft = mOverscanRight;
3840                    overscanTop = mOverscanBottom;
3841                    overscanRight = mOverscanLeft;
3842                    overscanBottom = mOverscanTop;
3843                    break;
3844                case Surface.ROTATION_270:
3845                    overscanLeft = mOverscanBottom;
3846                    overscanTop = mOverscanLeft;
3847                    overscanRight = mOverscanTop;
3848                    overscanBottom = mOverscanRight;
3849                    break;
3850                default:
3851                    overscanLeft = mOverscanLeft;
3852                    overscanTop = mOverscanTop;
3853                    overscanRight = mOverscanRight;
3854                    overscanBottom = mOverscanBottom;
3855                    break;
3856            }
3857        } else {
3858            overscanLeft = 0;
3859            overscanTop = 0;
3860            overscanRight = 0;
3861            overscanBottom = 0;
3862        }
3863        mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
3864        mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
3865        mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
3866        mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
3867        mSystemLeft = 0;
3868        mSystemTop = 0;
3869        mSystemRight = displayWidth;
3870        mSystemBottom = displayHeight;
3871        mUnrestrictedScreenLeft = overscanLeft;
3872        mUnrestrictedScreenTop = overscanTop;
3873        mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
3874        mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
3875        mRestrictedScreenLeft = mUnrestrictedScreenLeft;
3876        mRestrictedScreenTop = mUnrestrictedScreenTop;
3877        mRestrictedScreenWidth = mSystemGestures.screenWidth = mUnrestrictedScreenWidth;
3878        mRestrictedScreenHeight = mSystemGestures.screenHeight = mUnrestrictedScreenHeight;
3879        mDockLeft = mContentLeft = mVoiceContentLeft = mStableLeft = mStableFullscreenLeft
3880                = mCurLeft = mUnrestrictedScreenLeft;
3881        mDockTop = mContentTop = mVoiceContentTop = mStableTop = mStableFullscreenTop
3882                = mCurTop = mUnrestrictedScreenTop;
3883        mDockRight = mContentRight = mVoiceContentRight = mStableRight = mStableFullscreenRight
3884                = mCurRight = displayWidth - overscanRight;
3885        mDockBottom = mContentBottom = mVoiceContentBottom = mStableBottom = mStableFullscreenBottom
3886                = mCurBottom = displayHeight - overscanBottom;
3887        mDockLayer = 0x10000000;
3888        mStatusBarLayer = -1;
3889
3890        // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
3891        final Rect pf = mTmpParentFrame;
3892        final Rect df = mTmpDisplayFrame;
3893        final Rect of = mTmpOverscanFrame;
3894        final Rect vf = mTmpVisibleFrame;
3895        final Rect dcf = mTmpDecorFrame;
3896        pf.left = df.left = of.left = vf.left = mDockLeft;
3897        pf.top = df.top = of.top = vf.top = mDockTop;
3898        pf.right = df.right = of.right = vf.right = mDockRight;
3899        pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
3900        dcf.setEmpty();  // Decor frame N/A for system bars.
3901
3902        if (isDefaultDisplay) {
3903            // For purposes of putting out fake window up to steal focus, we will
3904            // drive nav being hidden only by whether it is requested.
3905            final int sysui = mLastSystemUiFlags;
3906            boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
3907            boolean navTranslucent = (sysui
3908                    & (View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT)) != 0;
3909            boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
3910            boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
3911            boolean navAllowedHidden = immersive || immersiveSticky;
3912            navTranslucent &= !immersiveSticky;  // transient trumps translucent
3913            boolean isKeyguardShowing = isStatusBarKeyguard() && !mHideLockScreen;
3914            if (!isKeyguardShowing) {
3915                navTranslucent &= areTranslucentBarsAllowed();
3916            }
3917
3918            // When the navigation bar isn't visible, we put up a fake
3919            // input window to catch all touch events.  This way we can
3920            // detect when the user presses anywhere to bring back the nav
3921            // bar and ensure the application doesn't see the event.
3922            if (navVisible || navAllowedHidden) {
3923                if (mInputConsumer != null) {
3924                    mInputConsumer.dismiss();
3925                    mInputConsumer = null;
3926                }
3927            } else if (mInputConsumer == null) {
3928                mInputConsumer = mWindowManagerFuncs.addInputConsumer(mHandler.getLooper(),
3929                        mHideNavInputEventReceiverFactory);
3930            }
3931
3932            // For purposes of positioning and showing the nav bar, if we have
3933            // decided that it can't be hidden (because of the screen aspect ratio),
3934            // then take that into account.
3935            navVisible |= !canHideNavigationBar();
3936
3937            boolean updateSysUiVisibility = layoutNavigationBar(displayWidth, displayHeight,
3938                    displayRotation, uiMode, overscanRight, overscanBottom, dcf, navVisible, navTranslucent,
3939                    navAllowedHidden);
3940            if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
3941                    mDockLeft, mDockTop, mDockRight, mDockBottom));
3942            updateSysUiVisibility |= layoutStatusBar(pf, df, of, vf, dcf, sysui, isKeyguardShowing);
3943            if (updateSysUiVisibility) {
3944                updateSystemUiVisibilityLw();
3945            }
3946        }
3947    }
3948
3949    private boolean layoutStatusBar(Rect pf, Rect df, Rect of, Rect vf, Rect dcf, int sysui,
3950            boolean isKeyguardShowing) {
3951        // decide where the status bar goes ahead of time
3952        if (mStatusBar != null) {
3953            // apply any navigation bar insets
3954            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3955            pf.top = df.top = of.top = mUnrestrictedScreenTop;
3956            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
3957            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
3958                    + mUnrestrictedScreenTop;
3959            vf.left = mStableLeft;
3960            vf.top = mStableTop;
3961            vf.right = mStableRight;
3962            vf.bottom = mStableBottom;
3963
3964            mStatusBarLayer = mStatusBar.getSurfaceLayer();
3965
3966            // Let the status bar determine its size.
3967            mStatusBar.computeFrameLw(pf /* parentFrame */, df /* displayFrame */,
3968                    vf /* overlayFrame */, vf /* contentFrame */, vf /* visibleFrame */,
3969                    dcf /* decorFrame */, vf /* stableFrame */, vf /* outsetFrame */);
3970
3971            // For layout, the status bar is always at the top with our fixed height.
3972            mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
3973
3974            boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
3975            boolean statusBarTranslucent = (sysui
3976                    & (View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT)) != 0;
3977            if (!isKeyguardShowing) {
3978                statusBarTranslucent &= areTranslucentBarsAllowed();
3979            }
3980
3981            // If the status bar is hidden, we don't want to cause
3982            // windows behind it to scroll.
3983            if (mStatusBar.isVisibleLw() && !statusBarTransient) {
3984                // Status bar may go away, so the screen area it occupies
3985                // is available to apps but just covering them when the
3986                // status bar is visible.
3987                mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
3988
3989                mContentTop = mVoiceContentTop = mCurTop = mDockTop;
3990                mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
3991                mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
3992                mContentRight = mVoiceContentRight = mCurRight = mDockRight;
3993
3994                if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
3995                        String.format(
3996                                "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
3997                                mDockLeft, mDockTop, mDockRight, mDockBottom,
3998                                mContentLeft, mContentTop, mContentRight, mContentBottom,
3999                                mCurLeft, mCurTop, mCurRight, mCurBottom));
4000            }
4001            if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
4002                    && !statusBarTransient && !statusBarTranslucent
4003                    && !mStatusBarController.wasRecentlyTranslucent()) {
4004                // If the opaque status bar is currently requested to be visible,
4005                // and not in the process of animating on or off, then
4006                // we can tell the app that it is covered by it.
4007                mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
4008            }
4009            if (mStatusBarController.checkHiddenLw()) {
4010                return true;
4011            }
4012        }
4013        return false;
4014    }
4015
4016    private boolean layoutNavigationBar(int displayWidth, int displayHeight, int displayRotation,
4017            int uiMode, int overscanRight, int overscanBottom, Rect dcf, boolean navVisible,
4018            boolean navTranslucent, boolean navAllowedHidden) {
4019        if (mNavigationBar != null) {
4020            boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
4021            // Force the navigation bar to its appropriate place and
4022            // size.  We need to do this directly, instead of relying on
4023            // it to bubble up from the nav bar, because this needs to
4024            // change atomically with screen rotations.
4025            mNavigationBarOnBottom = isNavigationBarOnBottom(displayWidth, displayHeight);
4026            if (mNavigationBarOnBottom) {
4027                // It's a system nav bar or a portrait screen; nav bar goes on bottom.
4028                int top = displayHeight - overscanBottom
4029                        - getNavigationBarHeight(displayRotation, uiMode);
4030                mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
4031                mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
4032                if (transientNavBarShowing) {
4033                    mNavigationBarController.setBarShowingLw(true);
4034                } else if (navVisible) {
4035                    mNavigationBarController.setBarShowingLw(true);
4036                    mDockBottom = mTmpNavigationFrame.top;
4037                    mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
4038                    mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
4039                } else {
4040                    // We currently want to hide the navigation UI.
4041                    mNavigationBarController.setBarShowingLw(false);
4042                }
4043                if (navVisible && !navTranslucent && !navAllowedHidden
4044                        && !mNavigationBar.isAnimatingLw()
4045                        && !mNavigationBarController.wasRecentlyTranslucent()) {
4046                    // If the opaque nav bar is currently requested to be visible,
4047                    // and not in the process of animating on or off, then
4048                    // we can tell the app that it is covered by it.
4049                    mSystemBottom = mTmpNavigationFrame.top;
4050                }
4051            } else {
4052                // Landscape screen; nav bar goes to the right.
4053                int left = displayWidth - overscanRight
4054                        - getNavigationBarWidth(displayRotation, uiMode);
4055                mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
4056                mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
4057                if (transientNavBarShowing) {
4058                    mNavigationBarController.setBarShowingLw(true);
4059                } else if (navVisible) {
4060                    mNavigationBarController.setBarShowingLw(true);
4061                    mDockRight = mTmpNavigationFrame.left;
4062                    mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
4063                    mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
4064                } else {
4065                    // We currently want to hide the navigation UI.
4066                    mNavigationBarController.setBarShowingLw(false);
4067                }
4068                if (navVisible && !navTranslucent && !navAllowedHidden
4069                        && !mNavigationBar.isAnimatingLw()
4070                        && !mNavigationBarController.wasRecentlyTranslucent()) {
4071                    // If the nav bar is currently requested to be visible,
4072                    // and not in the process of animating on or off, then
4073                    // we can tell the app that it is covered by it.
4074                    mSystemRight = mTmpNavigationFrame.left;
4075                }
4076            }
4077            // Make sure the content and current rectangles are updated to
4078            // account for the restrictions from the navigation bar.
4079            mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4080            mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4081            mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4082            mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4083            mStatusBarLayer = mNavigationBar.getSurfaceLayer();
4084            // And compute the final frame.
4085            mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
4086                    mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf,
4087                    mTmpNavigationFrame, mTmpNavigationFrame);
4088            if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
4089            if (mNavigationBarController.checkHiddenLw()) {
4090                return true;
4091            }
4092        }
4093        return false;
4094    }
4095
4096    private boolean isNavigationBarOnBottom(int displayWidth, int displayHeight) {
4097        return !mNavigationBarCanMove || displayWidth < displayHeight;
4098    }
4099
4100    /** {@inheritDoc} */
4101    @Override
4102    public int getSystemDecorLayerLw() {
4103        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
4104            return mStatusBar.getSurfaceLayer();
4105        }
4106
4107        if (mNavigationBar != null && mNavigationBar.isVisibleLw()) {
4108            return mNavigationBar.getSurfaceLayer();
4109        }
4110
4111        return 0;
4112    }
4113
4114    @Override
4115    public void getContentRectLw(Rect r) {
4116        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
4117    }
4118
4119    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
4120            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
4121        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
4122            // Here's a special case: if this attached window is a panel that is
4123            // above the dock window, and the window it is attached to is below
4124            // the dock window, then the frames we computed for the window it is
4125            // attached to can not be used because the dock is effectively part
4126            // of the underlying window and the attached window is floating on top
4127            // of the whole thing.  So, we ignore the attached window and explicitly
4128            // compute the frames that would be appropriate without the dock.
4129            df.left = of.left = cf.left = vf.left = mDockLeft;
4130            df.top = of.top = cf.top = vf.top = mDockTop;
4131            df.right = of.right = cf.right = vf.right = mDockRight;
4132            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
4133        } else {
4134            // The effective display frame of the attached window depends on
4135            // whether it is taking care of insetting its content.  If not,
4136            // we need to use the parent's content frame so that the entire
4137            // window is positioned within that content.  Otherwise we can use
4138            // the overscan frame and let the attached window take care of
4139            // positioning its content appropriately.
4140            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4141                // Set the content frame of the attached window to the parent's decor frame
4142                // (same as content frame when IME isn't present) if specifically requested by
4143                // setting {@link WindowManager.LayoutParams#FLAG_LAYOUT_ATTACHED_IN_DECOR} flag.
4144                // Otherwise, use the overscan frame.
4145                cf.set((fl & FLAG_LAYOUT_ATTACHED_IN_DECOR) != 0
4146                        ? attached.getContentFrameLw() : attached.getOverscanFrameLw());
4147            } else {
4148                // If the window is resizing, then we want to base the content
4149                // frame on our attached content frame to resize...  however,
4150                // things can be tricky if the attached window is NOT in resize
4151                // mode, in which case its content frame will be larger.
4152                // Ungh.  So to deal with that, make sure the content frame
4153                // we end up using is not covering the IM dock.
4154                cf.set(attached.getContentFrameLw());
4155                if (attached.isVoiceInteraction()) {
4156                    if (cf.left < mVoiceContentLeft) cf.left = mVoiceContentLeft;
4157                    if (cf.top < mVoiceContentTop) cf.top = mVoiceContentTop;
4158                    if (cf.right > mVoiceContentRight) cf.right = mVoiceContentRight;
4159                    if (cf.bottom > mVoiceContentBottom) cf.bottom = mVoiceContentBottom;
4160                } else if (attached.getSurfaceLayer() < mDockLayer) {
4161                    if (cf.left < mContentLeft) cf.left = mContentLeft;
4162                    if (cf.top < mContentTop) cf.top = mContentTop;
4163                    if (cf.right > mContentRight) cf.right = mContentRight;
4164                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
4165                }
4166            }
4167            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
4168            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
4169            vf.set(attached.getVisibleFrameLw());
4170        }
4171        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
4172        // window should be positioned relative to its parent or the entire
4173        // screen.
4174        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
4175                ? attached.getFrameLw() : df);
4176    }
4177
4178    private void applyStableConstraints(int sysui, int fl, Rect r) {
4179        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
4180            // If app is requesting a stable layout, don't let the
4181            // content insets go below the stable values.
4182            if ((fl & FLAG_FULLSCREEN) != 0) {
4183                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
4184                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
4185                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
4186                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
4187            } else {
4188                if (r.left < mStableLeft) r.left = mStableLeft;
4189                if (r.top < mStableTop) r.top = mStableTop;
4190                if (r.right > mStableRight) r.right = mStableRight;
4191                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
4192            }
4193        }
4194    }
4195
4196    private boolean canReceiveInput(WindowState win) {
4197        boolean notFocusable =
4198                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0;
4199        boolean altFocusableIm =
4200                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0;
4201        boolean notFocusableForIm = notFocusable ^ altFocusableIm;
4202        return !notFocusableForIm;
4203    }
4204
4205    /** {@inheritDoc} */
4206    @Override
4207    public void layoutWindowLw(WindowState win, WindowState attached) {
4208        // We've already done the navigation bar and status bar. If the status bar can receive
4209        // input, we need to layout it again to accomodate for the IME window.
4210        if ((win == mStatusBar && !canReceiveInput(win)) || win == mNavigationBar) {
4211            return;
4212        }
4213        final WindowManager.LayoutParams attrs = win.getAttrs();
4214        final boolean isDefaultDisplay = win.isDefaultDisplay();
4215        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
4216                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
4217        if (needsToOffsetInputMethodTarget) {
4218            if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
4219            offsetInputMethodWindowLw(mLastInputMethodWindow);
4220        }
4221
4222        final int fl = PolicyControl.getWindowFlags(win, attrs);
4223        final int sim = attrs.softInputMode;
4224        final int sysUiFl = PolicyControl.getSystemUiVisibility(win, null);
4225
4226        final Rect pf = mTmpParentFrame;
4227        final Rect df = mTmpDisplayFrame;
4228        final Rect of = mTmpOverscanFrame;
4229        final Rect cf = mTmpContentFrame;
4230        final Rect vf = mTmpVisibleFrame;
4231        final Rect dcf = mTmpDecorFrame;
4232        final Rect sf = mTmpStableFrame;
4233        Rect osf = null;
4234        dcf.setEmpty();
4235
4236        final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
4237                && mNavigationBar != null && mNavigationBar.isVisibleLw());
4238
4239        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
4240
4241        if (isDefaultDisplay) {
4242            sf.set(mStableLeft, mStableTop, mStableRight, mStableBottom);
4243        } else {
4244            sf.set(mOverscanLeft, mOverscanTop, mOverscanRight, mOverscanBottom);
4245        }
4246
4247        if (!isDefaultDisplay) {
4248            if (attached != null) {
4249                // If this window is attached to another, our display
4250                // frame is the same as the one we are attached to.
4251                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4252            } else {
4253                // Give the window full screen.
4254                pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4255                pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4256                pf.right = df.right = of.right = cf.right
4257                        = mOverscanScreenLeft + mOverscanScreenWidth;
4258                pf.bottom = df.bottom = of.bottom = cf.bottom
4259                        = mOverscanScreenTop + mOverscanScreenHeight;
4260            }
4261        } else if (attrs.type == TYPE_INPUT_METHOD) {
4262            pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
4263            pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
4264            pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
4265            // IM dock windows layout below the nav bar...
4266            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4267            // ...with content insets above the nav bar
4268            cf.bottom = vf.bottom = mStableBottom;
4269            // IM dock windows always go to the bottom of the screen.
4270            attrs.gravity = Gravity.BOTTOM;
4271            mDockLayer = win.getSurfaceLayer();
4272        } else if (attrs.type == TYPE_VOICE_INTERACTION) {
4273            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4274            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4275            pf.right = df.right = of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4276            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4277            cf.bottom = vf.bottom = mStableBottom;
4278            // Note: In Phone landscape mode, the button bar should also be excluded.
4279            cf.right = vf.right = mStableRight;
4280            cf.left = vf.left = mStableLeft;
4281            cf.top = vf.top = mStableTop;
4282        } else if (win == mStatusBar) {
4283            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4284            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4285            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
4286            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight + mUnrestrictedScreenTop;
4287            cf.left = vf.left = mStableLeft;
4288            cf.top = vf.top = mStableTop;
4289            cf.right = vf.right = mStableRight;
4290            vf.bottom = mStableBottom;
4291
4292            if (adjust == SOFT_INPUT_ADJUST_RESIZE) {
4293                cf.bottom = mContentBottom;
4294            } else {
4295                cf.bottom = mDockBottom;
4296                vf.bottom = mContentBottom;
4297            }
4298        } else {
4299
4300            // Default policy decor for the default display
4301            dcf.left = mSystemLeft;
4302            dcf.top = mSystemTop;
4303            dcf.right = mSystemRight;
4304            dcf.bottom = mSystemBottom;
4305            final boolean inheritTranslucentDecor = (attrs.privateFlags
4306                    & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
4307            final boolean isAppWindow =
4308                    attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
4309                    attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
4310            final boolean topAtRest =
4311                    win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
4312            if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
4313                if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
4314                        && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
4315                        && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0
4316                        && (fl & WindowManager.LayoutParams.
4317                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0
4318                        && !mForceWindowDrawsStatusBarBackground) {
4319                    // Ensure policy decor includes status bar
4320                    dcf.top = mStableTop;
4321                }
4322                if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
4323                        && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
4324                        && (fl & WindowManager.LayoutParams.
4325                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
4326                    // Ensure policy decor includes navigation bar
4327                    dcf.bottom = mStableBottom;
4328                    dcf.right = mStableRight;
4329                }
4330            }
4331
4332            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
4333                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
4334                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
4335                            + "): IN_SCREEN, INSET_DECOR");
4336                // This is the case for a normal activity window: we want it
4337                // to cover all of the screen space, and it can take care of
4338                // moving its contents to account for screen decorations that
4339                // intrude into that space.
4340                if (attached != null) {
4341                    // If this window is attached to another, our display
4342                    // frame is the same as the one we are attached to.
4343                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4344                } else {
4345                    if (attrs.type == TYPE_STATUS_BAR_PANEL
4346                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
4347                        // Status bar panels are the only windows who can go on top of
4348                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
4349                        // permission, so they have the same privileges as the status
4350                        // bar itself.
4351                        //
4352                        // However, they should still dodge the navigation bar if it exists.
4353
4354                        pf.left = df.left = of.left = hasNavBar
4355                                ? mDockLeft : mUnrestrictedScreenLeft;
4356                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
4357                        pf.right = df.right = of.right = hasNavBar
4358                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
4359                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4360                        pf.bottom = df.bottom = of.bottom = hasNavBar
4361                                ? mRestrictedScreenTop+mRestrictedScreenHeight
4362                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4363
4364                        if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4365                                        "Laying out status bar window: (%d,%d - %d,%d)",
4366                                        pf.left, pf.top, pf.right, pf.bottom));
4367                    } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4368                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4369                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4370                        // Asking to layout into the overscan region, so give it that pure
4371                        // unrestricted area.
4372                        pf.left = df.left = of.left = mOverscanScreenLeft;
4373                        pf.top = df.top = of.top = mOverscanScreenTop;
4374                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
4375                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
4376                                + mOverscanScreenHeight;
4377                    } else if (canHideNavigationBar()
4378                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4379                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4380                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4381                        // Asking for layout as if the nav bar is hidden, lets the
4382                        // application extend into the unrestricted overscan screen area.  We
4383                        // only do this for application windows to ensure no window that
4384                        // can be above the nav bar can do this.
4385                        pf.left = df.left = mOverscanScreenLeft;
4386                        pf.top = df.top = mOverscanScreenTop;
4387                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4388                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4389                        // We need to tell the app about where the frame inside the overscan
4390                        // is, so it can inset its content by that amount -- it didn't ask
4391                        // to actually extend itself into the overscan region.
4392                        of.left = mUnrestrictedScreenLeft;
4393                        of.top = mUnrestrictedScreenTop;
4394                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4395                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4396                    } else {
4397                        pf.left = df.left = mRestrictedOverscanScreenLeft;
4398                        pf.top = df.top = mRestrictedOverscanScreenTop;
4399                        pf.right = df.right = mRestrictedOverscanScreenLeft
4400                                + mRestrictedOverscanScreenWidth;
4401                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
4402                                + mRestrictedOverscanScreenHeight;
4403                        // We need to tell the app about where the frame inside the overscan
4404                        // is, so it can inset its content by that amount -- it didn't ask
4405                        // to actually extend itself into the overscan region.
4406                        of.left = mUnrestrictedScreenLeft;
4407                        of.top = mUnrestrictedScreenTop;
4408                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4409                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4410                    }
4411
4412                    if ((fl & FLAG_FULLSCREEN) == 0) {
4413                        if (win.isVoiceInteraction()) {
4414                            cf.left = mVoiceContentLeft;
4415                            cf.top = mVoiceContentTop;
4416                            cf.right = mVoiceContentRight;
4417                            cf.bottom = mVoiceContentBottom;
4418                        } else {
4419                            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4420                                cf.left = mDockLeft;
4421                                cf.top = mDockTop;
4422                                cf.right = mDockRight;
4423                                cf.bottom = mDockBottom;
4424                            } else {
4425                                cf.left = mContentLeft;
4426                                cf.top = mContentTop;
4427                                cf.right = mContentRight;
4428                                cf.bottom = mContentBottom;
4429                            }
4430                        }
4431                    } else {
4432                        // Full screen windows are always given a layout that is as if the
4433                        // status bar and other transient decors are gone.  This is to avoid
4434                        // bad states when moving from a window that is not hding the
4435                        // status bar to one that is.
4436                        cf.left = mRestrictedScreenLeft;
4437                        cf.top = mRestrictedScreenTop;
4438                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4439                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
4440                    }
4441                    applyStableConstraints(sysUiFl, fl, cf);
4442                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4443                        vf.left = mCurLeft;
4444                        vf.top = mCurTop;
4445                        vf.right = mCurRight;
4446                        vf.bottom = mCurBottom;
4447                    } else {
4448                        vf.set(cf);
4449                    }
4450                }
4451            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
4452                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
4453                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
4454                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4455                        "): IN_SCREEN");
4456                // A window that has requested to fill the entire screen just
4457                // gets everything, period.
4458                if (attrs.type == TYPE_STATUS_BAR_PANEL
4459                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL
4460                        || attrs.type == TYPE_VOLUME_OVERLAY) {
4461                    pf.left = df.left = of.left = cf.left = hasNavBar
4462                            ? mDockLeft : mUnrestrictedScreenLeft;
4463                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4464                    pf.right = df.right = of.right = cf.right = hasNavBar
4465                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
4466                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4467                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
4468                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
4469                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4470                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4471                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
4472                                    pf.left, pf.top, pf.right, pf.bottom));
4473                } else if (attrs.type == TYPE_NAVIGATION_BAR
4474                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
4475                    // The navigation bar has Real Ultimate Power.
4476                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4477                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
4478                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
4479                            + mUnrestrictedScreenWidth;
4480                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
4481                            + mUnrestrictedScreenHeight;
4482                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4483                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
4484                                    pf.left, pf.top, pf.right, pf.bottom));
4485                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
4486                                || attrs.type == TYPE_BOOT_PROGRESS
4487                                || attrs.type == TYPE_SCREENSHOT)
4488                        && ((fl & FLAG_FULLSCREEN) != 0)) {
4489                    // Fullscreen secure system overlays get what they ask for. Screenshot region
4490                    // selection overlay should also expand to full screen.
4491                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4492                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4493                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4494                            + mOverscanScreenWidth;
4495                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4496                            + mOverscanScreenHeight;
4497                } else if (attrs.type == TYPE_BOOT_PROGRESS) {
4498                    // Boot progress screen always covers entire display.
4499                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4500                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4501                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4502                            + mOverscanScreenWidth;
4503                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4504                            + mOverscanScreenHeight;
4505                } else if (attrs.type == TYPE_WALLPAPER) {
4506                    // The wallpaper also has Real Ultimate Power, but we want to tell
4507                    // it about the overscan area.
4508                    pf.left = df.left = mOverscanScreenLeft;
4509                    pf.top = df.top = mOverscanScreenTop;
4510                    pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4511                    pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4512                    of.left = cf.left = mUnrestrictedScreenLeft;
4513                    of.top = cf.top = mUnrestrictedScreenTop;
4514                    of.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4515                    of.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4516                } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4517                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4518                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4519                    // Asking to layout into the overscan region, so give it that pure
4520                    // unrestricted area.
4521                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4522                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4523                    pf.right = df.right = of.right = cf.right
4524                            = mOverscanScreenLeft + mOverscanScreenWidth;
4525                    pf.bottom = df.bottom = of.bottom = cf.bottom
4526                            = mOverscanScreenTop + mOverscanScreenHeight;
4527                } else if (canHideNavigationBar()
4528                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4529                        && (attrs.type == TYPE_STATUS_BAR
4530                            || attrs.type == TYPE_TOAST
4531                            || attrs.type == TYPE_DOCK_DIVIDER
4532                            || attrs.type == TYPE_VOICE_INTERACTION_STARTING
4533                            || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4534                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
4535                    // Asking for layout as if the nav bar is hidden, lets the
4536                    // application extend into the unrestricted screen area.  We
4537                    // only do this for application windows (or toasts) to ensure no window that
4538                    // can be above the nav bar can do this.
4539                    // XXX This assumes that an app asking for this will also
4540                    // ask for layout in only content.  We can't currently figure out
4541                    // what the screen would be if only laying out to hide the nav bar.
4542                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
4543                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4544                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
4545                            + mUnrestrictedScreenWidth;
4546                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
4547                            + mUnrestrictedScreenHeight;
4548                } else if ((sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0) {
4549                    pf.left = df.left = of.left = mRestrictedScreenLeft;
4550                    pf.top = df.top = of.top  = mRestrictedScreenTop;
4551                    pf.right = df.right = of.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4552                    pf.bottom = df.bottom = of.bottom = mRestrictedScreenTop
4553                            + mRestrictedScreenHeight;
4554                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4555                        cf.left = mDockLeft;
4556                        cf.top = mDockTop;
4557                        cf.right = mDockRight;
4558                        cf.bottom = mDockBottom;
4559                    } else {
4560                        cf.left = mContentLeft;
4561                        cf.top = mContentTop;
4562                        cf.right = mContentRight;
4563                        cf.bottom = mContentBottom;
4564                    }
4565                } else {
4566                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4567                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4568                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4569                            + mRestrictedScreenWidth;
4570                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4571                            + mRestrictedScreenHeight;
4572                }
4573
4574                applyStableConstraints(sysUiFl, fl, cf);
4575
4576                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4577                    vf.left = mCurLeft;
4578                    vf.top = mCurTop;
4579                    vf.right = mCurRight;
4580                    vf.bottom = mCurBottom;
4581                } else {
4582                    vf.set(cf);
4583                }
4584            } else if (attached != null) {
4585                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4586                        "): attached to " + attached);
4587                // A child window should be placed inside of the same visible
4588                // frame that its parent had.
4589                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
4590            } else {
4591                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4592                        "): normal window");
4593                // Otherwise, a normal window must be placed inside the content
4594                // of all screen decorations.
4595                if (attrs.type == TYPE_STATUS_BAR_PANEL || attrs.type == TYPE_VOLUME_OVERLAY) {
4596                    // Status bar panels and the volume dialog are the only windows who can go on
4597                    // top of the status bar.  They are protected by the STATUS_BAR_SERVICE
4598                    // permission, so they have the same privileges as the status
4599                    // bar itself.
4600                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4601                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4602                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4603                            + mRestrictedScreenWidth;
4604                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4605                            + mRestrictedScreenHeight;
4606                } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT) {
4607                    // These dialogs are stable to interim decor changes.
4608                    pf.left = df.left = of.left = cf.left = mStableLeft;
4609                    pf.top = df.top = of.top = cf.top = mStableTop;
4610                    pf.right = df.right = of.right = cf.right = mStableRight;
4611                    pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
4612                } else {
4613                    pf.left = mContentLeft;
4614                    pf.top = mContentTop;
4615                    pf.right = mContentRight;
4616                    pf.bottom = mContentBottom;
4617                    if (win.isVoiceInteraction()) {
4618                        df.left = of.left = cf.left = mVoiceContentLeft;
4619                        df.top = of.top = cf.top = mVoiceContentTop;
4620                        df.right = of.right = cf.right = mVoiceContentRight;
4621                        df.bottom = of.bottom = cf.bottom = mVoiceContentBottom;
4622                    } else if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4623                        df.left = of.left = cf.left = mDockLeft;
4624                        df.top = of.top = cf.top = mDockTop;
4625                        df.right = of.right = cf.right = mDockRight;
4626                        df.bottom = of.bottom = cf.bottom = mDockBottom;
4627                    } else {
4628                        df.left = of.left = cf.left = mContentLeft;
4629                        df.top = of.top = cf.top = mContentTop;
4630                        df.right = of.right = cf.right = mContentRight;
4631                        df.bottom = of.bottom = cf.bottom = mContentBottom;
4632                    }
4633                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4634                        vf.left = mCurLeft;
4635                        vf.top = mCurTop;
4636                        vf.right = mCurRight;
4637                        vf.bottom = mCurBottom;
4638                    } else {
4639                        vf.set(cf);
4640                    }
4641                }
4642            }
4643        }
4644
4645        // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
4646        // Also, we don't allow windows in multi-window mode to extend out of the screen.
4647        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR
4648                && !win.isInMultiWindowMode()) {
4649            df.left = df.top = -10000;
4650            df.right = df.bottom = 10000;
4651            if (attrs.type != TYPE_WALLPAPER) {
4652                of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
4653                of.right = of.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
4654            }
4655        }
4656
4657        // If the device has a chin (e.g. some watches), a dead area at the bottom of the screen we
4658        // need to provide information to the clients that want to pretend that you can draw there.
4659        // We only want to apply outsets to certain types of windows. For example, we never want to
4660        // apply the outsets to floating dialogs, because they wouldn't make sense there.
4661        final boolean useOutsets = shouldUseOutsets(attrs, fl);
4662        if (isDefaultDisplay && useOutsets) {
4663            osf = mTmpOutsetFrame;
4664            osf.set(cf.left, cf.top, cf.right, cf.bottom);
4665            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
4666            if (outset > 0) {
4667                int rotation = mDisplayRotation;
4668                if (rotation == Surface.ROTATION_0) {
4669                    osf.bottom += outset;
4670                } else if (rotation == Surface.ROTATION_90) {
4671                    osf.right += outset;
4672                } else if (rotation == Surface.ROTATION_180) {
4673                    osf.top -= outset;
4674                } else if (rotation == Surface.ROTATION_270) {
4675                    osf.left -= outset;
4676                }
4677                if (DEBUG_LAYOUT) Slog.v(TAG, "applying bottom outset of " + outset
4678                        + " with rotation " + rotation + ", result: " + osf);
4679            }
4680        }
4681
4682        if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
4683                + ": sim=#" + Integer.toHexString(sim)
4684                + " attach=" + attached + " type=" + attrs.type
4685                + String.format(" flags=0x%08x", fl)
4686                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
4687                + " of=" + of.toShortString()
4688                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
4689                + " dcf=" + dcf.toShortString()
4690                + " sf=" + sf.toShortString()
4691                + " osf=" + (osf == null ? "null" : osf.toShortString()));
4692
4693        win.computeFrameLw(pf, df, of, cf, vf, dcf, sf, osf);
4694
4695        // Dock windows carve out the bottom of the screen, so normal windows
4696        // can't appear underneath them.
4697        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
4698                && !win.getGivenInsetsPendingLw()) {
4699            setLastInputMethodWindowLw(null, null);
4700            offsetInputMethodWindowLw(win);
4701        }
4702        if (attrs.type == TYPE_VOICE_INTERACTION && win.isVisibleOrBehindKeyguardLw()
4703                && !win.getGivenInsetsPendingLw()) {
4704            offsetVoiceInputWindowLw(win);
4705        }
4706    }
4707
4708    private void offsetInputMethodWindowLw(WindowState win) {
4709        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4710        top += win.getGivenContentInsetsLw().top;
4711        if (mContentBottom > top) {
4712            mContentBottom = top;
4713        }
4714        if (mVoiceContentBottom > top) {
4715            mVoiceContentBottom = top;
4716        }
4717        top = win.getVisibleFrameLw().top;
4718        top += win.getGivenVisibleInsetsLw().top;
4719        if (mCurBottom > top) {
4720            mCurBottom = top;
4721        }
4722        if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
4723                + mDockBottom + " mContentBottom="
4724                + mContentBottom + " mCurBottom=" + mCurBottom);
4725    }
4726
4727    private void offsetVoiceInputWindowLw(WindowState win) {
4728        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4729        top += win.getGivenContentInsetsLw().top;
4730        if (mVoiceContentBottom > top) {
4731            mVoiceContentBottom = top;
4732        }
4733    }
4734
4735    /** {@inheritDoc} */
4736    @Override
4737    public void finishLayoutLw() {
4738        return;
4739    }
4740
4741    /** {@inheritDoc} */
4742    @Override
4743    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
4744        mTopFullscreenOpaqueWindowState = null;
4745        mTopFullscreenOpaqueOrDimmingWindowState = null;
4746        mTopDockedOpaqueWindowState = null;
4747        mTopDockedOpaqueOrDimmingWindowState = null;
4748        mAppsToBeHidden.clear();
4749        mAppsThatDismissKeyguard.clear();
4750        mForceStatusBar = false;
4751        mForceStatusBarFromKeyguard = false;
4752        mForceStatusBarTransparent = false;
4753        mForcingShowNavBar = false;
4754        mForcingShowNavBarLayer = -1;
4755
4756        mHideLockScreen = false;
4757        mAllowLockscreenWhenOn = false;
4758        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
4759        mShowingLockscreen = false;
4760        mShowingDream = false;
4761        mWinShowWhenLocked = null;
4762        mKeyguardSecure = isKeyguardSecure();
4763        mKeyguardSecureIncludingHidden = mKeyguardSecure
4764                && (mKeyguardDelegate != null && mKeyguardDelegate.isShowing());
4765    }
4766
4767    /** {@inheritDoc} */
4768    @Override
4769    public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs,
4770            WindowState attached) {
4771        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
4772                + win.isVisibleOrBehindKeyguardLw());
4773        final int fl = PolicyControl.getWindowFlags(win, attrs);
4774        if (mTopFullscreenOpaqueWindowState == null
4775                && win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD) {
4776            mForcingShowNavBar = true;
4777            mForcingShowNavBarLayer = win.getSurfaceLayer();
4778        }
4779        if (attrs.type == TYPE_STATUS_BAR) {
4780            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4781                mForceStatusBarFromKeyguard = true;
4782                mShowingLockscreen = true;
4783            }
4784            if ((attrs.privateFlags & PRIVATE_FLAG_FORCE_STATUS_BAR_VISIBLE_TRANSPARENT) != 0) {
4785                mForceStatusBarTransparent = true;
4786            }
4787        }
4788
4789        boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
4790                && attrs.type < FIRST_SYSTEM_WINDOW;
4791        final boolean showWhenLocked = (fl & FLAG_SHOW_WHEN_LOCKED) != 0;
4792        final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
4793        final int stackId = win.getStackId();
4794        if (mTopFullscreenOpaqueWindowState == null &&
4795                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
4796            if ((fl & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
4797                if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4798                    mForceStatusBarFromKeyguard = true;
4799                } else {
4800                    mForceStatusBar = true;
4801                }
4802            }
4803            if (attrs.type == TYPE_DREAM) {
4804                // If the lockscreen was showing when the dream started then wait
4805                // for the dream to draw before hiding the lockscreen.
4806                if (!mDreamingLockscreen
4807                        || (win.isVisibleLw() && win.hasDrawnLw())) {
4808                    mShowingDream = true;
4809                    appWindow = true;
4810                }
4811            }
4812
4813            final IApplicationToken appToken = win.getAppToken();
4814
4815            // For app windows that are not attached, we decide if all windows in the app they
4816            // represent should be hidden or if we should hide the lockscreen. For attached app
4817            // windows we defer the decision to the window it is attached to.
4818            if (appWindow && attached == null) {
4819                if (showWhenLocked) {
4820                    // Remove any previous windows with the same appToken.
4821                    mAppsToBeHidden.remove(appToken);
4822                    mAppsThatDismissKeyguard.remove(appToken);
4823                    if (mAppsToBeHidden.isEmpty()) {
4824                        if (dismissKeyguard && !mKeyguardSecure) {
4825                            mAppsThatDismissKeyguard.add(appToken);
4826                        } else if (win.isDrawnLw() || win.hasAppShownWindows()) {
4827                            mWinShowWhenLocked = win;
4828                            mHideLockScreen = true;
4829                            mForceStatusBarFromKeyguard = false;
4830                        }
4831                    }
4832                } else if (dismissKeyguard) {
4833                    if (mKeyguardSecure) {
4834                        mAppsToBeHidden.add(appToken);
4835                    } else {
4836                        mAppsToBeHidden.remove(appToken);
4837                    }
4838                    mAppsThatDismissKeyguard.add(appToken);
4839                } else {
4840                    mAppsToBeHidden.add(appToken);
4841                }
4842                if (isFullscreen(attrs) && StackId.normallyFullscreenWindows(stackId)) {
4843                    if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
4844                    mTopFullscreenOpaqueWindowState = win;
4845                    if (mTopFullscreenOpaqueOrDimmingWindowState == null) {
4846                        mTopFullscreenOpaqueOrDimmingWindowState = win;
4847                    }
4848                    if (!mAppsThatDismissKeyguard.isEmpty() &&
4849                            mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
4850                        if (DEBUG_LAYOUT) Slog.v(TAG,
4851                                "Setting mDismissKeyguard true by win " + win);
4852                        mDismissKeyguard = (mWinDismissingKeyguard == win
4853                                && mSecureDismissingKeyguard == mKeyguardSecure)
4854                                ? DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
4855                        mWinDismissingKeyguard = win;
4856                        mSecureDismissingKeyguard = mKeyguardSecure;
4857                        mForceStatusBarFromKeyguard = mShowingLockscreen && mKeyguardSecure;
4858                    } else if (mAppsToBeHidden.isEmpty() && showWhenLocked
4859                            && (win.isDrawnLw() || win.hasAppShownWindows())) {
4860                        if (DEBUG_LAYOUT) Slog.v(TAG,
4861                                "Setting mHideLockScreen to true by win " + win);
4862                        mHideLockScreen = true;
4863                        mForceStatusBarFromKeyguard = false;
4864                    }
4865                    if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
4866                        mAllowLockscreenWhenOn = true;
4867                    }
4868                }
4869
4870                if (mWinShowWhenLocked != null &&
4871                        mWinShowWhenLocked.getAppToken() != win.getAppToken() &&
4872                        (attrs.flags & FLAG_SHOW_WHEN_LOCKED) == 0) {
4873                    win.hideLw(false);
4874                }
4875            }
4876        } else if (mTopFullscreenOpaqueWindowState == null && mWinShowWhenLocked == null) {
4877            // No TopFullscreenOpaqueWindow is showing, but we found a SHOW_WHEN_LOCKED window
4878            // that is being hidden in an animation - keep the
4879            // keyguard hidden until the new window shows up and
4880            // we know whether to show the keyguard or not.
4881            if (win.isAnimatingLw() && appWindow && showWhenLocked && mKeyguardHidden) {
4882                mHideLockScreen = true;
4883                mWinShowWhenLocked = win;
4884            }
4885        }
4886
4887        // Keep track of the window if it's dimming but not necessarily fullscreen.
4888        final boolean reallyVisible = win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw();
4889        if (mTopFullscreenOpaqueOrDimmingWindowState == null &&  reallyVisible
4890                && win.isDimming() && StackId.normallyFullscreenWindows(stackId)) {
4891            mTopFullscreenOpaqueOrDimmingWindowState = win;
4892        }
4893
4894        // We need to keep track of the top "fullscreen" opaque window for the docked stack
4895        // separately, because both the "real fullscreen" opaque window and the one for the docked
4896        // stack can control View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.
4897        if (mTopDockedOpaqueWindowState == null && reallyVisible && appWindow && attached == null
4898                && isFullscreen(attrs) && stackId == DOCKED_STACK_ID) {
4899            mTopDockedOpaqueWindowState = win;
4900            if (mTopDockedOpaqueOrDimmingWindowState == null) {
4901                mTopDockedOpaqueOrDimmingWindowState = win;
4902            }
4903        }
4904
4905        // Also keep track of any windows that are dimming but not necessarily fullscreen in the
4906        // docked stack.
4907        if (mTopDockedOpaqueOrDimmingWindowState == null && reallyVisible && win.isDimming()
4908                && stackId == DOCKED_STACK_ID) {
4909            mTopDockedOpaqueOrDimmingWindowState = win;
4910        }
4911    }
4912
4913    private boolean isFullscreen(WindowManager.LayoutParams attrs) {
4914        return attrs.x == 0 && attrs.y == 0
4915                && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
4916                && attrs.height == WindowManager.LayoutParams.MATCH_PARENT;
4917    }
4918
4919    /** {@inheritDoc} */
4920    @Override
4921    public int finishPostLayoutPolicyLw() {
4922        if (mWinShowWhenLocked != null && mTopFullscreenOpaqueWindowState != null &&
4923                mWinShowWhenLocked.getAppToken() != mTopFullscreenOpaqueWindowState.getAppToken()
4924                && isKeyguardLocked()) {
4925            // A dialog is dismissing the keyguard. Put the wallpaper behind it and hide the
4926            // fullscreen window.
4927            // TODO: Make sure FLAG_SHOW_WALLPAPER is restored when dialog is dismissed. Or not.
4928            mWinShowWhenLocked.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4929            mTopFullscreenOpaqueWindowState.hideLw(false);
4930            mTopFullscreenOpaqueWindowState = mWinShowWhenLocked;
4931        }
4932
4933        int changes = 0;
4934        boolean topIsFullscreen = false;
4935
4936        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
4937                ? mTopFullscreenOpaqueWindowState.getAttrs()
4938                : null;
4939
4940        // If we are not currently showing a dream then remember the current
4941        // lockscreen state.  We will use this to determine whether the dream
4942        // started while the lockscreen was showing and remember this state
4943        // while the dream is showing.
4944        if (!mShowingDream) {
4945            mDreamingLockscreen = mShowingLockscreen;
4946            if (mDreamingSleepTokenNeeded) {
4947                mDreamingSleepTokenNeeded = false;
4948                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 0, 1).sendToTarget();
4949            }
4950        } else {
4951            if (!mDreamingSleepTokenNeeded) {
4952                mDreamingSleepTokenNeeded = true;
4953                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 1, 1).sendToTarget();
4954            }
4955        }
4956
4957        if (mStatusBar != null) {
4958            if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
4959                    + " forcefkg=" + mForceStatusBarFromKeyguard
4960                    + " top=" + mTopFullscreenOpaqueWindowState);
4961            boolean shouldBeTransparent = mForceStatusBarTransparent
4962                    && !mForceStatusBar
4963                    && !mForceStatusBarFromKeyguard;
4964            if (!shouldBeTransparent) {
4965                mStatusBarController.setShowTransparent(false /* transparent */);
4966            } else if (!mStatusBar.isVisibleLw()) {
4967                mStatusBarController.setShowTransparent(true /* transparent */);
4968            }
4969            if (mForceStatusBar || mForceStatusBarFromKeyguard || mForceStatusBarTransparent) {
4970                if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
4971                if (mStatusBarController.setBarShowingLw(true)) {
4972                    changes |= FINISH_LAYOUT_REDO_LAYOUT;
4973                }
4974                // Maintain fullscreen layout until incoming animation is complete.
4975                topIsFullscreen = mTopIsFullscreen && mStatusBar.isAnimatingLw();
4976                // Transient status bar on the lockscreen is not allowed
4977                if (mForceStatusBarFromKeyguard && mStatusBarController.isTransientShowing()) {
4978                    mStatusBarController.updateVisibilityLw(false /*transientAllowed*/,
4979                            mLastSystemUiFlags, mLastSystemUiFlags);
4980                }
4981            } else if (mTopFullscreenOpaqueWindowState != null) {
4982                final int fl = PolicyControl.getWindowFlags(null, lp);
4983                if (localLOGV) {
4984                    Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
4985                            + " shown position: "
4986                            + mTopFullscreenOpaqueWindowState.getShownPositionLw());
4987                    Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
4988                            + " lp.flags=0x" + Integer.toHexString(fl));
4989                }
4990                topIsFullscreen = (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
4991                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
4992                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
4993                // and mTopIsFullscreen is that mTopIsFullscreen is set only if the window
4994                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
4995                // case though.
4996                if (mStatusBarController.isTransientShowing()) {
4997                    if (mStatusBarController.setBarShowingLw(true)) {
4998                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
4999                    }
5000                } else if (topIsFullscreen
5001                        && !mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID)
5002                        && !mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID)) {
5003                    if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
5004                    if (mStatusBarController.setBarShowingLw(false)) {
5005                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
5006                    } else {
5007                        if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
5008                    }
5009                } else {
5010                    if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
5011                    if (mStatusBarController.setBarShowingLw(true)) {
5012                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
5013                    }
5014                }
5015            }
5016        }
5017
5018        if (mTopIsFullscreen != topIsFullscreen) {
5019            if (!topIsFullscreen) {
5020                // Force another layout when status bar becomes fully shown.
5021                changes |= FINISH_LAYOUT_REDO_LAYOUT;
5022            }
5023            mTopIsFullscreen = topIsFullscreen;
5024        }
5025
5026        // Hide the key guard if a visible window explicitly specifies that it wants to be
5027        // displayed when the screen is locked.
5028        if (mKeyguardDelegate != null && mStatusBar != null) {
5029            if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
5030                    + mHideLockScreen);
5031            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardSecure) {
5032                mKeyguardHidden = true;
5033                if (setKeyguardOccludedLw(true)) {
5034                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5035                            | FINISH_LAYOUT_REDO_CONFIG
5036                            | FINISH_LAYOUT_REDO_WALLPAPER;
5037                }
5038                if (mKeyguardDelegate.isShowing()) {
5039                    mHandler.post(new Runnable() {
5040                        @Override
5041                        public void run() {
5042                            mKeyguardDelegate.keyguardDone(false, false);
5043                        }
5044                    });
5045                }
5046            } else if (mHideLockScreen) {
5047                mKeyguardHidden = true;
5048                mWinDismissingKeyguard = null;
5049                if (setKeyguardOccludedLw(true)) {
5050                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5051                            | FINISH_LAYOUT_REDO_CONFIG
5052                            | FINISH_LAYOUT_REDO_WALLPAPER;
5053                }
5054            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
5055                mKeyguardHidden = false;
5056                if (setKeyguardOccludedLw(false)) {
5057                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5058                            | FINISH_LAYOUT_REDO_CONFIG
5059                            | FINISH_LAYOUT_REDO_WALLPAPER;
5060                }
5061                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
5062                    // Only launch the next keyguard unlock window once per window.
5063                    mHandler.post(new Runnable() {
5064                        @Override
5065                        public void run() {
5066                            mKeyguardDelegate.dismiss();
5067                        }
5068                    });
5069                }
5070            } else {
5071                mWinDismissingKeyguard = null;
5072                mSecureDismissingKeyguard = false;
5073                mKeyguardHidden = false;
5074                if (setKeyguardOccludedLw(false)) {
5075                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5076                            | FINISH_LAYOUT_REDO_CONFIG
5077                            | FINISH_LAYOUT_REDO_WALLPAPER;
5078                }
5079            }
5080        }
5081
5082        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
5083            // If the navigation bar has been hidden or shown, we need to do another
5084            // layout pass to update that window.
5085            changes |= FINISH_LAYOUT_REDO_LAYOUT;
5086        }
5087
5088        // update since mAllowLockscreenWhenOn might have changed
5089        updateLockScreenTimeout();
5090        return changes;
5091    }
5092
5093    /**
5094     * Updates the occluded state of the Keyguard.
5095     *
5096     * @return Whether the flags have changed and we have to redo the layout.
5097     */
5098    private boolean setKeyguardOccludedLw(boolean isOccluded) {
5099        boolean wasOccluded = mKeyguardOccluded;
5100        boolean showing = mKeyguardDelegate.isShowing();
5101        if (wasOccluded && !isOccluded && showing) {
5102            mKeyguardOccluded = false;
5103            mKeyguardDelegate.setOccluded(false);
5104            mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
5105            mStatusBar.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
5106            return true;
5107        } else if (!wasOccluded && isOccluded && showing) {
5108            mKeyguardOccluded = true;
5109            mKeyguardDelegate.setOccluded(true);
5110            mStatusBar.getAttrs().privateFlags &= ~PRIVATE_FLAG_KEYGUARD;
5111            mStatusBar.getAttrs().flags &= ~FLAG_SHOW_WALLPAPER;
5112            return true;
5113        } else {
5114            return false;
5115        }
5116    }
5117
5118    private boolean isStatusBarKeyguard() {
5119        return mStatusBar != null
5120                && (mStatusBar.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
5121    }
5122
5123    @Override
5124    public boolean allowAppAnimationsLw() {
5125        if (isStatusBarKeyguard() || mShowingDream) {
5126            // If keyguard or dreams is currently visible, no reason to animate behind it.
5127            return false;
5128        }
5129        return true;
5130    }
5131
5132    @Override
5133    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
5134        mFocusedWindow = newFocus;
5135        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
5136            // If the navigation bar has been hidden or shown, we need to do another
5137            // layout pass to update that window.
5138            return FINISH_LAYOUT_REDO_LAYOUT;
5139        }
5140        return 0;
5141    }
5142
5143    /** {@inheritDoc} */
5144    @Override
5145    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
5146        // lid changed state
5147        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
5148        if (newLidState == mLidState) {
5149            return;
5150        }
5151
5152        mLidState = newLidState;
5153        applyLidSwitchState();
5154        updateRotation(true);
5155
5156        if (lidOpen) {
5157            wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromLidSwitch,
5158                    "android.policy:LID");
5159        } else if (!mLidControlsSleep) {
5160            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5161        }
5162    }
5163
5164    @Override
5165    public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered) {
5166        int lensCoverState = lensCovered ? CAMERA_LENS_COVERED : CAMERA_LENS_UNCOVERED;
5167        if (mCameraLensCoverState == lensCoverState) {
5168            return;
5169        }
5170        if (mCameraLensCoverState == CAMERA_LENS_COVERED &&
5171                lensCoverState == CAMERA_LENS_UNCOVERED) {
5172            Intent intent;
5173            final boolean keyguardActive = mKeyguardDelegate == null ? false :
5174                    mKeyguardDelegate.isShowing();
5175            if (keyguardActive) {
5176                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
5177            } else {
5178                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
5179            }
5180            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromCameraLens,
5181                    "android.policy:CAMERA_COVER");
5182            startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
5183        }
5184        mCameraLensCoverState = lensCoverState;
5185    }
5186
5187    void setHdmiPlugged(boolean plugged) {
5188        if (mHdmiPlugged != plugged) {
5189            mHdmiPlugged = plugged;
5190            updateRotation(true, true);
5191            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
5192            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5193            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
5194            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
5195        }
5196    }
5197
5198    void initializeHdmiState() {
5199        boolean plugged = false;
5200        // watch for HDMI plug messages if the hdmi switch exists
5201        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
5202            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
5203
5204            final String filename = "/sys/class/switch/hdmi/state";
5205            FileReader reader = null;
5206            try {
5207                reader = new FileReader(filename);
5208                char[] buf = new char[15];
5209                int n = reader.read(buf);
5210                if (n > 1) {
5211                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
5212                }
5213            } catch (IOException ex) {
5214                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
5215            } catch (NumberFormatException ex) {
5216                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
5217            } finally {
5218                if (reader != null) {
5219                    try {
5220                        reader.close();
5221                    } catch (IOException ex) {
5222                    }
5223                }
5224            }
5225        }
5226        // This dance forces the code in setHdmiPlugged to run.
5227        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
5228        mHdmiPlugged = !plugged;
5229        setHdmiPlugged(!mHdmiPlugged);
5230    }
5231
5232    final Object mScreenshotLock = new Object();
5233    ServiceConnection mScreenshotConnection = null;
5234
5235    final Runnable mScreenshotTimeout = new Runnable() {
5236        @Override public void run() {
5237            synchronized (mScreenshotLock) {
5238                if (mScreenshotConnection != null) {
5239                    mContext.unbindService(mScreenshotConnection);
5240                    mScreenshotConnection = null;
5241                    notifyScreenshotError();
5242                }
5243            }
5244        }
5245    };
5246
5247    // Assume this is called from the Handler thread.
5248    private void takeScreenshot(final int screenshotType) {
5249        synchronized (mScreenshotLock) {
5250            if (mScreenshotConnection != null) {
5251                return;
5252            }
5253            final ComponentName serviceComponent = new ComponentName(SYSUI_PACKAGE,
5254                    SYSUI_SCREENSHOT_SERVICE);
5255            final Intent serviceIntent = new Intent();
5256            serviceIntent.setComponent(serviceComponent);
5257            ServiceConnection conn = new ServiceConnection() {
5258                @Override
5259                public void onServiceConnected(ComponentName name, IBinder service) {
5260                    synchronized (mScreenshotLock) {
5261                        if (mScreenshotConnection != this) {
5262                            return;
5263                        }
5264                        Messenger messenger = new Messenger(service);
5265                        Message msg = Message.obtain(null, screenshotType);
5266                        final ServiceConnection myConn = this;
5267                        Handler h = new Handler(mHandler.getLooper()) {
5268                            @Override
5269                            public void handleMessage(Message msg) {
5270                                synchronized (mScreenshotLock) {
5271                                    if (mScreenshotConnection == myConn) {
5272                                        mContext.unbindService(mScreenshotConnection);
5273                                        mScreenshotConnection = null;
5274                                        mHandler.removeCallbacks(mScreenshotTimeout);
5275                                    }
5276                                }
5277                            }
5278                        };
5279                        msg.replyTo = new Messenger(h);
5280                        msg.arg1 = msg.arg2 = 0;
5281                        if (mStatusBar != null && mStatusBar.isVisibleLw())
5282                            msg.arg1 = 1;
5283                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
5284                            msg.arg2 = 1;
5285                        try {
5286                            messenger.send(msg);
5287                        } catch (RemoteException e) {
5288                        }
5289                    }
5290                }
5291
5292                @Override
5293                public void onServiceDisconnected(ComponentName name) {
5294                    notifyScreenshotError();
5295                }
5296            };
5297            if (mContext.bindServiceAsUser(serviceIntent, conn,
5298                    Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE,
5299                    UserHandle.CURRENT)) {
5300                mScreenshotConnection = conn;
5301                mHandler.postDelayed(mScreenshotTimeout, 10000);
5302            }
5303        }
5304    }
5305
5306    /**
5307     * Notifies the screenshot service to show an error.
5308     */
5309    private void notifyScreenshotError() {
5310        // If the service process is killed, then ask it to clean up after itself
5311        final ComponentName errorComponent = new ComponentName(SYSUI_PACKAGE,
5312                SYSUI_SCREENSHOT_ERROR_RECEIVER);
5313        Intent errorIntent = new Intent();
5314        errorIntent.setComponent(errorComponent);
5315        errorIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
5316                Intent.FLAG_RECEIVER_FOREGROUND);
5317        mContext.sendBroadcastAsUser(errorIntent, UserHandle.ALL);
5318    }
5319
5320    /** {@inheritDoc} */
5321    @Override
5322    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
5323        if (!mSystemBooted) {
5324            // If we have not yet booted, don't let key events do anything.
5325            return 0;
5326        }
5327
5328        final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;
5329        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
5330        final boolean canceled = event.isCanceled();
5331        final int keyCode = event.getKeyCode();
5332
5333        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
5334
5335        // If screen is off then we treat the case where the keyguard is open but hidden
5336        // the same as if it were open and in front.
5337        // This will prevent any keys other than the power button from waking the screen
5338        // when the keyguard is hidden by another activity.
5339        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
5340                                            (interactive ?
5341                                                isKeyguardShowingAndNotOccluded() :
5342                                                mKeyguardDelegate.isShowing()));
5343
5344        if (DEBUG_INPUT) {
5345            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
5346                    + " interactive=" + interactive + " keyguardActive=" + keyguardActive
5347                    + " policyFlags=" + Integer.toHexString(policyFlags));
5348        }
5349
5350        // Basic policy based on interactive state.
5351        int result;
5352        boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
5353                || event.isWakeKey();
5354        if (interactive || (isInjected && !isWakeKey)) {
5355            // When the device is interactive or the key is injected pass the
5356            // key to the application.
5357            result = ACTION_PASS_TO_USER;
5358            isWakeKey = false;
5359        } else if (!interactive && shouldDispatchInputWhenNonInteractive()) {
5360            // If we're currently dozing with the screen on and the keyguard showing, pass the key
5361            // to the application but preserve its wake key status to make sure we still move
5362            // from dozing to fully interactive if we would normally go from off to fully
5363            // interactive.
5364            result = ACTION_PASS_TO_USER;
5365        } else {
5366            // When the screen is off and the key is not injected, determine whether
5367            // to wake the device but don't pass the key to the application.
5368            result = 0;
5369            if (isWakeKey && (!down || !isWakeKeyWhenScreenOff(keyCode))) {
5370                isWakeKey = false;
5371            }
5372        }
5373
5374        // If the key would be handled globally, just return the result, don't worry about special
5375        // key processing.
5376        if (isValidGlobalKey(keyCode)
5377                && mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
5378            if (isWakeKey) {
5379                wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5380            }
5381            return result;
5382        }
5383
5384        boolean useHapticFeedback = down
5385                && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
5386                && event.getRepeatCount() == 0;
5387
5388        // Handle special keys.
5389        switch (keyCode) {
5390            case KeyEvent.KEYCODE_BACK: {
5391                if (down) {
5392                    mBackKeyHandled = false;
5393                    if (hasLongPressOnBackBehavior()) {
5394                        Message msg = mHandler.obtainMessage(MSG_BACK_LONG_PRESS);
5395                        msg.setAsynchronous(true);
5396                        mHandler.sendMessageDelayed(msg,
5397                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5398                    }
5399                } else {
5400                    boolean handled = mBackKeyHandled;
5401
5402                    // Reset back key state
5403                    cancelPendingBackKeyAction();
5404
5405                    // Don't pass back press to app if we've already handled it
5406                    if (handled) {
5407                        result &= ~ACTION_PASS_TO_USER;
5408                    }
5409                }
5410                break;
5411            }
5412
5413            case KeyEvent.KEYCODE_VOLUME_DOWN:
5414            case KeyEvent.KEYCODE_VOLUME_UP:
5415            case KeyEvent.KEYCODE_VOLUME_MUTE: {
5416                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
5417                    if (down) {
5418                        if (interactive && !mScreenshotChordVolumeDownKeyTriggered
5419                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5420                            mScreenshotChordVolumeDownKeyTriggered = true;
5421                            mScreenshotChordVolumeDownKeyTime = event.getDownTime();
5422                            mScreenshotChordVolumeDownKeyConsumed = false;
5423                            cancelPendingPowerKeyAction();
5424                            interceptScreenshotChord();
5425                        }
5426                    } else {
5427                        mScreenshotChordVolumeDownKeyTriggered = false;
5428                        cancelPendingScreenshotChordAction();
5429                    }
5430                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
5431                    if (down) {
5432                        if (interactive && !mScreenshotChordVolumeUpKeyTriggered
5433                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5434                            mScreenshotChordVolumeUpKeyTriggered = true;
5435                            cancelPendingPowerKeyAction();
5436                            cancelPendingScreenshotChordAction();
5437                        }
5438                    } else {
5439                        mScreenshotChordVolumeUpKeyTriggered = false;
5440                        cancelPendingScreenshotChordAction();
5441                    }
5442                }
5443                if (down) {
5444                    TelecomManager telecomManager = getTelecommService();
5445                    if (telecomManager != null) {
5446                        if (telecomManager.isRinging()) {
5447                            // If an incoming call is ringing, either VOLUME key means
5448                            // "silence ringer".  We handle these keys here, rather than
5449                            // in the InCallScreen, to make sure we'll respond to them
5450                            // even if the InCallScreen hasn't come to the foreground yet.
5451                            // Look for the DOWN event here, to agree with the "fallback"
5452                            // behavior in the InCallScreen.
5453                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5454                                  + " VOLUME key-down while ringing: Silence ringer!");
5455
5456                            // Silence the ringer.  (It's safe to call this
5457                            // even if the ringer has already been silenced.)
5458                            telecomManager.silenceRinger();
5459
5460                            // And *don't* pass this key thru to the current activity
5461                            // (which is probably the InCallScreen.)
5462                            result &= ~ACTION_PASS_TO_USER;
5463                            break;
5464                        }
5465                        if (telecomManager.isInCall()
5466                                && (result & ACTION_PASS_TO_USER) == 0) {
5467                            // If we are in call but we decided not to pass the key to
5468                            // the application, just pass it to the session service.
5469
5470                            MediaSessionLegacyHelper.getHelper(mContext)
5471                                    .sendVolumeKeyEvent(event, false);
5472                            break;
5473                        }
5474                    }
5475                }
5476                if (mUseTvRouting) {
5477                    // On TVs, defer special key handlings to
5478                    // {@link interceptKeyBeforeDispatching()}.
5479                    result |= ACTION_PASS_TO_USER;
5480                } else if ((result & ACTION_PASS_TO_USER) == 0) {
5481                    // If we aren't passing to the user and no one else
5482                    // handled it send it to the session manager to
5483                    // figure out.
5484                    MediaSessionLegacyHelper.getHelper(mContext)
5485                            .sendVolumeKeyEvent(event, true);
5486                }
5487                break;
5488            }
5489
5490            case KeyEvent.KEYCODE_ENDCALL: {
5491                result &= ~ACTION_PASS_TO_USER;
5492                if (down) {
5493                    TelecomManager telecomManager = getTelecommService();
5494                    boolean hungUp = false;
5495                    if (telecomManager != null) {
5496                        hungUp = telecomManager.endCall();
5497                    }
5498                    if (interactive && !hungUp) {
5499                        mEndCallKeyHandled = false;
5500                        mHandler.postDelayed(mEndCallLongPress,
5501                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5502                    } else {
5503                        mEndCallKeyHandled = true;
5504                    }
5505                } else {
5506                    if (!mEndCallKeyHandled) {
5507                        mHandler.removeCallbacks(mEndCallLongPress);
5508                        if (!canceled) {
5509                            if ((mEndcallBehavior
5510                                    & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
5511                                if (goHome()) {
5512                                    break;
5513                                }
5514                            }
5515                            if ((mEndcallBehavior
5516                                    & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
5517                                mPowerManager.goToSleep(event.getEventTime(),
5518                                        PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
5519                                isWakeKey = false;
5520                            }
5521                        }
5522                    }
5523                }
5524                break;
5525            }
5526
5527            case KeyEvent.KEYCODE_POWER: {
5528                result &= ~ACTION_PASS_TO_USER;
5529                isWakeKey = false; // wake-up will be handled separately
5530                if (down) {
5531                    interceptPowerKeyDown(event, interactive);
5532                } else {
5533                    interceptPowerKeyUp(event, interactive, canceled);
5534                }
5535                break;
5536            }
5537
5538            case KeyEvent.KEYCODE_SLEEP: {
5539                result &= ~ACTION_PASS_TO_USER;
5540                isWakeKey = false;
5541                if (!mPowerManager.isInteractive()) {
5542                    useHapticFeedback = false; // suppress feedback if already non-interactive
5543                }
5544                if (down) {
5545                    sleepPress(event.getEventTime());
5546                } else {
5547                    sleepRelease(event.getEventTime());
5548                }
5549                break;
5550            }
5551
5552            case KeyEvent.KEYCODE_SOFT_SLEEP: {
5553                result &= ~ACTION_PASS_TO_USER;
5554                isWakeKey = false;
5555                if (!down) {
5556                    mPowerManagerInternal.setUserInactiveOverrideFromWindowManager();
5557                }
5558                break;
5559            }
5560
5561            case KeyEvent.KEYCODE_WAKEUP: {
5562                result &= ~ACTION_PASS_TO_USER;
5563                isWakeKey = true;
5564                break;
5565            }
5566
5567            case KeyEvent.KEYCODE_MEDIA_PLAY:
5568            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5569            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5570            case KeyEvent.KEYCODE_HEADSETHOOK:
5571            case KeyEvent.KEYCODE_MUTE:
5572            case KeyEvent.KEYCODE_MEDIA_STOP:
5573            case KeyEvent.KEYCODE_MEDIA_NEXT:
5574            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5575            case KeyEvent.KEYCODE_MEDIA_REWIND:
5576            case KeyEvent.KEYCODE_MEDIA_RECORD:
5577            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5578            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
5579                if (MediaSessionLegacyHelper.getHelper(mContext).isGlobalPriorityActive()) {
5580                    // If the global session is active pass all media keys to it
5581                    // instead of the active window.
5582                    result &= ~ACTION_PASS_TO_USER;
5583                }
5584                if ((result & ACTION_PASS_TO_USER) == 0) {
5585                    // Only do this if we would otherwise not pass it to the user. In that
5586                    // case, the PhoneWindow class will do the same thing, except it will
5587                    // only do it if the showing app doesn't process the key on its own.
5588                    // Note that we need to make a copy of the key event here because the
5589                    // original key event will be recycled when we return.
5590                    mBroadcastWakeLock.acquire();
5591                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
5592                            new KeyEvent(event));
5593                    msg.setAsynchronous(true);
5594                    msg.sendToTarget();
5595                }
5596                break;
5597            }
5598
5599            case KeyEvent.KEYCODE_CALL: {
5600                if (down) {
5601                    TelecomManager telecomManager = getTelecommService();
5602                    if (telecomManager != null) {
5603                        if (telecomManager.isRinging()) {
5604                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5605                                  + " CALL key-down while ringing: Answer the call!");
5606                            telecomManager.acceptRingingCall();
5607
5608                            // And *don't* pass this key thru to the current activity
5609                            // (which is presumably the InCallScreen.)
5610                            result &= ~ACTION_PASS_TO_USER;
5611                        }
5612                    }
5613                }
5614                break;
5615            }
5616            case KeyEvent.KEYCODE_VOICE_ASSIST: {
5617                // Only do this if we would otherwise not pass it to the user. In that case,
5618                // interceptKeyBeforeDispatching would apply a similar but different policy in
5619                // order to invoke voice assist actions. Note that we need to make a copy of the
5620                // key event here because the original key event will be recycled when we return.
5621                if ((result & ACTION_PASS_TO_USER) == 0 && !down) {
5622                    mBroadcastWakeLock.acquire();
5623                    Message msg = mHandler.obtainMessage(MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK,
5624                            keyguardActive ? 1 : 0, 0);
5625                    msg.setAsynchronous(true);
5626                    msg.sendToTarget();
5627                }
5628                break;
5629            }
5630            case KeyEvent.KEYCODE_WINDOW: {
5631                if (mShortPressWindowBehavior == SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE) {
5632                    if (!down) {
5633                        requestTvPictureInPicture(event);
5634                    }
5635                    result &= ~ACTION_PASS_TO_USER;
5636                }
5637                break;
5638            }
5639        }
5640
5641        if (useHapticFeedback) {
5642            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
5643        }
5644
5645        if (isWakeKey) {
5646            wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5647        }
5648
5649        return result;
5650    }
5651
5652    /**
5653     * Returns true if the key can have global actions attached to it.
5654     * We reserve all power management keys for the system since they require
5655     * very careful handling.
5656     */
5657    private static boolean isValidGlobalKey(int keyCode) {
5658        switch (keyCode) {
5659            case KeyEvent.KEYCODE_POWER:
5660            case KeyEvent.KEYCODE_WAKEUP:
5661            case KeyEvent.KEYCODE_SLEEP:
5662                return false;
5663            default:
5664                return true;
5665        }
5666    }
5667
5668    /**
5669     * When the screen is off we ignore some keys that might otherwise typically
5670     * be considered wake keys.  We filter them out here.
5671     *
5672     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
5673     * is always considered a wake key.
5674     */
5675    private boolean isWakeKeyWhenScreenOff(int keyCode) {
5676        switch (keyCode) {
5677            // ignore volume keys unless docked
5678            case KeyEvent.KEYCODE_VOLUME_UP:
5679            case KeyEvent.KEYCODE_VOLUME_DOWN:
5680            case KeyEvent.KEYCODE_VOLUME_MUTE:
5681                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
5682
5683            // ignore media and camera keys
5684            case KeyEvent.KEYCODE_MUTE:
5685            case KeyEvent.KEYCODE_HEADSETHOOK:
5686            case KeyEvent.KEYCODE_MEDIA_PLAY:
5687            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5688            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5689            case KeyEvent.KEYCODE_MEDIA_STOP:
5690            case KeyEvent.KEYCODE_MEDIA_NEXT:
5691            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5692            case KeyEvent.KEYCODE_MEDIA_REWIND:
5693            case KeyEvent.KEYCODE_MEDIA_RECORD:
5694            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5695            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
5696            case KeyEvent.KEYCODE_CAMERA:
5697                return false;
5698        }
5699        return true;
5700    }
5701
5702
5703    /** {@inheritDoc} */
5704    @Override
5705    public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
5706        if ((policyFlags & FLAG_WAKE) != 0) {
5707            if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion,
5708                    "android.policy:MOTION")) {
5709                return 0;
5710            }
5711        }
5712
5713        if (shouldDispatchInputWhenNonInteractive()) {
5714            return ACTION_PASS_TO_USER;
5715        }
5716
5717        // If we have not passed the action up and we are in theater mode without dreaming,
5718        // there will be no dream to intercept the touch and wake into ambient.  The device should
5719        // wake up in this case.
5720        if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
5721            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotionWhenNotDreaming,
5722                    "android.policy:MOTION");
5723        }
5724
5725        return 0;
5726    }
5727
5728    private boolean shouldDispatchInputWhenNonInteractive() {
5729        // Send events to keyguard while the screen is on.
5730        if (isKeyguardShowingAndNotOccluded() && mDisplay != null
5731                && mDisplay.getState() != Display.STATE_OFF) {
5732            return true;
5733        }
5734
5735        // Send events to a dozing dream even if the screen is off since the dream
5736        // is in control of the state of the screen.
5737        IDreamManager dreamManager = getDreamManager();
5738
5739        try {
5740            if (dreamManager != null && dreamManager.isDreaming()) {
5741                return true;
5742            }
5743        } catch (RemoteException e) {
5744            Slog.e(TAG, "RemoteException when checking if dreaming", e);
5745        }
5746
5747        // Otherwise, consume events since the user can't see what is being
5748        // interacted with.
5749        return false;
5750    }
5751
5752    private void dispatchDirectAudioEvent(KeyEvent event) {
5753        if (event.getAction() != KeyEvent.ACTION_DOWN) {
5754            return;
5755        }
5756        int keyCode = event.getKeyCode();
5757        int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
5758                | AudioManager.FLAG_FROM_KEY;
5759        String pkgName = mContext.getOpPackageName();
5760        switch (keyCode) {
5761            case KeyEvent.KEYCODE_VOLUME_UP:
5762                try {
5763                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
5764                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5765                } catch (RemoteException e) {
5766                    Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
5767                }
5768                break;
5769            case KeyEvent.KEYCODE_VOLUME_DOWN:
5770                try {
5771                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
5772                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5773                } catch (RemoteException e) {
5774                    Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
5775                }
5776                break;
5777            case KeyEvent.KEYCODE_VOLUME_MUTE:
5778                try {
5779                    if (event.getRepeatCount() == 0) {
5780                        getAudioService().adjustSuggestedStreamVolume(
5781                                AudioManager.ADJUST_TOGGLE_MUTE,
5782                                AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5783                    }
5784                } catch (RemoteException e) {
5785                    Log.e(TAG, "Error dispatching mute in dispatchTvAudioEvent.", e);
5786                }
5787                break;
5788        }
5789    }
5790
5791    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
5792        if (DEBUG_INPUT) {
5793            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
5794        }
5795
5796        if (mHavePendingMediaKeyRepeatWithWakeLock) {
5797            if (DEBUG_INPUT) {
5798                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
5799            }
5800
5801            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
5802            mHavePendingMediaKeyRepeatWithWakeLock = false;
5803            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
5804        }
5805
5806        dispatchMediaKeyWithWakeLockToAudioService(event);
5807
5808        if (event.getAction() == KeyEvent.ACTION_DOWN
5809                && event.getRepeatCount() == 0) {
5810            mHavePendingMediaKeyRepeatWithWakeLock = true;
5811
5812            Message msg = mHandler.obtainMessage(
5813                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
5814            msg.setAsynchronous(true);
5815            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
5816        } else {
5817            mBroadcastWakeLock.release();
5818        }
5819    }
5820
5821    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
5822        mHavePendingMediaKeyRepeatWithWakeLock = false;
5823
5824        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
5825                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
5826        if (DEBUG_INPUT) {
5827            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
5828        }
5829
5830        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
5831        mBroadcastWakeLock.release();
5832    }
5833
5834    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
5835        if (ActivityManagerNative.isSystemReady()) {
5836            MediaSessionLegacyHelper.getHelper(mContext).sendMediaButtonEvent(event, true);
5837        }
5838    }
5839
5840    void launchVoiceAssistWithWakeLock(boolean keyguardActive) {
5841        IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
5842                ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
5843        if (dic != null) {
5844            try {
5845                dic.exitIdle("voice-search");
5846            } catch (RemoteException e) {
5847            }
5848        }
5849        Intent voiceIntent =
5850            new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
5851        voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, keyguardActive);
5852        startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
5853        mBroadcastWakeLock.release();
5854    }
5855
5856    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
5857        @Override
5858        public void onReceive(Context context, Intent intent) {
5859            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
5860                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
5861                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
5862            } else {
5863                try {
5864                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
5865                            ServiceManager.getService(Context.UI_MODE_SERVICE));
5866                    mUiMode = uiModeService.getCurrentModeType();
5867                } catch (RemoteException e) {
5868                }
5869            }
5870            updateRotation(true);
5871            synchronized (mLock) {
5872                updateOrientationListenerLp();
5873            }
5874        }
5875    };
5876
5877    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
5878        @Override
5879        public void onReceive(Context context, Intent intent) {
5880            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
5881                if (mKeyguardDelegate != null) {
5882                    mKeyguardDelegate.onDreamingStarted();
5883                }
5884            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
5885                if (mKeyguardDelegate != null) {
5886                    mKeyguardDelegate.onDreamingStopped();
5887                }
5888            }
5889        }
5890    };
5891
5892    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
5893        @Override
5894        public void onReceive(Context context, Intent intent) {
5895            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
5896                // tickle the settings observer: this first ensures that we're
5897                // observing the relevant settings for the newly-active user,
5898                // and then updates our own bookkeeping based on the now-
5899                // current user.
5900                mSettingsObserver.onChange(false);
5901
5902                // force a re-application of focused window sysui visibility.
5903                // the window may never have been shown for this user
5904                // e.g. the keyguard when going through the new-user setup flow
5905                synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5906                    mLastSystemUiFlags = 0;
5907                    updateSystemUiVisibilityLw();
5908                }
5909            }
5910        }
5911    };
5912
5913    private final Runnable mHiddenNavPanic = new Runnable() {
5914        @Override
5915        public void run() {
5916            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5917                if (!isUserSetupComplete()) {
5918                    // Swipe-up for navigation bar is disabled during setup
5919                    return;
5920                }
5921                mPendingPanicGestureUptime = SystemClock.uptimeMillis();
5922                mNavigationBarController.showTransient();
5923            }
5924        }
5925    };
5926
5927    private void requestTransientBars(WindowState swipeTarget) {
5928        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5929            if (!isUserSetupComplete()) {
5930                // Swipe-up for navigation bar is disabled during setup
5931                return;
5932            }
5933            boolean sb = mStatusBarController.checkShowTransientBarLw();
5934            boolean nb = mNavigationBarController.checkShowTransientBarLw();
5935            if (sb || nb) {
5936                // Don't show status bar when swiping on already visible navigation bar
5937                if (!nb && swipeTarget == mNavigationBar) {
5938                    if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
5939                    return;
5940                }
5941                if (sb) mStatusBarController.showTransient();
5942                if (nb) mNavigationBarController.showTransient();
5943                mImmersiveModeConfirmation.confirmCurrentPrompt();
5944                updateSystemUiVisibilityLw();
5945            }
5946        }
5947    }
5948
5949    // Called on the PowerManager's Notifier thread.
5950    @Override
5951    public void startedGoingToSleep(int why) {
5952        if (DEBUG_WAKEUP) Slog.i(TAG, "Started going to sleep... (why=" + why + ")");
5953        if (mKeyguardDelegate != null) {
5954            mKeyguardDelegate.onStartedGoingToSleep(why);
5955        }
5956    }
5957
5958    // Called on the PowerManager's Notifier thread.
5959    @Override
5960    public void finishedGoingToSleep(int why) {
5961        EventLog.writeEvent(70000, 0);
5962        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished going to sleep... (why=" + why + ")");
5963        MetricsLogger.histogram(mContext, "screen_timeout", mLockScreenTimeout / 1000);
5964
5965        // We must get this work done here because the power manager will drop
5966        // the wake lock and let the system suspend once this function returns.
5967        synchronized (mLock) {
5968            mAwake = false;
5969            updateWakeGestureListenerLp();
5970            updateOrientationListenerLp();
5971            updateLockScreenTimeout();
5972        }
5973        if (mKeyguardDelegate != null) {
5974            mKeyguardDelegate.onFinishedGoingToSleep(why);
5975        }
5976    }
5977
5978    // Called on the PowerManager's Notifier thread.
5979    @Override
5980    public void startedWakingUp() {
5981        EventLog.writeEvent(70000, 1);
5982        if (DEBUG_WAKEUP) Slog.i(TAG, "Started waking up...");
5983
5984        // Since goToSleep performs these functions synchronously, we must
5985        // do the same here.  We cannot post this work to a handler because
5986        // that might cause it to become reordered with respect to what
5987        // may happen in a future call to goToSleep.
5988        synchronized (mLock) {
5989            mAwake = true;
5990
5991            updateWakeGestureListenerLp();
5992            updateOrientationListenerLp();
5993            updateLockScreenTimeout();
5994        }
5995
5996        if (mKeyguardDelegate != null) {
5997            mKeyguardDelegate.onStartedWakingUp();
5998        }
5999    }
6000
6001    // Called on the PowerManager's Notifier thread.
6002    @Override
6003    public void finishedWakingUp() {
6004        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");
6005    }
6006
6007    private void wakeUpFromPowerKey(long eventTime) {
6008        wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey, "android.policy:POWER");
6009    }
6010
6011    private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode, String reason) {
6012        final boolean theaterModeEnabled = isTheaterModeEnabled();
6013        if (!wakeInTheaterMode && theaterModeEnabled) {
6014            return false;
6015        }
6016
6017        if (theaterModeEnabled) {
6018            Settings.Global.putInt(mContext.getContentResolver(),
6019                    Settings.Global.THEATER_MODE_ON, 0);
6020        }
6021
6022        mPowerManager.wakeUp(wakeTime, reason);
6023        return true;
6024    }
6025
6026    private void finishKeyguardDrawn() {
6027        synchronized (mLock) {
6028            if (!mScreenOnEarly || mKeyguardDrawComplete) {
6029                return; // We are not awake yet or we have already informed of this event.
6030            }
6031
6032            mKeyguardDrawComplete = true;
6033            if (mKeyguardDelegate != null) {
6034                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
6035            }
6036            mWindowManagerDrawComplete = false;
6037        }
6038
6039        // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
6040        // as well as enabling the orientation change logic/sensor.
6041        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
6042                WAITING_FOR_DRAWN_TIMEOUT);
6043    }
6044
6045    // Called on the DisplayManager's DisplayPowerController thread.
6046    @Override
6047    public void screenTurnedOff() {
6048        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turned off...");
6049
6050        updateScreenOffSleepToken(true);
6051        synchronized (mLock) {
6052            mScreenOnEarly = false;
6053            mScreenOnFully = false;
6054            mKeyguardDrawComplete = false;
6055            mWindowManagerDrawComplete = false;
6056            mScreenOnListener = null;
6057            updateOrientationListenerLp();
6058
6059            if (mKeyguardDelegate != null) {
6060                mKeyguardDelegate.onScreenTurnedOff();
6061            }
6062        }
6063    }
6064
6065    // Called on the DisplayManager's DisplayPowerController thread.
6066    @Override
6067    public void screenTurningOn(final ScreenOnListener screenOnListener) {
6068        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
6069
6070        updateScreenOffSleepToken(false);
6071        synchronized (mLock) {
6072            mScreenOnEarly = true;
6073            mScreenOnFully = false;
6074            mKeyguardDrawComplete = false;
6075            mWindowManagerDrawComplete = false;
6076            mScreenOnListener = screenOnListener;
6077
6078            if (mKeyguardDelegate != null) {
6079                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
6080                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
6081                mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
6082            } else {
6083                if (DEBUG_WAKEUP) Slog.d(TAG,
6084                        "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
6085                finishKeyguardDrawn();
6086            }
6087        }
6088    }
6089
6090    // Called on the DisplayManager's DisplayPowerController thread.
6091    @Override
6092    public void screenTurnedOn() {
6093        synchronized (mLock) {
6094            if (mKeyguardDelegate != null) {
6095                mKeyguardDelegate.onScreenTurnedOn();
6096            }
6097        }
6098    }
6099
6100    private void finishWindowsDrawn() {
6101        synchronized (mLock) {
6102            if (!mScreenOnEarly || mWindowManagerDrawComplete) {
6103                return; // Screen is not turned on or we did already handle this case earlier.
6104            }
6105
6106            mWindowManagerDrawComplete = true;
6107        }
6108
6109        finishScreenTurningOn();
6110    }
6111
6112    private void finishScreenTurningOn() {
6113        synchronized (mLock) {
6114            // We have just finished drawing screen content. Since the orientation listener
6115            // gets only installed when all windows are drawn, we try to install it again.
6116            updateOrientationListenerLp();
6117        }
6118        final ScreenOnListener listener;
6119        final boolean enableScreen;
6120        synchronized (mLock) {
6121            if (DEBUG_WAKEUP) Slog.d(TAG,
6122                    "finishScreenTurningOn: mAwake=" + mAwake
6123                            + ", mScreenOnEarly=" + mScreenOnEarly
6124                            + ", mScreenOnFully=" + mScreenOnFully
6125                            + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
6126                            + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
6127
6128            if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
6129                    || (mAwake && !mKeyguardDrawComplete)) {
6130                return; // spurious or not ready yet
6131            }
6132
6133            if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
6134            listener = mScreenOnListener;
6135            mScreenOnListener = null;
6136            mScreenOnFully = true;
6137
6138            // Remember the first time we draw the keyguard so we know when we're done with
6139            // the main part of booting and can enable the screen and hide boot messages.
6140            if (!mKeyguardDrawnOnce && mAwake) {
6141                mKeyguardDrawnOnce = true;
6142                enableScreen = true;
6143                if (mBootMessageNeedsHiding) {
6144                    mBootMessageNeedsHiding = false;
6145                    hideBootMessages();
6146                }
6147            } else {
6148                enableScreen = false;
6149            }
6150        }
6151
6152        if (listener != null) {
6153            listener.onScreenOn();
6154        }
6155
6156        if (enableScreen) {
6157            try {
6158                mWindowManager.enableScreenIfNeeded();
6159            } catch (RemoteException unhandled) {
6160            }
6161        }
6162    }
6163
6164    private void handleHideBootMessage() {
6165        synchronized (mLock) {
6166            if (!mKeyguardDrawnOnce) {
6167                mBootMessageNeedsHiding = true;
6168                return; // keyguard hasn't drawn the first time yet, not done booting
6169            }
6170        }
6171
6172        if (mBootMsgDialog != null) {
6173            if (DEBUG_WAKEUP) Slog.d(TAG, "handleHideBootMessage: dismissing");
6174            mBootMsgDialog.dismiss();
6175            mBootMsgDialog = null;
6176        }
6177    }
6178
6179    @Override
6180    public boolean isScreenOn() {
6181        return mScreenOnFully;
6182    }
6183
6184    /** {@inheritDoc} */
6185    @Override
6186    public void enableKeyguard(boolean enabled) {
6187        if (mKeyguardDelegate != null) {
6188            mKeyguardDelegate.setKeyguardEnabled(enabled);
6189        }
6190    }
6191
6192    /** {@inheritDoc} */
6193    @Override
6194    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
6195        if (mKeyguardDelegate != null) {
6196            mKeyguardDelegate.verifyUnlock(callback);
6197        }
6198    }
6199
6200    private boolean isKeyguardShowingAndNotOccluded() {
6201        if (mKeyguardDelegate == null) return false;
6202        return mKeyguardDelegate.isShowing() && !mKeyguardOccluded;
6203    }
6204
6205    /** {@inheritDoc} */
6206    @Override
6207    public boolean isKeyguardLocked() {
6208        return keyguardOn();
6209    }
6210
6211    /** {@inheritDoc} */
6212    @Override
6213    public boolean isKeyguardSecure() {
6214        if (mKeyguardDelegate == null) return false;
6215        return mKeyguardDelegate.isSecure();
6216    }
6217
6218    /** {@inheritDoc} */
6219    @Override
6220    public boolean isKeyguardShowingOrOccluded() {
6221        return mKeyguardDelegate == null ? false : mKeyguardDelegate.isShowing();
6222    }
6223
6224    /** {@inheritDoc} */
6225    @Override
6226    public boolean inKeyguardRestrictedKeyInputMode() {
6227        if (mKeyguardDelegate == null) return false;
6228        return mKeyguardDelegate.isInputRestricted();
6229    }
6230
6231    @Override
6232    public void dismissKeyguardLw() {
6233        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
6234            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.dismissKeyguardLw");
6235            mHandler.post(new Runnable() {
6236                @Override
6237                public void run() {
6238                    // ask the keyguard to prompt the user to authenticate if necessary
6239                    mKeyguardDelegate.dismiss();
6240                }
6241            });
6242        }
6243    }
6244
6245    public void notifyActivityDrawnForKeyguardLw() {
6246        if (mKeyguardDelegate != null) {
6247            mHandler.post(new Runnable() {
6248                @Override
6249                public void run() {
6250                    mKeyguardDelegate.onActivityDrawn();
6251                }
6252            });
6253        }
6254    }
6255
6256    @Override
6257    public boolean isKeyguardDrawnLw() {
6258        synchronized (mLock) {
6259            return mKeyguardDrawnOnce;
6260        }
6261    }
6262
6263    @Override
6264    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
6265        if (mKeyguardDelegate != null) {
6266            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation");
6267            mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration);
6268        }
6269    }
6270
6271    @Override
6272    public void getStableInsetsLw(int displayRotation, int displayWidth, int displayHeight,
6273            Rect outInsets) {
6274        outInsets.setEmpty();
6275
6276        // Navigation bar and status bar.
6277        getNonDecorInsetsLw(displayRotation, displayWidth, displayHeight, outInsets);
6278        if (mStatusBar != null) {
6279            outInsets.top = mStatusBarHeight;
6280        }
6281    }
6282
6283    @Override
6284    public void getNonDecorInsetsLw(int displayRotation, int displayWidth, int displayHeight,
6285            Rect outInsets) {
6286        outInsets.setEmpty();
6287
6288        // Only navigation bar
6289        if (mNavigationBar != null) {
6290            if (isNavigationBarOnBottom(displayWidth, displayHeight)) {
6291                outInsets.bottom = getNavigationBarHeight(displayRotation, mUiMode);
6292            } else {
6293                outInsets.right = getNavigationBarWidth(displayRotation, mUiMode);
6294            }
6295        }
6296    }
6297
6298    @Override
6299    public boolean isNavBarForcedShownLw(WindowState windowState) {
6300        return mForceShowSystemBars;
6301    }
6302
6303    @Override
6304    public boolean isDockSideAllowed(int dockSide) {
6305
6306        // We do not allow all dock sides at which the navigation bar touches the docked stack.
6307        if (!mNavigationBarCanMove) {
6308            return dockSide == DOCKED_TOP || dockSide == DOCKED_LEFT || dockSide == DOCKED_RIGHT;
6309        } else {
6310            return dockSide == DOCKED_TOP || dockSide == DOCKED_LEFT;
6311        }
6312    }
6313
6314    void sendCloseSystemWindows() {
6315        PhoneWindow.sendCloseSystemWindows(mContext, null);
6316    }
6317
6318    void sendCloseSystemWindows(String reason) {
6319        PhoneWindow.sendCloseSystemWindows(mContext, reason);
6320    }
6321
6322    @Override
6323    public int rotationForOrientationLw(int orientation, int lastRotation) {
6324        if (false) {
6325            Slog.v(TAG, "rotationForOrientationLw(orient="
6326                        + orientation + ", last=" + lastRotation
6327                        + "); user=" + mUserRotation + " "
6328                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
6329                            ? "USER_ROTATION_LOCKED" : "")
6330                        );
6331        }
6332
6333        if (mForceDefaultOrientation) {
6334            return Surface.ROTATION_0;
6335        }
6336
6337        synchronized (mLock) {
6338            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
6339            if (sensorRotation < 0) {
6340                sensorRotation = lastRotation;
6341            }
6342
6343            final int preferredRotation;
6344            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
6345                // Ignore sensor when lid switch is open and rotation is forced.
6346                preferredRotation = mLidOpenRotation;
6347            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
6348                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
6349                // Ignore sensor when in car dock unless explicitly enabled.
6350                // This case can override the behavior of NOSENSOR, and can also
6351                // enable 180 degree rotation while docked.
6352                preferredRotation = mCarDockEnablesAccelerometer
6353                        ? sensorRotation : mCarDockRotation;
6354            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6355                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
6356                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
6357                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
6358                // Ignore sensor when in desk dock unless explicitly enabled.
6359                // This case can override the behavior of NOSENSOR, and can also
6360                // enable 180 degree rotation while docked.
6361                preferredRotation = mDeskDockEnablesAccelerometer
6362                        ? sensorRotation : mDeskDockRotation;
6363            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
6364                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
6365                // Note that the dock orientation overrides the HDMI orientation.
6366                preferredRotation = mDemoHdmiRotation;
6367            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
6368                    && mUndockedHdmiRotation >= 0) {
6369                // Ignore sensor when plugged into HDMI and an undocked orientation has
6370                // been specified in the configuration (only for legacy devices without
6371                // full multi-display support).
6372                // Note that the dock orientation overrides the HDMI orientation.
6373                preferredRotation = mUndockedHdmiRotation;
6374            } else if (mDemoRotationLock) {
6375                // Ignore sensor when demo rotation lock is enabled.
6376                // Note that the dock orientation and HDMI rotation lock override this.
6377                preferredRotation = mDemoRotation;
6378            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
6379                // Application just wants to remain locked in the last rotation.
6380                preferredRotation = lastRotation;
6381            } else if (!mSupportAutoRotation) {
6382                // If we don't support auto-rotation then bail out here and ignore
6383                // the sensor and any rotation lock settings.
6384                preferredRotation = -1;
6385            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
6386                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
6387                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
6388                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
6389                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
6390                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
6391                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
6392                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6393                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
6394                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
6395                // Otherwise, use sensor only if requested by the application or enabled
6396                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
6397                if (mAllowAllRotations < 0) {
6398                    // Can't read this during init() because the context doesn't
6399                    // have display metrics at that time so we cannot determine
6400                    // tablet vs. phone then.
6401                    mAllowAllRotations = mContext.getResources().getBoolean(
6402                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
6403                }
6404                if (sensorRotation != Surface.ROTATION_180
6405                        || mAllowAllRotations == 1
6406                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6407                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
6408                    preferredRotation = sensorRotation;
6409                } else {
6410                    preferredRotation = lastRotation;
6411                }
6412            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
6413                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
6414                // Apply rotation lock.  Does not apply to NOSENSOR.
6415                // The idea is that the user rotation expresses a weak preference for the direction
6416                // of gravity and as NOSENSOR is never affected by gravity, then neither should
6417                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
6418                preferredRotation = mUserRotation;
6419            } else {
6420                // No overriding preference.
6421                // We will do exactly what the application asked us to do.
6422                preferredRotation = -1;
6423            }
6424
6425            switch (orientation) {
6426                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6427                    // Return portrait unless overridden.
6428                    if (isAnyPortrait(preferredRotation)) {
6429                        return preferredRotation;
6430                    }
6431                    return mPortraitRotation;
6432
6433                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6434                    // Return landscape unless overridden.
6435                    if (isLandscapeOrSeascape(preferredRotation)) {
6436                        return preferredRotation;
6437                    }
6438                    return mLandscapeRotation;
6439
6440                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6441                    // Return reverse portrait unless overridden.
6442                    if (isAnyPortrait(preferredRotation)) {
6443                        return preferredRotation;
6444                    }
6445                    return mUpsideDownRotation;
6446
6447                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6448                    // Return seascape unless overridden.
6449                    if (isLandscapeOrSeascape(preferredRotation)) {
6450                        return preferredRotation;
6451                    }
6452                    return mSeascapeRotation;
6453
6454                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6455                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
6456                    // Return either landscape rotation.
6457                    if (isLandscapeOrSeascape(preferredRotation)) {
6458                        return preferredRotation;
6459                    }
6460                    if (isLandscapeOrSeascape(lastRotation)) {
6461                        return lastRotation;
6462                    }
6463                    return mLandscapeRotation;
6464
6465                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6466                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
6467                    // Return either portrait rotation.
6468                    if (isAnyPortrait(preferredRotation)) {
6469                        return preferredRotation;
6470                    }
6471                    if (isAnyPortrait(lastRotation)) {
6472                        return lastRotation;
6473                    }
6474                    return mPortraitRotation;
6475
6476                default:
6477                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
6478                    // just return the preferred orientation we already calculated.
6479                    if (preferredRotation >= 0) {
6480                        return preferredRotation;
6481                    }
6482                    return Surface.ROTATION_0;
6483            }
6484        }
6485    }
6486
6487    @Override
6488    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
6489        switch (orientation) {
6490            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6491            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6492            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6493                return isAnyPortrait(rotation);
6494
6495            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6496            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6497            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6498                return isLandscapeOrSeascape(rotation);
6499
6500            default:
6501                return true;
6502        }
6503    }
6504
6505    @Override
6506    public void setRotationLw(int rotation) {
6507        mOrientationListener.setCurrentRotation(rotation);
6508    }
6509
6510    private boolean isLandscapeOrSeascape(int rotation) {
6511        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
6512    }
6513
6514    private boolean isAnyPortrait(int rotation) {
6515        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
6516    }
6517
6518    @Override
6519    public int getUserRotationMode() {
6520        return Settings.System.getIntForUser(mContext.getContentResolver(),
6521                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
6522                        WindowManagerPolicy.USER_ROTATION_FREE :
6523                                WindowManagerPolicy.USER_ROTATION_LOCKED;
6524    }
6525
6526    // User rotation: to be used when all else fails in assigning an orientation to the device
6527    @Override
6528    public void setUserRotationMode(int mode, int rot) {
6529        ContentResolver res = mContext.getContentResolver();
6530
6531        // mUserRotationMode and mUserRotation will be assigned by the content observer
6532        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
6533            Settings.System.putIntForUser(res,
6534                    Settings.System.USER_ROTATION,
6535                    rot,
6536                    UserHandle.USER_CURRENT);
6537            Settings.System.putIntForUser(res,
6538                    Settings.System.ACCELEROMETER_ROTATION,
6539                    0,
6540                    UserHandle.USER_CURRENT);
6541        } else {
6542            Settings.System.putIntForUser(res,
6543                    Settings.System.ACCELEROMETER_ROTATION,
6544                    1,
6545                    UserHandle.USER_CURRENT);
6546        }
6547    }
6548
6549    @Override
6550    public void setSafeMode(boolean safeMode) {
6551        mSafeMode = safeMode;
6552        performHapticFeedbackLw(null, safeMode
6553                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
6554                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
6555    }
6556
6557    static long[] getLongIntArray(Resources r, int resid) {
6558        int[] ar = r.getIntArray(resid);
6559        if (ar == null) {
6560            return null;
6561        }
6562        long[] out = new long[ar.length];
6563        for (int i=0; i<ar.length; i++) {
6564            out[i] = ar[i];
6565        }
6566        return out;
6567    }
6568
6569    /** {@inheritDoc} */
6570    @Override
6571    public void systemReady() {
6572        mKeyguardDelegate = new KeyguardServiceDelegate(mContext);
6573        mKeyguardDelegate.onSystemReady();
6574
6575        readCameraLensCoverState();
6576        updateUiMode();
6577        boolean bindKeyguardNow;
6578        synchronized (mLock) {
6579            updateOrientationListenerLp();
6580            mSystemReady = true;
6581            mHandler.post(new Runnable() {
6582                @Override
6583                public void run() {
6584                    updateSettings();
6585                }
6586            });
6587
6588            bindKeyguardNow = mDeferBindKeyguard;
6589            if (bindKeyguardNow) {
6590                // systemBooted ran but wasn't able to bind to the Keyguard, we'll do it now.
6591                mDeferBindKeyguard = false;
6592            }
6593        }
6594
6595        if (bindKeyguardNow) {
6596            mKeyguardDelegate.bindService(mContext);
6597            mKeyguardDelegate.onBootCompleted();
6598        }
6599        mSystemGestures.systemReady();
6600    }
6601
6602    /** {@inheritDoc} */
6603    @Override
6604    public void systemBooted() {
6605        boolean bindKeyguardNow = false;
6606        synchronized (mLock) {
6607            // Time to bind Keyguard; take care to only bind it once, either here if ready or
6608            // in systemReady if not.
6609            if (mKeyguardDelegate != null) {
6610                bindKeyguardNow = true;
6611            } else {
6612                // Because mKeyguardDelegate is null, we know that the synchronized block in
6613                // systemReady didn't run yet and setting this will actually have an effect.
6614                mDeferBindKeyguard = true;
6615            }
6616        }
6617        if (bindKeyguardNow) {
6618            mKeyguardDelegate.bindService(mContext);
6619            mKeyguardDelegate.onBootCompleted();
6620        }
6621        synchronized (mLock) {
6622            mSystemBooted = true;
6623        }
6624        startedWakingUp();
6625        screenTurningOn(null);
6626        screenTurnedOn();
6627    }
6628
6629    ProgressDialog mBootMsgDialog = null;
6630
6631    /** {@inheritDoc} */
6632    @Override
6633    public void showBootMessage(final CharSequence msg, final boolean always) {
6634        mHandler.post(new Runnable() {
6635            @Override public void run() {
6636                if (mBootMsgDialog == null) {
6637                    int theme;
6638                    if (mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
6639                        theme = com.android.internal.R.style.Theme_Micro_Dialog_Alert;
6640                    } else if (mContext.getPackageManager().hasSystemFeature(FEATURE_TELEVISION)) {
6641                        theme = com.android.internal.R.style.Theme_Leanback_Dialog_Alert;
6642                    } else {
6643                        theme = 0;
6644                    }
6645
6646                    mBootMsgDialog = new ProgressDialog(mContext, theme) {
6647                        // This dialog will consume all events coming in to
6648                        // it, to avoid it trying to do things too early in boot.
6649                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
6650                            return true;
6651                        }
6652                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6653                            return true;
6654                        }
6655                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
6656                            return true;
6657                        }
6658                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
6659                            return true;
6660                        }
6661                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
6662                            return true;
6663                        }
6664                        @Override public boolean dispatchPopulateAccessibilityEvent(
6665                                AccessibilityEvent event) {
6666                            return true;
6667                        }
6668                    };
6669                    if (mContext.getPackageManager().isUpgrade()) {
6670                        mBootMsgDialog.setTitle(R.string.android_upgrading_title);
6671                    } else {
6672                        mBootMsgDialog.setTitle(R.string.android_start_title);
6673                    }
6674                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
6675                    mBootMsgDialog.setIndeterminate(true);
6676                    mBootMsgDialog.getWindow().setType(
6677                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
6678                    mBootMsgDialog.getWindow().addFlags(
6679                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
6680                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
6681                    mBootMsgDialog.getWindow().setDimAmount(1);
6682                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
6683                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
6684                    mBootMsgDialog.getWindow().setAttributes(lp);
6685                    mBootMsgDialog.setCancelable(false);
6686                    mBootMsgDialog.show();
6687                }
6688                mBootMsgDialog.setMessage(msg);
6689            }
6690        });
6691    }
6692
6693    /** {@inheritDoc} */
6694    @Override
6695    public void hideBootMessages() {
6696        mHandler.sendEmptyMessage(MSG_HIDE_BOOT_MESSAGE);
6697    }
6698
6699    /** {@inheritDoc} */
6700    @Override
6701    public void userActivity() {
6702        // ***************************************
6703        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
6704        // ***************************************
6705        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
6706        // WITH ITS LOCKS HELD.
6707        //
6708        // This code must be VERY careful about the locks
6709        // it acquires.
6710        // In fact, the current code acquires way too many,
6711        // and probably has lurking deadlocks.
6712
6713        synchronized (mScreenLockTimeout) {
6714            if (mLockScreenTimerActive) {
6715                // reset the timer
6716                mHandler.removeCallbacks(mScreenLockTimeout);
6717                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6718            }
6719        }
6720    }
6721
6722    class ScreenLockTimeout implements Runnable {
6723        Bundle options;
6724
6725        @Override
6726        public void run() {
6727            synchronized (this) {
6728                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
6729                if (mKeyguardDelegate != null) {
6730                    mKeyguardDelegate.doKeyguardTimeout(options);
6731                }
6732                mLockScreenTimerActive = false;
6733                options = null;
6734            }
6735        }
6736
6737        public void setLockOptions(Bundle options) {
6738            this.options = options;
6739        }
6740    }
6741
6742    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
6743
6744    @Override
6745    public void lockNow(Bundle options) {
6746        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
6747        mHandler.removeCallbacks(mScreenLockTimeout);
6748        if (options != null) {
6749            // In case multiple calls are made to lockNow, we don't wipe out the options
6750            // until the runnable actually executes.
6751            mScreenLockTimeout.setLockOptions(options);
6752        }
6753        mHandler.post(mScreenLockTimeout);
6754    }
6755
6756    private void updateLockScreenTimeout() {
6757        synchronized (mScreenLockTimeout) {
6758            boolean enable = (mAllowLockscreenWhenOn && mAwake &&
6759                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
6760            if (mLockScreenTimerActive != enable) {
6761                if (enable) {
6762                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
6763                    mHandler.removeCallbacks(mScreenLockTimeout); // remove any pending requests
6764                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6765                } else {
6766                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
6767                    mHandler.removeCallbacks(mScreenLockTimeout);
6768                }
6769                mLockScreenTimerActive = enable;
6770            }
6771        }
6772    }
6773
6774    private void updateDreamingSleepToken(boolean acquire) {
6775        if (acquire) {
6776            if (mDreamingSleepToken == null) {
6777                mDreamingSleepToken = mActivityManagerInternal.acquireSleepToken("Dream");
6778            }
6779        } else {
6780            if (mDreamingSleepToken != null) {
6781                mDreamingSleepToken.release();
6782                mDreamingSleepToken = null;
6783            }
6784        }
6785    }
6786
6787    private void updateScreenOffSleepToken(boolean acquire) {
6788        if (acquire) {
6789            if (mScreenOffSleepToken == null) {
6790                mScreenOffSleepToken = mActivityManagerInternal.acquireSleepToken("ScreenOff");
6791            }
6792        } else {
6793            if (mScreenOffSleepToken != null) {
6794                mScreenOffSleepToken.release();
6795                mScreenOffSleepToken = null;
6796            }
6797        }
6798    }
6799
6800    /** {@inheritDoc} */
6801    @Override
6802    public void enableScreenAfterBoot() {
6803        readLidState();
6804        applyLidSwitchState();
6805        updateRotation(true);
6806    }
6807
6808    private void applyLidSwitchState() {
6809        if (mLidState == LID_CLOSED && mLidControlsSleep) {
6810            mPowerManager.goToSleep(SystemClock.uptimeMillis(),
6811                    PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
6812                    PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
6813        } else if (mLidState == LID_CLOSED && mLidControlsScreenLock) {
6814            mWindowManagerFuncs.lockDeviceNow();
6815        }
6816
6817        synchronized (mLock) {
6818            updateWakeGestureListenerLp();
6819        }
6820    }
6821
6822    void updateUiMode() {
6823        if (mUiModeManager == null) {
6824            mUiModeManager = IUiModeManager.Stub.asInterface(
6825                    ServiceManager.getService(Context.UI_MODE_SERVICE));
6826        }
6827        try {
6828            mUiMode = mUiModeManager.getCurrentModeType();
6829        } catch (RemoteException e) {
6830        }
6831    }
6832
6833    void updateRotation(boolean alwaysSendConfiguration) {
6834        try {
6835            //set orientation on WindowManager
6836            mWindowManager.updateRotation(alwaysSendConfiguration, false);
6837        } catch (RemoteException e) {
6838            // Ignore
6839        }
6840    }
6841
6842    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
6843        try {
6844            //set orientation on WindowManager
6845            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
6846        } catch (RemoteException e) {
6847            // Ignore
6848        }
6849    }
6850
6851    /**
6852     * Return an Intent to launch the currently active dock app as home.  Returns
6853     * null if the standard home should be launched, which is the case if any of the following is
6854     * true:
6855     * <ul>
6856     *  <li>The device is not in either car mode or desk mode
6857     *  <li>The device is in car mode but mEnableCarDockHomeCapture is false
6858     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
6859     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
6860     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
6861     * </ul>
6862     * @return A dock intent.
6863     */
6864    Intent createHomeDockIntent() {
6865        Intent intent = null;
6866
6867        // What home does is based on the mode, not the dock state.  That
6868        // is, when in car mode you should be taken to car home regardless
6869        // of whether we are actually in a car dock.
6870        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
6871            if (mEnableCarDockHomeCapture) {
6872                intent = mCarDockIntent;
6873            }
6874        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
6875            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
6876                intent = mDeskDockIntent;
6877            }
6878        } else if (mUiMode == Configuration.UI_MODE_TYPE_WATCH
6879                && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6880                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK
6881                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK)) {
6882            // Always launch dock home from home when watch is docked, if it exists.
6883            intent = mDeskDockIntent;
6884        }
6885
6886        if (intent == null) {
6887            return null;
6888        }
6889
6890        ActivityInfo ai = null;
6891        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
6892                intent,
6893                PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
6894                mCurrentUserId);
6895        if (info != null) {
6896            ai = info.activityInfo;
6897        }
6898        if (ai != null
6899                && ai.metaData != null
6900                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
6901            intent = new Intent(intent);
6902            intent.setClassName(ai.packageName, ai.name);
6903            return intent;
6904        }
6905
6906        return null;
6907    }
6908
6909    void startDockOrHome(boolean fromHomeKey, boolean awakenFromDreams) {
6910        if (awakenFromDreams) {
6911            awakenDreams();
6912        }
6913
6914        Intent dock = createHomeDockIntent();
6915        if (dock != null) {
6916            try {
6917                if (fromHomeKey) {
6918                    dock.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6919                }
6920                startActivityAsUser(dock, UserHandle.CURRENT);
6921                return;
6922            } catch (ActivityNotFoundException e) {
6923            }
6924        }
6925
6926        Intent intent;
6927
6928        if (fromHomeKey) {
6929            intent = new Intent(mHomeIntent);
6930            intent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6931        } else {
6932            intent = mHomeIntent;
6933        }
6934
6935        startActivityAsUser(intent, UserHandle.CURRENT);
6936    }
6937
6938    /**
6939     * goes to the home screen
6940     * @return whether it did anything
6941     */
6942    boolean goHome() {
6943        if (!isUserSetupComplete()) {
6944            Slog.i(TAG, "Not going home because user setup is in progress.");
6945            return false;
6946        }
6947        if (false) {
6948            // This code always brings home to the front.
6949            try {
6950                ActivityManagerNative.getDefault().stopAppSwitches();
6951            } catch (RemoteException e) {
6952            }
6953            sendCloseSystemWindows();
6954            startDockOrHome(false /*fromHomeKey*/, true /* awakenFromDreams */);
6955        } else {
6956            // This code brings home to the front or, if it is already
6957            // at the front, puts the device to sleep.
6958            try {
6959                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
6960                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
6961                    Log.d(TAG, "UTS-TEST-MODE");
6962                } else {
6963                    ActivityManagerNative.getDefault().stopAppSwitches();
6964                    sendCloseSystemWindows();
6965                    Intent dock = createHomeDockIntent();
6966                    if (dock != null) {
6967                        int result = ActivityManagerNative.getDefault()
6968                                .startActivityAsUser(null, null, dock,
6969                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
6970                                        null, null, 0,
6971                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6972                                        null, null, UserHandle.USER_CURRENT);
6973                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6974                            return false;
6975                        }
6976                    }
6977                }
6978                int result = ActivityManagerNative.getDefault()
6979                        .startActivityAsUser(null, null, mHomeIntent,
6980                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
6981                                null, null, 0,
6982                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
6983                                null, null, UserHandle.USER_CURRENT);
6984                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
6985                    return false;
6986                }
6987            } catch (RemoteException ex) {
6988                // bummer, the activity manager, which is in this process, is dead
6989            }
6990        }
6991        return true;
6992    }
6993
6994    @Override
6995    public void setCurrentOrientationLw(int newOrientation) {
6996        synchronized (mLock) {
6997            if (newOrientation != mCurrentAppOrientation) {
6998                mCurrentAppOrientation = newOrientation;
6999                updateOrientationListenerLp();
7000            }
7001        }
7002    }
7003
7004    private void performAuditoryFeedbackForAccessibilityIfNeed() {
7005        if (!isGlobalAccessibilityGestureEnabled()) {
7006            return;
7007        }
7008        AudioManager audioManager = (AudioManager) mContext.getSystemService(
7009                Context.AUDIO_SERVICE);
7010        if (audioManager.isSilentMode()) {
7011            return;
7012        }
7013        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
7014                Settings.System.DEFAULT_NOTIFICATION_URI);
7015        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
7016        ringTone.play();
7017    }
7018
7019    private boolean isTheaterModeEnabled() {
7020        return Settings.Global.getInt(mContext.getContentResolver(),
7021                Settings.Global.THEATER_MODE_ON, 0) == 1;
7022    }
7023
7024    private boolean isGlobalAccessibilityGestureEnabled() {
7025        return Settings.Global.getInt(mContext.getContentResolver(),
7026                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
7027    }
7028
7029    @Override
7030    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
7031        if (!mVibrator.hasVibrator()) {
7032            return false;
7033        }
7034        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
7035                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
7036        if (hapticsDisabled && !always) {
7037            return false;
7038        }
7039        long[] pattern = null;
7040        switch (effectId) {
7041            case HapticFeedbackConstants.LONG_PRESS:
7042                pattern = mLongPressVibePattern;
7043                break;
7044            case HapticFeedbackConstants.VIRTUAL_KEY:
7045                pattern = mVirtualKeyVibePattern;
7046                break;
7047            case HapticFeedbackConstants.KEYBOARD_TAP:
7048                pattern = mKeyboardTapVibePattern;
7049                break;
7050            case HapticFeedbackConstants.CLOCK_TICK:
7051                pattern = mClockTickVibePattern;
7052                break;
7053            case HapticFeedbackConstants.CALENDAR_DATE:
7054                pattern = mCalendarDateVibePattern;
7055                break;
7056            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
7057                pattern = mSafeModeDisabledVibePattern;
7058                break;
7059            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
7060                pattern = mSafeModeEnabledVibePattern;
7061                break;
7062            case HapticFeedbackConstants.CONTEXT_CLICK:
7063                pattern = mContextClickVibePattern;
7064                break;
7065            default:
7066                return false;
7067        }
7068        int owningUid;
7069        String owningPackage;
7070        if (win != null) {
7071            owningUid = win.getOwningUid();
7072            owningPackage = win.getOwningPackage();
7073        } else {
7074            owningUid = android.os.Process.myUid();
7075            owningPackage = mContext.getOpPackageName();
7076        }
7077        if (pattern.length == 1) {
7078            // One-shot vibration
7079            mVibrator.vibrate(owningUid, owningPackage, pattern[0], VIBRATION_ATTRIBUTES);
7080        } else {
7081            // Pattern vibration
7082            mVibrator.vibrate(owningUid, owningPackage, pattern, -1, VIBRATION_ATTRIBUTES);
7083        }
7084        return true;
7085    }
7086
7087    @Override
7088    public void keepScreenOnStartedLw() {
7089    }
7090
7091    @Override
7092    public void keepScreenOnStoppedLw() {
7093        if (isKeyguardShowingAndNotOccluded()) {
7094            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
7095        }
7096    }
7097
7098    private int updateSystemUiVisibilityLw() {
7099        // If there is no window focused, there will be nobody to handle the events
7100        // anyway, so just hang on in whatever state we're in until things settle down.
7101        final WindowState win = mFocusedWindow != null ? mFocusedWindow
7102                : mTopFullscreenOpaqueWindowState;
7103        if (win == null) {
7104            return 0;
7105        }
7106        if ((win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 && mHideLockScreen == true) {
7107            // We are updating at a point where the keyguard has gotten
7108            // focus, but we were last in a state where the top window is
7109            // hiding it.  This is probably because the keyguard as been
7110            // shown while the top window was displayed, so we want to ignore
7111            // it here because this is just a very transient change and it
7112            // will quickly lose focus once it correctly gets hidden.
7113            return 0;
7114        }
7115
7116        int tmpVisibility = PolicyControl.getSystemUiVisibility(win, null)
7117                & ~mResettingSystemUiFlags
7118                & ~mForceClearedSystemUiFlags;
7119        if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
7120            tmpVisibility &= ~PolicyControl.adjustClearableFlags(win, View.SYSTEM_UI_CLEARABLE_FLAGS);
7121        }
7122
7123        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
7124            tmpVisibility |= StatusBarManager.DISABLE_RECENT;
7125        }
7126
7127        final int fullscreenVisibility = updateLightStatusBarLw(0 /* vis */,
7128                mTopFullscreenOpaqueWindowState, mTopFullscreenOpaqueOrDimmingWindowState);
7129        final int dockedVisibility = updateLightStatusBarLw(0 /* vis */,
7130                mTopDockedOpaqueWindowState, mTopDockedOpaqueOrDimmingWindowState);
7131        mWindowManagerFuncs.getStackBounds(HOME_STACK_ID, mNonDockedStackBounds);
7132        mWindowManagerFuncs.getStackBounds(DOCKED_STACK_ID, mDockedStackBounds);
7133        final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
7134        final int diff = visibility ^ mLastSystemUiFlags;
7135        final int fullscreenDiff = fullscreenVisibility ^ mLastFullscreenStackSysUiFlags;
7136        final int dockedDiff = dockedVisibility ^ mLastDockedStackSysUiFlags;
7137        final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
7138        if (diff == 0 && fullscreenDiff == 0 && dockedDiff == 0 && mLastFocusNeedsMenu == needsMenu
7139                && mFocusedApp == win.getAppToken()
7140                && mLastNonDockedStackBounds.equals(mNonDockedStackBounds)
7141                && mLastDockedStackBounds.equals(mDockedStackBounds)) {
7142            return 0;
7143        }
7144        mLastSystemUiFlags = visibility;
7145        mLastFullscreenStackSysUiFlags = fullscreenVisibility;
7146        mLastDockedStackSysUiFlags = dockedVisibility;
7147        mLastFocusNeedsMenu = needsMenu;
7148        mFocusedApp = win.getAppToken();
7149        final Rect fullscreenStackBounds = new Rect(mNonDockedStackBounds);
7150        final Rect dockedStackBounds = new Rect(mDockedStackBounds);
7151        mHandler.post(new Runnable() {
7152                @Override
7153                public void run() {
7154                    StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
7155                    if (statusbar != null) {
7156                        statusbar.setSystemUiVisibility(visibility, fullscreenVisibility,
7157                                dockedVisibility, 0xffffffff, fullscreenStackBounds,
7158                                dockedStackBounds, win.toString());
7159                        statusbar.topAppWindowChanged(needsMenu);
7160                    }
7161                }
7162            });
7163        return diff;
7164    }
7165
7166    private int updateLightStatusBarLw(int vis, WindowState opaque, WindowState opaqueOrDimming) {
7167        WindowState statusColorWin = isStatusBarKeyguard() && !mHideLockScreen
7168                ? mStatusBar
7169                : opaqueOrDimming;
7170
7171        if (statusColorWin != null) {
7172            if (statusColorWin == opaque) {
7173                // If the top fullscreen-or-dimming window is also the top fullscreen, respect
7174                // its light flag.
7175                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7176                vis |= PolicyControl.getSystemUiVisibility(statusColorWin, null)
7177                        & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7178            } else if (statusColorWin != null && statusColorWin.isDimming()) {
7179                // Otherwise if it's dimming, clear the light flag.
7180                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7181            }
7182        }
7183        return vis;
7184    }
7185
7186    private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
7187        final boolean dockedStackVisible = mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID);
7188        final boolean freeformStackVisible =
7189                mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID);
7190        final boolean resizing = mWindowManagerInternal.isDockedDividerResizing();
7191
7192        // We need to force system bars when the docked stack is visible, when the freeform stack
7193        // is visible but also when we are resizing for the transitions when docked stack
7194        // visibility changes.
7195        mForceShowSystemBars = dockedStackVisible || freeformStackVisible || resizing;
7196        final boolean forceOpaqueStatusBar = mForceShowSystemBars && !mForceStatusBarFromKeyguard;
7197
7198        // apply translucent bar vis flags
7199        WindowState transWin = isStatusBarKeyguard() && !mHideLockScreen
7200                ? mStatusBar
7201                : mTopFullscreenOpaqueWindowState;
7202        vis = mStatusBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
7203        vis = mNavigationBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
7204
7205        // prevent status bar interaction from clearing certain flags
7206        int type = win.getAttrs().type;
7207        boolean statusBarHasFocus = type == TYPE_STATUS_BAR;
7208        if (statusBarHasFocus && !isStatusBarKeyguard()) {
7209            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
7210                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
7211                    | View.SYSTEM_UI_FLAG_IMMERSIVE
7212                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
7213                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7214            if (mHideLockScreen) {
7215                flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
7216            }
7217            vis = (vis & ~flags) | (oldVis & flags);
7218        }
7219
7220        if ((!areTranslucentBarsAllowed() && transWin != mStatusBar)
7221                || forceOpaqueStatusBar) {
7222            vis &= ~(View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT);
7223        }
7224
7225        vis = configureNavBarOpacity(vis, dockedStackVisible, freeformStackVisible, resizing);
7226
7227        if (mForceWindowDrawsStatusBarBackground) {
7228            vis |= View.STATUS_BAR_TRANSPARENT;
7229            vis &= ~View.STATUS_BAR_TRANSLUCENT;
7230        }
7231
7232        // update status bar
7233        boolean immersiveSticky =
7234                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7235        final boolean hideStatusBarWM =
7236                mTopFullscreenOpaqueWindowState != null
7237                && (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
7238                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
7239        final boolean hideStatusBarSysui =
7240                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
7241        final boolean hideNavBarSysui =
7242                (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
7243
7244        final boolean transientStatusBarAllowed = mStatusBar != null
7245                && (statusBarHasFocus || (!mForceShowSystemBars
7246                        && (hideStatusBarWM || (hideStatusBarSysui && immersiveSticky))));
7247
7248        final boolean transientNavBarAllowed = mNavigationBar != null
7249                && !mForceShowSystemBars && hideNavBarSysui && immersiveSticky;
7250
7251        final long now = SystemClock.uptimeMillis();
7252        final boolean pendingPanic = mPendingPanicGestureUptime != 0
7253                && now - mPendingPanicGestureUptime <= PANIC_GESTURE_EXPIRATION;
7254        if (pendingPanic && hideNavBarSysui && !isStatusBarKeyguard() && mKeyguardDrawComplete) {
7255            // The user performed the panic gesture recently, we're about to hide the bars,
7256            // we're no longer on the Keyguard and the screen is ready. We can now request the bars.
7257            mPendingPanicGestureUptime = 0;
7258            mStatusBarController.showTransient();
7259            mNavigationBarController.showTransient();
7260        }
7261
7262        final boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
7263                && !transientStatusBarAllowed && hideStatusBarSysui;
7264        final boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
7265                && !transientNavBarAllowed;
7266        if (denyTransientStatus || denyTransientNav || mForceShowSystemBars) {
7267            // clear the clearable flags instead
7268            clearClearableFlagsLw();
7269            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
7270        }
7271
7272        final boolean immersive = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
7273        immersiveSticky = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7274        final boolean navAllowedHidden = immersive || immersiveSticky;
7275
7276        if (hideNavBarSysui && !navAllowedHidden && windowTypeToLayerLw(win.getBaseType())
7277                > windowTypeToLayerLw(TYPE_INPUT_CONSUMER)) {
7278            // We can't hide the navbar from this window otherwise the input consumer would not get
7279            // the input events.
7280            vis = (vis & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
7281        }
7282
7283        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
7284
7285        // update navigation bar
7286        boolean oldImmersiveMode = isImmersiveMode(oldVis);
7287        boolean newImmersiveMode = isImmersiveMode(vis);
7288        if (win != null && oldImmersiveMode != newImmersiveMode) {
7289            final String pkg = win.getOwningPackage();
7290            mImmersiveModeConfirmation.immersiveModeChanged(pkg, newImmersiveMode,
7291                    isUserSetupComplete());
7292        }
7293
7294        vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
7295
7296        return vis;
7297    }
7298
7299    /**
7300     * @return the current visibility flags with the nav-bar opacity related flags toggled based
7301     *         on the nav bar opacity rules chosen by {@link #mNavBarOpacityMode}.
7302     */
7303    private int configureNavBarOpacity(int visibility, boolean dockedStackVisible,
7304            boolean freeformStackVisible, boolean isDockedDividerResizing) {
7305        if (mNavBarOpacityMode == NAV_BAR_OPAQUE_WHEN_FREEFORM_OR_DOCKED) {
7306            if (dockedStackVisible || freeformStackVisible || isDockedDividerResizing) {
7307                visibility = setNavBarOpaqueFlag(visibility);
7308            }
7309        } else if (mNavBarOpacityMode == NAV_BAR_TRANSLUCENT_WHEN_FREEFORM_OPAQUE_OTHERWISE) {
7310            if (isDockedDividerResizing) {
7311                visibility = setNavBarOpaqueFlag(visibility);
7312            } else if (freeformStackVisible) {
7313                visibility = setNavBarTranslucentFlag(visibility);
7314            } else {
7315                visibility = setNavBarOpaqueFlag(visibility);
7316            }
7317        }
7318
7319        if (!areTranslucentBarsAllowed()) {
7320            visibility &= ~View.NAVIGATION_BAR_TRANSLUCENT;
7321        }
7322        return visibility;
7323    }
7324
7325    private int setNavBarOpaqueFlag(int visibility) {
7326        return visibility &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT);
7327    }
7328
7329    private int setNavBarTranslucentFlag(int visibility) {
7330        visibility &= ~View.NAVIGATION_BAR_TRANSPARENT;
7331        return visibility |= View.NAVIGATION_BAR_TRANSLUCENT;
7332    }
7333
7334    private void clearClearableFlagsLw() {
7335        int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
7336        if (newVal != mResettingSystemUiFlags) {
7337            mResettingSystemUiFlags = newVal;
7338            mWindowManagerFuncs.reevaluateStatusBarVisibility();
7339        }
7340    }
7341
7342    private boolean isImmersiveMode(int vis) {
7343        final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
7344        return mNavigationBar != null
7345                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
7346                && (vis & flags) != 0
7347                && canHideNavigationBar();
7348    }
7349
7350    /**
7351     * @return whether the navigation or status bar can be made translucent
7352     *
7353     * This should return true unless touch exploration is not enabled or
7354     * R.boolean.config_enableTranslucentDecor is false.
7355     */
7356    private boolean areTranslucentBarsAllowed() {
7357        return mTranslucentDecorEnabled;
7358    }
7359
7360    // Use this instead of checking config_showNavigationBar so that it can be consistently
7361    // overridden by qemu.hw.mainkeys in the emulator.
7362    @Override
7363    public boolean hasNavigationBar() {
7364        return mHasNavigationBar;
7365    }
7366
7367    @Override
7368    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
7369        mLastInputMethodWindow = ime;
7370        mLastInputMethodTargetWindow = target;
7371    }
7372
7373    @Override
7374    public int getInputMethodWindowVisibleHeightLw() {
7375        return mDockBottom - mCurBottom;
7376    }
7377
7378    @Override
7379    public void setCurrentUserLw(int newUserId) {
7380        mCurrentUserId = newUserId;
7381        if (mKeyguardDelegate != null) {
7382            mKeyguardDelegate.setCurrentUser(newUserId);
7383        }
7384        if (mStatusBarService != null) {
7385            try {
7386                mStatusBarService.setCurrentUser(newUserId);
7387            } catch (RemoteException e) {
7388                // oh well
7389            }
7390        }
7391        setLastInputMethodWindowLw(null, null);
7392    }
7393
7394    @Override
7395    public boolean canMagnifyWindow(int windowType) {
7396        switch (windowType) {
7397            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
7398            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
7399            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
7400            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
7401                return false;
7402            }
7403        }
7404        return true;
7405    }
7406
7407    @Override
7408    public boolean isTopLevelWindow(int windowType) {
7409        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
7410                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
7411            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
7412        }
7413        return true;
7414    }
7415
7416    @Override
7417    public void dump(String prefix, PrintWriter pw, String[] args) {
7418        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
7419                pw.print(" mSystemReady="); pw.print(mSystemReady);
7420                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
7421        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
7422                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
7423                pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
7424                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
7425        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
7426                || mForceClearedSystemUiFlags != 0) {
7427            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
7428                    pw.print(Integer.toHexString(mLastSystemUiFlags));
7429                    pw.print(" mResettingSystemUiFlags=0x");
7430                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
7431                    pw.print(" mForceClearedSystemUiFlags=0x");
7432                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
7433        }
7434        if (mLastFocusNeedsMenu) {
7435            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
7436                    pw.println(mLastFocusNeedsMenu);
7437        }
7438        pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
7439                pw.println(mWakeGestureEnabledSetting);
7440
7441        pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
7442        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
7443                pw.print(" mDockMode="); pw.print(mDockMode);
7444                pw.print(" mEnableCarDockHomeCapture="); pw.print(mEnableCarDockHomeCapture);
7445                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
7446                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
7447        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
7448                pw.print(" mUserRotation="); pw.print(mUserRotation);
7449                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
7450        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
7451        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
7452                pw.print(mCarDockEnablesAccelerometer);
7453                pw.print(" mDeskDockEnablesAccelerometer=");
7454                pw.println(mDeskDockEnablesAccelerometer);
7455        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
7456                pw.print(mLidKeyboardAccessibility);
7457                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
7458                pw.print(" mLidControlsScreenLock="); pw.println(mLidControlsScreenLock);
7459                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
7460        pw.print(prefix);
7461                pw.print(" mLongPressOnBackBehavior="); pw.println(mLongPressOnBackBehavior);
7462        pw.print(prefix);
7463                pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
7464                pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
7465        pw.print(prefix);
7466                pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
7467                pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
7468        pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
7469        pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
7470        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
7471                pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
7472        pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
7473                pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
7474        pw.print(prefix); pw.print("mOrientationSensorEnabled=");
7475                pw.println(mOrientationSensorEnabled);
7476        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
7477                pw.print(","); pw.print(mOverscanScreenTop);
7478                pw.print(") "); pw.print(mOverscanScreenWidth);
7479                pw.print("x"); pw.println(mOverscanScreenHeight);
7480        if (mOverscanLeft != 0 || mOverscanTop != 0
7481                || mOverscanRight != 0 || mOverscanBottom != 0) {
7482            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
7483                    pw.print(" top="); pw.print(mOverscanTop);
7484                    pw.print(" right="); pw.print(mOverscanRight);
7485                    pw.print(" bottom="); pw.println(mOverscanBottom);
7486        }
7487        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
7488                pw.print(mRestrictedOverscanScreenLeft);
7489                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
7490                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
7491                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
7492        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
7493                pw.print(","); pw.print(mUnrestrictedScreenTop);
7494                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
7495                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
7496        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
7497                pw.print(","); pw.print(mRestrictedScreenTop);
7498                pw.print(") "); pw.print(mRestrictedScreenWidth);
7499                pw.print("x"); pw.println(mRestrictedScreenHeight);
7500        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
7501                pw.print(","); pw.print(mStableFullscreenTop);
7502                pw.print(")-("); pw.print(mStableFullscreenRight);
7503                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
7504        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
7505                pw.print(","); pw.print(mStableTop);
7506                pw.print(")-("); pw.print(mStableRight);
7507                pw.print(","); pw.print(mStableBottom); pw.println(")");
7508        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
7509                pw.print(","); pw.print(mSystemTop);
7510                pw.print(")-("); pw.print(mSystemRight);
7511                pw.print(","); pw.print(mSystemBottom); pw.println(")");
7512        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
7513                pw.print(","); pw.print(mCurTop);
7514                pw.print(")-("); pw.print(mCurRight);
7515                pw.print(","); pw.print(mCurBottom); pw.println(")");
7516        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
7517                pw.print(","); pw.print(mContentTop);
7518                pw.print(")-("); pw.print(mContentRight);
7519                pw.print(","); pw.print(mContentBottom); pw.println(")");
7520        pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
7521                pw.print(","); pw.print(mVoiceContentTop);
7522                pw.print(")-("); pw.print(mVoiceContentRight);
7523                pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
7524        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
7525                pw.print(","); pw.print(mDockTop);
7526                pw.print(")-("); pw.print(mDockRight);
7527                pw.print(","); pw.print(mDockBottom); pw.println(")");
7528        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
7529                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
7530        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
7531                pw.print(" mShowingDream="); pw.print(mShowingDream);
7532                pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
7533                pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
7534        if (mLastInputMethodWindow != null) {
7535            pw.print(prefix); pw.print("mLastInputMethodWindow=");
7536                    pw.println(mLastInputMethodWindow);
7537        }
7538        if (mLastInputMethodTargetWindow != null) {
7539            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
7540                    pw.println(mLastInputMethodTargetWindow);
7541        }
7542        if (mStatusBar != null) {
7543            pw.print(prefix); pw.print("mStatusBar=");
7544                    pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
7545                    pw.println(isStatusBarKeyguard());
7546        }
7547        if (mNavigationBar != null) {
7548            pw.print(prefix); pw.print("mNavigationBar=");
7549                    pw.println(mNavigationBar);
7550        }
7551        if (mFocusedWindow != null) {
7552            pw.print(prefix); pw.print("mFocusedWindow=");
7553                    pw.println(mFocusedWindow);
7554        }
7555        if (mFocusedApp != null) {
7556            pw.print(prefix); pw.print("mFocusedApp=");
7557                    pw.println(mFocusedApp);
7558        }
7559        if (mWinDismissingKeyguard != null) {
7560            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
7561                    pw.println(mWinDismissingKeyguard);
7562        }
7563        if (mTopFullscreenOpaqueWindowState != null) {
7564            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
7565                    pw.println(mTopFullscreenOpaqueWindowState);
7566        }
7567        if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
7568            pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
7569                    pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
7570        }
7571        if (mForcingShowNavBar) {
7572            pw.print(prefix); pw.print("mForcingShowNavBar=");
7573                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
7574                    pw.println(mForcingShowNavBarLayer);
7575        }
7576        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
7577                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
7578        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
7579                pw.print(" mForceStatusBarFromKeyguard=");
7580                pw.println(mForceStatusBarFromKeyguard);
7581        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
7582                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
7583                pw.print(" mHomePressed="); pw.println(mHomePressed);
7584        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
7585                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
7586                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
7587        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
7588                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
7589                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
7590        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
7591                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
7592        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
7593                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
7594        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
7595                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
7596        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
7597
7598        mGlobalKeyManager.dump(prefix, pw);
7599        mStatusBarController.dump(pw, prefix);
7600        mNavigationBarController.dump(pw, prefix);
7601        PolicyControl.dump(prefix, pw);
7602
7603        if (mWakeGestureListener != null) {
7604            mWakeGestureListener.dump(pw, prefix);
7605        }
7606        if (mOrientationListener != null) {
7607            mOrientationListener.dump(pw, prefix);
7608        }
7609        if (mBurnInProtectionHelper != null) {
7610            mBurnInProtectionHelper.dump(prefix, pw);
7611        }
7612        if (mKeyguardDelegate != null) {
7613            mKeyguardDelegate.dump(prefix, pw);
7614        }
7615    }
7616}
7617