PhoneWindowManager.java revision b5dd049089a8c62efea445be9abd1f476fbf1ab9
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                    if (isUserSetupComplete()) {
3400                        shortcutService.notifyShortcutKeyPressed(shortcutCode);
3401                    }
3402                } catch (RemoteException e) {
3403                    mShortcutKeyServices.delete(shortcutCode);
3404                }
3405                return -1;
3406            }
3407        }
3408
3409        // Reserve all the META modifier combos for system behavior
3410        if ((metaState & KeyEvent.META_META_ON) != 0) {
3411            return -1;
3412        }
3413
3414        // Let the application handle the key.
3415        return 0;
3416    }
3417
3418    /** {@inheritDoc} */
3419    @Override
3420    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
3421        // Note: This method is only called if the initial down was unhandled.
3422        if (DEBUG_INPUT) {
3423            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
3424                    + ", flags=" + event.getFlags()
3425                    + ", keyCode=" + event.getKeyCode()
3426                    + ", scanCode=" + event.getScanCode()
3427                    + ", metaState=" + event.getMetaState()
3428                    + ", repeatCount=" + event.getRepeatCount()
3429                    + ", policyFlags=" + policyFlags);
3430        }
3431
3432        KeyEvent fallbackEvent = null;
3433        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3434            final KeyCharacterMap kcm = event.getKeyCharacterMap();
3435            final int keyCode = event.getKeyCode();
3436            final int metaState = event.getMetaState();
3437            final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
3438                    && event.getRepeatCount() == 0;
3439
3440            // Check for fallback actions specified by the key character map.
3441            final FallbackAction fallbackAction;
3442            if (initialDown) {
3443                fallbackAction = kcm.getFallbackAction(keyCode, metaState);
3444            } else {
3445                fallbackAction = mFallbackActions.get(keyCode);
3446            }
3447
3448            if (fallbackAction != null) {
3449                if (DEBUG_INPUT) {
3450                    Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
3451                            + " metaState=" + Integer.toHexString(fallbackAction.metaState));
3452                }
3453
3454                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
3455                fallbackEvent = KeyEvent.obtain(
3456                        event.getDownTime(), event.getEventTime(),
3457                        event.getAction(), fallbackAction.keyCode,
3458                        event.getRepeatCount(), fallbackAction.metaState,
3459                        event.getDeviceId(), event.getScanCode(),
3460                        flags, event.getSource(), null);
3461
3462                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
3463                    fallbackEvent.recycle();
3464                    fallbackEvent = null;
3465                }
3466
3467                if (initialDown) {
3468                    mFallbackActions.put(keyCode, fallbackAction);
3469                } else if (event.getAction() == KeyEvent.ACTION_UP) {
3470                    mFallbackActions.remove(keyCode);
3471                    fallbackAction.recycle();
3472                }
3473            }
3474        }
3475
3476        if (DEBUG_INPUT) {
3477            if (fallbackEvent == null) {
3478                Slog.d(TAG, "No fallback.");
3479            } else {
3480                Slog.d(TAG, "Performing fallback: " + fallbackEvent);
3481            }
3482        }
3483        return fallbackEvent;
3484    }
3485
3486    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
3487        int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
3488        if ((actions & ACTION_PASS_TO_USER) != 0) {
3489            long delayMillis = interceptKeyBeforeDispatching(
3490                    win, fallbackEvent, policyFlags);
3491            if (delayMillis == 0) {
3492                return true;
3493            }
3494        }
3495        return false;
3496    }
3497
3498    public void registerShortcutKey(long shortcutCode, IShortcutService shortcutService)
3499            throws RemoteException {
3500        synchronized (mLock) {
3501            IShortcutService service = mShortcutKeyServices.get(shortcutCode);
3502            if (service != null && service.asBinder().pingBinder()) {
3503                throw new RemoteException("Key already exists.");
3504            }
3505
3506            mShortcutKeyServices.put(shortcutCode, shortcutService);
3507        }
3508    }
3509
3510    private void launchAssistLongPressAction() {
3511        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3512        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3513
3514        // launch the search activity
3515        Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
3516        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3517        try {
3518            // TODO: This only stops the factory-installed search manager.
3519            // Need to formalize an API to handle others
3520            SearchManager searchManager = getSearchManager();
3521            if (searchManager != null) {
3522                searchManager.stopSearch();
3523            }
3524            startActivityAsUser(intent, UserHandle.CURRENT);
3525        } catch (ActivityNotFoundException e) {
3526            Slog.w(TAG, "No activity to handle assist long press action.", e);
3527        }
3528    }
3529
3530    private void launchAssistAction(String hint, int deviceId) {
3531        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3532        if (!isUserSetupComplete()) {
3533            // Disable opening assist window during setup
3534            return;
3535        }
3536        Bundle args = null;
3537        if (deviceId > Integer.MIN_VALUE) {
3538            args = new Bundle();
3539            args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
3540        }
3541        if ((mContext.getResources().getConfiguration().uiMode
3542                & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
3543            // On TV, use legacy handling until assistants are implemented in the proper way.
3544            ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
3545                    .launchLegacyAssist(hint, UserHandle.myUserId(), args);
3546        } else {
3547            try {
3548                if (hint != null) {
3549                    if (args == null) {
3550                        args = new Bundle();
3551                    }
3552                    args.putBoolean(hint, true);
3553                }
3554                IStatusBarService statusbar = getStatusBarService();
3555                if (statusbar != null) {
3556                    statusbar.startAssist(args);
3557                }
3558            } catch (RemoteException e) {
3559                Slog.e(TAG, "RemoteException when starting assist", e);
3560                // re-acquire status bar service next time it is needed.
3561                mStatusBarService = null;
3562            }
3563        }
3564    }
3565
3566    private void startActivityAsUser(Intent intent, UserHandle handle) {
3567        if (isUserSetupComplete()) {
3568            mContext.startActivityAsUser(intent, handle);
3569        } else {
3570            Slog.i(TAG, "Not starting activity because user setup is in progress: " + intent);
3571        }
3572    }
3573
3574    private SearchManager getSearchManager() {
3575        if (mSearchManager == null) {
3576            mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
3577        }
3578        return mSearchManager;
3579    }
3580
3581    private void preloadRecentApps() {
3582        mPreloadedRecentApps = true;
3583        try {
3584            IStatusBarService statusbar = getStatusBarService();
3585            if (statusbar != null) {
3586                statusbar.preloadRecentApps();
3587            }
3588        } catch (RemoteException e) {
3589            Slog.e(TAG, "RemoteException when preloading recent apps", e);
3590            // re-acquire status bar service next time it is needed.
3591            mStatusBarService = null;
3592        }
3593    }
3594
3595    private void cancelPreloadRecentApps() {
3596        if (mPreloadedRecentApps) {
3597            mPreloadedRecentApps = false;
3598            try {
3599                IStatusBarService statusbar = getStatusBarService();
3600                if (statusbar != null) {
3601                    statusbar.cancelPreloadRecentApps();
3602                }
3603            } catch (RemoteException e) {
3604                Slog.e(TAG, "RemoteException when cancelling recent apps preload", e);
3605                // re-acquire status bar service next time it is needed.
3606                mStatusBarService = null;
3607            }
3608        }
3609    }
3610
3611    private void toggleRecentApps() {
3612        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3613        try {
3614            IStatusBarService statusbar = getStatusBarService();
3615            if (statusbar != null) {
3616                statusbar.toggleRecentApps();
3617            }
3618        } catch (RemoteException e) {
3619            Slog.e(TAG, "RemoteException when toggling recent apps", e);
3620            // re-acquire status bar service next time it is needed.
3621            mStatusBarService = null;
3622        }
3623    }
3624
3625    @Override
3626    public void showRecentApps() {
3627        mHandler.removeMessages(MSG_DISPATCH_SHOW_RECENTS);
3628        mHandler.sendEmptyMessage(MSG_DISPATCH_SHOW_RECENTS);
3629    }
3630
3631    private void showRecentApps(boolean triggeredFromAltTab) {
3632        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3633        try {
3634            IStatusBarService statusbar = getStatusBarService();
3635            if (statusbar != null) {
3636                statusbar.showRecentApps(triggeredFromAltTab);
3637            }
3638        } catch (RemoteException e) {
3639            Slog.e(TAG, "RemoteException when showing recent apps", e);
3640            // re-acquire status bar service next time it is needed.
3641            mStatusBarService = null;
3642        }
3643    }
3644
3645    private void toggleKeyboardShortcutsMenu(int deviceId) {
3646        try {
3647            IStatusBarService statusbar = getStatusBarService();
3648            if (statusbar != null) {
3649                statusbar.toggleKeyboardShortcutsMenu(deviceId);
3650            }
3651        } catch (RemoteException e) {
3652            Slog.e(TAG, "RemoteException when showing keyboard shortcuts menu", e);
3653        }
3654    }
3655
3656    private void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHome) {
3657        mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3658        try {
3659            IStatusBarService statusbar = getStatusBarService();
3660            if (statusbar != null) {
3661                statusbar.hideRecentApps(triggeredFromAltTab, triggeredFromHome);
3662            }
3663        } catch (RemoteException e) {
3664            Slog.e(TAG, "RemoteException when closing recent apps", e);
3665            // re-acquire status bar service next time it is needed.
3666            mStatusBarService = null;
3667        }
3668    }
3669
3670    void launchHomeFromHotKey() {
3671        launchHomeFromHotKey(true /* awakenFromDreams */, true /*respectKeyguard*/);
3672    }
3673
3674    /**
3675     * A home key -> launch home action was detected.  Take the appropriate action
3676     * given the situation with the keyguard.
3677     */
3678    void launchHomeFromHotKey(final boolean awakenFromDreams, final boolean respectKeyguard) {
3679        if (respectKeyguard) {
3680            if (isKeyguardShowingAndNotOccluded()) {
3681                // don't launch home if keyguard showing
3682                return;
3683            }
3684
3685            if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
3686                // when in keyguard restricted mode, must first verify unlock
3687                // before launching home
3688                mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
3689                    @Override
3690                    public void onKeyguardExitResult(boolean success) {
3691                        if (success) {
3692                            try {
3693                                ActivityManagerNative.getDefault().stopAppSwitches();
3694                            } catch (RemoteException e) {
3695                            }
3696                            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3697                            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3698                        }
3699                    }
3700                });
3701                return;
3702            }
3703        }
3704
3705        // no keyguard stuff to worry about, just launch home!
3706        try {
3707            ActivityManagerNative.getDefault().stopAppSwitches();
3708        } catch (RemoteException e) {
3709        }
3710        if (mRecentsVisible) {
3711            // Hide Recents and notify it to launch Home
3712            if (awakenFromDreams) {
3713                awakenDreams();
3714            }
3715            hideRecentApps(false, true);
3716        } else {
3717            // Otherwise, just launch Home
3718            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3719            startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3720        }
3721    }
3722
3723    private final Runnable mClearHideNavigationFlag = new Runnable() {
3724        @Override
3725        public void run() {
3726            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3727                // Clear flags.
3728                mForceClearedSystemUiFlags &=
3729                        ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3730            }
3731            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3732        }
3733    };
3734
3735    /**
3736     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
3737     * to determine when the nav bar should be shown and prevent applications from
3738     * receiving those touches.
3739     */
3740    final class HideNavInputEventReceiver extends InputEventReceiver {
3741        public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
3742            super(inputChannel, looper);
3743        }
3744
3745        @Override
3746        public void onInputEvent(InputEvent event) {
3747            boolean handled = false;
3748            try {
3749                if (event instanceof MotionEvent
3750                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3751                    final MotionEvent motionEvent = (MotionEvent)event;
3752                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
3753                        // When the user taps down, we re-show the nav bar.
3754                        boolean changed = false;
3755                        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3756                            // Any user activity always causes us to show the
3757                            // navigation controls, if they had been hidden.
3758                            // We also clear the low profile and only content
3759                            // flags so that tapping on the screen will atomically
3760                            // restore all currently hidden screen decorations.
3761                            int newVal = mResettingSystemUiFlags |
3762                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3763                                    View.SYSTEM_UI_FLAG_LOW_PROFILE |
3764                                    View.SYSTEM_UI_FLAG_FULLSCREEN;
3765                            if (mResettingSystemUiFlags != newVal) {
3766                                mResettingSystemUiFlags = newVal;
3767                                changed = true;
3768                            }
3769                            // We don't allow the system's nav bar to be hidden
3770                            // again for 1 second, to prevent applications from
3771                            // spamming us and keeping it from being shown.
3772                            newVal = mForceClearedSystemUiFlags |
3773                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3774                            if (mForceClearedSystemUiFlags != newVal) {
3775                                mForceClearedSystemUiFlags = newVal;
3776                                changed = true;
3777                                mHandler.postDelayed(mClearHideNavigationFlag, 1000);
3778                            }
3779                        }
3780                        if (changed) {
3781                            mWindowManagerFuncs.reevaluateStatusBarVisibility();
3782                        }
3783                    }
3784                }
3785            } finally {
3786                finishInputEvent(event, handled);
3787            }
3788        }
3789    }
3790    final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
3791            new InputEventReceiver.Factory() {
3792        @Override
3793        public InputEventReceiver createInputEventReceiver(
3794                InputChannel inputChannel, Looper looper) {
3795            return new HideNavInputEventReceiver(inputChannel, looper);
3796        }
3797    };
3798
3799    @Override
3800    public int adjustSystemUiVisibilityLw(int visibility) {
3801        mStatusBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3802        mNavigationBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
3803        mRecentsVisible = (visibility & View.RECENT_APPS_VISIBLE) > 0;
3804
3805        // Reset any bits in mForceClearingStatusBarVisibility that
3806        // are now clear.
3807        mResettingSystemUiFlags &= visibility;
3808        // Clear any bits in the new visibility that are currently being
3809        // force cleared, before reporting it.
3810        return visibility & ~mResettingSystemUiFlags
3811                & ~mForceClearedSystemUiFlags;
3812    }
3813
3814    @Override
3815    public boolean getInsetHintLw(WindowManager.LayoutParams attrs, int displayRotation,
3816            Rect outContentInsets, Rect outStableInsets, Rect outOutsets) {
3817        final int fl = PolicyControl.getWindowFlags(null, attrs);
3818        final int sysuiVis = PolicyControl.getSystemUiVisibility(null, attrs);
3819        final int systemUiVisibility = (sysuiVis | attrs.subtreeSystemUiVisibility);
3820
3821        final boolean useOutsets = outOutsets != null && shouldUseOutsets(attrs, fl);
3822        if (useOutsets) {
3823            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
3824            if (outset > 0) {
3825                if (displayRotation == Surface.ROTATION_0) {
3826                    outOutsets.bottom += outset;
3827                } else if (displayRotation == Surface.ROTATION_90) {
3828                    outOutsets.right += outset;
3829                } else if (displayRotation == Surface.ROTATION_180) {
3830                    outOutsets.top += outset;
3831                } else if (displayRotation == Surface.ROTATION_270) {
3832                    outOutsets.left += outset;
3833                }
3834            }
3835        }
3836
3837        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3838                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3839            int availRight, availBottom;
3840            if (canHideNavigationBar() &&
3841                    (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
3842                availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3843                availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3844            } else {
3845                availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
3846                availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3847            }
3848            if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
3849                if ((fl & FLAG_FULLSCREEN) != 0) {
3850                    outContentInsets.set(mStableFullscreenLeft, mStableFullscreenTop,
3851                            availRight - mStableFullscreenRight,
3852                            availBottom - mStableFullscreenBottom);
3853                } else {
3854                    outContentInsets.set(mStableLeft, mStableTop,
3855                            availRight - mStableRight, availBottom - mStableBottom);
3856                }
3857            } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
3858                outContentInsets.setEmpty();
3859            } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
3860                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
3861                outContentInsets.set(mCurLeft, mCurTop,
3862                        availRight - mCurRight, availBottom - mCurBottom);
3863            } else {
3864                outContentInsets.set(mCurLeft, mCurTop,
3865                        availRight - mCurRight, availBottom - mCurBottom);
3866            }
3867
3868            outStableInsets.set(mStableLeft, mStableTop,
3869                    availRight - mStableRight, availBottom - mStableBottom);
3870            return mForceShowSystemBars;
3871        }
3872        outContentInsets.setEmpty();
3873        outStableInsets.setEmpty();
3874        return mForceShowSystemBars;
3875    }
3876
3877    private boolean shouldUseOutsets(WindowManager.LayoutParams attrs, int fl) {
3878        return attrs.type == TYPE_WALLPAPER || (fl & (WindowManager.LayoutParams.FLAG_FULLSCREEN
3879                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN)) != 0;
3880    }
3881
3882    /** {@inheritDoc} */
3883    @Override
3884    public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
3885                              int displayRotation, int uiMode) {
3886        mDisplayRotation = displayRotation;
3887        final int overscanLeft, overscanTop, overscanRight, overscanBottom;
3888        if (isDefaultDisplay) {
3889            switch (displayRotation) {
3890                case Surface.ROTATION_90:
3891                    overscanLeft = mOverscanTop;
3892                    overscanTop = mOverscanRight;
3893                    overscanRight = mOverscanBottom;
3894                    overscanBottom = mOverscanLeft;
3895                    break;
3896                case Surface.ROTATION_180:
3897                    overscanLeft = mOverscanRight;
3898                    overscanTop = mOverscanBottom;
3899                    overscanRight = mOverscanLeft;
3900                    overscanBottom = mOverscanTop;
3901                    break;
3902                case Surface.ROTATION_270:
3903                    overscanLeft = mOverscanBottom;
3904                    overscanTop = mOverscanLeft;
3905                    overscanRight = mOverscanTop;
3906                    overscanBottom = mOverscanRight;
3907                    break;
3908                default:
3909                    overscanLeft = mOverscanLeft;
3910                    overscanTop = mOverscanTop;
3911                    overscanRight = mOverscanRight;
3912                    overscanBottom = mOverscanBottom;
3913                    break;
3914            }
3915        } else {
3916            overscanLeft = 0;
3917            overscanTop = 0;
3918            overscanRight = 0;
3919            overscanBottom = 0;
3920        }
3921        mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
3922        mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
3923        mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
3924        mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
3925        mSystemLeft = 0;
3926        mSystemTop = 0;
3927        mSystemRight = displayWidth;
3928        mSystemBottom = displayHeight;
3929        mUnrestrictedScreenLeft = overscanLeft;
3930        mUnrestrictedScreenTop = overscanTop;
3931        mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
3932        mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
3933        mRestrictedScreenLeft = mUnrestrictedScreenLeft;
3934        mRestrictedScreenTop = mUnrestrictedScreenTop;
3935        mRestrictedScreenWidth = mSystemGestures.screenWidth = mUnrestrictedScreenWidth;
3936        mRestrictedScreenHeight = mSystemGestures.screenHeight = mUnrestrictedScreenHeight;
3937        mDockLeft = mContentLeft = mVoiceContentLeft = mStableLeft = mStableFullscreenLeft
3938                = mCurLeft = mUnrestrictedScreenLeft;
3939        mDockTop = mContentTop = mVoiceContentTop = mStableTop = mStableFullscreenTop
3940                = mCurTop = mUnrestrictedScreenTop;
3941        mDockRight = mContentRight = mVoiceContentRight = mStableRight = mStableFullscreenRight
3942                = mCurRight = displayWidth - overscanRight;
3943        mDockBottom = mContentBottom = mVoiceContentBottom = mStableBottom = mStableFullscreenBottom
3944                = mCurBottom = displayHeight - overscanBottom;
3945        mDockLayer = 0x10000000;
3946        mStatusBarLayer = -1;
3947
3948        // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
3949        final Rect pf = mTmpParentFrame;
3950        final Rect df = mTmpDisplayFrame;
3951        final Rect of = mTmpOverscanFrame;
3952        final Rect vf = mTmpVisibleFrame;
3953        final Rect dcf = mTmpDecorFrame;
3954        pf.left = df.left = of.left = vf.left = mDockLeft;
3955        pf.top = df.top = of.top = vf.top = mDockTop;
3956        pf.right = df.right = of.right = vf.right = mDockRight;
3957        pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
3958        dcf.setEmpty();  // Decor frame N/A for system bars.
3959
3960        if (isDefaultDisplay) {
3961            // For purposes of putting out fake window up to steal focus, we will
3962            // drive nav being hidden only by whether it is requested.
3963            final int sysui = mLastSystemUiFlags;
3964            boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
3965            boolean navTranslucent = (sysui
3966                    & (View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT)) != 0;
3967            boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
3968            boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
3969            boolean navAllowedHidden = immersive || immersiveSticky;
3970            navTranslucent &= !immersiveSticky;  // transient trumps translucent
3971            boolean isKeyguardShowing = isStatusBarKeyguard() && !mHideLockScreen;
3972            if (!isKeyguardShowing) {
3973                navTranslucent &= areTranslucentBarsAllowed();
3974            }
3975
3976            // When the navigation bar isn't visible, we put up a fake
3977            // input window to catch all touch events.  This way we can
3978            // detect when the user presses anywhere to bring back the nav
3979            // bar and ensure the application doesn't see the event.
3980            if (navVisible || navAllowedHidden) {
3981                if (mInputConsumer != null) {
3982                    mInputConsumer.dismiss();
3983                    mInputConsumer = null;
3984                }
3985            } else if (mInputConsumer == null) {
3986                mInputConsumer = mWindowManagerFuncs.addInputConsumer(mHandler.getLooper(),
3987                        mHideNavInputEventReceiverFactory);
3988            }
3989
3990            // For purposes of positioning and showing the nav bar, if we have
3991            // decided that it can't be hidden (because of the screen aspect ratio),
3992            // then take that into account.
3993            navVisible |= !canHideNavigationBar();
3994
3995            boolean updateSysUiVisibility = layoutNavigationBar(displayWidth, displayHeight,
3996                    displayRotation, uiMode, overscanRight, overscanBottom, dcf, navVisible, navTranslucent,
3997                    navAllowedHidden);
3998            if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
3999                    mDockLeft, mDockTop, mDockRight, mDockBottom));
4000            updateSysUiVisibility |= layoutStatusBar(pf, df, of, vf, dcf, sysui, isKeyguardShowing);
4001            if (updateSysUiVisibility) {
4002                updateSystemUiVisibilityLw();
4003            }
4004        }
4005    }
4006
4007    private boolean layoutStatusBar(Rect pf, Rect df, Rect of, Rect vf, Rect dcf, int sysui,
4008            boolean isKeyguardShowing) {
4009        // decide where the status bar goes ahead of time
4010        if (mStatusBar != null) {
4011            // apply any navigation bar insets
4012            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4013            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4014            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
4015            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
4016                    + mUnrestrictedScreenTop;
4017            vf.left = mStableLeft;
4018            vf.top = mStableTop;
4019            vf.right = mStableRight;
4020            vf.bottom = mStableBottom;
4021
4022            mStatusBarLayer = mStatusBar.getSurfaceLayer();
4023
4024            // Let the status bar determine its size.
4025            mStatusBar.computeFrameLw(pf /* parentFrame */, df /* displayFrame */,
4026                    vf /* overlayFrame */, vf /* contentFrame */, vf /* visibleFrame */,
4027                    dcf /* decorFrame */, vf /* stableFrame */, vf /* outsetFrame */);
4028
4029            // For layout, the status bar is always at the top with our fixed height.
4030            mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
4031
4032            boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
4033            boolean statusBarTranslucent = (sysui
4034                    & (View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT)) != 0;
4035            if (!isKeyguardShowing) {
4036                statusBarTranslucent &= areTranslucentBarsAllowed();
4037            }
4038
4039            // If the status bar is hidden, we don't want to cause
4040            // windows behind it to scroll.
4041            if (mStatusBar.isVisibleLw() && !statusBarTransient) {
4042                // Status bar may go away, so the screen area it occupies
4043                // is available to apps but just covering them when the
4044                // status bar is visible.
4045                mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
4046
4047                mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4048                mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4049                mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4050                mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4051
4052                if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
4053                        String.format(
4054                                "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
4055                                mDockLeft, mDockTop, mDockRight, mDockBottom,
4056                                mContentLeft, mContentTop, mContentRight, mContentBottom,
4057                                mCurLeft, mCurTop, mCurRight, mCurBottom));
4058            }
4059            if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
4060                    && !statusBarTransient && !statusBarTranslucent
4061                    && !mStatusBarController.wasRecentlyTranslucent()) {
4062                // If the opaque status bar is currently requested to be visible,
4063                // and not in the process of animating on or off, then
4064                // we can tell the app that it is covered by it.
4065                mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
4066            }
4067            if (mStatusBarController.checkHiddenLw()) {
4068                return true;
4069            }
4070        }
4071        return false;
4072    }
4073
4074    private boolean layoutNavigationBar(int displayWidth, int displayHeight, int displayRotation,
4075            int uiMode, int overscanRight, int overscanBottom, Rect dcf, boolean navVisible,
4076            boolean navTranslucent, boolean navAllowedHidden) {
4077        if (mNavigationBar != null) {
4078            boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
4079            // Force the navigation bar to its appropriate place and
4080            // size.  We need to do this directly, instead of relying on
4081            // it to bubble up from the nav bar, because this needs to
4082            // change atomically with screen rotations.
4083            mNavigationBarOnBottom = isNavigationBarOnBottom(displayWidth, displayHeight);
4084            if (mNavigationBarOnBottom) {
4085                // It's a system nav bar or a portrait screen; nav bar goes on bottom.
4086                int top = displayHeight - overscanBottom
4087                        - getNavigationBarHeight(displayRotation, uiMode);
4088                mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
4089                mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
4090                if (transientNavBarShowing) {
4091                    mNavigationBarController.setBarShowingLw(true);
4092                } else if (navVisible) {
4093                    mNavigationBarController.setBarShowingLw(true);
4094                    mDockBottom = mTmpNavigationFrame.top;
4095                    mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
4096                    mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
4097                } else {
4098                    // We currently want to hide the navigation UI.
4099                    mNavigationBarController.setBarShowingLw(false);
4100                }
4101                if (navVisible && !navTranslucent && !navAllowedHidden
4102                        && !mNavigationBar.isAnimatingLw()
4103                        && !mNavigationBarController.wasRecentlyTranslucent()) {
4104                    // If the opaque nav bar is currently requested to be visible,
4105                    // and not in the process of animating on or off, then
4106                    // we can tell the app that it is covered by it.
4107                    mSystemBottom = mTmpNavigationFrame.top;
4108                }
4109            } else {
4110                // Landscape screen; nav bar goes to the right.
4111                int left = displayWidth - overscanRight
4112                        - getNavigationBarWidth(displayRotation, uiMode);
4113                mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
4114                mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
4115                if (transientNavBarShowing) {
4116                    mNavigationBarController.setBarShowingLw(true);
4117                } else if (navVisible) {
4118                    mNavigationBarController.setBarShowingLw(true);
4119                    mDockRight = mTmpNavigationFrame.left;
4120                    mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
4121                    mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
4122                } else {
4123                    // We currently want to hide the navigation UI.
4124                    mNavigationBarController.setBarShowingLw(false);
4125                }
4126                if (navVisible && !navTranslucent && !navAllowedHidden
4127                        && !mNavigationBar.isAnimatingLw()
4128                        && !mNavigationBarController.wasRecentlyTranslucent()) {
4129                    // If the nav bar is currently requested to be visible,
4130                    // and not in the process of animating on or off, then
4131                    // we can tell the app that it is covered by it.
4132                    mSystemRight = mTmpNavigationFrame.left;
4133                }
4134            }
4135            // Make sure the content and current rectangles are updated to
4136            // account for the restrictions from the navigation bar.
4137            mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4138            mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4139            mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4140            mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4141            mStatusBarLayer = mNavigationBar.getSurfaceLayer();
4142            // And compute the final frame.
4143            mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
4144                    mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf,
4145                    mTmpNavigationFrame, mTmpNavigationFrame);
4146            if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
4147            if (mNavigationBarController.checkHiddenLw()) {
4148                return true;
4149            }
4150        }
4151        return false;
4152    }
4153
4154    private boolean isNavigationBarOnBottom(int displayWidth, int displayHeight) {
4155        return !mNavigationBarCanMove || displayWidth < displayHeight;
4156    }
4157
4158    /** {@inheritDoc} */
4159    @Override
4160    public int getSystemDecorLayerLw() {
4161        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
4162            return mStatusBar.getSurfaceLayer();
4163        }
4164
4165        if (mNavigationBar != null && mNavigationBar.isVisibleLw()) {
4166            return mNavigationBar.getSurfaceLayer();
4167        }
4168
4169        return 0;
4170    }
4171
4172    @Override
4173    public void getContentRectLw(Rect r) {
4174        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
4175    }
4176
4177    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
4178            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
4179        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
4180            // Here's a special case: if this attached window is a panel that is
4181            // above the dock window, and the window it is attached to is below
4182            // the dock window, then the frames we computed for the window it is
4183            // attached to can not be used because the dock is effectively part
4184            // of the underlying window and the attached window is floating on top
4185            // of the whole thing.  So, we ignore the attached window and explicitly
4186            // compute the frames that would be appropriate without the dock.
4187            df.left = of.left = cf.left = vf.left = mDockLeft;
4188            df.top = of.top = cf.top = vf.top = mDockTop;
4189            df.right = of.right = cf.right = vf.right = mDockRight;
4190            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
4191        } else {
4192            // The effective display frame of the attached window depends on
4193            // whether it is taking care of insetting its content.  If not,
4194            // we need to use the parent's content frame so that the entire
4195            // window is positioned within that content.  Otherwise we can use
4196            // the overscan frame and let the attached window take care of
4197            // positioning its content appropriately.
4198            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4199                // Set the content frame of the attached window to the parent's decor frame
4200                // (same as content frame when IME isn't present) if specifically requested by
4201                // setting {@link WindowManager.LayoutParams#FLAG_LAYOUT_ATTACHED_IN_DECOR} flag.
4202                // Otherwise, use the overscan frame.
4203                cf.set((fl & FLAG_LAYOUT_ATTACHED_IN_DECOR) != 0
4204                        ? attached.getContentFrameLw() : attached.getOverscanFrameLw());
4205            } else {
4206                // If the window is resizing, then we want to base the content
4207                // frame on our attached content frame to resize...  however,
4208                // things can be tricky if the attached window is NOT in resize
4209                // mode, in which case its content frame will be larger.
4210                // Ungh.  So to deal with that, make sure the content frame
4211                // we end up using is not covering the IM dock.
4212                cf.set(attached.getContentFrameLw());
4213                if (attached.isVoiceInteraction()) {
4214                    if (cf.left < mVoiceContentLeft) cf.left = mVoiceContentLeft;
4215                    if (cf.top < mVoiceContentTop) cf.top = mVoiceContentTop;
4216                    if (cf.right > mVoiceContentRight) cf.right = mVoiceContentRight;
4217                    if (cf.bottom > mVoiceContentBottom) cf.bottom = mVoiceContentBottom;
4218                } else if (attached.getSurfaceLayer() < mDockLayer) {
4219                    if (cf.left < mContentLeft) cf.left = mContentLeft;
4220                    if (cf.top < mContentTop) cf.top = mContentTop;
4221                    if (cf.right > mContentRight) cf.right = mContentRight;
4222                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
4223                }
4224            }
4225            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
4226            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
4227            vf.set(attached.getVisibleFrameLw());
4228        }
4229        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
4230        // window should be positioned relative to its parent or the entire
4231        // screen.
4232        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
4233                ? attached.getFrameLw() : df);
4234    }
4235
4236    private void applyStableConstraints(int sysui, int fl, Rect r) {
4237        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
4238            // If app is requesting a stable layout, don't let the
4239            // content insets go below the stable values.
4240            if ((fl & FLAG_FULLSCREEN) != 0) {
4241                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
4242                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
4243                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
4244                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
4245            } else {
4246                if (r.left < mStableLeft) r.left = mStableLeft;
4247                if (r.top < mStableTop) r.top = mStableTop;
4248                if (r.right > mStableRight) r.right = mStableRight;
4249                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
4250            }
4251        }
4252    }
4253
4254    private boolean canReceiveInput(WindowState win) {
4255        boolean notFocusable =
4256                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0;
4257        boolean altFocusableIm =
4258                (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0;
4259        boolean notFocusableForIm = notFocusable ^ altFocusableIm;
4260        return !notFocusableForIm;
4261    }
4262
4263    /** {@inheritDoc} */
4264    @Override
4265    public void layoutWindowLw(WindowState win, WindowState attached) {
4266        // We've already done the navigation bar and status bar. If the status bar can receive
4267        // input, we need to layout it again to accomodate for the IME window.
4268        if ((win == mStatusBar && !canReceiveInput(win)) || win == mNavigationBar) {
4269            return;
4270        }
4271        final WindowManager.LayoutParams attrs = win.getAttrs();
4272        final boolean isDefaultDisplay = win.isDefaultDisplay();
4273        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
4274                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
4275        if (needsToOffsetInputMethodTarget) {
4276            if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
4277            offsetInputMethodWindowLw(mLastInputMethodWindow);
4278        }
4279
4280        final int fl = PolicyControl.getWindowFlags(win, attrs);
4281        final int pfl = attrs.privateFlags;
4282        final int sim = attrs.softInputMode;
4283        final int sysUiFl = PolicyControl.getSystemUiVisibility(win, null);
4284
4285        final Rect pf = mTmpParentFrame;
4286        final Rect df = mTmpDisplayFrame;
4287        final Rect of = mTmpOverscanFrame;
4288        final Rect cf = mTmpContentFrame;
4289        final Rect vf = mTmpVisibleFrame;
4290        final Rect dcf = mTmpDecorFrame;
4291        final Rect sf = mTmpStableFrame;
4292        Rect osf = null;
4293        dcf.setEmpty();
4294
4295        final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
4296                && mNavigationBar != null && mNavigationBar.isVisibleLw());
4297
4298        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
4299
4300        if (isDefaultDisplay) {
4301            sf.set(mStableLeft, mStableTop, mStableRight, mStableBottom);
4302        } else {
4303            sf.set(mOverscanLeft, mOverscanTop, mOverscanRight, mOverscanBottom);
4304        }
4305
4306        if (!isDefaultDisplay) {
4307            if (attached != null) {
4308                // If this window is attached to another, our display
4309                // frame is the same as the one we are attached to.
4310                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4311            } else {
4312                // Give the window full screen.
4313                pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4314                pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4315                pf.right = df.right = of.right = cf.right
4316                        = mOverscanScreenLeft + mOverscanScreenWidth;
4317                pf.bottom = df.bottom = of.bottom = cf.bottom
4318                        = mOverscanScreenTop + mOverscanScreenHeight;
4319            }
4320        } else if (attrs.type == TYPE_INPUT_METHOD) {
4321            pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
4322            pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
4323            pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
4324            // IM dock windows layout below the nav bar...
4325            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4326            // ...with content insets above the nav bar
4327            cf.bottom = vf.bottom = mStableBottom;
4328            // IM dock windows always go to the bottom of the screen.
4329            attrs.gravity = Gravity.BOTTOM;
4330            mDockLayer = win.getSurfaceLayer();
4331        } else if (attrs.type == TYPE_VOICE_INTERACTION) {
4332            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4333            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4334            pf.right = df.right = of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4335            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4336            cf.bottom = vf.bottom = mStableBottom;
4337            // Note: In Phone landscape mode, the button bar should also be excluded.
4338            cf.right = vf.right = mStableRight;
4339            cf.left = vf.left = mStableLeft;
4340            cf.top = vf.top = mStableTop;
4341        } else if (win == mStatusBar) {
4342            pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4343            pf.top = df.top = of.top = mUnrestrictedScreenTop;
4344            pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
4345            pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight + mUnrestrictedScreenTop;
4346            cf.left = vf.left = mStableLeft;
4347            cf.top = vf.top = mStableTop;
4348            cf.right = vf.right = mStableRight;
4349            vf.bottom = mStableBottom;
4350
4351            if (adjust == SOFT_INPUT_ADJUST_RESIZE) {
4352                cf.bottom = mContentBottom;
4353            } else {
4354                cf.bottom = mDockBottom;
4355                vf.bottom = mContentBottom;
4356            }
4357        } else {
4358
4359            // Default policy decor for the default display
4360            dcf.left = mSystemLeft;
4361            dcf.top = mSystemTop;
4362            dcf.right = mSystemRight;
4363            dcf.bottom = mSystemBottom;
4364            final boolean inheritTranslucentDecor = (attrs.privateFlags
4365                    & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
4366            final boolean isAppWindow =
4367                    attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
4368                    attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
4369            final boolean topAtRest =
4370                    win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
4371            if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
4372                if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
4373                        && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
4374                        && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0
4375                        && (fl & WindowManager.LayoutParams.
4376                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0
4377                        && (pfl & PRIVATE_FLAG_FORCE_DRAW_STATUS_BAR_BACKGROUND) == 0) {
4378                    // Ensure policy decor includes status bar
4379                    dcf.top = mStableTop;
4380                }
4381                if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
4382                        && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
4383                        && (fl & WindowManager.LayoutParams.
4384                                FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
4385                    // Ensure policy decor includes navigation bar
4386                    dcf.bottom = mStableBottom;
4387                    dcf.right = mStableRight;
4388                }
4389            }
4390
4391            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
4392                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
4393                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
4394                            + "): IN_SCREEN, INSET_DECOR");
4395                // This is the case for a normal activity window: we want it
4396                // to cover all of the screen space, and it can take care of
4397                // moving its contents to account for screen decorations that
4398                // intrude into that space.
4399                if (attached != null) {
4400                    // If this window is attached to another, our display
4401                    // frame is the same as the one we are attached to.
4402                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4403                } else {
4404                    if (attrs.type == TYPE_STATUS_BAR_PANEL
4405                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
4406                        // Status bar panels are the only windows who can go on top of
4407                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
4408                        // permission, so they have the same privileges as the status
4409                        // bar itself.
4410                        //
4411                        // However, they should still dodge the navigation bar if it exists.
4412
4413                        pf.left = df.left = of.left = hasNavBar
4414                                ? mDockLeft : mUnrestrictedScreenLeft;
4415                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
4416                        pf.right = df.right = of.right = hasNavBar
4417                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
4418                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4419                        pf.bottom = df.bottom = of.bottom = hasNavBar
4420                                ? mRestrictedScreenTop+mRestrictedScreenHeight
4421                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4422
4423                        if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4424                                        "Laying out status bar window: (%d,%d - %d,%d)",
4425                                        pf.left, pf.top, pf.right, pf.bottom));
4426                    } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4427                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4428                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4429                        // Asking to layout into the overscan region, so give it that pure
4430                        // unrestricted area.
4431                        pf.left = df.left = of.left = mOverscanScreenLeft;
4432                        pf.top = df.top = of.top = mOverscanScreenTop;
4433                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
4434                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
4435                                + mOverscanScreenHeight;
4436                    } else if (canHideNavigationBar()
4437                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4438                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4439                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4440                        // Asking for layout as if the nav bar is hidden, lets the
4441                        // application extend into the unrestricted overscan screen area.  We
4442                        // only do this for application windows to ensure no window that
4443                        // can be above the nav bar can do this.
4444                        pf.left = df.left = mOverscanScreenLeft;
4445                        pf.top = df.top = mOverscanScreenTop;
4446                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4447                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4448                        // We need to tell the app about where the frame inside the overscan
4449                        // is, so it can inset its content by that amount -- it didn't ask
4450                        // to actually extend itself into the overscan region.
4451                        of.left = mUnrestrictedScreenLeft;
4452                        of.top = mUnrestrictedScreenTop;
4453                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4454                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4455                    } else {
4456                        pf.left = df.left = mRestrictedOverscanScreenLeft;
4457                        pf.top = df.top = mRestrictedOverscanScreenTop;
4458                        pf.right = df.right = mRestrictedOverscanScreenLeft
4459                                + mRestrictedOverscanScreenWidth;
4460                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
4461                                + mRestrictedOverscanScreenHeight;
4462                        // We need to tell the app about where the frame inside the overscan
4463                        // is, so it can inset its content by that amount -- it didn't ask
4464                        // to actually extend itself into the overscan region.
4465                        of.left = mUnrestrictedScreenLeft;
4466                        of.top = mUnrestrictedScreenTop;
4467                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4468                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4469                    }
4470
4471                    if ((fl & FLAG_FULLSCREEN) == 0) {
4472                        if (win.isVoiceInteraction()) {
4473                            cf.left = mVoiceContentLeft;
4474                            cf.top = mVoiceContentTop;
4475                            cf.right = mVoiceContentRight;
4476                            cf.bottom = mVoiceContentBottom;
4477                        } else {
4478                            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4479                                cf.left = mDockLeft;
4480                                cf.top = mDockTop;
4481                                cf.right = mDockRight;
4482                                cf.bottom = mDockBottom;
4483                            } else {
4484                                cf.left = mContentLeft;
4485                                cf.top = mContentTop;
4486                                cf.right = mContentRight;
4487                                cf.bottom = mContentBottom;
4488                            }
4489                        }
4490                    } else {
4491                        // Full screen windows are always given a layout that is as if the
4492                        // status bar and other transient decors are gone.  This is to avoid
4493                        // bad states when moving from a window that is not hding the
4494                        // status bar to one that is.
4495                        cf.left = mRestrictedScreenLeft;
4496                        cf.top = mRestrictedScreenTop;
4497                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4498                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
4499                    }
4500                    applyStableConstraints(sysUiFl, fl, cf);
4501                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4502                        vf.left = mCurLeft;
4503                        vf.top = mCurTop;
4504                        vf.right = mCurRight;
4505                        vf.bottom = mCurBottom;
4506                    } else {
4507                        vf.set(cf);
4508                    }
4509                }
4510            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
4511                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
4512                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
4513                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4514                        "): IN_SCREEN");
4515                // A window that has requested to fill the entire screen just
4516                // gets everything, period.
4517                if (attrs.type == TYPE_STATUS_BAR_PANEL
4518                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL
4519                        || attrs.type == TYPE_VOLUME_OVERLAY) {
4520                    pf.left = df.left = of.left = cf.left = hasNavBar
4521                            ? mDockLeft : mUnrestrictedScreenLeft;
4522                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4523                    pf.right = df.right = of.right = cf.right = hasNavBar
4524                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
4525                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4526                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
4527                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
4528                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4529                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4530                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
4531                                    pf.left, pf.top, pf.right, pf.bottom));
4532                } else if (attrs.type == TYPE_NAVIGATION_BAR
4533                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
4534                    // The navigation bar has Real Ultimate Power.
4535                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4536                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
4537                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
4538                            + mUnrestrictedScreenWidth;
4539                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
4540                            + mUnrestrictedScreenHeight;
4541                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4542                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
4543                                    pf.left, pf.top, pf.right, pf.bottom));
4544                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
4545                                || attrs.type == TYPE_BOOT_PROGRESS
4546                                || attrs.type == TYPE_SCREENSHOT)
4547                        && ((fl & FLAG_FULLSCREEN) != 0)) {
4548                    // Fullscreen secure system overlays get what they ask for. Screenshot region
4549                    // selection overlay should also expand to full screen.
4550                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4551                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4552                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4553                            + mOverscanScreenWidth;
4554                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4555                            + mOverscanScreenHeight;
4556                } else if (attrs.type == TYPE_BOOT_PROGRESS) {
4557                    // Boot progress screen always covers entire display.
4558                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4559                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4560                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4561                            + mOverscanScreenWidth;
4562                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4563                            + mOverscanScreenHeight;
4564                } else if (attrs.type == TYPE_WALLPAPER) {
4565                    // The wallpaper also has Real Ultimate Power, but we want to tell
4566                    // it about the overscan area.
4567                    pf.left = df.left = mOverscanScreenLeft;
4568                    pf.top = df.top = mOverscanScreenTop;
4569                    pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4570                    pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4571                    of.left = cf.left = mUnrestrictedScreenLeft;
4572                    of.top = cf.top = mUnrestrictedScreenTop;
4573                    of.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4574                    of.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4575                } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4576                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4577                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4578                    // Asking to layout into the overscan region, so give it that pure
4579                    // unrestricted area.
4580                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4581                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4582                    pf.right = df.right = of.right = cf.right
4583                            = mOverscanScreenLeft + mOverscanScreenWidth;
4584                    pf.bottom = df.bottom = of.bottom = cf.bottom
4585                            = mOverscanScreenTop + mOverscanScreenHeight;
4586                } else if (canHideNavigationBar()
4587                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4588                        && (attrs.type == TYPE_STATUS_BAR
4589                            || attrs.type == TYPE_TOAST
4590                            || attrs.type == TYPE_DOCK_DIVIDER
4591                            || attrs.type == TYPE_VOICE_INTERACTION_STARTING
4592                            || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4593                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
4594                    // Asking for layout as if the nav bar is hidden, lets the
4595                    // application extend into the unrestricted screen area.  We
4596                    // only do this for application windows (or toasts) to ensure no window that
4597                    // can be above the nav bar can do this.
4598                    // XXX This assumes that an app asking for this will also
4599                    // ask for layout in only content.  We can't currently figure out
4600                    // what the screen would be if only laying out to hide the nav bar.
4601                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
4602                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4603                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
4604                            + mUnrestrictedScreenWidth;
4605                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
4606                            + mUnrestrictedScreenHeight;
4607                } else if ((sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0) {
4608                    pf.left = df.left = of.left = mRestrictedScreenLeft;
4609                    pf.top = df.top = of.top  = mRestrictedScreenTop;
4610                    pf.right = df.right = of.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4611                    pf.bottom = df.bottom = of.bottom = mRestrictedScreenTop
4612                            + mRestrictedScreenHeight;
4613                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4614                        cf.left = mDockLeft;
4615                        cf.top = mDockTop;
4616                        cf.right = mDockRight;
4617                        cf.bottom = mDockBottom;
4618                    } else {
4619                        cf.left = mContentLeft;
4620                        cf.top = mContentTop;
4621                        cf.right = mContentRight;
4622                        cf.bottom = mContentBottom;
4623                    }
4624                } else {
4625                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4626                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4627                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4628                            + mRestrictedScreenWidth;
4629                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4630                            + mRestrictedScreenHeight;
4631                }
4632
4633                applyStableConstraints(sysUiFl, fl, cf);
4634
4635                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4636                    vf.left = mCurLeft;
4637                    vf.top = mCurTop;
4638                    vf.right = mCurRight;
4639                    vf.bottom = mCurBottom;
4640                } else {
4641                    vf.set(cf);
4642                }
4643            } else if (attached != null) {
4644                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4645                        "): attached to " + attached);
4646                // A child window should be placed inside of the same visible
4647                // frame that its parent had.
4648                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
4649            } else {
4650                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4651                        "): normal window");
4652                // Otherwise, a normal window must be placed inside the content
4653                // of all screen decorations.
4654                if (attrs.type == TYPE_STATUS_BAR_PANEL || attrs.type == TYPE_VOLUME_OVERLAY) {
4655                    // Status bar panels and the volume dialog are the only windows who can go on
4656                    // top of the status bar.  They are protected by the STATUS_BAR_SERVICE
4657                    // permission, so they have the same privileges as the status
4658                    // bar itself.
4659                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4660                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4661                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4662                            + mRestrictedScreenWidth;
4663                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4664                            + mRestrictedScreenHeight;
4665                } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT) {
4666                    // These dialogs are stable to interim decor changes.
4667                    pf.left = df.left = of.left = cf.left = mStableLeft;
4668                    pf.top = df.top = of.top = cf.top = mStableTop;
4669                    pf.right = df.right = of.right = cf.right = mStableRight;
4670                    pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
4671                } else {
4672                    pf.left = mContentLeft;
4673                    pf.top = mContentTop;
4674                    pf.right = mContentRight;
4675                    pf.bottom = mContentBottom;
4676                    if (win.isVoiceInteraction()) {
4677                        df.left = of.left = cf.left = mVoiceContentLeft;
4678                        df.top = of.top = cf.top = mVoiceContentTop;
4679                        df.right = of.right = cf.right = mVoiceContentRight;
4680                        df.bottom = of.bottom = cf.bottom = mVoiceContentBottom;
4681                    } else if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4682                        df.left = of.left = cf.left = mDockLeft;
4683                        df.top = of.top = cf.top = mDockTop;
4684                        df.right = of.right = cf.right = mDockRight;
4685                        df.bottom = of.bottom = cf.bottom = mDockBottom;
4686                    } else {
4687                        df.left = of.left = cf.left = mContentLeft;
4688                        df.top = of.top = cf.top = mContentTop;
4689                        df.right = of.right = cf.right = mContentRight;
4690                        df.bottom = of.bottom = cf.bottom = mContentBottom;
4691                    }
4692                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4693                        vf.left = mCurLeft;
4694                        vf.top = mCurTop;
4695                        vf.right = mCurRight;
4696                        vf.bottom = mCurBottom;
4697                    } else {
4698                        vf.set(cf);
4699                    }
4700                }
4701            }
4702        }
4703
4704        // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
4705        // Also, we don't allow windows in multi-window mode to extend out of the screen.
4706        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR
4707                && !win.isInMultiWindowMode()) {
4708            df.left = df.top = -10000;
4709            df.right = df.bottom = 10000;
4710            if (attrs.type != TYPE_WALLPAPER) {
4711                of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
4712                of.right = of.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
4713            }
4714        }
4715
4716        // If the device has a chin (e.g. some watches), a dead area at the bottom of the screen we
4717        // need to provide information to the clients that want to pretend that you can draw there.
4718        // We only want to apply outsets to certain types of windows. For example, we never want to
4719        // apply the outsets to floating dialogs, because they wouldn't make sense there.
4720        final boolean useOutsets = shouldUseOutsets(attrs, fl);
4721        if (isDefaultDisplay && useOutsets) {
4722            osf = mTmpOutsetFrame;
4723            osf.set(cf.left, cf.top, cf.right, cf.bottom);
4724            int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
4725            if (outset > 0) {
4726                int rotation = mDisplayRotation;
4727                if (rotation == Surface.ROTATION_0) {
4728                    osf.bottom += outset;
4729                } else if (rotation == Surface.ROTATION_90) {
4730                    osf.right += outset;
4731                } else if (rotation == Surface.ROTATION_180) {
4732                    osf.top -= outset;
4733                } else if (rotation == Surface.ROTATION_270) {
4734                    osf.left -= outset;
4735                }
4736                if (DEBUG_LAYOUT) Slog.v(TAG, "applying bottom outset of " + outset
4737                        + " with rotation " + rotation + ", result: " + osf);
4738            }
4739        }
4740
4741        if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
4742                + ": sim=#" + Integer.toHexString(sim)
4743                + " attach=" + attached + " type=" + attrs.type
4744                + String.format(" flags=0x%08x", fl)
4745                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
4746                + " of=" + of.toShortString()
4747                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
4748                + " dcf=" + dcf.toShortString()
4749                + " sf=" + sf.toShortString()
4750                + " osf=" + (osf == null ? "null" : osf.toShortString()));
4751
4752        win.computeFrameLw(pf, df, of, cf, vf, dcf, sf, osf);
4753
4754        // Dock windows carve out the bottom of the screen, so normal windows
4755        // can't appear underneath them.
4756        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
4757                && !win.getGivenInsetsPendingLw()) {
4758            setLastInputMethodWindowLw(null, null);
4759            offsetInputMethodWindowLw(win);
4760        }
4761        if (attrs.type == TYPE_VOICE_INTERACTION && win.isVisibleOrBehindKeyguardLw()
4762                && !win.getGivenInsetsPendingLw()) {
4763            offsetVoiceInputWindowLw(win);
4764        }
4765    }
4766
4767    private void offsetInputMethodWindowLw(WindowState win) {
4768        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4769        top += win.getGivenContentInsetsLw().top;
4770        if (mContentBottom > top) {
4771            mContentBottom = top;
4772        }
4773        if (mVoiceContentBottom > top) {
4774            mVoiceContentBottom = top;
4775        }
4776        top = win.getVisibleFrameLw().top;
4777        top += win.getGivenVisibleInsetsLw().top;
4778        if (mCurBottom > top) {
4779            mCurBottom = top;
4780        }
4781        if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
4782                + mDockBottom + " mContentBottom="
4783                + mContentBottom + " mCurBottom=" + mCurBottom);
4784    }
4785
4786    private void offsetVoiceInputWindowLw(WindowState win) {
4787        int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
4788        top += win.getGivenContentInsetsLw().top;
4789        if (mVoiceContentBottom > top) {
4790            mVoiceContentBottom = top;
4791        }
4792    }
4793
4794    /** {@inheritDoc} */
4795    @Override
4796    public void finishLayoutLw() {
4797        return;
4798    }
4799
4800    /** {@inheritDoc} */
4801    @Override
4802    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
4803        mTopFullscreenOpaqueWindowState = null;
4804        mTopFullscreenOpaqueOrDimmingWindowState = null;
4805        mTopDockedOpaqueWindowState = null;
4806        mTopDockedOpaqueOrDimmingWindowState = null;
4807        mAppsToBeHidden.clear();
4808        mAppsThatDismissKeyguard.clear();
4809        mForceStatusBar = false;
4810        mForceStatusBarFromKeyguard = false;
4811        mForceStatusBarTransparent = false;
4812        mForcingShowNavBar = false;
4813        mForcingShowNavBarLayer = -1;
4814
4815        mHideLockScreen = false;
4816        mAllowLockscreenWhenOn = false;
4817        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
4818        mShowingLockscreen = false;
4819        mShowingDream = false;
4820        mWinShowWhenLocked = null;
4821        mKeyguardSecure = isKeyguardSecure();
4822        mKeyguardSecureIncludingHidden = mKeyguardSecure
4823                && (mKeyguardDelegate != null && mKeyguardDelegate.isShowing());
4824    }
4825
4826    /** {@inheritDoc} */
4827    @Override
4828    public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs,
4829            WindowState attached) {
4830        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
4831                + win.isVisibleOrBehindKeyguardLw());
4832        final int fl = PolicyControl.getWindowFlags(win, attrs);
4833        if (mTopFullscreenOpaqueWindowState == null
4834                && win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD) {
4835            mForcingShowNavBar = true;
4836            mForcingShowNavBarLayer = win.getSurfaceLayer();
4837        }
4838        if (attrs.type == TYPE_STATUS_BAR) {
4839            if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4840                mForceStatusBarFromKeyguard = true;
4841                mShowingLockscreen = true;
4842            }
4843            if ((attrs.privateFlags & PRIVATE_FLAG_FORCE_STATUS_BAR_VISIBLE_TRANSPARENT) != 0) {
4844                mForceStatusBarTransparent = true;
4845            }
4846        }
4847
4848        boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
4849                && attrs.type < FIRST_SYSTEM_WINDOW;
4850        final boolean showWhenLocked = (fl & FLAG_SHOW_WHEN_LOCKED) != 0;
4851        final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
4852        final int stackId = win.getStackId();
4853        if (mTopFullscreenOpaqueWindowState == null &&
4854                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
4855            if ((fl & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
4856                if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
4857                    mForceStatusBarFromKeyguard = true;
4858                } else {
4859                    mForceStatusBar = true;
4860                }
4861            }
4862            if (attrs.type == TYPE_DREAM) {
4863                // If the lockscreen was showing when the dream started then wait
4864                // for the dream to draw before hiding the lockscreen.
4865                if (!mDreamingLockscreen
4866                        || (win.isVisibleLw() && win.hasDrawnLw())) {
4867                    mShowingDream = true;
4868                    appWindow = true;
4869                }
4870            }
4871
4872            final IApplicationToken appToken = win.getAppToken();
4873
4874            // For app windows that are not attached, we decide if all windows in the app they
4875            // represent should be hidden or if we should hide the lockscreen. For attached app
4876            // windows we defer the decision to the window it is attached to.
4877            if (appWindow && attached == null) {
4878                if (showWhenLocked) {
4879                    // Remove any previous windows with the same appToken.
4880                    mAppsToBeHidden.remove(appToken);
4881                    mAppsThatDismissKeyguard.remove(appToken);
4882                    if (mAppsToBeHidden.isEmpty()) {
4883                        if (dismissKeyguard && !mKeyguardSecure) {
4884                            mAppsThatDismissKeyguard.add(appToken);
4885                        } else if (win.isDrawnLw() || win.hasAppShownWindows()) {
4886                            mWinShowWhenLocked = win;
4887                            mHideLockScreen = true;
4888                            mForceStatusBarFromKeyguard = false;
4889                        }
4890                    }
4891                } else if (dismissKeyguard) {
4892                    if (mKeyguardSecure) {
4893                        mAppsToBeHidden.add(appToken);
4894                    } else {
4895                        mAppsToBeHidden.remove(appToken);
4896                    }
4897                    mAppsThatDismissKeyguard.add(appToken);
4898                } else {
4899                    mAppsToBeHidden.add(appToken);
4900                }
4901                if (isFullscreen(attrs) && StackId.normallyFullscreenWindows(stackId)) {
4902                    if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
4903                    mTopFullscreenOpaqueWindowState = win;
4904                    if (mTopFullscreenOpaqueOrDimmingWindowState == null) {
4905                        mTopFullscreenOpaqueOrDimmingWindowState = win;
4906                    }
4907                    if (!mAppsThatDismissKeyguard.isEmpty() &&
4908                            mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
4909                        if (DEBUG_LAYOUT) Slog.v(TAG,
4910                                "Setting mDismissKeyguard true by win " + win);
4911                        mDismissKeyguard = (mWinDismissingKeyguard == win
4912                                && mSecureDismissingKeyguard == mKeyguardSecure)
4913                                ? DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
4914                        mWinDismissingKeyguard = win;
4915                        mSecureDismissingKeyguard = mKeyguardSecure;
4916                        mForceStatusBarFromKeyguard = mShowingLockscreen && mKeyguardSecure;
4917                    } else if (mAppsToBeHidden.isEmpty() && showWhenLocked
4918                            && (win.isDrawnLw() || win.hasAppShownWindows())) {
4919                        if (DEBUG_LAYOUT) Slog.v(TAG,
4920                                "Setting mHideLockScreen to true by win " + win);
4921                        mHideLockScreen = true;
4922                        mForceStatusBarFromKeyguard = false;
4923                    }
4924                    if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
4925                        mAllowLockscreenWhenOn = true;
4926                    }
4927                }
4928
4929                if (mWinShowWhenLocked != null &&
4930                        mWinShowWhenLocked.getAppToken() != win.getAppToken() &&
4931                        (attrs.flags & FLAG_SHOW_WHEN_LOCKED) == 0) {
4932                    win.hideLw(false);
4933                }
4934            }
4935        } else if (mTopFullscreenOpaqueWindowState == null && mWinShowWhenLocked == null) {
4936            // No TopFullscreenOpaqueWindow is showing, but we found a SHOW_WHEN_LOCKED window
4937            // that is being hidden in an animation - keep the
4938            // keyguard hidden until the new window shows up and
4939            // we know whether to show the keyguard or not.
4940            if (win.isAnimatingLw() && appWindow && showWhenLocked && mKeyguardHidden) {
4941                mHideLockScreen = true;
4942                mWinShowWhenLocked = win;
4943            }
4944        }
4945
4946        // Keep track of the window if it's dimming but not necessarily fullscreen.
4947        final boolean reallyVisible = win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw();
4948        if (mTopFullscreenOpaqueOrDimmingWindowState == null &&  reallyVisible
4949                && win.isDimming() && StackId.normallyFullscreenWindows(stackId)) {
4950            mTopFullscreenOpaqueOrDimmingWindowState = win;
4951        }
4952
4953        // We need to keep track of the top "fullscreen" opaque window for the docked stack
4954        // separately, because both the "real fullscreen" opaque window and the one for the docked
4955        // stack can control View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.
4956        if (mTopDockedOpaqueWindowState == null && reallyVisible && appWindow && attached == null
4957                && isFullscreen(attrs) && stackId == DOCKED_STACK_ID) {
4958            mTopDockedOpaqueWindowState = win;
4959            if (mTopDockedOpaqueOrDimmingWindowState == null) {
4960                mTopDockedOpaqueOrDimmingWindowState = win;
4961            }
4962        }
4963
4964        // Also keep track of any windows that are dimming but not necessarily fullscreen in the
4965        // docked stack.
4966        if (mTopDockedOpaqueOrDimmingWindowState == null && reallyVisible && win.isDimming()
4967                && stackId == DOCKED_STACK_ID) {
4968            mTopDockedOpaqueOrDimmingWindowState = win;
4969        }
4970    }
4971
4972    private boolean isFullscreen(WindowManager.LayoutParams attrs) {
4973        return attrs.x == 0 && attrs.y == 0
4974                && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
4975                && attrs.height == WindowManager.LayoutParams.MATCH_PARENT;
4976    }
4977
4978    /** {@inheritDoc} */
4979    @Override
4980    public int finishPostLayoutPolicyLw() {
4981        if (mWinShowWhenLocked != null && mTopFullscreenOpaqueWindowState != null &&
4982                mWinShowWhenLocked.getAppToken() != mTopFullscreenOpaqueWindowState.getAppToken()
4983                && isKeyguardLocked()) {
4984            // A dialog is dismissing the keyguard. Put the wallpaper behind it and hide the
4985            // fullscreen window.
4986            // TODO: Make sure FLAG_SHOW_WALLPAPER is restored when dialog is dismissed. Or not.
4987            mWinShowWhenLocked.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
4988            mTopFullscreenOpaqueWindowState.hideLw(false);
4989            mTopFullscreenOpaqueWindowState = mWinShowWhenLocked;
4990        }
4991
4992        int changes = 0;
4993        boolean topIsFullscreen = false;
4994
4995        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
4996                ? mTopFullscreenOpaqueWindowState.getAttrs()
4997                : null;
4998
4999        // If we are not currently showing a dream then remember the current
5000        // lockscreen state.  We will use this to determine whether the dream
5001        // started while the lockscreen was showing and remember this state
5002        // while the dream is showing.
5003        if (!mShowingDream) {
5004            mDreamingLockscreen = mShowingLockscreen;
5005            if (mDreamingSleepTokenNeeded) {
5006                mDreamingSleepTokenNeeded = false;
5007                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 0, 1).sendToTarget();
5008            }
5009        } else {
5010            if (!mDreamingSleepTokenNeeded) {
5011                mDreamingSleepTokenNeeded = true;
5012                mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 1, 1).sendToTarget();
5013            }
5014        }
5015
5016        if (mStatusBar != null) {
5017            if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
5018                    + " forcefkg=" + mForceStatusBarFromKeyguard
5019                    + " top=" + mTopFullscreenOpaqueWindowState);
5020            boolean shouldBeTransparent = mForceStatusBarTransparent
5021                    && !mForceStatusBar
5022                    && !mForceStatusBarFromKeyguard;
5023            if (!shouldBeTransparent) {
5024                mStatusBarController.setShowTransparent(false /* transparent */);
5025            } else if (!mStatusBar.isVisibleLw()) {
5026                mStatusBarController.setShowTransparent(true /* transparent */);
5027            }
5028            if (mForceStatusBar || mForceStatusBarFromKeyguard || mForceStatusBarTransparent) {
5029                if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
5030                if (mStatusBarController.setBarShowingLw(true)) {
5031                    changes |= FINISH_LAYOUT_REDO_LAYOUT;
5032                }
5033                // Maintain fullscreen layout until incoming animation is complete.
5034                topIsFullscreen = mTopIsFullscreen && mStatusBar.isAnimatingLw();
5035                // Transient status bar on the lockscreen is not allowed
5036                if (mForceStatusBarFromKeyguard && mStatusBarController.isTransientShowing()) {
5037                    mStatusBarController.updateVisibilityLw(false /*transientAllowed*/,
5038                            mLastSystemUiFlags, mLastSystemUiFlags);
5039                }
5040            } else if (mTopFullscreenOpaqueWindowState != null) {
5041                final int fl = PolicyControl.getWindowFlags(null, lp);
5042                if (localLOGV) {
5043                    Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
5044                            + " shown position: "
5045                            + mTopFullscreenOpaqueWindowState.getShownPositionLw());
5046                    Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
5047                            + " lp.flags=0x" + Integer.toHexString(fl));
5048                }
5049                topIsFullscreen = (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
5050                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
5051                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
5052                // and mTopIsFullscreen is that mTopIsFullscreen is set only if the window
5053                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
5054                // case though.
5055                if (mStatusBarController.isTransientShowing()) {
5056                    if (mStatusBarController.setBarShowingLw(true)) {
5057                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
5058                    }
5059                } else if (topIsFullscreen
5060                        && !mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID)
5061                        && !mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID)) {
5062                    if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
5063                    if (mStatusBarController.setBarShowingLw(false)) {
5064                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
5065                    } else {
5066                        if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
5067                    }
5068                } else {
5069                    if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
5070                    if (mStatusBarController.setBarShowingLw(true)) {
5071                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
5072                    }
5073                }
5074            }
5075        }
5076
5077        if (mTopIsFullscreen != topIsFullscreen) {
5078            if (!topIsFullscreen) {
5079                // Force another layout when status bar becomes fully shown.
5080                changes |= FINISH_LAYOUT_REDO_LAYOUT;
5081            }
5082            mTopIsFullscreen = topIsFullscreen;
5083        }
5084
5085        // Hide the key guard if a visible window explicitly specifies that it wants to be
5086        // displayed when the screen is locked.
5087        if (mKeyguardDelegate != null && mStatusBar != null) {
5088            if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
5089                    + mHideLockScreen);
5090            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardSecure) {
5091                mKeyguardHidden = true;
5092                if (setKeyguardOccludedLw(true)) {
5093                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5094                            | FINISH_LAYOUT_REDO_CONFIG
5095                            | FINISH_LAYOUT_REDO_WALLPAPER;
5096                }
5097                if (mKeyguardDelegate.isShowing()) {
5098                    mHandler.post(new Runnable() {
5099                        @Override
5100                        public void run() {
5101                            mKeyguardDelegate.keyguardDone(false, false);
5102                        }
5103                    });
5104                }
5105            } else if (mHideLockScreen) {
5106                mKeyguardHidden = true;
5107                mWinDismissingKeyguard = null;
5108                if (setKeyguardOccludedLw(true)) {
5109                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5110                            | FINISH_LAYOUT_REDO_CONFIG
5111                            | FINISH_LAYOUT_REDO_WALLPAPER;
5112                }
5113            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
5114                mKeyguardHidden = false;
5115                if (setKeyguardOccludedLw(false)) {
5116                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5117                            | FINISH_LAYOUT_REDO_CONFIG
5118                            | FINISH_LAYOUT_REDO_WALLPAPER;
5119                }
5120                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
5121                    // Only launch the next keyguard unlock window once per window.
5122                    mHandler.post(new Runnable() {
5123                        @Override
5124                        public void run() {
5125                            mKeyguardDelegate.dismiss();
5126                        }
5127                    });
5128                }
5129            } else {
5130                mWinDismissingKeyguard = null;
5131                mSecureDismissingKeyguard = false;
5132                mKeyguardHidden = false;
5133                if (setKeyguardOccludedLw(false)) {
5134                    changes |= FINISH_LAYOUT_REDO_LAYOUT
5135                            | FINISH_LAYOUT_REDO_CONFIG
5136                            | FINISH_LAYOUT_REDO_WALLPAPER;
5137                }
5138            }
5139        }
5140
5141        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
5142            // If the navigation bar has been hidden or shown, we need to do another
5143            // layout pass to update that window.
5144            changes |= FINISH_LAYOUT_REDO_LAYOUT;
5145        }
5146
5147        // update since mAllowLockscreenWhenOn might have changed
5148        updateLockScreenTimeout();
5149        return changes;
5150    }
5151
5152    /**
5153     * Updates the occluded state of the Keyguard.
5154     *
5155     * @return Whether the flags have changed and we have to redo the layout.
5156     */
5157    private boolean setKeyguardOccludedLw(boolean isOccluded) {
5158        boolean wasOccluded = mKeyguardOccluded;
5159        boolean showing = mKeyguardDelegate.isShowing();
5160        if (wasOccluded && !isOccluded && showing) {
5161            mKeyguardOccluded = false;
5162            mKeyguardDelegate.setOccluded(false);
5163            mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
5164            mStatusBar.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
5165            return true;
5166        } else if (!wasOccluded && isOccluded && showing) {
5167            mKeyguardOccluded = true;
5168            mKeyguardDelegate.setOccluded(true);
5169            mStatusBar.getAttrs().privateFlags &= ~PRIVATE_FLAG_KEYGUARD;
5170            mStatusBar.getAttrs().flags &= ~FLAG_SHOW_WALLPAPER;
5171            return true;
5172        } else {
5173            return false;
5174        }
5175    }
5176
5177    private boolean isStatusBarKeyguard() {
5178        return mStatusBar != null
5179                && (mStatusBar.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
5180    }
5181
5182    @Override
5183    public boolean allowAppAnimationsLw() {
5184        if (isStatusBarKeyguard() || mShowingDream) {
5185            // If keyguard or dreams is currently visible, no reason to animate behind it.
5186            return false;
5187        }
5188        return true;
5189    }
5190
5191    @Override
5192    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
5193        mFocusedWindow = newFocus;
5194        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
5195            // If the navigation bar has been hidden or shown, we need to do another
5196            // layout pass to update that window.
5197            return FINISH_LAYOUT_REDO_LAYOUT;
5198        }
5199        return 0;
5200    }
5201
5202    /** {@inheritDoc} */
5203    @Override
5204    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
5205        // lid changed state
5206        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
5207        if (newLidState == mLidState) {
5208            return;
5209        }
5210
5211        mLidState = newLidState;
5212        applyLidSwitchState();
5213        updateRotation(true);
5214
5215        if (lidOpen) {
5216            wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromLidSwitch,
5217                    "android.policy:LID");
5218        } else if (!mLidControlsSleep) {
5219            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5220        }
5221    }
5222
5223    @Override
5224    public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered) {
5225        int lensCoverState = lensCovered ? CAMERA_LENS_COVERED : CAMERA_LENS_UNCOVERED;
5226        if (mCameraLensCoverState == lensCoverState) {
5227            return;
5228        }
5229        if (mCameraLensCoverState == CAMERA_LENS_COVERED &&
5230                lensCoverState == CAMERA_LENS_UNCOVERED) {
5231            Intent intent;
5232            final boolean keyguardActive = mKeyguardDelegate == null ? false :
5233                    mKeyguardDelegate.isShowing();
5234            if (keyguardActive) {
5235                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
5236            } else {
5237                intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
5238            }
5239            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromCameraLens,
5240                    "android.policy:CAMERA_COVER");
5241            startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
5242        }
5243        mCameraLensCoverState = lensCoverState;
5244    }
5245
5246    void setHdmiPlugged(boolean plugged) {
5247        if (mHdmiPlugged != plugged) {
5248            mHdmiPlugged = plugged;
5249            updateRotation(true, true);
5250            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
5251            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5252            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
5253            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
5254        }
5255    }
5256
5257    void initializeHdmiState() {
5258        boolean plugged = false;
5259        // watch for HDMI plug messages if the hdmi switch exists
5260        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
5261            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
5262
5263            final String filename = "/sys/class/switch/hdmi/state";
5264            FileReader reader = null;
5265            try {
5266                reader = new FileReader(filename);
5267                char[] buf = new char[15];
5268                int n = reader.read(buf);
5269                if (n > 1) {
5270                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
5271                }
5272            } catch (IOException ex) {
5273                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
5274            } catch (NumberFormatException ex) {
5275                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
5276            } finally {
5277                if (reader != null) {
5278                    try {
5279                        reader.close();
5280                    } catch (IOException ex) {
5281                    }
5282                }
5283            }
5284        }
5285        // This dance forces the code in setHdmiPlugged to run.
5286        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
5287        mHdmiPlugged = !plugged;
5288        setHdmiPlugged(!mHdmiPlugged);
5289    }
5290
5291    final Object mScreenshotLock = new Object();
5292    ServiceConnection mScreenshotConnection = null;
5293
5294    final Runnable mScreenshotTimeout = new Runnable() {
5295        @Override public void run() {
5296            synchronized (mScreenshotLock) {
5297                if (mScreenshotConnection != null) {
5298                    mContext.unbindService(mScreenshotConnection);
5299                    mScreenshotConnection = null;
5300                    notifyScreenshotError();
5301                }
5302            }
5303        }
5304    };
5305
5306    // Assume this is called from the Handler thread.
5307    private void takeScreenshot(final int screenshotType) {
5308        synchronized (mScreenshotLock) {
5309            if (mScreenshotConnection != null) {
5310                return;
5311            }
5312            final ComponentName serviceComponent = new ComponentName(SYSUI_PACKAGE,
5313                    SYSUI_SCREENSHOT_SERVICE);
5314            final Intent serviceIntent = new Intent();
5315            serviceIntent.setComponent(serviceComponent);
5316            ServiceConnection conn = new ServiceConnection() {
5317                @Override
5318                public void onServiceConnected(ComponentName name, IBinder service) {
5319                    synchronized (mScreenshotLock) {
5320                        if (mScreenshotConnection != this) {
5321                            return;
5322                        }
5323                        Messenger messenger = new Messenger(service);
5324                        Message msg = Message.obtain(null, screenshotType);
5325                        final ServiceConnection myConn = this;
5326                        Handler h = new Handler(mHandler.getLooper()) {
5327                            @Override
5328                            public void handleMessage(Message msg) {
5329                                synchronized (mScreenshotLock) {
5330                                    if (mScreenshotConnection == myConn) {
5331                                        mContext.unbindService(mScreenshotConnection);
5332                                        mScreenshotConnection = null;
5333                                        mHandler.removeCallbacks(mScreenshotTimeout);
5334                                    }
5335                                }
5336                            }
5337                        };
5338                        msg.replyTo = new Messenger(h);
5339                        msg.arg1 = msg.arg2 = 0;
5340                        if (mStatusBar != null && mStatusBar.isVisibleLw())
5341                            msg.arg1 = 1;
5342                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
5343                            msg.arg2 = 1;
5344                        try {
5345                            messenger.send(msg);
5346                        } catch (RemoteException e) {
5347                        }
5348                    }
5349                }
5350
5351                @Override
5352                public void onServiceDisconnected(ComponentName name) {
5353                    notifyScreenshotError();
5354                }
5355            };
5356            if (mContext.bindServiceAsUser(serviceIntent, conn,
5357                    Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE,
5358                    UserHandle.CURRENT)) {
5359                mScreenshotConnection = conn;
5360                mHandler.postDelayed(mScreenshotTimeout, 10000);
5361            }
5362        }
5363    }
5364
5365    /**
5366     * Notifies the screenshot service to show an error.
5367     */
5368    private void notifyScreenshotError() {
5369        // If the service process is killed, then ask it to clean up after itself
5370        final ComponentName errorComponent = new ComponentName(SYSUI_PACKAGE,
5371                SYSUI_SCREENSHOT_ERROR_RECEIVER);
5372        Intent errorIntent = new Intent();
5373        errorIntent.setComponent(errorComponent);
5374        errorIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
5375                Intent.FLAG_RECEIVER_FOREGROUND);
5376        mContext.sendBroadcastAsUser(errorIntent, UserHandle.ALL);
5377    }
5378
5379    /** {@inheritDoc} */
5380    @Override
5381    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
5382        if (!mSystemBooted) {
5383            // If we have not yet booted, don't let key events do anything.
5384            return 0;
5385        }
5386
5387        final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;
5388        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
5389        final boolean canceled = event.isCanceled();
5390        final int keyCode = event.getKeyCode();
5391
5392        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
5393
5394        // If screen is off then we treat the case where the keyguard is open but hidden
5395        // the same as if it were open and in front.
5396        // This will prevent any keys other than the power button from waking the screen
5397        // when the keyguard is hidden by another activity.
5398        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
5399                                            (interactive ?
5400                                                isKeyguardShowingAndNotOccluded() :
5401                                                mKeyguardDelegate.isShowing()));
5402
5403        if (DEBUG_INPUT) {
5404            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
5405                    + " interactive=" + interactive + " keyguardActive=" + keyguardActive
5406                    + " policyFlags=" + Integer.toHexString(policyFlags));
5407        }
5408
5409        // Basic policy based on interactive state.
5410        int result;
5411        boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
5412                || event.isWakeKey();
5413        if (interactive || (isInjected && !isWakeKey)) {
5414            // When the device is interactive or the key is injected pass the
5415            // key to the application.
5416            result = ACTION_PASS_TO_USER;
5417            isWakeKey = false;
5418        } else if (!interactive && shouldDispatchInputWhenNonInteractive()) {
5419            // If we're currently dozing with the screen on and the keyguard showing, pass the key
5420            // to the application but preserve its wake key status to make sure we still move
5421            // from dozing to fully interactive if we would normally go from off to fully
5422            // interactive.
5423            result = ACTION_PASS_TO_USER;
5424        } else {
5425            // When the screen is off and the key is not injected, determine whether
5426            // to wake the device but don't pass the key to the application.
5427            result = 0;
5428            if (isWakeKey && (!down || !isWakeKeyWhenScreenOff(keyCode))) {
5429                isWakeKey = false;
5430            }
5431        }
5432
5433        // If the key would be handled globally, just return the result, don't worry about special
5434        // key processing.
5435        if (isValidGlobalKey(keyCode)
5436                && mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
5437            if (isWakeKey) {
5438                wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5439            }
5440            return result;
5441        }
5442
5443        boolean useHapticFeedback = down
5444                && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
5445                && event.getRepeatCount() == 0;
5446
5447        // Handle special keys.
5448        switch (keyCode) {
5449            case KeyEvent.KEYCODE_BACK: {
5450                if (down) {
5451                    mBackKeyHandled = false;
5452                    if (hasLongPressOnBackBehavior()) {
5453                        Message msg = mHandler.obtainMessage(MSG_BACK_LONG_PRESS);
5454                        msg.setAsynchronous(true);
5455                        mHandler.sendMessageDelayed(msg,
5456                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5457                    }
5458                } else {
5459                    boolean handled = mBackKeyHandled;
5460
5461                    // Reset back key state
5462                    cancelPendingBackKeyAction();
5463
5464                    // Don't pass back press to app if we've already handled it
5465                    if (handled) {
5466                        result &= ~ACTION_PASS_TO_USER;
5467                    }
5468                }
5469                break;
5470            }
5471
5472            case KeyEvent.KEYCODE_VOLUME_DOWN:
5473            case KeyEvent.KEYCODE_VOLUME_UP:
5474            case KeyEvent.KEYCODE_VOLUME_MUTE: {
5475                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
5476                    if (down) {
5477                        if (interactive && !mScreenshotChordVolumeDownKeyTriggered
5478                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5479                            mScreenshotChordVolumeDownKeyTriggered = true;
5480                            mScreenshotChordVolumeDownKeyTime = event.getDownTime();
5481                            mScreenshotChordVolumeDownKeyConsumed = false;
5482                            cancelPendingPowerKeyAction();
5483                            interceptScreenshotChord();
5484                        }
5485                    } else {
5486                        mScreenshotChordVolumeDownKeyTriggered = false;
5487                        cancelPendingScreenshotChordAction();
5488                    }
5489                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
5490                    if (down) {
5491                        if (interactive && !mScreenshotChordVolumeUpKeyTriggered
5492                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5493                            mScreenshotChordVolumeUpKeyTriggered = true;
5494                            cancelPendingPowerKeyAction();
5495                            cancelPendingScreenshotChordAction();
5496                        }
5497                    } else {
5498                        mScreenshotChordVolumeUpKeyTriggered = false;
5499                        cancelPendingScreenshotChordAction();
5500                    }
5501                }
5502                if (down) {
5503                    TelecomManager telecomManager = getTelecommService();
5504                    if (telecomManager != null) {
5505                        if (telecomManager.isRinging()) {
5506                            // If an incoming call is ringing, either VOLUME key means
5507                            // "silence ringer".  We handle these keys here, rather than
5508                            // in the InCallScreen, to make sure we'll respond to them
5509                            // even if the InCallScreen hasn't come to the foreground yet.
5510                            // Look for the DOWN event here, to agree with the "fallback"
5511                            // behavior in the InCallScreen.
5512                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5513                                  + " VOLUME key-down while ringing: Silence ringer!");
5514
5515                            // Silence the ringer.  (It's safe to call this
5516                            // even if the ringer has already been silenced.)
5517                            telecomManager.silenceRinger();
5518
5519                            // And *don't* pass this key thru to the current activity
5520                            // (which is probably the InCallScreen.)
5521                            result &= ~ACTION_PASS_TO_USER;
5522                            break;
5523                        }
5524                        if (telecomManager.isInCall()
5525                                && (result & ACTION_PASS_TO_USER) == 0) {
5526                            // If we are in call but we decided not to pass the key to
5527                            // the application, just pass it to the session service.
5528
5529                            MediaSessionLegacyHelper.getHelper(mContext)
5530                                    .sendVolumeKeyEvent(event, false);
5531                            break;
5532                        }
5533                    }
5534                }
5535                if (mUseTvRouting) {
5536                    // On TVs, defer special key handlings to
5537                    // {@link interceptKeyBeforeDispatching()}.
5538                    result |= ACTION_PASS_TO_USER;
5539                } else if ((result & ACTION_PASS_TO_USER) == 0) {
5540                    // If we aren't passing to the user and no one else
5541                    // handled it send it to the session manager to
5542                    // figure out.
5543                    MediaSessionLegacyHelper.getHelper(mContext)
5544                            .sendVolumeKeyEvent(event, true);
5545                }
5546                break;
5547            }
5548
5549            case KeyEvent.KEYCODE_ENDCALL: {
5550                result &= ~ACTION_PASS_TO_USER;
5551                if (down) {
5552                    TelecomManager telecomManager = getTelecommService();
5553                    boolean hungUp = false;
5554                    if (telecomManager != null) {
5555                        hungUp = telecomManager.endCall();
5556                    }
5557                    if (interactive && !hungUp) {
5558                        mEndCallKeyHandled = false;
5559                        mHandler.postDelayed(mEndCallLongPress,
5560                                ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5561                    } else {
5562                        mEndCallKeyHandled = true;
5563                    }
5564                } else {
5565                    if (!mEndCallKeyHandled) {
5566                        mHandler.removeCallbacks(mEndCallLongPress);
5567                        if (!canceled) {
5568                            if ((mEndcallBehavior
5569                                    & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
5570                                if (goHome()) {
5571                                    break;
5572                                }
5573                            }
5574                            if ((mEndcallBehavior
5575                                    & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
5576                                mPowerManager.goToSleep(event.getEventTime(),
5577                                        PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
5578                                isWakeKey = false;
5579                            }
5580                        }
5581                    }
5582                }
5583                break;
5584            }
5585
5586            case KeyEvent.KEYCODE_POWER: {
5587                result &= ~ACTION_PASS_TO_USER;
5588                isWakeKey = false; // wake-up will be handled separately
5589                if (down) {
5590                    interceptPowerKeyDown(event, interactive);
5591                } else {
5592                    interceptPowerKeyUp(event, interactive, canceled);
5593                }
5594                break;
5595            }
5596
5597            case KeyEvent.KEYCODE_SLEEP: {
5598                result &= ~ACTION_PASS_TO_USER;
5599                isWakeKey = false;
5600                if (!mPowerManager.isInteractive()) {
5601                    useHapticFeedback = false; // suppress feedback if already non-interactive
5602                }
5603                if (down) {
5604                    sleepPress(event.getEventTime());
5605                } else {
5606                    sleepRelease(event.getEventTime());
5607                }
5608                break;
5609            }
5610
5611            case KeyEvent.KEYCODE_SOFT_SLEEP: {
5612                result &= ~ACTION_PASS_TO_USER;
5613                isWakeKey = false;
5614                if (!down) {
5615                    mPowerManagerInternal.setUserInactiveOverrideFromWindowManager();
5616                }
5617                break;
5618            }
5619
5620            case KeyEvent.KEYCODE_WAKEUP: {
5621                result &= ~ACTION_PASS_TO_USER;
5622                isWakeKey = true;
5623                break;
5624            }
5625
5626            case KeyEvent.KEYCODE_MEDIA_PLAY:
5627            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5628            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5629            case KeyEvent.KEYCODE_HEADSETHOOK:
5630            case KeyEvent.KEYCODE_MUTE:
5631            case KeyEvent.KEYCODE_MEDIA_STOP:
5632            case KeyEvent.KEYCODE_MEDIA_NEXT:
5633            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5634            case KeyEvent.KEYCODE_MEDIA_REWIND:
5635            case KeyEvent.KEYCODE_MEDIA_RECORD:
5636            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5637            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
5638                if (MediaSessionLegacyHelper.getHelper(mContext).isGlobalPriorityActive()) {
5639                    // If the global session is active pass all media keys to it
5640                    // instead of the active window.
5641                    result &= ~ACTION_PASS_TO_USER;
5642                }
5643                if ((result & ACTION_PASS_TO_USER) == 0) {
5644                    // Only do this if we would otherwise not pass it to the user. In that
5645                    // case, the PhoneWindow class will do the same thing, except it will
5646                    // only do it if the showing app doesn't process the key on its own.
5647                    // Note that we need to make a copy of the key event here because the
5648                    // original key event will be recycled when we return.
5649                    mBroadcastWakeLock.acquire();
5650                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
5651                            new KeyEvent(event));
5652                    msg.setAsynchronous(true);
5653                    msg.sendToTarget();
5654                }
5655                break;
5656            }
5657
5658            case KeyEvent.KEYCODE_CALL: {
5659                if (down) {
5660                    TelecomManager telecomManager = getTelecommService();
5661                    if (telecomManager != null) {
5662                        if (telecomManager.isRinging()) {
5663                            Log.i(TAG, "interceptKeyBeforeQueueing:"
5664                                  + " CALL key-down while ringing: Answer the call!");
5665                            telecomManager.acceptRingingCall();
5666
5667                            // And *don't* pass this key thru to the current activity
5668                            // (which is presumably the InCallScreen.)
5669                            result &= ~ACTION_PASS_TO_USER;
5670                        }
5671                    }
5672                }
5673                break;
5674            }
5675            case KeyEvent.KEYCODE_VOICE_ASSIST: {
5676                // Only do this if we would otherwise not pass it to the user. In that case,
5677                // interceptKeyBeforeDispatching would apply a similar but different policy in
5678                // order to invoke voice assist actions. Note that we need to make a copy of the
5679                // key event here because the original key event will be recycled when we return.
5680                if ((result & ACTION_PASS_TO_USER) == 0 && !down) {
5681                    mBroadcastWakeLock.acquire();
5682                    Message msg = mHandler.obtainMessage(MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK,
5683                            keyguardActive ? 1 : 0, 0);
5684                    msg.setAsynchronous(true);
5685                    msg.sendToTarget();
5686                }
5687                break;
5688            }
5689            case KeyEvent.KEYCODE_WINDOW: {
5690                if (mShortPressWindowBehavior == SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE) {
5691                    if (!down) {
5692                        requestTvPictureInPicture(event);
5693                    }
5694                    result &= ~ACTION_PASS_TO_USER;
5695                }
5696                break;
5697            }
5698        }
5699
5700        if (useHapticFeedback) {
5701            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
5702        }
5703
5704        if (isWakeKey) {
5705            wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5706        }
5707
5708        return result;
5709    }
5710
5711    /**
5712     * Returns true if the key can have global actions attached to it.
5713     * We reserve all power management keys for the system since they require
5714     * very careful handling.
5715     */
5716    private static boolean isValidGlobalKey(int keyCode) {
5717        switch (keyCode) {
5718            case KeyEvent.KEYCODE_POWER:
5719            case KeyEvent.KEYCODE_WAKEUP:
5720            case KeyEvent.KEYCODE_SLEEP:
5721                return false;
5722            default:
5723                return true;
5724        }
5725    }
5726
5727    /**
5728     * When the screen is off we ignore some keys that might otherwise typically
5729     * be considered wake keys.  We filter them out here.
5730     *
5731     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
5732     * is always considered a wake key.
5733     */
5734    private boolean isWakeKeyWhenScreenOff(int keyCode) {
5735        switch (keyCode) {
5736            // ignore volume keys unless docked
5737            case KeyEvent.KEYCODE_VOLUME_UP:
5738            case KeyEvent.KEYCODE_VOLUME_DOWN:
5739            case KeyEvent.KEYCODE_VOLUME_MUTE:
5740                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
5741
5742            // ignore media and camera keys
5743            case KeyEvent.KEYCODE_MUTE:
5744            case KeyEvent.KEYCODE_HEADSETHOOK:
5745            case KeyEvent.KEYCODE_MEDIA_PLAY:
5746            case KeyEvent.KEYCODE_MEDIA_PAUSE:
5747            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5748            case KeyEvent.KEYCODE_MEDIA_STOP:
5749            case KeyEvent.KEYCODE_MEDIA_NEXT:
5750            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5751            case KeyEvent.KEYCODE_MEDIA_REWIND:
5752            case KeyEvent.KEYCODE_MEDIA_RECORD:
5753            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5754            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
5755            case KeyEvent.KEYCODE_CAMERA:
5756                return false;
5757        }
5758        return true;
5759    }
5760
5761
5762    /** {@inheritDoc} */
5763    @Override
5764    public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
5765        if ((policyFlags & FLAG_WAKE) != 0) {
5766            if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion,
5767                    "android.policy:MOTION")) {
5768                return 0;
5769            }
5770        }
5771
5772        if (shouldDispatchInputWhenNonInteractive()) {
5773            return ACTION_PASS_TO_USER;
5774        }
5775
5776        // If we have not passed the action up and we are in theater mode without dreaming,
5777        // there will be no dream to intercept the touch and wake into ambient.  The device should
5778        // wake up in this case.
5779        if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
5780            wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotionWhenNotDreaming,
5781                    "android.policy:MOTION");
5782        }
5783
5784        return 0;
5785    }
5786
5787    private boolean shouldDispatchInputWhenNonInteractive() {
5788        final boolean displayOff = (mDisplay == null || mDisplay.getState() == Display.STATE_OFF);
5789
5790        if (displayOff && !mHasFeatureWatch) {
5791            return false;
5792        }
5793
5794        // Send events to keyguard while the screen is on and it's showing.
5795        if (isKeyguardShowingAndNotOccluded() && !displayOff) {
5796            return true;
5797        }
5798
5799        // Send events to a dozing dream even if the screen is off since the dream
5800        // is in control of the state of the screen.
5801        IDreamManager dreamManager = getDreamManager();
5802
5803        try {
5804            if (dreamManager != null && dreamManager.isDreaming()) {
5805                return true;
5806            }
5807        } catch (RemoteException e) {
5808            Slog.e(TAG, "RemoteException when checking if dreaming", e);
5809        }
5810
5811        // Otherwise, consume events since the user can't see what is being
5812        // interacted with.
5813        return false;
5814    }
5815
5816    private void dispatchDirectAudioEvent(KeyEvent event) {
5817        if (event.getAction() != KeyEvent.ACTION_DOWN) {
5818            return;
5819        }
5820        int keyCode = event.getKeyCode();
5821        int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
5822                | AudioManager.FLAG_FROM_KEY;
5823        String pkgName = mContext.getOpPackageName();
5824        switch (keyCode) {
5825            case KeyEvent.KEYCODE_VOLUME_UP:
5826                try {
5827                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
5828                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5829                } catch (RemoteException e) {
5830                    Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
5831                }
5832                break;
5833            case KeyEvent.KEYCODE_VOLUME_DOWN:
5834                try {
5835                    getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
5836                            AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5837                } catch (RemoteException e) {
5838                    Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
5839                }
5840                break;
5841            case KeyEvent.KEYCODE_VOLUME_MUTE:
5842                try {
5843                    if (event.getRepeatCount() == 0) {
5844                        getAudioService().adjustSuggestedStreamVolume(
5845                                AudioManager.ADJUST_TOGGLE_MUTE,
5846                                AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
5847                    }
5848                } catch (RemoteException e) {
5849                    Log.e(TAG, "Error dispatching mute in dispatchTvAudioEvent.", e);
5850                }
5851                break;
5852        }
5853    }
5854
5855    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
5856        if (DEBUG_INPUT) {
5857            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
5858        }
5859
5860        if (mHavePendingMediaKeyRepeatWithWakeLock) {
5861            if (DEBUG_INPUT) {
5862                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
5863            }
5864
5865            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
5866            mHavePendingMediaKeyRepeatWithWakeLock = false;
5867            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
5868        }
5869
5870        dispatchMediaKeyWithWakeLockToAudioService(event);
5871
5872        if (event.getAction() == KeyEvent.ACTION_DOWN
5873                && event.getRepeatCount() == 0) {
5874            mHavePendingMediaKeyRepeatWithWakeLock = true;
5875
5876            Message msg = mHandler.obtainMessage(
5877                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
5878            msg.setAsynchronous(true);
5879            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
5880        } else {
5881            mBroadcastWakeLock.release();
5882        }
5883    }
5884
5885    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
5886        mHavePendingMediaKeyRepeatWithWakeLock = false;
5887
5888        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
5889                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
5890        if (DEBUG_INPUT) {
5891            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
5892        }
5893
5894        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
5895        mBroadcastWakeLock.release();
5896    }
5897
5898    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
5899        if (ActivityManagerNative.isSystemReady()) {
5900            MediaSessionLegacyHelper.getHelper(mContext).sendMediaButtonEvent(event, true);
5901        }
5902    }
5903
5904    void launchVoiceAssistWithWakeLock(boolean keyguardActive) {
5905        IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
5906                ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
5907        if (dic != null) {
5908            try {
5909                dic.exitIdle("voice-search");
5910            } catch (RemoteException e) {
5911            }
5912        }
5913        Intent voiceIntent =
5914            new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
5915        voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, keyguardActive);
5916        startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
5917        mBroadcastWakeLock.release();
5918    }
5919
5920    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
5921        @Override
5922        public void onReceive(Context context, Intent intent) {
5923            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
5924                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
5925                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
5926            } else {
5927                try {
5928                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
5929                            ServiceManager.getService(Context.UI_MODE_SERVICE));
5930                    mUiMode = uiModeService.getCurrentModeType();
5931                } catch (RemoteException e) {
5932                }
5933            }
5934            updateRotation(true);
5935            synchronized (mLock) {
5936                updateOrientationListenerLp();
5937            }
5938        }
5939    };
5940
5941    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
5942        @Override
5943        public void onReceive(Context context, Intent intent) {
5944            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
5945                if (mKeyguardDelegate != null) {
5946                    mKeyguardDelegate.onDreamingStarted();
5947                }
5948            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
5949                if (mKeyguardDelegate != null) {
5950                    mKeyguardDelegate.onDreamingStopped();
5951                }
5952            }
5953        }
5954    };
5955
5956    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
5957        @Override
5958        public void onReceive(Context context, Intent intent) {
5959            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
5960                // tickle the settings observer: this first ensures that we're
5961                // observing the relevant settings for the newly-active user,
5962                // and then updates our own bookkeeping based on the now-
5963                // current user.
5964                mSettingsObserver.onChange(false);
5965
5966                // force a re-application of focused window sysui visibility.
5967                // the window may never have been shown for this user
5968                // e.g. the keyguard when going through the new-user setup flow
5969                synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5970                    mLastSystemUiFlags = 0;
5971                    updateSystemUiVisibilityLw();
5972                }
5973            }
5974        }
5975    };
5976
5977    private final Runnable mHiddenNavPanic = new Runnable() {
5978        @Override
5979        public void run() {
5980            synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5981                if (!isUserSetupComplete()) {
5982                    // Swipe-up for navigation bar is disabled during setup
5983                    return;
5984                }
5985                mPendingPanicGestureUptime = SystemClock.uptimeMillis();
5986                mNavigationBarController.showTransient();
5987            }
5988        }
5989    };
5990
5991    private void requestTransientBars(WindowState swipeTarget) {
5992        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
5993            if (!isUserSetupComplete()) {
5994                // Swipe-up for navigation bar is disabled during setup
5995                return;
5996            }
5997            boolean sb = mStatusBarController.checkShowTransientBarLw();
5998            boolean nb = mNavigationBarController.checkShowTransientBarLw();
5999            if (sb || nb) {
6000                // Don't show status bar when swiping on already visible navigation bar
6001                if (!nb && swipeTarget == mNavigationBar) {
6002                    if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
6003                    return;
6004                }
6005                if (sb) mStatusBarController.showTransient();
6006                if (nb) mNavigationBarController.showTransient();
6007                mImmersiveModeConfirmation.confirmCurrentPrompt();
6008                updateSystemUiVisibilityLw();
6009            }
6010        }
6011    }
6012
6013    // Called on the PowerManager's Notifier thread.
6014    @Override
6015    public void startedGoingToSleep(int why) {
6016        if (DEBUG_WAKEUP) Slog.i(TAG, "Started going to sleep... (why=" + why + ")");
6017        mCameraGestureTriggeredDuringGoingToSleep = false;
6018        mGoingToSleep = true;
6019        if (mKeyguardDelegate != null) {
6020            mKeyguardDelegate.onStartedGoingToSleep(why);
6021        }
6022    }
6023
6024    // Called on the PowerManager's Notifier thread.
6025    @Override
6026    public void finishedGoingToSleep(int why) {
6027        EventLog.writeEvent(70000, 0);
6028        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished going to sleep... (why=" + why + ")");
6029        MetricsLogger.histogram(mContext, "screen_timeout", mLockScreenTimeout / 1000);
6030
6031        mGoingToSleep = false;
6032
6033        // We must get this work done here because the power manager will drop
6034        // the wake lock and let the system suspend once this function returns.
6035        synchronized (mLock) {
6036            mAwake = false;
6037            updateWakeGestureListenerLp();
6038            updateOrientationListenerLp();
6039            updateLockScreenTimeout();
6040        }
6041        if (mKeyguardDelegate != null) {
6042            mKeyguardDelegate.onFinishedGoingToSleep(why,
6043                    mCameraGestureTriggeredDuringGoingToSleep);
6044        }
6045        mCameraGestureTriggeredDuringGoingToSleep = false;
6046    }
6047
6048    // Called on the PowerManager's Notifier thread.
6049    @Override
6050    public void startedWakingUp() {
6051        EventLog.writeEvent(70000, 1);
6052        if (DEBUG_WAKEUP) Slog.i(TAG, "Started waking up...");
6053
6054        // Since goToSleep performs these functions synchronously, we must
6055        // do the same here.  We cannot post this work to a handler because
6056        // that might cause it to become reordered with respect to what
6057        // may happen in a future call to goToSleep.
6058        synchronized (mLock) {
6059            mAwake = true;
6060
6061            updateWakeGestureListenerLp();
6062            updateOrientationListenerLp();
6063            updateLockScreenTimeout();
6064        }
6065
6066        if (mKeyguardDelegate != null) {
6067            mKeyguardDelegate.onStartedWakingUp();
6068        }
6069    }
6070
6071    // Called on the PowerManager's Notifier thread.
6072    @Override
6073    public void finishedWakingUp() {
6074        if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");
6075    }
6076
6077    private void wakeUpFromPowerKey(long eventTime) {
6078        wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey, "android.policy:POWER");
6079    }
6080
6081    private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode, String reason) {
6082        final boolean theaterModeEnabled = isTheaterModeEnabled();
6083        if (!wakeInTheaterMode && theaterModeEnabled) {
6084            return false;
6085        }
6086
6087        if (theaterModeEnabled) {
6088            Settings.Global.putInt(mContext.getContentResolver(),
6089                    Settings.Global.THEATER_MODE_ON, 0);
6090        }
6091
6092        mPowerManager.wakeUp(wakeTime, reason);
6093        return true;
6094    }
6095
6096    private void finishKeyguardDrawn() {
6097        synchronized (mLock) {
6098            if (!mScreenOnEarly || mKeyguardDrawComplete) {
6099                return; // We are not awake yet or we have already informed of this event.
6100            }
6101
6102            mKeyguardDrawComplete = true;
6103            if (mKeyguardDelegate != null) {
6104                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
6105            }
6106            mWindowManagerDrawComplete = false;
6107        }
6108
6109        // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
6110        // as well as enabling the orientation change logic/sensor.
6111        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
6112                WAITING_FOR_DRAWN_TIMEOUT);
6113    }
6114
6115    // Called on the DisplayManager's DisplayPowerController thread.
6116    @Override
6117    public void screenTurnedOff() {
6118        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turned off...");
6119
6120        updateScreenOffSleepToken(true);
6121        synchronized (mLock) {
6122            mScreenOnEarly = false;
6123            mScreenOnFully = false;
6124            mKeyguardDrawComplete = false;
6125            mWindowManagerDrawComplete = false;
6126            mScreenOnListener = null;
6127            updateOrientationListenerLp();
6128
6129            if (mKeyguardDelegate != null) {
6130                mKeyguardDelegate.onScreenTurnedOff();
6131            }
6132        }
6133    }
6134
6135    // Called on the DisplayManager's DisplayPowerController thread.
6136    @Override
6137    public void screenTurningOn(final ScreenOnListener screenOnListener) {
6138        if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
6139
6140        updateScreenOffSleepToken(false);
6141        synchronized (mLock) {
6142            mScreenOnEarly = true;
6143            mScreenOnFully = false;
6144            mKeyguardDrawComplete = false;
6145            mWindowManagerDrawComplete = false;
6146            mScreenOnListener = screenOnListener;
6147
6148            if (mKeyguardDelegate != null) {
6149                mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
6150                mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
6151                mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
6152            } else {
6153                if (DEBUG_WAKEUP) Slog.d(TAG,
6154                        "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
6155                finishKeyguardDrawn();
6156            }
6157        }
6158    }
6159
6160    // Called on the DisplayManager's DisplayPowerController thread.
6161    @Override
6162    public void screenTurnedOn() {
6163        synchronized (mLock) {
6164            if (mKeyguardDelegate != null) {
6165                mKeyguardDelegate.onScreenTurnedOn();
6166            }
6167        }
6168    }
6169
6170    private void finishWindowsDrawn() {
6171        synchronized (mLock) {
6172            if (!mScreenOnEarly || mWindowManagerDrawComplete) {
6173                return; // Screen is not turned on or we did already handle this case earlier.
6174            }
6175
6176            mWindowManagerDrawComplete = true;
6177        }
6178
6179        finishScreenTurningOn();
6180    }
6181
6182    private void finishScreenTurningOn() {
6183        synchronized (mLock) {
6184            // We have just finished drawing screen content. Since the orientation listener
6185            // gets only installed when all windows are drawn, we try to install it again.
6186            updateOrientationListenerLp();
6187        }
6188        final ScreenOnListener listener;
6189        final boolean enableScreen;
6190        synchronized (mLock) {
6191            if (DEBUG_WAKEUP) Slog.d(TAG,
6192                    "finishScreenTurningOn: mAwake=" + mAwake
6193                            + ", mScreenOnEarly=" + mScreenOnEarly
6194                            + ", mScreenOnFully=" + mScreenOnFully
6195                            + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
6196                            + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
6197
6198            if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
6199                    || (mAwake && !mKeyguardDrawComplete)) {
6200                return; // spurious or not ready yet
6201            }
6202
6203            if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
6204            listener = mScreenOnListener;
6205            mScreenOnListener = null;
6206            mScreenOnFully = true;
6207
6208            // Remember the first time we draw the keyguard so we know when we're done with
6209            // the main part of booting and can enable the screen and hide boot messages.
6210            if (!mKeyguardDrawnOnce && mAwake) {
6211                mKeyguardDrawnOnce = true;
6212                enableScreen = true;
6213                if (mBootMessageNeedsHiding) {
6214                    mBootMessageNeedsHiding = false;
6215                    hideBootMessages();
6216                }
6217            } else {
6218                enableScreen = false;
6219            }
6220        }
6221
6222        if (listener != null) {
6223            listener.onScreenOn();
6224        }
6225
6226        if (enableScreen) {
6227            try {
6228                mWindowManager.enableScreenIfNeeded();
6229            } catch (RemoteException unhandled) {
6230            }
6231        }
6232    }
6233
6234    private void handleHideBootMessage() {
6235        synchronized (mLock) {
6236            if (!mKeyguardDrawnOnce) {
6237                mBootMessageNeedsHiding = true;
6238                return; // keyguard hasn't drawn the first time yet, not done booting
6239            }
6240        }
6241
6242        if (mBootMsgDialog != null) {
6243            if (DEBUG_WAKEUP) Slog.d(TAG, "handleHideBootMessage: dismissing");
6244            mBootMsgDialog.dismiss();
6245            mBootMsgDialog = null;
6246        }
6247    }
6248
6249    @Override
6250    public boolean isScreenOn() {
6251        return mScreenOnFully;
6252    }
6253
6254    /** {@inheritDoc} */
6255    @Override
6256    public void enableKeyguard(boolean enabled) {
6257        if (mKeyguardDelegate != null) {
6258            mKeyguardDelegate.setKeyguardEnabled(enabled);
6259        }
6260    }
6261
6262    /** {@inheritDoc} */
6263    @Override
6264    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
6265        if (mKeyguardDelegate != null) {
6266            mKeyguardDelegate.verifyUnlock(callback);
6267        }
6268    }
6269
6270    private boolean isKeyguardShowingAndNotOccluded() {
6271        if (mKeyguardDelegate == null) return false;
6272        return mKeyguardDelegate.isShowing() && !mKeyguardOccluded;
6273    }
6274
6275    /** {@inheritDoc} */
6276    @Override
6277    public boolean isKeyguardLocked() {
6278        return keyguardOn();
6279    }
6280
6281    /** {@inheritDoc} */
6282    @Override
6283    public boolean isKeyguardSecure() {
6284        if (mKeyguardDelegate == null) return false;
6285        return mKeyguardDelegate.isSecure();
6286    }
6287
6288    /** {@inheritDoc} */
6289    @Override
6290    public boolean isKeyguardShowingOrOccluded() {
6291        return mKeyguardDelegate == null ? false : mKeyguardDelegate.isShowing();
6292    }
6293
6294    /** {@inheritDoc} */
6295    @Override
6296    public boolean inKeyguardRestrictedKeyInputMode() {
6297        if (mKeyguardDelegate == null) return false;
6298        return mKeyguardDelegate.isInputRestricted();
6299    }
6300
6301    @Override
6302    public void dismissKeyguardLw() {
6303        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
6304            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.dismissKeyguardLw");
6305            mHandler.post(new Runnable() {
6306                @Override
6307                public void run() {
6308                    // ask the keyguard to prompt the user to authenticate if necessary
6309                    mKeyguardDelegate.dismiss();
6310                }
6311            });
6312        }
6313    }
6314
6315    public void notifyActivityDrawnForKeyguardLw() {
6316        if (mKeyguardDelegate != null) {
6317            mHandler.post(new Runnable() {
6318                @Override
6319                public void run() {
6320                    mKeyguardDelegate.onActivityDrawn();
6321                }
6322            });
6323        }
6324    }
6325
6326    @Override
6327    public boolean isKeyguardDrawnLw() {
6328        synchronized (mLock) {
6329            return mKeyguardDrawnOnce;
6330        }
6331    }
6332
6333    @Override
6334    public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
6335        if (mKeyguardDelegate != null) {
6336            if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation");
6337            mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration);
6338        }
6339    }
6340
6341    @Override
6342    public void getStableInsetsLw(int displayRotation, int displayWidth, int displayHeight,
6343            Rect outInsets) {
6344        outInsets.setEmpty();
6345
6346        // Navigation bar and status bar.
6347        getNonDecorInsetsLw(displayRotation, displayWidth, displayHeight, outInsets);
6348        if (mStatusBar != null) {
6349            outInsets.top = mStatusBarHeight;
6350        }
6351    }
6352
6353    @Override
6354    public void getNonDecorInsetsLw(int displayRotation, int displayWidth, int displayHeight,
6355            Rect outInsets) {
6356        outInsets.setEmpty();
6357
6358        // Only navigation bar
6359        if (mNavigationBar != null) {
6360            if (isNavigationBarOnBottom(displayWidth, displayHeight)) {
6361                outInsets.bottom = getNavigationBarHeight(displayRotation, mUiMode);
6362            } else {
6363                outInsets.right = getNavigationBarWidth(displayRotation, mUiMode);
6364            }
6365        }
6366    }
6367
6368    @Override
6369    public boolean isNavBarForcedShownLw(WindowState windowState) {
6370        return mForceShowSystemBars;
6371    }
6372
6373    @Override
6374    public boolean isDockSideAllowed(int dockSide) {
6375
6376        // We do not allow all dock sides at which the navigation bar touches the docked stack.
6377        if (!mNavigationBarCanMove) {
6378            return dockSide == DOCKED_TOP || dockSide == DOCKED_LEFT || dockSide == DOCKED_RIGHT;
6379        } else {
6380            return dockSide == DOCKED_TOP || dockSide == DOCKED_LEFT;
6381        }
6382    }
6383
6384    void sendCloseSystemWindows() {
6385        PhoneWindow.sendCloseSystemWindows(mContext, null);
6386    }
6387
6388    void sendCloseSystemWindows(String reason) {
6389        PhoneWindow.sendCloseSystemWindows(mContext, reason);
6390    }
6391
6392    @Override
6393    public int rotationForOrientationLw(int orientation, int lastRotation) {
6394        if (false) {
6395            Slog.v(TAG, "rotationForOrientationLw(orient="
6396                        + orientation + ", last=" + lastRotation
6397                        + "); user=" + mUserRotation + " "
6398                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
6399                            ? "USER_ROTATION_LOCKED" : "")
6400                        );
6401        }
6402
6403        if (mForceDefaultOrientation) {
6404            return Surface.ROTATION_0;
6405        }
6406
6407        synchronized (mLock) {
6408            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
6409            if (sensorRotation < 0) {
6410                sensorRotation = lastRotation;
6411            }
6412
6413            final int preferredRotation;
6414            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
6415                // Ignore sensor when lid switch is open and rotation is forced.
6416                preferredRotation = mLidOpenRotation;
6417            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
6418                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
6419                // Ignore sensor when in car dock unless explicitly enabled.
6420                // This case can override the behavior of NOSENSOR, and can also
6421                // enable 180 degree rotation while docked.
6422                preferredRotation = mCarDockEnablesAccelerometer
6423                        ? sensorRotation : mCarDockRotation;
6424            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6425                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
6426                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
6427                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
6428                // Ignore sensor when in desk dock unless explicitly enabled.
6429                // This case can override the behavior of NOSENSOR, and can also
6430                // enable 180 degree rotation while docked.
6431                preferredRotation = mDeskDockEnablesAccelerometer
6432                        ? sensorRotation : mDeskDockRotation;
6433            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
6434                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
6435                // Note that the dock orientation overrides the HDMI orientation.
6436                preferredRotation = mDemoHdmiRotation;
6437            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
6438                    && mUndockedHdmiRotation >= 0) {
6439                // Ignore sensor when plugged into HDMI and an undocked orientation has
6440                // been specified in the configuration (only for legacy devices without
6441                // full multi-display support).
6442                // Note that the dock orientation overrides the HDMI orientation.
6443                preferredRotation = mUndockedHdmiRotation;
6444            } else if (mDemoRotationLock) {
6445                // Ignore sensor when demo rotation lock is enabled.
6446                // Note that the dock orientation and HDMI rotation lock override this.
6447                preferredRotation = mDemoRotation;
6448            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
6449                // Application just wants to remain locked in the last rotation.
6450                preferredRotation = lastRotation;
6451            } else if (!mSupportAutoRotation) {
6452                // If we don't support auto-rotation then bail out here and ignore
6453                // the sensor and any rotation lock settings.
6454                preferredRotation = -1;
6455            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
6456                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
6457                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
6458                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
6459                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
6460                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
6461                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
6462                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6463                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
6464                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
6465                // Otherwise, use sensor only if requested by the application or enabled
6466                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
6467                if (mAllowAllRotations < 0) {
6468                    // Can't read this during init() because the context doesn't
6469                    // have display metrics at that time so we cannot determine
6470                    // tablet vs. phone then.
6471                    mAllowAllRotations = mContext.getResources().getBoolean(
6472                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
6473                }
6474                if (sensorRotation != Surface.ROTATION_180
6475                        || mAllowAllRotations == 1
6476                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6477                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
6478                    preferredRotation = sensorRotation;
6479                } else {
6480                    preferredRotation = lastRotation;
6481                }
6482            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
6483                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
6484                // Apply rotation lock.  Does not apply to NOSENSOR.
6485                // The idea is that the user rotation expresses a weak preference for the direction
6486                // of gravity and as NOSENSOR is never affected by gravity, then neither should
6487                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
6488                preferredRotation = mUserRotation;
6489            } else {
6490                // No overriding preference.
6491                // We will do exactly what the application asked us to do.
6492                preferredRotation = -1;
6493            }
6494
6495            switch (orientation) {
6496                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6497                    // Return portrait unless overridden.
6498                    if (isAnyPortrait(preferredRotation)) {
6499                        return preferredRotation;
6500                    }
6501                    return mPortraitRotation;
6502
6503                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6504                    // Return landscape unless overridden.
6505                    if (isLandscapeOrSeascape(preferredRotation)) {
6506                        return preferredRotation;
6507                    }
6508                    return mLandscapeRotation;
6509
6510                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6511                    // Return reverse portrait unless overridden.
6512                    if (isAnyPortrait(preferredRotation)) {
6513                        return preferredRotation;
6514                    }
6515                    return mUpsideDownRotation;
6516
6517                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6518                    // Return seascape unless overridden.
6519                    if (isLandscapeOrSeascape(preferredRotation)) {
6520                        return preferredRotation;
6521                    }
6522                    return mSeascapeRotation;
6523
6524                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6525                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
6526                    // Return either landscape rotation.
6527                    if (isLandscapeOrSeascape(preferredRotation)) {
6528                        return preferredRotation;
6529                    }
6530                    if (isLandscapeOrSeascape(lastRotation)) {
6531                        return lastRotation;
6532                    }
6533                    return mLandscapeRotation;
6534
6535                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6536                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
6537                    // Return either portrait rotation.
6538                    if (isAnyPortrait(preferredRotation)) {
6539                        return preferredRotation;
6540                    }
6541                    if (isAnyPortrait(lastRotation)) {
6542                        return lastRotation;
6543                    }
6544                    return mPortraitRotation;
6545
6546                default:
6547                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
6548                    // just return the preferred orientation we already calculated.
6549                    if (preferredRotation >= 0) {
6550                        return preferredRotation;
6551                    }
6552                    return Surface.ROTATION_0;
6553            }
6554        }
6555    }
6556
6557    @Override
6558    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
6559        switch (orientation) {
6560            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6561            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6562            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6563                return isAnyPortrait(rotation);
6564
6565            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6566            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6567            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6568                return isLandscapeOrSeascape(rotation);
6569
6570            default:
6571                return true;
6572        }
6573    }
6574
6575    @Override
6576    public void setRotationLw(int rotation) {
6577        mOrientationListener.setCurrentRotation(rotation);
6578    }
6579
6580    private boolean isLandscapeOrSeascape(int rotation) {
6581        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
6582    }
6583
6584    private boolean isAnyPortrait(int rotation) {
6585        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
6586    }
6587
6588    @Override
6589    public int getUserRotationMode() {
6590        return Settings.System.getIntForUser(mContext.getContentResolver(),
6591                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
6592                        WindowManagerPolicy.USER_ROTATION_FREE :
6593                                WindowManagerPolicy.USER_ROTATION_LOCKED;
6594    }
6595
6596    // User rotation: to be used when all else fails in assigning an orientation to the device
6597    @Override
6598    public void setUserRotationMode(int mode, int rot) {
6599        ContentResolver res = mContext.getContentResolver();
6600
6601        // mUserRotationMode and mUserRotation will be assigned by the content observer
6602        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
6603            Settings.System.putIntForUser(res,
6604                    Settings.System.USER_ROTATION,
6605                    rot,
6606                    UserHandle.USER_CURRENT);
6607            Settings.System.putIntForUser(res,
6608                    Settings.System.ACCELEROMETER_ROTATION,
6609                    0,
6610                    UserHandle.USER_CURRENT);
6611        } else {
6612            Settings.System.putIntForUser(res,
6613                    Settings.System.ACCELEROMETER_ROTATION,
6614                    1,
6615                    UserHandle.USER_CURRENT);
6616        }
6617    }
6618
6619    @Override
6620    public void setSafeMode(boolean safeMode) {
6621        mSafeMode = safeMode;
6622        performHapticFeedbackLw(null, safeMode
6623                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
6624                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
6625    }
6626
6627    static long[] getLongIntArray(Resources r, int resid) {
6628        int[] ar = r.getIntArray(resid);
6629        if (ar == null) {
6630            return null;
6631        }
6632        long[] out = new long[ar.length];
6633        for (int i=0; i<ar.length; i++) {
6634            out[i] = ar[i];
6635        }
6636        return out;
6637    }
6638
6639    /** {@inheritDoc} */
6640    @Override
6641    public void systemReady() {
6642        mKeyguardDelegate = new KeyguardServiceDelegate(mContext);
6643        mKeyguardDelegate.onSystemReady();
6644
6645        readCameraLensCoverState();
6646        updateUiMode();
6647        boolean bindKeyguardNow;
6648        synchronized (mLock) {
6649            updateOrientationListenerLp();
6650            mSystemReady = true;
6651            mHandler.post(new Runnable() {
6652                @Override
6653                public void run() {
6654                    updateSettings();
6655                }
6656            });
6657
6658            bindKeyguardNow = mDeferBindKeyguard;
6659            if (bindKeyguardNow) {
6660                // systemBooted ran but wasn't able to bind to the Keyguard, we'll do it now.
6661                mDeferBindKeyguard = false;
6662            }
6663        }
6664
6665        if (bindKeyguardNow) {
6666            mKeyguardDelegate.bindService(mContext);
6667            mKeyguardDelegate.onBootCompleted();
6668        }
6669        mSystemGestures.systemReady();
6670    }
6671
6672    /** {@inheritDoc} */
6673    @Override
6674    public void systemBooted() {
6675        boolean bindKeyguardNow = false;
6676        synchronized (mLock) {
6677            // Time to bind Keyguard; take care to only bind it once, either here if ready or
6678            // in systemReady if not.
6679            if (mKeyguardDelegate != null) {
6680                bindKeyguardNow = true;
6681            } else {
6682                // Because mKeyguardDelegate is null, we know that the synchronized block in
6683                // systemReady didn't run yet and setting this will actually have an effect.
6684                mDeferBindKeyguard = true;
6685            }
6686        }
6687        if (bindKeyguardNow) {
6688            mKeyguardDelegate.bindService(mContext);
6689            mKeyguardDelegate.onBootCompleted();
6690        }
6691        synchronized (mLock) {
6692            mSystemBooted = true;
6693        }
6694        startedWakingUp();
6695        screenTurningOn(null);
6696        screenTurnedOn();
6697    }
6698
6699    ProgressDialog mBootMsgDialog = null;
6700
6701    /** {@inheritDoc} */
6702    @Override
6703    public void showBootMessage(final CharSequence msg, final boolean always) {
6704        mHandler.post(new Runnable() {
6705            @Override public void run() {
6706                if (mBootMsgDialog == null) {
6707                    int theme;
6708                    if (mHasFeatureWatch) {
6709                        theme = com.android.internal.R.style.Theme_Micro_Dialog_Alert;
6710                    } else if (mContext.getPackageManager().hasSystemFeature(FEATURE_TELEVISION)) {
6711                        theme = com.android.internal.R.style.Theme_Leanback_Dialog_Alert;
6712                    } else {
6713                        theme = 0;
6714                    }
6715
6716                    mBootMsgDialog = new ProgressDialog(mContext, theme) {
6717                        // This dialog will consume all events coming in to
6718                        // it, to avoid it trying to do things too early in boot.
6719                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
6720                            return true;
6721                        }
6722                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
6723                            return true;
6724                        }
6725                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
6726                            return true;
6727                        }
6728                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
6729                            return true;
6730                        }
6731                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
6732                            return true;
6733                        }
6734                        @Override public boolean dispatchPopulateAccessibilityEvent(
6735                                AccessibilityEvent event) {
6736                            return true;
6737                        }
6738                    };
6739                    if (mContext.getPackageManager().isUpgrade()) {
6740                        mBootMsgDialog.setTitle(R.string.android_upgrading_title);
6741                    } else {
6742                        mBootMsgDialog.setTitle(R.string.android_start_title);
6743                    }
6744                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
6745                    mBootMsgDialog.setIndeterminate(true);
6746                    mBootMsgDialog.getWindow().setType(
6747                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
6748                    mBootMsgDialog.getWindow().addFlags(
6749                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
6750                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
6751                    mBootMsgDialog.getWindow().setDimAmount(1);
6752                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
6753                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
6754                    mBootMsgDialog.getWindow().setAttributes(lp);
6755                    mBootMsgDialog.setCancelable(false);
6756                    mBootMsgDialog.show();
6757                }
6758                mBootMsgDialog.setMessage(msg);
6759            }
6760        });
6761    }
6762
6763    /** {@inheritDoc} */
6764    @Override
6765    public void hideBootMessages() {
6766        mHandler.sendEmptyMessage(MSG_HIDE_BOOT_MESSAGE);
6767    }
6768
6769    /** {@inheritDoc} */
6770    @Override
6771    public void userActivity() {
6772        // ***************************************
6773        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
6774        // ***************************************
6775        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
6776        // WITH ITS LOCKS HELD.
6777        //
6778        // This code must be VERY careful about the locks
6779        // it acquires.
6780        // In fact, the current code acquires way too many,
6781        // and probably has lurking deadlocks.
6782
6783        synchronized (mScreenLockTimeout) {
6784            if (mLockScreenTimerActive) {
6785                // reset the timer
6786                mHandler.removeCallbacks(mScreenLockTimeout);
6787                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6788            }
6789        }
6790    }
6791
6792    class ScreenLockTimeout implements Runnable {
6793        Bundle options;
6794
6795        @Override
6796        public void run() {
6797            synchronized (this) {
6798                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
6799                if (mKeyguardDelegate != null) {
6800                    mKeyguardDelegate.doKeyguardTimeout(options);
6801                }
6802                mLockScreenTimerActive = false;
6803                options = null;
6804            }
6805        }
6806
6807        public void setLockOptions(Bundle options) {
6808            this.options = options;
6809        }
6810    }
6811
6812    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
6813
6814    @Override
6815    public void lockNow(Bundle options) {
6816        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
6817        mHandler.removeCallbacks(mScreenLockTimeout);
6818        if (options != null) {
6819            // In case multiple calls are made to lockNow, we don't wipe out the options
6820            // until the runnable actually executes.
6821            mScreenLockTimeout.setLockOptions(options);
6822        }
6823        mHandler.post(mScreenLockTimeout);
6824    }
6825
6826    private void updateLockScreenTimeout() {
6827        synchronized (mScreenLockTimeout) {
6828            boolean enable = (mAllowLockscreenWhenOn && mAwake &&
6829                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
6830            if (mLockScreenTimerActive != enable) {
6831                if (enable) {
6832                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
6833                    mHandler.removeCallbacks(mScreenLockTimeout); // remove any pending requests
6834                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
6835                } else {
6836                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
6837                    mHandler.removeCallbacks(mScreenLockTimeout);
6838                }
6839                mLockScreenTimerActive = enable;
6840            }
6841        }
6842    }
6843
6844    private void updateDreamingSleepToken(boolean acquire) {
6845        if (acquire) {
6846            if (mDreamingSleepToken == null) {
6847                mDreamingSleepToken = mActivityManagerInternal.acquireSleepToken("Dream");
6848            }
6849        } else {
6850            if (mDreamingSleepToken != null) {
6851                mDreamingSleepToken.release();
6852                mDreamingSleepToken = null;
6853            }
6854        }
6855    }
6856
6857    private void updateScreenOffSleepToken(boolean acquire) {
6858        if (acquire) {
6859            if (mScreenOffSleepToken == null) {
6860                mScreenOffSleepToken = mActivityManagerInternal.acquireSleepToken("ScreenOff");
6861            }
6862        } else {
6863            if (mScreenOffSleepToken != null) {
6864                mScreenOffSleepToken.release();
6865                mScreenOffSleepToken = null;
6866            }
6867        }
6868    }
6869
6870    /** {@inheritDoc} */
6871    @Override
6872    public void enableScreenAfterBoot() {
6873        readLidState();
6874        applyLidSwitchState();
6875        updateRotation(true);
6876    }
6877
6878    private void applyLidSwitchState() {
6879        if (mLidState == LID_CLOSED && mLidControlsSleep) {
6880            mPowerManager.goToSleep(SystemClock.uptimeMillis(),
6881                    PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
6882                    PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
6883        } else if (mLidState == LID_CLOSED && mLidControlsScreenLock) {
6884            mWindowManagerFuncs.lockDeviceNow();
6885        }
6886
6887        synchronized (mLock) {
6888            updateWakeGestureListenerLp();
6889        }
6890    }
6891
6892    void updateUiMode() {
6893        if (mUiModeManager == null) {
6894            mUiModeManager = IUiModeManager.Stub.asInterface(
6895                    ServiceManager.getService(Context.UI_MODE_SERVICE));
6896        }
6897        try {
6898            mUiMode = mUiModeManager.getCurrentModeType();
6899        } catch (RemoteException e) {
6900        }
6901    }
6902
6903    void updateRotation(boolean alwaysSendConfiguration) {
6904        try {
6905            //set orientation on WindowManager
6906            mWindowManager.updateRotation(alwaysSendConfiguration, false);
6907        } catch (RemoteException e) {
6908            // Ignore
6909        }
6910    }
6911
6912    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
6913        try {
6914            //set orientation on WindowManager
6915            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
6916        } catch (RemoteException e) {
6917            // Ignore
6918        }
6919    }
6920
6921    /**
6922     * Return an Intent to launch the currently active dock app as home.  Returns
6923     * null if the standard home should be launched, which is the case if any of the following is
6924     * true:
6925     * <ul>
6926     *  <li>The device is not in either car mode or desk mode
6927     *  <li>The device is in car mode but mEnableCarDockHomeCapture is false
6928     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
6929     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
6930     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
6931     * </ul>
6932     * @return A dock intent.
6933     */
6934    Intent createHomeDockIntent() {
6935        Intent intent = null;
6936
6937        // What home does is based on the mode, not the dock state.  That
6938        // is, when in car mode you should be taken to car home regardless
6939        // of whether we are actually in a car dock.
6940        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
6941            if (mEnableCarDockHomeCapture) {
6942                intent = mCarDockIntent;
6943            }
6944        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
6945            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
6946                intent = mDeskDockIntent;
6947            }
6948        } else if (mUiMode == Configuration.UI_MODE_TYPE_WATCH
6949                && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6950                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK
6951                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK)) {
6952            // Always launch dock home from home when watch is docked, if it exists.
6953            intent = mDeskDockIntent;
6954        }
6955
6956        if (intent == null) {
6957            return null;
6958        }
6959
6960        ActivityInfo ai = null;
6961        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
6962                intent,
6963                PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
6964                mCurrentUserId);
6965        if (info != null) {
6966            ai = info.activityInfo;
6967        }
6968        if (ai != null
6969                && ai.metaData != null
6970                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
6971            intent = new Intent(intent);
6972            intent.setClassName(ai.packageName, ai.name);
6973            return intent;
6974        }
6975
6976        return null;
6977    }
6978
6979    void startDockOrHome(boolean fromHomeKey, boolean awakenFromDreams) {
6980        if (awakenFromDreams) {
6981            awakenDreams();
6982        }
6983
6984        Intent dock = createHomeDockIntent();
6985        if (dock != null) {
6986            try {
6987                if (fromHomeKey) {
6988                    dock.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
6989                }
6990                startActivityAsUser(dock, UserHandle.CURRENT);
6991                return;
6992            } catch (ActivityNotFoundException e) {
6993            }
6994        }
6995
6996        Intent intent;
6997
6998        if (fromHomeKey) {
6999            intent = new Intent(mHomeIntent);
7000            intent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
7001        } else {
7002            intent = mHomeIntent;
7003        }
7004
7005        startActivityAsUser(intent, UserHandle.CURRENT);
7006    }
7007
7008    /**
7009     * goes to the home screen
7010     * @return whether it did anything
7011     */
7012    boolean goHome() {
7013        if (!isUserSetupComplete()) {
7014            Slog.i(TAG, "Not going home because user setup is in progress.");
7015            return false;
7016        }
7017        if (false) {
7018            // This code always brings home to the front.
7019            try {
7020                ActivityManagerNative.getDefault().stopAppSwitches();
7021            } catch (RemoteException e) {
7022            }
7023            sendCloseSystemWindows();
7024            startDockOrHome(false /*fromHomeKey*/, true /* awakenFromDreams */);
7025        } else {
7026            // This code brings home to the front or, if it is already
7027            // at the front, puts the device to sleep.
7028            try {
7029                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
7030                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
7031                    Log.d(TAG, "UTS-TEST-MODE");
7032                } else {
7033                    ActivityManagerNative.getDefault().stopAppSwitches();
7034                    sendCloseSystemWindows();
7035                    Intent dock = createHomeDockIntent();
7036                    if (dock != null) {
7037                        int result = ActivityManagerNative.getDefault()
7038                                .startActivityAsUser(null, null, dock,
7039                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
7040                                        null, null, 0,
7041                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
7042                                        null, null, UserHandle.USER_CURRENT);
7043                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
7044                            return false;
7045                        }
7046                    }
7047                }
7048                int result = ActivityManagerNative.getDefault()
7049                        .startActivityAsUser(null, null, mHomeIntent,
7050                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
7051                                null, null, 0,
7052                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
7053                                null, null, UserHandle.USER_CURRENT);
7054                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
7055                    return false;
7056                }
7057            } catch (RemoteException ex) {
7058                // bummer, the activity manager, which is in this process, is dead
7059            }
7060        }
7061        return true;
7062    }
7063
7064    @Override
7065    public void setCurrentOrientationLw(int newOrientation) {
7066        synchronized (mLock) {
7067            if (newOrientation != mCurrentAppOrientation) {
7068                mCurrentAppOrientation = newOrientation;
7069                updateOrientationListenerLp();
7070            }
7071        }
7072    }
7073
7074    private void performAuditoryFeedbackForAccessibilityIfNeed() {
7075        if (!isGlobalAccessibilityGestureEnabled()) {
7076            return;
7077        }
7078        AudioManager audioManager = (AudioManager) mContext.getSystemService(
7079                Context.AUDIO_SERVICE);
7080        if (audioManager.isSilentMode()) {
7081            return;
7082        }
7083        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
7084                Settings.System.DEFAULT_NOTIFICATION_URI);
7085        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
7086        ringTone.play();
7087    }
7088
7089    private boolean isTheaterModeEnabled() {
7090        return Settings.Global.getInt(mContext.getContentResolver(),
7091                Settings.Global.THEATER_MODE_ON, 0) == 1;
7092    }
7093
7094    private boolean isGlobalAccessibilityGestureEnabled() {
7095        return Settings.Global.getInt(mContext.getContentResolver(),
7096                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
7097    }
7098
7099    @Override
7100    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
7101        if (!mVibrator.hasVibrator()) {
7102            return false;
7103        }
7104        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
7105                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
7106        if (hapticsDisabled && !always) {
7107            return false;
7108        }
7109        long[] pattern = null;
7110        switch (effectId) {
7111            case HapticFeedbackConstants.LONG_PRESS:
7112                pattern = mLongPressVibePattern;
7113                break;
7114            case HapticFeedbackConstants.VIRTUAL_KEY:
7115                pattern = mVirtualKeyVibePattern;
7116                break;
7117            case HapticFeedbackConstants.KEYBOARD_TAP:
7118                pattern = mKeyboardTapVibePattern;
7119                break;
7120            case HapticFeedbackConstants.CLOCK_TICK:
7121                pattern = mClockTickVibePattern;
7122                break;
7123            case HapticFeedbackConstants.CALENDAR_DATE:
7124                pattern = mCalendarDateVibePattern;
7125                break;
7126            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
7127                pattern = mSafeModeDisabledVibePattern;
7128                break;
7129            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
7130                pattern = mSafeModeEnabledVibePattern;
7131                break;
7132            case HapticFeedbackConstants.CONTEXT_CLICK:
7133                pattern = mContextClickVibePattern;
7134                break;
7135            default:
7136                return false;
7137        }
7138        int owningUid;
7139        String owningPackage;
7140        if (win != null) {
7141            owningUid = win.getOwningUid();
7142            owningPackage = win.getOwningPackage();
7143        } else {
7144            owningUid = android.os.Process.myUid();
7145            owningPackage = mContext.getOpPackageName();
7146        }
7147        if (pattern.length == 1) {
7148            // One-shot vibration
7149            mVibrator.vibrate(owningUid, owningPackage, pattern[0], VIBRATION_ATTRIBUTES);
7150        } else {
7151            // Pattern vibration
7152            mVibrator.vibrate(owningUid, owningPackage, pattern, -1, VIBRATION_ATTRIBUTES);
7153        }
7154        return true;
7155    }
7156
7157    @Override
7158    public void keepScreenOnStartedLw() {
7159    }
7160
7161    @Override
7162    public void keepScreenOnStoppedLw() {
7163        if (isKeyguardShowingAndNotOccluded()) {
7164            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
7165        }
7166    }
7167
7168    private int updateSystemUiVisibilityLw() {
7169        // If there is no window focused, there will be nobody to handle the events
7170        // anyway, so just hang on in whatever state we're in until things settle down.
7171        final WindowState win = mFocusedWindow != null ? mFocusedWindow
7172                : mTopFullscreenOpaqueWindowState;
7173        if (win == null) {
7174            return 0;
7175        }
7176        if ((win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 && mHideLockScreen == true) {
7177            // We are updating at a point where the keyguard has gotten
7178            // focus, but we were last in a state where the top window is
7179            // hiding it.  This is probably because the keyguard as been
7180            // shown while the top window was displayed, so we want to ignore
7181            // it here because this is just a very transient change and it
7182            // will quickly lose focus once it correctly gets hidden.
7183            return 0;
7184        }
7185
7186        int tmpVisibility = PolicyControl.getSystemUiVisibility(win, null)
7187                & ~mResettingSystemUiFlags
7188                & ~mForceClearedSystemUiFlags;
7189        if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
7190            tmpVisibility &= ~PolicyControl.adjustClearableFlags(win, View.SYSTEM_UI_CLEARABLE_FLAGS);
7191        }
7192
7193        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
7194            tmpVisibility |= StatusBarManager.DISABLE_RECENT;
7195        }
7196
7197        final int fullscreenVisibility = updateLightStatusBarLw(0 /* vis */,
7198                mTopFullscreenOpaqueWindowState, mTopFullscreenOpaqueOrDimmingWindowState);
7199        final int dockedVisibility = updateLightStatusBarLw(0 /* vis */,
7200                mTopDockedOpaqueWindowState, mTopDockedOpaqueOrDimmingWindowState);
7201        mWindowManagerFuncs.getStackBounds(HOME_STACK_ID, mNonDockedStackBounds);
7202        mWindowManagerFuncs.getStackBounds(DOCKED_STACK_ID, mDockedStackBounds);
7203        final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
7204        final int diff = visibility ^ mLastSystemUiFlags;
7205        final int fullscreenDiff = fullscreenVisibility ^ mLastFullscreenStackSysUiFlags;
7206        final int dockedDiff = dockedVisibility ^ mLastDockedStackSysUiFlags;
7207        final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
7208        if (diff == 0 && fullscreenDiff == 0 && dockedDiff == 0 && mLastFocusNeedsMenu == needsMenu
7209                && mFocusedApp == win.getAppToken()
7210                && mLastNonDockedStackBounds.equals(mNonDockedStackBounds)
7211                && mLastDockedStackBounds.equals(mDockedStackBounds)) {
7212            return 0;
7213        }
7214        mLastSystemUiFlags = visibility;
7215        mLastFullscreenStackSysUiFlags = fullscreenVisibility;
7216        mLastDockedStackSysUiFlags = dockedVisibility;
7217        mLastFocusNeedsMenu = needsMenu;
7218        mFocusedApp = win.getAppToken();
7219        final Rect fullscreenStackBounds = new Rect(mNonDockedStackBounds);
7220        final Rect dockedStackBounds = new Rect(mDockedStackBounds);
7221        mHandler.post(new Runnable() {
7222                @Override
7223                public void run() {
7224                    StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
7225                    if (statusbar != null) {
7226                        statusbar.setSystemUiVisibility(visibility, fullscreenVisibility,
7227                                dockedVisibility, 0xffffffff, fullscreenStackBounds,
7228                                dockedStackBounds, win.toString());
7229                        statusbar.topAppWindowChanged(needsMenu);
7230                    }
7231                }
7232            });
7233        return diff;
7234    }
7235
7236    private int updateLightStatusBarLw(int vis, WindowState opaque, WindowState opaqueOrDimming) {
7237        WindowState statusColorWin = isStatusBarKeyguard() && !mHideLockScreen
7238                ? mStatusBar
7239                : opaqueOrDimming;
7240
7241        if (statusColorWin != null) {
7242            if (statusColorWin == opaque) {
7243                // If the top fullscreen-or-dimming window is also the top fullscreen, respect
7244                // its light flag.
7245                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7246                vis |= PolicyControl.getSystemUiVisibility(statusColorWin, null)
7247                        & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7248            } else if (statusColorWin != null && statusColorWin.isDimming()) {
7249                // Otherwise if it's dimming, clear the light flag.
7250                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7251            }
7252        }
7253        return vis;
7254    }
7255
7256    private boolean drawsSystemBarBackground(WindowState win) {
7257        return win == null || (win.getAttrs().flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0;
7258    }
7259
7260    private boolean forcesDrawStatusBarBackground(WindowState win) {
7261        return win == null || (win.getAttrs().privateFlags
7262                & PRIVATE_FLAG_FORCE_DRAW_STATUS_BAR_BACKGROUND) != 0;
7263    }
7264
7265    private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
7266        final boolean dockedStackVisible = mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID);
7267        final boolean freeformStackVisible =
7268                mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID);
7269        final boolean resizing = mWindowManagerInternal.isDockedDividerResizing();
7270
7271        // We need to force system bars when the docked stack is visible, when the freeform stack
7272        // is visible but also when we are resizing for the transitions when docked stack
7273        // visibility changes.
7274        mForceShowSystemBars = dockedStackVisible || freeformStackVisible || resizing;
7275        final boolean forceOpaqueStatusBar = mForceShowSystemBars && !mForceStatusBarFromKeyguard;
7276
7277        // apply translucent bar vis flags
7278        WindowState fullscreenTransWin = isStatusBarKeyguard() && !mHideLockScreen
7279                ? mStatusBar
7280                : mTopFullscreenOpaqueWindowState;
7281        vis = mStatusBarController.applyTranslucentFlagLw(fullscreenTransWin, vis, oldVis);
7282        vis = mNavigationBarController.applyTranslucentFlagLw(fullscreenTransWin, vis, oldVis);
7283        final int dockedVis = mStatusBarController.applyTranslucentFlagLw(
7284                mTopDockedOpaqueWindowState, 0, 0);
7285
7286        final boolean fullscreenDrawsStatusBarBackground =
7287                (drawsSystemBarBackground(mTopFullscreenOpaqueWindowState)
7288                        && (vis & View.STATUS_BAR_TRANSLUCENT) == 0)
7289                || forcesDrawStatusBarBackground(mTopFullscreenOpaqueWindowState);
7290        final boolean dockedDrawsStatusBarBackground =
7291                (drawsSystemBarBackground(mTopDockedOpaqueWindowState)
7292                        && (dockedVis & View.STATUS_BAR_TRANSLUCENT) == 0)
7293                || forcesDrawStatusBarBackground(mTopDockedOpaqueWindowState);
7294
7295        // prevent status bar interaction from clearing certain flags
7296        int type = win.getAttrs().type;
7297        boolean statusBarHasFocus = type == TYPE_STATUS_BAR;
7298        if (statusBarHasFocus && !isStatusBarKeyguard()) {
7299            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
7300                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
7301                    | View.SYSTEM_UI_FLAG_IMMERSIVE
7302                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
7303                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7304            if (mHideLockScreen) {
7305                flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
7306            }
7307            vis = (vis & ~flags) | (oldVis & flags);
7308        }
7309
7310        if (fullscreenDrawsStatusBarBackground && dockedDrawsStatusBarBackground) {
7311            vis |= View.STATUS_BAR_TRANSPARENT;
7312            vis &= ~View.STATUS_BAR_TRANSLUCENT;
7313        } else if ((!areTranslucentBarsAllowed() && fullscreenTransWin != mStatusBar)
7314                || forceOpaqueStatusBar) {
7315            vis &= ~(View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT);
7316        }
7317
7318        vis = configureNavBarOpacity(vis, dockedStackVisible, freeformStackVisible, resizing);
7319
7320        // update status bar
7321        boolean immersiveSticky =
7322                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7323        final boolean hideStatusBarWM =
7324                mTopFullscreenOpaqueWindowState != null
7325                && (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
7326                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
7327        final boolean hideStatusBarSysui =
7328                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
7329        final boolean hideNavBarSysui =
7330                (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
7331
7332        final boolean transientStatusBarAllowed = mStatusBar != null
7333                && (statusBarHasFocus || (!mForceShowSystemBars
7334                        && (hideStatusBarWM || (hideStatusBarSysui && immersiveSticky))));
7335
7336        final boolean transientNavBarAllowed = mNavigationBar != null
7337                && !mForceShowSystemBars && hideNavBarSysui && immersiveSticky;
7338
7339        final long now = SystemClock.uptimeMillis();
7340        final boolean pendingPanic = mPendingPanicGestureUptime != 0
7341                && now - mPendingPanicGestureUptime <= PANIC_GESTURE_EXPIRATION;
7342        if (pendingPanic && hideNavBarSysui && !isStatusBarKeyguard() && mKeyguardDrawComplete) {
7343            // The user performed the panic gesture recently, we're about to hide the bars,
7344            // we're no longer on the Keyguard and the screen is ready. We can now request the bars.
7345            mPendingPanicGestureUptime = 0;
7346            mStatusBarController.showTransient();
7347            mNavigationBarController.showTransient();
7348        }
7349
7350        final boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
7351                && !transientStatusBarAllowed && hideStatusBarSysui;
7352        final boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
7353                && !transientNavBarAllowed;
7354        if (denyTransientStatus || denyTransientNav || mForceShowSystemBars) {
7355            // clear the clearable flags instead
7356            clearClearableFlagsLw();
7357            vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
7358        }
7359
7360        final boolean immersive = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
7361        immersiveSticky = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7362        final boolean navAllowedHidden = immersive || immersiveSticky;
7363
7364        if (hideNavBarSysui && !navAllowedHidden && windowTypeToLayerLw(win.getBaseType())
7365                > windowTypeToLayerLw(TYPE_INPUT_CONSUMER)) {
7366            // We can't hide the navbar from this window otherwise the input consumer would not get
7367            // the input events.
7368            vis = (vis & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
7369        }
7370
7371        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
7372
7373        // update navigation bar
7374        boolean oldImmersiveMode = isImmersiveMode(oldVis);
7375        boolean newImmersiveMode = isImmersiveMode(vis);
7376        if (win != null && oldImmersiveMode != newImmersiveMode) {
7377            final String pkg = win.getOwningPackage();
7378            mImmersiveModeConfirmation.immersiveModeChanged(pkg, newImmersiveMode,
7379                    isUserSetupComplete());
7380        }
7381
7382        vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
7383
7384        return vis;
7385    }
7386
7387    /**
7388     * @return the current visibility flags with the nav-bar opacity related flags toggled based
7389     *         on the nav bar opacity rules chosen by {@link #mNavBarOpacityMode}.
7390     */
7391    private int configureNavBarOpacity(int visibility, boolean dockedStackVisible,
7392            boolean freeformStackVisible, boolean isDockedDividerResizing) {
7393        if (mNavBarOpacityMode == NAV_BAR_OPAQUE_WHEN_FREEFORM_OR_DOCKED) {
7394            if (dockedStackVisible || freeformStackVisible || isDockedDividerResizing) {
7395                visibility = setNavBarOpaqueFlag(visibility);
7396            }
7397        } else if (mNavBarOpacityMode == NAV_BAR_TRANSLUCENT_WHEN_FREEFORM_OPAQUE_OTHERWISE) {
7398            if (isDockedDividerResizing) {
7399                visibility = setNavBarOpaqueFlag(visibility);
7400            } else if (freeformStackVisible) {
7401                visibility = setNavBarTranslucentFlag(visibility);
7402            } else {
7403                visibility = setNavBarOpaqueFlag(visibility);
7404            }
7405        }
7406
7407        if (!areTranslucentBarsAllowed()) {
7408            visibility &= ~View.NAVIGATION_BAR_TRANSLUCENT;
7409        }
7410        return visibility;
7411    }
7412
7413    private int setNavBarOpaqueFlag(int visibility) {
7414        return visibility &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT);
7415    }
7416
7417    private int setNavBarTranslucentFlag(int visibility) {
7418        visibility &= ~View.NAVIGATION_BAR_TRANSPARENT;
7419        return visibility |= View.NAVIGATION_BAR_TRANSLUCENT;
7420    }
7421
7422    private void clearClearableFlagsLw() {
7423        int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
7424        if (newVal != mResettingSystemUiFlags) {
7425            mResettingSystemUiFlags = newVal;
7426            mWindowManagerFuncs.reevaluateStatusBarVisibility();
7427        }
7428    }
7429
7430    private boolean isImmersiveMode(int vis) {
7431        final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
7432        return mNavigationBar != null
7433                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
7434                && (vis & flags) != 0
7435                && canHideNavigationBar();
7436    }
7437
7438    /**
7439     * @return whether the navigation or status bar can be made translucent
7440     *
7441     * This should return true unless touch exploration is not enabled or
7442     * R.boolean.config_enableTranslucentDecor is false.
7443     */
7444    private boolean areTranslucentBarsAllowed() {
7445        return mTranslucentDecorEnabled;
7446    }
7447
7448    // Use this instead of checking config_showNavigationBar so that it can be consistently
7449    // overridden by qemu.hw.mainkeys in the emulator.
7450    @Override
7451    public boolean hasNavigationBar() {
7452        return mHasNavigationBar;
7453    }
7454
7455    @Override
7456    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
7457        mLastInputMethodWindow = ime;
7458        mLastInputMethodTargetWindow = target;
7459    }
7460
7461    @Override
7462    public int getInputMethodWindowVisibleHeightLw() {
7463        return mDockBottom - mCurBottom;
7464    }
7465
7466    @Override
7467    public void setCurrentUserLw(int newUserId) {
7468        mCurrentUserId = newUserId;
7469        if (mKeyguardDelegate != null) {
7470            mKeyguardDelegate.setCurrentUser(newUserId);
7471        }
7472        if (mStatusBarService != null) {
7473            try {
7474                mStatusBarService.setCurrentUser(newUserId);
7475            } catch (RemoteException e) {
7476                // oh well
7477            }
7478        }
7479        setLastInputMethodWindowLw(null, null);
7480    }
7481
7482    @Override
7483    public boolean canMagnifyWindow(int windowType) {
7484        switch (windowType) {
7485            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
7486            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
7487            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
7488            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
7489                return false;
7490            }
7491        }
7492        return true;
7493    }
7494
7495    @Override
7496    public boolean isTopLevelWindow(int windowType) {
7497        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
7498                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
7499            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
7500        }
7501        return true;
7502    }
7503
7504    @Override
7505    public void dump(String prefix, PrintWriter pw, String[] args) {
7506        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
7507                pw.print(" mSystemReady="); pw.print(mSystemReady);
7508                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
7509        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
7510                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
7511                pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
7512                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
7513        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
7514                || mForceClearedSystemUiFlags != 0) {
7515            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
7516                    pw.print(Integer.toHexString(mLastSystemUiFlags));
7517                    pw.print(" mResettingSystemUiFlags=0x");
7518                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
7519                    pw.print(" mForceClearedSystemUiFlags=0x");
7520                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
7521        }
7522        if (mLastFocusNeedsMenu) {
7523            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
7524                    pw.println(mLastFocusNeedsMenu);
7525        }
7526        pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
7527                pw.println(mWakeGestureEnabledSetting);
7528
7529        pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
7530        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
7531                pw.print(" mDockMode="); pw.print(mDockMode);
7532                pw.print(" mEnableCarDockHomeCapture="); pw.print(mEnableCarDockHomeCapture);
7533                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
7534                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
7535        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
7536                pw.print(" mUserRotation="); pw.print(mUserRotation);
7537                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
7538        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
7539        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
7540                pw.print(mCarDockEnablesAccelerometer);
7541                pw.print(" mDeskDockEnablesAccelerometer=");
7542                pw.println(mDeskDockEnablesAccelerometer);
7543        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
7544                pw.print(mLidKeyboardAccessibility);
7545                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
7546                pw.print(" mLidControlsScreenLock="); pw.println(mLidControlsScreenLock);
7547                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
7548        pw.print(prefix);
7549                pw.print(" mLongPressOnBackBehavior="); pw.println(mLongPressOnBackBehavior);
7550        pw.print(prefix);
7551                pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
7552                pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
7553        pw.print(prefix);
7554                pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
7555                pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
7556        pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
7557        pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
7558        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
7559                pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
7560        pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
7561                pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
7562        pw.print(prefix); pw.print("mOrientationSensorEnabled=");
7563                pw.println(mOrientationSensorEnabled);
7564        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
7565                pw.print(","); pw.print(mOverscanScreenTop);
7566                pw.print(") "); pw.print(mOverscanScreenWidth);
7567                pw.print("x"); pw.println(mOverscanScreenHeight);
7568        if (mOverscanLeft != 0 || mOverscanTop != 0
7569                || mOverscanRight != 0 || mOverscanBottom != 0) {
7570            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
7571                    pw.print(" top="); pw.print(mOverscanTop);
7572                    pw.print(" right="); pw.print(mOverscanRight);
7573                    pw.print(" bottom="); pw.println(mOverscanBottom);
7574        }
7575        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
7576                pw.print(mRestrictedOverscanScreenLeft);
7577                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
7578                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
7579                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
7580        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
7581                pw.print(","); pw.print(mUnrestrictedScreenTop);
7582                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
7583                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
7584        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
7585                pw.print(","); pw.print(mRestrictedScreenTop);
7586                pw.print(") "); pw.print(mRestrictedScreenWidth);
7587                pw.print("x"); pw.println(mRestrictedScreenHeight);
7588        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
7589                pw.print(","); pw.print(mStableFullscreenTop);
7590                pw.print(")-("); pw.print(mStableFullscreenRight);
7591                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
7592        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
7593                pw.print(","); pw.print(mStableTop);
7594                pw.print(")-("); pw.print(mStableRight);
7595                pw.print(","); pw.print(mStableBottom); pw.println(")");
7596        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
7597                pw.print(","); pw.print(mSystemTop);
7598                pw.print(")-("); pw.print(mSystemRight);
7599                pw.print(","); pw.print(mSystemBottom); pw.println(")");
7600        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
7601                pw.print(","); pw.print(mCurTop);
7602                pw.print(")-("); pw.print(mCurRight);
7603                pw.print(","); pw.print(mCurBottom); pw.println(")");
7604        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
7605                pw.print(","); pw.print(mContentTop);
7606                pw.print(")-("); pw.print(mContentRight);
7607                pw.print(","); pw.print(mContentBottom); pw.println(")");
7608        pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
7609                pw.print(","); pw.print(mVoiceContentTop);
7610                pw.print(")-("); pw.print(mVoiceContentRight);
7611                pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
7612        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
7613                pw.print(","); pw.print(mDockTop);
7614                pw.print(")-("); pw.print(mDockRight);
7615                pw.print(","); pw.print(mDockBottom); pw.println(")");
7616        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
7617                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
7618        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
7619                pw.print(" mShowingDream="); pw.print(mShowingDream);
7620                pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
7621                pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
7622        if (mLastInputMethodWindow != null) {
7623            pw.print(prefix); pw.print("mLastInputMethodWindow=");
7624                    pw.println(mLastInputMethodWindow);
7625        }
7626        if (mLastInputMethodTargetWindow != null) {
7627            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
7628                    pw.println(mLastInputMethodTargetWindow);
7629        }
7630        if (mStatusBar != null) {
7631            pw.print(prefix); pw.print("mStatusBar=");
7632                    pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
7633                    pw.println(isStatusBarKeyguard());
7634        }
7635        if (mNavigationBar != null) {
7636            pw.print(prefix); pw.print("mNavigationBar=");
7637                    pw.println(mNavigationBar);
7638        }
7639        if (mFocusedWindow != null) {
7640            pw.print(prefix); pw.print("mFocusedWindow=");
7641                    pw.println(mFocusedWindow);
7642        }
7643        if (mFocusedApp != null) {
7644            pw.print(prefix); pw.print("mFocusedApp=");
7645                    pw.println(mFocusedApp);
7646        }
7647        if (mWinDismissingKeyguard != null) {
7648            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
7649                    pw.println(mWinDismissingKeyguard);
7650        }
7651        if (mTopFullscreenOpaqueWindowState != null) {
7652            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
7653                    pw.println(mTopFullscreenOpaqueWindowState);
7654        }
7655        if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
7656            pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
7657                    pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
7658        }
7659        if (mForcingShowNavBar) {
7660            pw.print(prefix); pw.print("mForcingShowNavBar=");
7661                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
7662                    pw.println(mForcingShowNavBarLayer);
7663        }
7664        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
7665                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
7666        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
7667                pw.print(" mForceStatusBarFromKeyguard=");
7668                pw.println(mForceStatusBarFromKeyguard);
7669        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
7670                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
7671                pw.print(" mHomePressed="); pw.println(mHomePressed);
7672        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
7673                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
7674                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
7675        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
7676                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
7677                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
7678        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
7679                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
7680        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
7681                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
7682        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
7683                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
7684        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
7685
7686        mGlobalKeyManager.dump(prefix, pw);
7687        mStatusBarController.dump(pw, prefix);
7688        mNavigationBarController.dump(pw, prefix);
7689        PolicyControl.dump(prefix, pw);
7690
7691        if (mWakeGestureListener != null) {
7692            mWakeGestureListener.dump(pw, prefix);
7693        }
7694        if (mOrientationListener != null) {
7695            mOrientationListener.dump(pw, prefix);
7696        }
7697        if (mBurnInProtectionHelper != null) {
7698            mBurnInProtectionHelper.dump(prefix, pw);
7699        }
7700        if (mKeyguardDelegate != null) {
7701            mKeyguardDelegate.dump(prefix, pw);
7702        }
7703    }
7704}
7705