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