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