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