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