OSDN Git Service

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