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