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