OSDN Git Service

keyboard: re-add code to detect lid state and handle lights
[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     private boolean isBuiltInKeyboardVisible() {
2410         return mHaveBuiltInKeyboard && !isHidden(mLidKeyboardAccessibility);
2411     }
2412
2413     /** {@inheritDoc} */
2414     @Override
2415     public void adjustConfigurationLw(Configuration config, int keyboardPresence,
2416             int navigationPresence) {
2417         mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
2418
2419         readLidState();
2420
2421         if (config.keyboard == Configuration.KEYBOARD_NOKEYS
2422                 || (keyboardPresence == PRESENCE_INTERNAL
2423                         && isHidden(mLidKeyboardAccessibility))) {
2424             config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
2425             if (!mHasSoftInput) {
2426                 config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES;
2427             }
2428         }
2429
2430         if (config.navigation == Configuration.NAVIGATION_NONAV
2431                 || (navigationPresence == PRESENCE_INTERNAL
2432                         && isHidden(mLidNavigationAccessibility))) {
2433             config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
2434         }
2435     }
2436
2437     @Override
2438     public void onConfigurationChanged() {
2439         final Resources res = mContext.getResources();
2440
2441         mStatusBarHeight =
2442                 res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
2443
2444         // Height of the navigation bar when presented horizontally at bottom
2445         mNavigationBarHeightForRotationDefault[mPortraitRotation] =
2446         mNavigationBarHeightForRotationDefault[mUpsideDownRotation] =
2447                 res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_height);
2448         mNavigationBarHeightForRotationDefault[mLandscapeRotation] =
2449         mNavigationBarHeightForRotationDefault[mSeascapeRotation] = res.getDimensionPixelSize(
2450                 com.android.internal.R.dimen.navigation_bar_height_landscape);
2451
2452         // Width of the navigation bar when presented vertically along one side
2453         mNavigationBarWidthForRotationDefault[mPortraitRotation] =
2454         mNavigationBarWidthForRotationDefault[mUpsideDownRotation] =
2455         mNavigationBarWidthForRotationDefault[mLandscapeRotation] =
2456         mNavigationBarWidthForRotationDefault[mSeascapeRotation] =
2457                 res.getDimensionPixelSize(com.android.internal.R.dimen.navigation_bar_width);
2458
2459         // Height of the navigation bar when presented horizontally at bottom
2460         mNavigationBarHeightForRotationInCarMode[mPortraitRotation] =
2461         mNavigationBarHeightForRotationInCarMode[mUpsideDownRotation] =
2462                 res.getDimensionPixelSize(
2463                         com.android.internal.R.dimen.navigation_bar_height_car_mode);
2464         mNavigationBarHeightForRotationInCarMode[mLandscapeRotation] =
2465         mNavigationBarHeightForRotationInCarMode[mSeascapeRotation] = res.getDimensionPixelSize(
2466                 com.android.internal.R.dimen.navigation_bar_height_landscape_car_mode);
2467
2468         // Width of the navigation bar when presented vertically along one side
2469         mNavigationBarWidthForRotationInCarMode[mPortraitRotation] =
2470         mNavigationBarWidthForRotationInCarMode[mUpsideDownRotation] =
2471         mNavigationBarWidthForRotationInCarMode[mLandscapeRotation] =
2472         mNavigationBarWidthForRotationInCarMode[mSeascapeRotation] =
2473                 res.getDimensionPixelSize(
2474                         com.android.internal.R.dimen.navigation_bar_width_car_mode);
2475     }
2476
2477     /** {@inheritDoc} */
2478     @Override
2479     public int windowTypeToLayerLw(int type) {
2480         if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
2481             return 2;
2482         }
2483         switch (type) {
2484         case TYPE_PRIVATE_PRESENTATION:
2485             return 2;
2486         case TYPE_WALLPAPER:
2487             // wallpaper is at the bottom, though the window manager may move it.
2488             return 2;
2489         case TYPE_DOCK_DIVIDER:
2490             return 2;
2491         case TYPE_QS_DIALOG:
2492             return 2;
2493         case TYPE_PHONE:
2494             return 3;
2495         case TYPE_SEARCH_BAR:
2496         case TYPE_VOICE_INTERACTION_STARTING:
2497             return 4;
2498         case TYPE_VOICE_INTERACTION:
2499             // voice interaction layer is almost immediately above apps.
2500             return 5;
2501         case TYPE_INPUT_CONSUMER:
2502             return 6;
2503         case TYPE_SYSTEM_DIALOG:
2504             return 7;
2505         case TYPE_TOAST:
2506             // toasts and the plugged-in battery thing
2507             return 8;
2508         case TYPE_PRIORITY_PHONE:
2509             // SIM errors and unlock.  Not sure if this really should be in a high layer.
2510             return 9;
2511         case TYPE_DREAM:
2512             // used for Dreams (screensavers with TYPE_DREAM windows)
2513             return 10;
2514         case TYPE_SYSTEM_ALERT:
2515             // like the ANR / app crashed dialogs
2516             return 11;
2517         case TYPE_INPUT_METHOD:
2518             // on-screen keyboards and other such input method user interfaces go here.
2519             return 12;
2520         case TYPE_INPUT_METHOD_DIALOG:
2521             // on-screen keyboards and other such input method user interfaces go here.
2522             return 13;
2523         case TYPE_KEYGUARD_SCRIM:
2524             // the safety window that shows behind keyguard while keyguard is starting
2525             return 14;
2526         case TYPE_STATUS_BAR_SUB_PANEL:
2527             return 15;
2528         case TYPE_STATUS_BAR:
2529             return 16;
2530         case TYPE_STATUS_BAR_PANEL:
2531             return 17;
2532         case TYPE_KEYGUARD_DIALOG:
2533             return 18;
2534         case TYPE_VOLUME_OVERLAY:
2535             // the on-screen volume indicator and controller shown when the user
2536             // changes the device volume
2537             return 19;
2538         case TYPE_SYSTEM_OVERLAY:
2539             // the on-screen volume indicator and controller shown when the user
2540             // changes the device volume
2541             return 20;
2542         case TYPE_NAVIGATION_BAR:
2543             // the navigation bar, if available, shows atop most things
2544             return 21;
2545         case TYPE_NAVIGATION_BAR_PANEL:
2546             // some panels (e.g. search) need to show on top of the navigation bar
2547             return 22;
2548         case TYPE_SCREENSHOT:
2549             // screenshot selection layer shouldn't go above system error, but it should cover
2550             // navigation bars at the very least.
2551             return 23;
2552         case TYPE_SYSTEM_ERROR:
2553             // system-level error dialogs
2554             return 24;
2555         case TYPE_MAGNIFICATION_OVERLAY:
2556             // used to highlight the magnified portion of a display
2557             return 25;
2558         case TYPE_DISPLAY_OVERLAY:
2559             // used to simulate secondary display devices
2560             return 26;
2561         case TYPE_DRAG:
2562             // the drag layer: input for drag-and-drop is associated with this window,
2563             // which sits above all other focusable windows
2564             return 27;
2565         case TYPE_ACCESSIBILITY_OVERLAY:
2566             // overlay put by accessibility services to intercept user interaction
2567             return 28;
2568         case TYPE_SECURE_SYSTEM_OVERLAY:
2569             return 29;
2570         case TYPE_BOOT_PROGRESS:
2571             return 30;
2572         case TYPE_POINTER:
2573             // the (mouse) pointer layer
2574             return 31;
2575         }
2576         Log.e(TAG, "Unknown window type: " + type);
2577         return 2;
2578     }
2579
2580     /** {@inheritDoc} */
2581     @Override
2582     public int subWindowTypeToLayerLw(int type) {
2583         switch (type) {
2584         case TYPE_APPLICATION_PANEL:
2585         case TYPE_APPLICATION_ATTACHED_DIALOG:
2586             return APPLICATION_PANEL_SUBLAYER;
2587         case TYPE_APPLICATION_MEDIA:
2588             return APPLICATION_MEDIA_SUBLAYER;
2589         case TYPE_APPLICATION_MEDIA_OVERLAY:
2590             return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
2591         case TYPE_APPLICATION_SUB_PANEL:
2592             return APPLICATION_SUB_PANEL_SUBLAYER;
2593         case TYPE_APPLICATION_ABOVE_SUB_PANEL:
2594             return APPLICATION_ABOVE_SUB_PANEL_SUBLAYER;
2595         }
2596         Log.e(TAG, "Unknown sub-window type: " + type);
2597         return 0;
2598     }
2599
2600     @Override
2601     public int getMaxWallpaperLayer() {
2602         return windowTypeToLayerLw(TYPE_STATUS_BAR);
2603     }
2604
2605     private int getNavigationBarWidth(int rotation, int uiMode) {
2606         if ((uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR) {
2607             return mNavigationBarWidthForRotationInCarMode[rotation];
2608         } else {
2609             return mNavigationBarWidthForRotationDefault[rotation];
2610         }
2611     }
2612
2613     @Override
2614     public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation,
2615             int uiMode) {
2616         if (mHasNavigationBar) {
2617             // For a basic navigation bar, when we are in landscape mode we place
2618             // the navigation bar to the side.
2619             if (mNavigationBarCanMove && fullWidth > fullHeight) {
2620                 return fullWidth - getNavigationBarWidth(rotation, uiMode);
2621             }
2622         }
2623         return fullWidth;
2624     }
2625
2626     private int getNavigationBarHeight(int rotation, int uiMode) {
2627         if ((uiMode & UI_MODE_TYPE_MASK) == UI_MODE_TYPE_CAR) {
2628             return mNavigationBarHeightForRotationInCarMode[rotation];
2629         } else {
2630             return mNavigationBarHeightForRotationDefault[rotation];
2631         }
2632     }
2633
2634     @Override
2635     public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation,
2636             int uiMode) {
2637         if (mHasNavigationBar) {
2638             // For a basic navigation bar, when we are in portrait mode we place
2639             // the navigation bar to the bottom.
2640             if (!mNavigationBarCanMove || fullWidth < fullHeight) {
2641                 return fullHeight - getNavigationBarHeight(rotation, uiMode);
2642             }
2643         }
2644         return fullHeight;
2645     }
2646
2647     @Override
2648     public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation, int uiMode) {
2649         return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation, uiMode);
2650     }
2651
2652     @Override
2653     public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation, int uiMode) {
2654         // There is a separate status bar at the top of the display.  We don't count that as part
2655         // of the fixed decor, since it can hide; however, for purposes of configurations,
2656         // we do want to exclude it since applications can't generally use that part
2657         // of the screen.
2658         return getNonDecorDisplayHeight(
2659                 fullWidth, fullHeight, rotation, uiMode) - mStatusBarHeight;
2660     }
2661
2662     @Override
2663     public boolean isForceHiding(WindowManager.LayoutParams attrs) {
2664         return (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 ||
2665                 (isKeyguardHostWindow(attrs) &&
2666                         (mKeyguardDelegate != null && mKeyguardDelegate.isShowing())) ||
2667                 (attrs.type == TYPE_KEYGUARD_SCRIM);
2668     }
2669
2670     @Override
2671     public boolean isKeyguardHostWindow(WindowManager.LayoutParams attrs) {
2672         return attrs.type == TYPE_STATUS_BAR;
2673     }
2674
2675     @Override
2676     public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
2677         switch (attrs.type) {
2678             case TYPE_STATUS_BAR:
2679             case TYPE_NAVIGATION_BAR:
2680             case TYPE_WALLPAPER:
2681             case TYPE_DREAM:
2682             case TYPE_KEYGUARD_SCRIM:
2683                 return false;
2684             default:
2685                 // Hide only windows below the keyguard host window.
2686                 return windowTypeToLayerLw(win.getBaseType())
2687                         < windowTypeToLayerLw(TYPE_STATUS_BAR);
2688         }
2689     }
2690
2691     @Override
2692     public WindowState getWinShowWhenLockedLw() {
2693         return mWinShowWhenLocked;
2694     }
2695
2696     /** {@inheritDoc} */
2697     @Override
2698     public View addStartingWindow(IBinder appToken, String packageName, int theme,
2699             CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel, int labelRes,
2700             int icon, int logo, int windowFlags, Configuration overrideConfig) {
2701         if (!SHOW_STARTING_ANIMATIONS) {
2702             return null;
2703         }
2704         if (packageName == null) {
2705             return null;
2706         }
2707
2708         WindowManager wm = null;
2709         View view = null;
2710
2711         try {
2712             Context context = mContext;
2713             if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow " + packageName
2714                     + ": nonLocalizedLabel=" + nonLocalizedLabel + " theme="
2715                     + Integer.toHexString(theme));
2716             if (theme != context.getThemeResId() || labelRes != 0) {
2717                 try {
2718                     context = context.createPackageContext(packageName, 0);
2719                     context.setTheme(theme);
2720                 } catch (PackageManager.NameNotFoundException e) {
2721                     // Ignore
2722                 }
2723             }
2724
2725             if (overrideConfig != null && overrideConfig != EMPTY) {
2726                 if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow: creating context based"
2727                         + " on overrideConfig" + overrideConfig + " for starting window");
2728                 final Context overrideContext = context.createConfigurationContext(overrideConfig);
2729                 overrideContext.setTheme(theme);
2730                 final TypedArray typedArray = overrideContext.obtainStyledAttributes(
2731                         com.android.internal.R.styleable.Window);
2732                 final int resId = typedArray.getResourceId(R.styleable.Window_windowBackground, 0);
2733                 if (resId != 0 && overrideContext.getDrawable(resId) != null) {
2734                     // We want to use the windowBackground for the override context if it is
2735                     // available, otherwise we use the default one to make sure a themed starting
2736                     // window is displayed for the app.
2737                     if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow: apply overrideConfig"
2738                             + overrideConfig + " to starting window resId=" + resId);
2739                     context = overrideContext;
2740                 }
2741             }
2742
2743             final PhoneWindow win = new PhoneWindow(context);
2744             win.setIsStartingWindow(true);
2745
2746             CharSequence label = context.getResources().getText(labelRes, null);
2747             // Only change the accessibility title if the label is localized
2748             if (label != null) {
2749                 win.setTitle(label, true);
2750             } else {
2751                 win.setTitle(nonLocalizedLabel, false);
2752             }
2753
2754             win.setType(
2755                 WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
2756
2757             synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
2758                 // Assumes it's safe to show starting windows of launched apps while
2759                 // the keyguard is being hidden. This is okay because starting windows never show
2760                 // secret information.
2761                 if (mKeyguardHidden) {
2762                     windowFlags |= FLAG_SHOW_WHEN_LOCKED;
2763                 }
2764             }
2765
2766             // Force the window flags: this is a fake window, so it is not really
2767             // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
2768             // flag because we do know that the next window will take input
2769             // focus, so we want to get the IME window up on top of us right away.
2770             win.setFlags(
2771                 windowFlags|
2772                 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2773                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2774                 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
2775                 windowFlags|
2776                 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
2777                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
2778                 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
2779
2780             win.setDefaultIcon(icon);
2781             win.setDefaultLogo(logo);
2782
2783             win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
2784                     WindowManager.LayoutParams.MATCH_PARENT);
2785
2786             final WindowManager.LayoutParams params = win.getAttributes();
2787             params.token = appToken;
2788             params.packageName = packageName;
2789             params.windowAnimations = win.getWindowStyle().getResourceId(
2790                     com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
2791             params.privateFlags |=
2792                     WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED;
2793             params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
2794
2795             if (!compatInfo.supportsScreen()) {
2796                 params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
2797             }
2798
2799             params.setTitle("Starting " + packageName);
2800
2801             wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
2802             view = win.getDecorView();
2803
2804             if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "Adding starting window for "
2805                 + packageName + " / " + appToken + ": " + (view.getParent() != null ? view : null));
2806
2807             wm.addView(view, params);
2808
2809             // Only return the view if it was successfully added to the
2810             // window manager... which we can tell by it having a parent.
2811             return view.getParent() != null ? view : null;
2812         } catch (WindowManager.BadTokenException e) {
2813             // ignore
2814             Log.w(TAG, appToken + " already running, starting window not displayed. " +
2815                     e.getMessage());
2816         } catch (RuntimeException e) {
2817             // don't crash if something else bad happens, for example a
2818             // failure loading resources because we are loading from an app
2819             // on external storage that has been unmounted.
2820             Log.w(TAG, appToken + " failed creating starting window", e);
2821         } finally {
2822             if (view != null && view.getParent() == null) {
2823                 Log.w(TAG, "view not successfully added to wm, removing view");
2824                 wm.removeViewImmediate(view);
2825             }
2826         }
2827
2828         return null;
2829     }
2830
2831     /** {@inheritDoc} */
2832     @Override
2833     public void removeStartingWindow(IBinder appToken, View window) {
2834         if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Removing starting window for " + appToken + ": "
2835                 + window + " Callers=" + Debug.getCallers(4));
2836
2837         if (window != null) {
2838             WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
2839             wm.removeView(window);
2840         }
2841     }
2842
2843     /**
2844      * Preflight adding a window to the system.
2845      *
2846      * Currently enforces that three window types are singletons:
2847      * <ul>
2848      * <li>STATUS_BAR_TYPE</li>
2849      * <li>KEYGUARD_TYPE</li>
2850      * </ul>
2851      *
2852      * @param win The window to be added
2853      * @param attrs Information about the window to be added
2854      *
2855      * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons,
2856      * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
2857      */
2858     @Override
2859     public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
2860         switch (attrs.type) {
2861             case TYPE_STATUS_BAR:
2862                 mContext.enforceCallingOrSelfPermission(
2863                         android.Manifest.permission.STATUS_BAR_SERVICE,
2864                         "PhoneWindowManager");
2865                 if (mStatusBar != null) {
2866                     if (mStatusBar.isAlive()) {
2867                         return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2868                     }
2869                 }
2870                 mStatusBar = win;
2871                 mStatusBarController.setWindow(win);
2872                 break;
2873             case TYPE_NAVIGATION_BAR:
2874                 mContext.enforceCallingOrSelfPermission(
2875                         android.Manifest.permission.STATUS_BAR_SERVICE,
2876                         "PhoneWindowManager");
2877                 if (mNavigationBar != null) {
2878                     if (mNavigationBar.isAlive()) {
2879                         return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2880                     }
2881                 }
2882                 mNavigationBar = win;
2883                 mNavigationBarController.setWindow(win);
2884                 if (DEBUG_LAYOUT) Slog.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
2885                 break;
2886             case TYPE_NAVIGATION_BAR_PANEL:
2887             case TYPE_STATUS_BAR_PANEL:
2888             case TYPE_STATUS_BAR_SUB_PANEL:
2889             case TYPE_VOICE_INTERACTION_STARTING:
2890                 mContext.enforceCallingOrSelfPermission(
2891                         android.Manifest.permission.STATUS_BAR_SERVICE,
2892                         "PhoneWindowManager");
2893                 break;
2894             case TYPE_KEYGUARD_SCRIM:
2895                 if (mKeyguardScrim != null) {
2896                     return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
2897                 }
2898                 mKeyguardScrim = win;
2899                 break;
2900         }
2901         return WindowManagerGlobal.ADD_OKAY;
2902     }
2903
2904     /** {@inheritDoc} */
2905     @Override
2906     public void removeWindowLw(WindowState win) {
2907         if (mStatusBar == win) {
2908             mStatusBar = null;
2909             mStatusBarController.setWindow(null);
2910             mKeyguardDelegate.showScrim();
2911         } else if (mKeyguardScrim == win) {
2912             Log.v(TAG, "Removing keyguard scrim");
2913             mKeyguardScrim = null;
2914         } if (mNavigationBar == win) {
2915             mNavigationBar = null;
2916             mNavigationBarController.setWindow(null);
2917         }
2918     }
2919
2920     static final boolean PRINT_ANIM = false;
2921
2922     /** {@inheritDoc} */
2923     @Override
2924     public int selectAnimationLw(WindowState win, int transit) {
2925         if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
2926               + ": transit=" + transit);
2927         if (win == mStatusBar) {
2928             boolean isKeyguard = (win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
2929             if (transit == TRANSIT_EXIT
2930                     || transit == TRANSIT_HIDE) {
2931                 return isKeyguard ? -1 : R.anim.dock_top_exit;
2932             } else if (transit == TRANSIT_ENTER
2933                     || transit == TRANSIT_SHOW) {
2934                 return isKeyguard ? -1 : R.anim.dock_top_enter;
2935             }
2936         } else if (win == mNavigationBar) {
2937             if (win.getAttrs().windowAnimations != 0) {
2938                 return 0;
2939             }
2940             // This can be on either the bottom or the right.
2941             if (mNavigationBarOnBottom) {
2942                 if (transit == TRANSIT_EXIT
2943                         || transit == TRANSIT_HIDE) {
2944                     return R.anim.dock_bottom_exit;
2945                 } else if (transit == TRANSIT_ENTER
2946                         || transit == TRANSIT_SHOW) {
2947                     return R.anim.dock_bottom_enter;
2948                 }
2949             } else {
2950                 if (transit == TRANSIT_EXIT
2951                         || transit == TRANSIT_HIDE) {
2952                     return R.anim.dock_right_exit;
2953                 } else if (transit == TRANSIT_ENTER
2954                         || transit == TRANSIT_SHOW) {
2955                     return R.anim.dock_right_enter;
2956                 }
2957             }
2958         } else if (win.getAttrs().type == TYPE_DOCK_DIVIDER) {
2959             return selectDockedDividerAnimationLw(win, transit);
2960         }
2961
2962         if (transit == TRANSIT_PREVIEW_DONE) {
2963             if (win.hasAppShownWindows()) {
2964                 if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
2965                 return com.android.internal.R.anim.app_starting_exit;
2966             }
2967         } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
2968                 && transit == TRANSIT_ENTER) {
2969             // Special case: we are animating in a dream, while the keyguard
2970             // is shown.  We don't want an animation on the dream, because
2971             // we need it shown immediately with the keyguard animating away
2972             // to reveal it.
2973             return -1;
2974         }
2975
2976         return 0;
2977     }
2978
2979     private int selectDockedDividerAnimationLw(WindowState win, int transit) {
2980         int insets = mWindowManagerFuncs.getDockedDividerInsetsLw();
2981
2982         // If the divider is behind the navigation bar, don't animate.
2983         final Rect frame = win.getFrameLw();
2984         final boolean behindNavBar = mNavigationBar != null
2985                 && ((mNavigationBarOnBottom
2986                         && frame.top + insets >= mNavigationBar.getFrameLw().top)
2987                 || (!mNavigationBarOnBottom
2988                         && frame.left + insets >= mNavigationBar.getFrameLw().left));
2989         final boolean landscape = frame.height() > frame.width();
2990         final boolean offscreenLandscape = landscape && (frame.right - insets <= 0
2991                 || frame.left + insets >= win.getDisplayFrameLw().right);
2992         final boolean offscreenPortrait = !landscape && (frame.top - insets <= 0
2993                 || frame.bottom + insets >= win.getDisplayFrameLw().bottom);
2994         final boolean offscreen = offscreenLandscape || offscreenPortrait;
2995         if (behindNavBar || offscreen) {
2996             return 0;
2997         }
2998         if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) {
2999             return R.anim.fade_in;
3000         } else if (transit == TRANSIT_EXIT) {
3001             return R.anim.fade_out;
3002         } else {
3003             return 0;
3004         }
3005     }
3006
3007     @Override
3008     public void selectRotationAnimationLw(int anim[]) {
3009         if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
3010                 + mTopFullscreenOpaqueWindowState + " rotationAnimation="
3011                 + (mTopFullscreenOpaqueWindowState == null ?
3012                         "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
3013         if (mTopFullscreenOpaqueWindowState != null && mTopIsFullscreen) {
3014             switch (mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation) {
3015                 case ROTATION_ANIMATION_CROSSFADE:
3016                     anim[0] = R.anim.rotation_animation_xfade_exit;
3017                     anim[1] = R.anim.rotation_animation_enter;
3018                     break;
3019                 case ROTATION_ANIMATION_JUMPCUT:
3020                     anim[0] = R.anim.rotation_animation_jump_exit;
3021                     anim[1] = R.anim.rotation_animation_enter;
3022                     break;
3023                 case ROTATION_ANIMATION_ROTATE:
3024                 default:
3025                     anim[0] = anim[1] = 0;
3026                     break;
3027             }
3028         } else {
3029             anim[0] = anim[1] = 0;
3030         }
3031     }
3032
3033     @Override
3034     public boolean validateRotationAnimationLw(int exitAnimId, int enterAnimId,
3035             boolean forceDefault) {
3036         switch (exitAnimId) {
3037             case R.anim.rotation_animation_xfade_exit:
3038             case R.anim.rotation_animation_jump_exit:
3039                 // These are the only cases that matter.
3040                 if (forceDefault) {
3041                     return false;
3042                 }
3043                 int anim[] = new int[2];
3044                 selectRotationAnimationLw(anim);
3045                 return (exitAnimId == anim[0] && enterAnimId == anim[1]);
3046             default:
3047                 return true;
3048         }
3049     }
3050
3051     @Override
3052     public Animation createForceHideEnterAnimation(boolean onWallpaper,
3053             boolean goingToNotificationShade) {
3054         if (goingToNotificationShade) {
3055             return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_behind_enter_fade_in);
3056         }
3057
3058         AnimationSet set = (AnimationSet) AnimationUtils.loadAnimation(mContext, onWallpaper ?
3059                     R.anim.lock_screen_behind_enter_wallpaper :
3060                     R.anim.lock_screen_behind_enter);
3061
3062         // TODO: Use XML interpolators when we have log interpolators available in XML.
3063         final List<Animation> animations = set.getAnimations();
3064         for (int i = animations.size() - 1; i >= 0; --i) {
3065             animations.get(i).setInterpolator(mLogDecelerateInterpolator);
3066         }
3067
3068         return set;
3069     }
3070
3071
3072     @Override
3073     public Animation createForceHideWallpaperExitAnimation(boolean goingToNotificationShade) {
3074         if (goingToNotificationShade) {
3075             return null;
3076         } else {
3077             return AnimationUtils.loadAnimation(mContext, R.anim.lock_screen_wallpaper_exit);
3078         }
3079     }
3080
3081     private static void awakenDreams() {
3082         IDreamManager dreamManager = getDreamManager();
3083         if (dreamManager != null) {
3084             try {
3085                 dreamManager.awaken();
3086             } catch (RemoteException e) {
3087                 // fine, stay asleep then
3088             }
3089         }
3090     }
3091
3092     static IDreamManager getDreamManager() {
3093         return IDreamManager.Stub.asInterface(
3094                 ServiceManager.checkService(DreamService.DREAM_SERVICE));
3095     }
3096
3097     TelecomManager getTelecommService() {
3098         return (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
3099     }
3100
3101     static IAudioService getAudioService() {
3102         IAudioService audioService = IAudioService.Stub.asInterface(
3103                 ServiceManager.checkService(Context.AUDIO_SERVICE));
3104         if (audioService == null) {
3105             Log.w(TAG, "Unable to find IAudioService interface.");
3106         }
3107         return audioService;
3108     }
3109
3110     boolean keyguardOn() {
3111         return isKeyguardShowingAndNotOccluded() || inKeyguardRestrictedKeyInputMode();
3112     }
3113
3114     private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
3115             WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
3116             WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
3117         };
3118
3119     /** {@inheritDoc} */
3120     @Override
3121     public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
3122         final boolean keyguardOn = keyguardOn();
3123         final int keyCode = event.getKeyCode();
3124         final int repeatCount = event.getRepeatCount();
3125         final int metaState = event.getMetaState();
3126         final int flags = event.getFlags();
3127         final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
3128         final boolean canceled = event.isCanceled();
3129         final boolean longPress = (flags & KeyEvent.FLAG_LONG_PRESS) != 0;
3130         final boolean virtualKey = event.getDeviceId() == KeyCharacterMap.VIRTUAL_KEYBOARD;
3131
3132         if (DEBUG_INPUT) {
3133             Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
3134                     + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
3135                     + " canceled=" + canceled);
3136         }
3137
3138         // If the boot mode is power off alarm, we should not dispatch the several physical keys
3139         // in power off alarm UI to avoid pausing power off alarm UI.
3140         boolean isAlarmBoot = SystemProperties.getBoolean("ro.alarm_boot", false);
3141         if (isAlarmBoot && (keyCode == KeyEvent.KEYCODE_HOME
3142                 || keyCode == KeyEvent.KEYCODE_SEARCH
3143                 || keyCode == KeyEvent.KEYCODE_MENU
3144                 || keyCode == KeyEvent.KEYCODE_APP_SWITCH)) {
3145             return -1;
3146         }
3147
3148         // If we think we might have a volume down & power key chord on the way
3149         // but we're not sure, then tell the dispatcher to wait a little while and
3150         // try again later before dispatching.
3151         if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
3152             if (mScreenshotChordVolumeDownKeyTriggered && !mScreenshotChordPowerKeyTriggered) {
3153                 final long now = SystemClock.uptimeMillis();
3154                 final long timeoutTime = mScreenshotChordVolumeDownKeyTime
3155                         + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
3156                 if (now < timeoutTime) {
3157                     return timeoutTime - now;
3158                 }
3159             }
3160             if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
3161                     && mScreenshotChordVolumeDownKeyConsumed) {
3162                 if (!down) {
3163                     mScreenshotChordVolumeDownKeyConsumed = false;
3164                 }
3165                 return -1;
3166             }
3167         }
3168
3169         // Cancel any pending meta actions if we see any other keys being pressed between the down
3170         // of the meta key and its corresponding up.
3171         if (mPendingMetaAction && !KeyEvent.isMetaKey(keyCode)) {
3172             mPendingMetaAction = false;
3173         }
3174         // Any key that is not Alt or Meta cancels Caps Lock combo tracking.
3175         if (mPendingCapsLockToggle && !KeyEvent.isMetaKey(keyCode) && !KeyEvent.isAltKey(keyCode)) {
3176             mPendingCapsLockToggle = false;
3177         }
3178
3179         // First we always handle the home key here, so applications
3180         // can never break it, although if keyguard is on, we do let
3181         // it handle it, because that gives us the correct 5 second
3182         // timeout.
3183         if (keyCode == KeyEvent.KEYCODE_HOME) {
3184
3185             // If we have released the home key, and didn't do anything else
3186             // while it was pressed, then it is time to go home!
3187             if (!down && mHomePressed) {
3188                 if (mDoubleTapOnHomeBehavior != KEY_ACTION_APP_SWITCH) {
3189                     cancelPreloadRecentApps();
3190                 }
3191
3192                 mHomePressed = false;
3193                 if (mHomeConsumed) {
3194                     mHomeConsumed = false;
3195                     return -1;
3196                 }
3197
3198                 if (canceled) {
3199                     Log.i(TAG, "Ignoring HOME; event canceled.");
3200                     return -1;
3201                 }
3202
3203                 // If an incoming call is ringing, HOME is totally disabled.
3204                 // (The user is already on the InCallUI at this point,
3205                 // and his ONLY options are to answer or reject the call.)
3206                 TelecomManager telecomManager = getTelecommService();
3207                 if (telecomManager != null && telecomManager.isRinging()) {
3208                     Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
3209                     return -1;
3210                 }
3211
3212                 // Delay handling home if a double-tap is possible.
3213                 if (mDoubleTapOnHomeBehavior != KEY_ACTION_NOTHING) {
3214                     mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable); // just in case
3215                     mHomeDoubleTapPending = true;
3216                     mHandler.postDelayed(mHomeDoubleTapTimeoutRunnable,
3217                             ViewConfiguration.getDoubleTapTimeout());
3218                     return -1;
3219                 }
3220
3221                 handleShortPressOnHome();
3222                 return -1;
3223             }
3224
3225             // If a system window has focus, then it doesn't make sense
3226             // right now to interact with applications.
3227             WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
3228             if (attrs != null) {
3229                 final int type = attrs.type;
3230                 if (type == WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM
3231                         || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG
3232                         || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
3233                     // the "app" is keyguard, so give it the key
3234                     return 0;
3235                 }
3236                 final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
3237                 for (int i=0; i<typeCount; i++) {
3238                     if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
3239                         // don't do anything, but also don't pass it to the app
3240                         return -1;
3241                     }
3242                 }
3243             }
3244
3245             // Remember that home is pressed and handle special actions.
3246             if (repeatCount == 0) {
3247                 mHomePressed = true;
3248                 if (mHomeDoubleTapPending) {
3249                     mHomeDoubleTapPending = false;
3250                     mHandler.removeCallbacks(mHomeDoubleTapTimeoutRunnable);
3251                     performKeyAction(mDoubleTapOnHomeBehavior, event);
3252                     mHomeConsumed = true;
3253                 } else if (mLongPressOnHomeBehavior == KEY_ACTION_APP_SWITCH
3254                         || mDoubleTapOnHomeBehavior == KEY_ACTION_APP_SWITCH) {
3255                     preloadRecentApps();
3256                 }
3257             } else if (longPress) {
3258                 if (!keyguardOn && !mHomeConsumed &&
3259                         mLongPressOnHomeBehavior != KEY_ACTION_NOTHING) {
3260                     if (mLongPressOnHomeBehavior != KEY_ACTION_APP_SWITCH) {
3261                         cancelPreloadRecentApps();
3262                     }
3263                     mHomePressed = true;
3264                     performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3265                     performKeyAction(mLongPressOnHomeBehavior, event);
3266                     mHomeConsumed = true;
3267                 }
3268             }
3269             return -1;
3270         } else if (keyCode == KeyEvent.KEYCODE_MENU) {
3271             // Hijack modified menu keys for debugging features
3272             final int chordBug = KeyEvent.META_SHIFT_ON;
3273             if (virtualKey || keyguardOn) {
3274                 // Let the app handle the key
3275                 return 0;
3276             }
3277
3278             if (down) {
3279                 if (mPressOnMenuBehavior == KEY_ACTION_APP_SWITCH
3280                         || mLongPressOnMenuBehavior == KEY_ACTION_APP_SWITCH) {
3281                     preloadRecentApps();
3282                 }
3283                 if (repeatCount == 0) {
3284                     mMenuPressed = true;
3285                     if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
3286                         Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
3287                         mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
3288                                 null, null, null, 0, null, null);
3289                         return -1;
3290                     } else if (SHOW_PROCESSES_ON_ALT_MENU &&
3291                             (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
3292                         Intent service = new Intent();
3293                         service.setClassName(mContext, "com.android.server.LoadAverageService");
3294                         ContentResolver res = mContext.getContentResolver();
3295                         boolean shown = Settings.Global.getInt(
3296                                 res, Settings.Global.SHOW_PROCESSES, 0) != 0;
3297                         if (!shown) {
3298                             mContext.startService(service);
3299                         } else {
3300                             mContext.stopService(service);
3301                         }
3302                         Settings.Global.putInt(
3303                                 res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
3304                         return -1;
3305                      }
3306                 } else if (longPress) {
3307                     if (!keyguardOn && mLongPressOnMenuBehavior != KEY_ACTION_NOTHING) {
3308                         if (mLongPressOnMenuBehavior != KEY_ACTION_APP_SWITCH) {
3309                             cancelPreloadRecentApps();
3310                         }
3311                         performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3312                         performKeyAction(mLongPressOnMenuBehavior, event);
3313                         mMenuPressed = false;
3314                         return -1;
3315                     }
3316                 }
3317             }
3318             if (!down && mMenuPressed) {
3319                 if (mPressOnMenuBehavior != KEY_ACTION_APP_SWITCH) {
3320                     cancelPreloadRecentApps();
3321                 }
3322                 mMenuPressed = false;
3323                 if (!canceled) {
3324                     performKeyAction(mPressOnMenuBehavior, event);
3325                 }
3326             }
3327             return -1;
3328         } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
3329             if (down) {
3330                 if (repeatCount == 0) {
3331                     mSearchKeyShortcutPending = true;
3332                     mConsumeSearchKeyUp = false;
3333                 }
3334             } else {
3335                 mSearchKeyShortcutPending = false;
3336                 if (mConsumeSearchKeyUp) {
3337                     mConsumeSearchKeyUp = false;
3338                     return -1;
3339                 }
3340             }
3341             return 0;
3342         } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
3343             if (down) {
3344                 if (mPressOnAppSwitchBehavior == KEY_ACTION_APP_SWITCH
3345                         || mLongPressOnAppSwitchBehavior == KEY_ACTION_APP_SWITCH) {
3346                     preloadRecentApps();
3347                 }
3348                 if (repeatCount == 0) {
3349                     mAppSwitchLongPressed = false;
3350                 } else if (longPress) {
3351                     if (!keyguardOn && mLongPressOnAppSwitchBehavior != KEY_ACTION_NOTHING) {
3352                         if (mLongPressOnAppSwitchBehavior != KEY_ACTION_APP_SWITCH) {
3353                             cancelPreloadRecentApps();
3354                         }
3355                         performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3356                         performKeyAction(mLongPressOnAppSwitchBehavior, event);
3357                         mAppSwitchLongPressed = true;
3358                    }
3359                 }
3360             } else {
3361                 if (mAppSwitchLongPressed) {
3362                     mAppSwitchLongPressed = false;
3363                 } else {
3364                     if (mPressOnAppSwitchBehavior != KEY_ACTION_APP_SWITCH) {
3365                         cancelPreloadRecentApps();
3366                     }
3367                     if (!canceled) {
3368                         performKeyAction(mPressOnAppSwitchBehavior, event);
3369                     }
3370                 }
3371             }
3372             return -1;
3373         } else if (keyCode == KeyEvent.KEYCODE_N && event.isMetaPressed()) {
3374             if (down) {
3375                 IStatusBarService service = getStatusBarService();
3376                 if (service != null) {
3377                     try {
3378                         service.expandNotificationsPanel();
3379                     } catch (RemoteException e) {
3380                         // do nothing.
3381                     }
3382                 }
3383             }
3384         } else if (keyCode == KeyEvent.KEYCODE_S && event.isMetaPressed()
3385                 && event.isCtrlPressed()) {
3386             if (down && repeatCount == 0) {
3387                 int type = event.isShiftPressed() ? TAKE_SCREENSHOT_SELECTED_REGION
3388                         : TAKE_SCREENSHOT_FULLSCREEN;
3389                 mScreenshotRunnable.setScreenshotType(type);
3390                 mHandler.post(mScreenshotRunnable);
3391                 return -1;
3392             }
3393         } else if (keyCode == KeyEvent.KEYCODE_SLASH && event.isMetaPressed()) {
3394             if (down && repeatCount == 0 && !isKeyguardLocked()) {
3395                 toggleKeyboardShortcutsMenu(event.getDeviceId());
3396             }
3397         } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
3398             if (down) {
3399                 if (mPressOnAssistBehavior == KEY_ACTION_APP_SWITCH
3400                         || mLongPressOnAssistBehavior == KEY_ACTION_APP_SWITCH) {
3401                     preloadRecentApps();
3402                 }
3403                 if (repeatCount == 0) {
3404                     mAssistKeyLongPressed = false;
3405                 } else if (longPress) {
3406                     if (!keyguardOn && mLongPressOnAssistBehavior != KEY_ACTION_NOTHING) {
3407                         if (mLongPressOnAssistBehavior != KEY_ACTION_APP_SWITCH) {
3408                             cancelPreloadRecentApps();
3409                         }
3410                         performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3411                         performKeyAction(mLongPressOnAssistBehavior, event);
3412                         mAssistKeyLongPressed = true;
3413                     }
3414                 }
3415             } else {
3416                 if (mAssistKeyLongPressed) {
3417                     mAssistKeyLongPressed = false;
3418                 } else {
3419                     if (mPressOnAssistBehavior != KEY_ACTION_APP_SWITCH) {
3420                         cancelPreloadRecentApps();
3421                     }
3422                     if (!canceled) {
3423                         performKeyAction(mPressOnAssistBehavior, event);
3424                     }
3425                 }
3426             }
3427             return -1;
3428         } else if (keyCode == KeyEvent.KEYCODE_VOICE_ASSIST) {
3429             if (!down) {
3430                 Intent voiceIntent;
3431                 if (!keyguardOn) {
3432                     voiceIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3433                 } else {
3434                     IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
3435                             ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
3436                     if (dic != null) {
3437                         try {
3438                             dic.exitIdle("voice-search");
3439                         } catch (RemoteException e) {
3440                         }
3441                     }
3442                     voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
3443                     voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, true);
3444                 }
3445                 startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
3446             }
3447         } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
3448             if (down && repeatCount == 0) {
3449                 mScreenshotRunnable.setScreenshotType(TAKE_SCREENSHOT_FULLSCREEN);
3450                 mHandler.post(mScreenshotRunnable);
3451             }
3452             return -1;
3453         } else if (keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP
3454                 || keyCode == KeyEvent.KEYCODE_BRIGHTNESS_DOWN) {
3455             if (down) {
3456                 int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1;
3457
3458                 // Disable autobrightness if it's on
3459                 int auto = Settings.System.getIntForUser(
3460                         mContext.getContentResolver(),
3461                         Settings.System.SCREEN_BRIGHTNESS_MODE,
3462                         Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3463                         UserHandle.USER_CURRENT_OR_SELF);
3464                 if (auto != 0) {
3465                     Settings.System.putIntForUser(mContext.getContentResolver(),
3466                             Settings.System.SCREEN_BRIGHTNESS_MODE,
3467                             Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
3468                             UserHandle.USER_CURRENT_OR_SELF);
3469                 }
3470
3471                 int min = mPowerManager.getMinimumScreenBrightnessSetting();
3472                 int max = mPowerManager.getMaximumScreenBrightnessSetting();
3473                 int step = (max - min + BRIGHTNESS_STEPS - 1) / BRIGHTNESS_STEPS * direction;
3474                 int brightness = Settings.System.getIntForUser(mContext.getContentResolver(),
3475                         Settings.System.SCREEN_BRIGHTNESS,
3476                         mPowerManager.getDefaultScreenBrightnessSetting(),
3477                         UserHandle.USER_CURRENT_OR_SELF);
3478                 brightness += step;
3479                 // Make sure we don't go beyond the limits.
3480                 brightness = Math.min(max, brightness);
3481                 brightness = Math.max(min, brightness);
3482
3483                 Settings.System.putIntForUser(mContext.getContentResolver(),
3484                         Settings.System.SCREEN_BRIGHTNESS, brightness,
3485                         UserHandle.USER_CURRENT_OR_SELF);
3486                 startActivityAsUser(new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG),
3487                         UserHandle.CURRENT_OR_SELF);
3488             }
3489             return -1;
3490         } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP
3491                 || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
3492                 || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
3493             if (mUseTvRouting) {
3494                 // On TVs volume keys never go to the foreground app.
3495                 dispatchDirectAudioEvent(event);
3496                 return -1;
3497             }
3498         }
3499
3500         // Toggle Caps Lock on META-ALT.
3501         boolean actionTriggered = false;
3502         if (KeyEvent.isModifierKey(keyCode)) {
3503             if (!mPendingCapsLockToggle) {
3504                 // Start tracking meta state for combo.
3505                 mInitialMetaState = mMetaState;
3506                 mPendingCapsLockToggle = true;
3507             } else if (event.getAction() == KeyEvent.ACTION_UP) {
3508                 int altOnMask = mMetaState & KeyEvent.META_ALT_MASK;
3509                 int metaOnMask = mMetaState & KeyEvent.META_META_MASK;
3510
3511                 // Check for Caps Lock toggle
3512                 if ((metaOnMask != 0) && (altOnMask != 0)) {
3513                     // Check if nothing else is pressed
3514                     if (mInitialMetaState == (mMetaState ^ (altOnMask | metaOnMask))) {
3515                         // Handle Caps Lock Toggle
3516                         mInputManagerInternal.toggleCapsLock(event.getDeviceId());
3517                         actionTriggered = true;
3518                     }
3519                 }
3520
3521                 // Always stop tracking when key goes up.
3522                 mPendingCapsLockToggle = false;
3523             }
3524         }
3525         // Store current meta state to be able to evaluate it later.
3526         mMetaState = metaState;
3527
3528         if (actionTriggered) {
3529             return -1;
3530         }
3531
3532         if (KeyEvent.isMetaKey(keyCode)) {
3533             if (down) {
3534                 mPendingMetaAction = true;
3535             } else if (mPendingMetaAction) {
3536                 launchAssistAction(Intent.EXTRA_ASSIST_INPUT_HINT_KEYBOARD, event.getDeviceId());
3537             }
3538             return -1;
3539         }
3540
3541         // Shortcuts are invoked through Search+key, so intercept those here
3542         // Any printing key that is chorded with Search should be consumed
3543         // even if no shortcut was invoked.  This prevents text from being
3544         // inadvertently inserted when using a keyboard that has built-in macro
3545         // shortcut keys (that emit Search+x) and some of them are not registered.
3546         if (mSearchKeyShortcutPending) {
3547             final KeyCharacterMap kcm = event.getKeyCharacterMap();
3548             if (kcm.isPrintingKey(keyCode)) {
3549                 mConsumeSearchKeyUp = true;
3550                 mSearchKeyShortcutPending = false;
3551                 if (down && repeatCount == 0 && !keyguardOn) {
3552                     Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
3553                     if (shortcutIntent != null) {
3554                         shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3555                         try {
3556                             startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3557                             dismissKeyboardShortcutsMenu();
3558                         } catch (ActivityNotFoundException ex) {
3559                             Slog.w(TAG, "Dropping shortcut key combination because "
3560                                     + "the activity to which it is registered was not found: "
3561                                     + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
3562                         }
3563                     } else {
3564                         Slog.i(TAG, "Dropping unregistered shortcut key combination: "
3565                                 + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
3566                     }
3567                 }
3568                 return -1;
3569             }
3570         }
3571
3572         // Invoke shortcuts using Meta.
3573         if (down && repeatCount == 0 && !keyguardOn
3574                 && (metaState & KeyEvent.META_META_ON) != 0) {
3575             final KeyCharacterMap kcm = event.getKeyCharacterMap();
3576             if (kcm.isPrintingKey(keyCode)) {
3577                 Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
3578                         metaState & ~(KeyEvent.META_META_ON
3579                                 | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
3580                 if (shortcutIntent != null) {
3581                     shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3582                     try {
3583                         startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
3584                         dismissKeyboardShortcutsMenu();
3585                     } catch (ActivityNotFoundException ex) {
3586                         Slog.w(TAG, "Dropping shortcut key combination because "
3587                                 + "the activity to which it is registered was not found: "
3588                                 + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
3589                     }
3590                     return -1;
3591                 }
3592             }
3593         }
3594
3595         // Handle application launch keys.
3596         if (down && repeatCount == 0 && !keyguardOn) {
3597             String category = sApplicationLaunchKeyCategories.get(keyCode);
3598             if (category != null) {
3599                 Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
3600                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3601                 try {
3602                     startActivityAsUser(intent, UserHandle.CURRENT);
3603                     dismissKeyboardShortcutsMenu();
3604                 } catch (ActivityNotFoundException ex) {
3605                     Slog.w(TAG, "Dropping application launch key because "
3606                             + "the activity to which it is registered was not found: "
3607                             + "keyCode=" + keyCode + ", category=" + category, ex);
3608                 }
3609                 return -1;
3610             }
3611         }
3612
3613         // Display task switcher for ALT-TAB.
3614         if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
3615             if (mRecentAppsHeldModifiers == 0 && !keyguardOn && isUserSetupComplete()) {
3616                 final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
3617                 if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)) {
3618                     mRecentAppsHeldModifiers = shiftlessModifiers;
3619                     showRecentApps(true, false);
3620                     return -1;
3621                 }
3622             }
3623         } else if (!down && mRecentAppsHeldModifiers != 0
3624                 && (metaState & mRecentAppsHeldModifiers) == 0) {
3625             mRecentAppsHeldModifiers = 0;
3626             hideRecentApps(true, false);
3627         }
3628
3629         // Handle input method switching.
3630         if (down && repeatCount == 0
3631                 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3632                         || (keyCode == KeyEvent.KEYCODE_SPACE
3633                                 && (metaState & KeyEvent.META_META_MASK) != 0))) {
3634             final boolean forwardDirection = (metaState & KeyEvent.META_SHIFT_MASK) == 0;
3635             mWindowManagerFuncs.switchInputMethod(forwardDirection);
3636             return -1;
3637         }
3638         if (mLanguageSwitchKeyPressed && !down
3639                 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
3640                         || keyCode == KeyEvent.KEYCODE_SPACE)) {
3641             mLanguageSwitchKeyPressed = false;
3642             return -1;
3643         }
3644
3645         if (isValidGlobalKey(keyCode)
3646                 && mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
3647             return -1;
3648         }
3649
3650         if (down) {
3651             long shortcutCode = keyCode;
3652             if (event.isCtrlPressed()) {
3653                 shortcutCode |= ((long) KeyEvent.META_CTRL_ON) << Integer.SIZE;
3654             }
3655
3656             if (event.isAltPressed()) {
3657                 shortcutCode |= ((long) KeyEvent.META_ALT_ON) << Integer.SIZE;
3658             }
3659
3660             if (event.isShiftPressed()) {
3661                 shortcutCode |= ((long) KeyEvent.META_SHIFT_ON) << Integer.SIZE;
3662             }
3663
3664             if (event.isMetaPressed()) {
3665                 shortcutCode |= ((long) KeyEvent.META_META_ON) << Integer.SIZE;
3666             }
3667
3668             IShortcutService shortcutService = mShortcutKeyServices.get(shortcutCode);
3669             if (shortcutService != null) {
3670                 try {
3671                     if (isUserSetupComplete()) {
3672                         shortcutService.notifyShortcutKeyPressed(shortcutCode);
3673                     }
3674                 } catch (RemoteException e) {
3675                     mShortcutKeyServices.delete(shortcutCode);
3676                 }
3677                 return -1;
3678             }
3679         }
3680
3681         // Reserve all the META modifier combos for system behavior
3682         if ((metaState & KeyEvent.META_META_ON) != 0) {
3683             return -1;
3684         }
3685
3686         // Let the application handle the key.
3687         return 0;
3688     }
3689
3690     /** {@inheritDoc} */
3691     @Override
3692     public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
3693         // Note: This method is only called if the initial down was unhandled.
3694         if (DEBUG_INPUT) {
3695             Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
3696                     + ", flags=" + event.getFlags()
3697                     + ", keyCode=" + event.getKeyCode()
3698                     + ", scanCode=" + event.getScanCode()
3699                     + ", metaState=" + event.getMetaState()
3700                     + ", repeatCount=" + event.getRepeatCount()
3701                     + ", policyFlags=" + policyFlags);
3702         }
3703
3704         KeyEvent fallbackEvent = null;
3705         if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3706             final KeyCharacterMap kcm = event.getKeyCharacterMap();
3707             final int keyCode = event.getKeyCode();
3708             final int metaState = event.getMetaState();
3709             final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
3710                     && event.getRepeatCount() == 0;
3711
3712             // Check for fallback actions specified by the key character map.
3713             final FallbackAction fallbackAction;
3714             if (initialDown) {
3715                 fallbackAction = kcm.getFallbackAction(keyCode, metaState);
3716             } else {
3717                 fallbackAction = mFallbackActions.get(keyCode);
3718             }
3719
3720             if (fallbackAction != null) {
3721                 if (DEBUG_INPUT) {
3722                     Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
3723                             + " metaState=" + Integer.toHexString(fallbackAction.metaState));
3724                 }
3725
3726                 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
3727                 fallbackEvent = KeyEvent.obtain(
3728                         event.getDownTime(), event.getEventTime(),
3729                         event.getAction(), fallbackAction.keyCode,
3730                         event.getRepeatCount(), fallbackAction.metaState,
3731                         event.getDeviceId(), event.getScanCode(),
3732                         flags, event.getSource(), null);
3733
3734                 if (!interceptFallback(win, fallbackEvent, policyFlags)) {
3735                     fallbackEvent.recycle();
3736                     fallbackEvent = null;
3737                 }
3738
3739                 if (initialDown) {
3740                     mFallbackActions.put(keyCode, fallbackAction);
3741                 } else if (event.getAction() == KeyEvent.ACTION_UP) {
3742                     mFallbackActions.remove(keyCode);
3743                     fallbackAction.recycle();
3744                 }
3745             }
3746         }
3747
3748         if (DEBUG_INPUT) {
3749             if (fallbackEvent == null) {
3750                 Slog.d(TAG, "No fallback.");
3751             } else {
3752                 Slog.d(TAG, "Performing fallback: " + fallbackEvent);
3753             }
3754         }
3755         return fallbackEvent;
3756     }
3757
3758     private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
3759         int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags);
3760         if ((actions & ACTION_PASS_TO_USER) != 0) {
3761             long delayMillis = interceptKeyBeforeDispatching(
3762                     win, fallbackEvent, policyFlags);
3763             if (delayMillis == 0) {
3764                 return true;
3765             }
3766         }
3767         return false;
3768     }
3769
3770     @Override
3771     public void registerShortcutKey(long shortcutCode, IShortcutService shortcutService)
3772             throws RemoteException {
3773         synchronized (mLock) {
3774             IShortcutService service = mShortcutKeyServices.get(shortcutCode);
3775             if (service != null && service.asBinder().pingBinder()) {
3776                 throw new RemoteException("Key already exists.");
3777             }
3778
3779             mShortcutKeyServices.put(shortcutCode, shortcutService);
3780         }
3781     }
3782
3783     private void launchAssistLongPressAction() {
3784         performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
3785         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3786
3787         // launch the search activity
3788         Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
3789         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3790         try {
3791             // TODO: This only stops the factory-installed search manager.
3792             // Need to formalize an API to handle others
3793             SearchManager searchManager = getSearchManager();
3794             if (searchManager != null) {
3795                 searchManager.stopSearch();
3796             }
3797             startActivityAsUser(intent, UserHandle.CURRENT);
3798         } catch (ActivityNotFoundException e) {
3799             Slog.w(TAG, "No activity to handle assist long press action.", e);
3800         }
3801     }
3802
3803     private void launchAssistAction(String hint, int deviceId) {
3804         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
3805         if (!isUserSetupComplete()) {
3806             // Disable opening assist window during setup
3807             return;
3808         }
3809         Bundle args = null;
3810         if (deviceId > Integer.MIN_VALUE) {
3811             args = new Bundle();
3812             args.putInt(Intent.EXTRA_ASSIST_INPUT_DEVICE_ID, deviceId);
3813         }
3814         if ((mContext.getResources().getConfiguration().uiMode
3815                 & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION) {
3816             // On TV, use legacy handling until assistants are implemented in the proper way.
3817             ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
3818                     .launchLegacyAssist(hint, UserHandle.myUserId(), args);
3819         } else {
3820             if (hint != null) {
3821                 if (args == null) {
3822                     args = new Bundle();
3823                 }
3824                 args.putBoolean(hint, true);
3825             }
3826             StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
3827             if (statusbar != null) {
3828                 statusbar.startAssist(args);
3829             }
3830         }
3831     }
3832
3833     private void startActivityAsUser(Intent intent, UserHandle handle) {
3834         if (isUserSetupComplete()) {
3835             mContext.startActivityAsUser(intent, handle);
3836         } else {
3837             Slog.i(TAG, "Not starting activity because user setup is in progress: " + intent);
3838         }
3839     }
3840
3841     private SearchManager getSearchManager() {
3842         if (mSearchManager == null) {
3843             mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
3844         }
3845         return mSearchManager;
3846     }
3847
3848     private void preloadRecentApps() {
3849         mPreloadedRecentApps = true;
3850         StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
3851         if (statusbar != null) {
3852             statusbar.preloadRecentApps();
3853         }
3854     }
3855
3856     private void cancelPreloadRecentApps() {
3857         if (mPreloadedRecentApps) {
3858             mPreloadedRecentApps = false;
3859             StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
3860             if (statusbar != null) {
3861                 statusbar.cancelPreloadRecentApps();
3862             }
3863         }
3864     }
3865
3866     private void toggleRecentApps() {
3867         mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3868         StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
3869         if (statusbar != null) {
3870             statusbar.toggleRecentApps();
3871         }
3872     }
3873
3874     @Override
3875     public void showRecentApps(boolean fromHome) {
3876         mHandler.removeMessages(MSG_DISPATCH_SHOW_RECENTS);
3877         mHandler.obtainMessage(MSG_DISPATCH_SHOW_RECENTS, fromHome ? 1 : 0, 0).sendToTarget();
3878     }
3879
3880     private void showRecentApps(boolean triggeredFromAltTab, boolean fromHome) {
3881         mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3882         StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
3883         if (statusbar != null) {
3884             statusbar.showRecentApps(triggeredFromAltTab, fromHome);
3885         }
3886     }
3887
3888     private void toggleKeyboardShortcutsMenu(int deviceId) {
3889         StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
3890         if (statusbar != null) {
3891             statusbar.toggleKeyboardShortcutsMenu(deviceId);
3892         }
3893     }
3894
3895     private void dismissKeyboardShortcutsMenu() {
3896         StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
3897         if (statusbar != null) {
3898             statusbar.dismissKeyboardShortcutsMenu();
3899         }
3900     }
3901
3902     private void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHome) {
3903         mPreloadedRecentApps = false; // preloading no longer needs to be canceled
3904         StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
3905         if (statusbar != null) {
3906             statusbar.hideRecentApps(triggeredFromAltTab, triggeredFromHome);
3907         }
3908     }
3909
3910     void launchHomeFromHotKey() {
3911         launchHomeFromHotKey(true /* awakenFromDreams */, true /*respectKeyguard*/);
3912     }
3913
3914     /**
3915      * A home key -> launch home action was detected.  Take the appropriate action
3916      * given the situation with the keyguard.
3917      */
3918     void launchHomeFromHotKey(final boolean awakenFromDreams, final boolean respectKeyguard) {
3919         if (respectKeyguard) {
3920             if (isKeyguardShowingAndNotOccluded()) {
3921                 // don't launch home if keyguard showing
3922                 return;
3923             }
3924
3925             if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
3926                 // when in keyguard restricted mode, must first verify unlock
3927                 // before launching home
3928                 mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
3929                     @Override
3930                     public void onKeyguardExitResult(boolean success) {
3931                         if (success) {
3932                             try {
3933                                 ActivityManagerNative.getDefault().stopAppSwitches();
3934                             } catch (RemoteException e) {
3935                             }
3936                             sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3937                             startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3938                         }
3939                     }
3940                 });
3941                 return;
3942             }
3943         }
3944
3945         // no keyguard stuff to worry about, just launch home!
3946         try {
3947             ActivityManagerNative.getDefault().stopAppSwitches();
3948         } catch (RemoteException e) {
3949         }
3950         if (mRecentsVisible) {
3951             // Hide Recents and notify it to launch Home
3952             if (awakenFromDreams) {
3953                 awakenDreams();
3954             }
3955             hideRecentApps(false, true);
3956         } else {
3957             // Otherwise, just launch Home
3958             sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
3959             startDockOrHome(true /*fromHomeKey*/, awakenFromDreams);
3960         }
3961     }
3962
3963     private final Runnable mClearHideNavigationFlag = new Runnable() {
3964         @Override
3965         public void run() {
3966             synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3967                 // Clear flags.
3968                 mForceClearedSystemUiFlags &=
3969                         ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
3970             }
3971             mWindowManagerFuncs.reevaluateStatusBarVisibility();
3972         }
3973     };
3974
3975     /**
3976      * Input handler used while nav bar is hidden.  Captures any touch on the screen,
3977      * to determine when the nav bar should be shown and prevent applications from
3978      * receiving those touches.
3979      */
3980     final class HideNavInputEventReceiver extends InputEventReceiver {
3981         public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
3982             super(inputChannel, looper);
3983         }
3984
3985         @Override
3986         public void onInputEvent(InputEvent event) {
3987             boolean handled = false;
3988             try {
3989                 if (event instanceof MotionEvent
3990                         && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
3991                     final MotionEvent motionEvent = (MotionEvent)event;
3992                     if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
3993                         // When the user taps down, we re-show the nav bar.
3994                         boolean changed = false;
3995                         synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
3996                             if (mInputConsumer == null) {
3997                                 return;
3998                             }
3999                             // Any user activity always causes us to show the
4000                             // navigation controls, if they had been hidden.
4001                             // We also clear the low profile and only content
4002                             // flags so that tapping on the screen will atomically
4003                             // restore all currently hidden screen decorations.
4004                             int newVal = mResettingSystemUiFlags |
4005                                     View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4006                                     View.SYSTEM_UI_FLAG_LOW_PROFILE |
4007                                     View.SYSTEM_UI_FLAG_FULLSCREEN;
4008                             if (mResettingSystemUiFlags != newVal) {
4009                                 mResettingSystemUiFlags = newVal;
4010                                 changed = true;
4011                             }
4012                             // We don't allow the system's nav bar to be hidden
4013                             // again for 1 second, to prevent applications from
4014                             // spamming us and keeping it from being shown.
4015                             newVal = mForceClearedSystemUiFlags |
4016                                     View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
4017                             if (mForceClearedSystemUiFlags != newVal) {
4018                                 mForceClearedSystemUiFlags = newVal;
4019                                 changed = true;
4020                                 mHandler.postDelayed(mClearHideNavigationFlag, 1000);
4021                             }
4022                         }
4023                         if (changed) {
4024                             mWindowManagerFuncs.reevaluateStatusBarVisibility();
4025                         }
4026                     }
4027                 }
4028             } finally {
4029                 finishInputEvent(event, handled);
4030             }
4031         }
4032     }
4033     final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
4034             new InputEventReceiver.Factory() {
4035         @Override
4036         public InputEventReceiver createInputEventReceiver(
4037                 InputChannel inputChannel, Looper looper) {
4038             return new HideNavInputEventReceiver(inputChannel, looper);
4039         }
4040     };
4041
4042     @Override
4043     public int adjustSystemUiVisibilityLw(int visibility) {
4044         mStatusBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
4045         mNavigationBarController.adjustSystemUiVisibilityLw(mLastSystemUiFlags, visibility);
4046         mRecentsVisible = (visibility & View.RECENT_APPS_VISIBLE) > 0;
4047         mTvPictureInPictureVisible = (visibility & View.TV_PICTURE_IN_PICTURE_VISIBLE) > 0;
4048
4049         // Reset any bits in mForceClearingStatusBarVisibility that
4050         // are now clear.
4051         mResettingSystemUiFlags &= visibility;
4052         // Clear any bits in the new visibility that are currently being
4053         // force cleared, before reporting it.
4054         return visibility & ~mResettingSystemUiFlags
4055                 & ~mForceClearedSystemUiFlags;
4056     }
4057
4058     @Override
4059     public boolean getInsetHintLw(WindowManager.LayoutParams attrs, Rect taskBounds,
4060             int displayRotation, int displayWidth, int displayHeight, Rect outContentInsets,
4061             Rect outStableInsets, Rect outOutsets) {
4062         final int fl = PolicyControl.getWindowFlags(null, attrs);
4063         final int sysuiVis = PolicyControl.getSystemUiVisibility(null, attrs);
4064         final int systemUiVisibility = (sysuiVis | attrs.subtreeSystemUiVisibility);
4065
4066         final boolean useOutsets = outOutsets != null && shouldUseOutsets(attrs, fl);
4067         if (useOutsets) {
4068             int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
4069             if (outset > 0) {
4070                 if (displayRotation == Surface.ROTATION_0) {
4071                     outOutsets.bottom += outset;
4072                 } else if (displayRotation == Surface.ROTATION_90) {
4073                     outOutsets.right += outset;
4074                 } else if (displayRotation == Surface.ROTATION_180) {
4075                     outOutsets.top += outset;
4076                 } else if (displayRotation == Surface.ROTATION_270) {
4077                     outOutsets.left += outset;
4078                 }
4079             }
4080         }
4081
4082         if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
4083                 == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
4084             int availRight, availBottom;
4085             if (canHideNavigationBar() &&
4086                     (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
4087                 availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4088                 availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4089             } else {
4090                 availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
4091                 availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
4092             }
4093             if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
4094                 if ((fl & FLAG_FULLSCREEN) != 0) {
4095                     outContentInsets.set(mStableFullscreenLeft, mStableFullscreenTop,
4096                             availRight - mStableFullscreenRight,
4097                             availBottom - mStableFullscreenBottom);
4098                 } else {
4099                     outContentInsets.set(mStableLeft, mStableTop,
4100                             availRight - mStableRight, availBottom - mStableBottom);
4101                 }
4102             } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
4103                 outContentInsets.setEmpty();
4104             } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
4105                         | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
4106                 outContentInsets.set(mCurLeft, mCurTop,
4107                         availRight - mCurRight, availBottom - mCurBottom);
4108             } else {
4109                 outContentInsets.set(mCurLeft, mCurTop,
4110                         availRight - mCurRight, availBottom - mCurBottom);
4111             }
4112
4113             outStableInsets.set(mStableLeft, mStableTop,
4114                     availRight - mStableRight, availBottom - mStableBottom);
4115             if (taskBounds != null) {
4116                 calculateRelevantTaskInsets(taskBounds, outContentInsets,
4117                         displayWidth, displayHeight);
4118                 calculateRelevantTaskInsets(taskBounds, outStableInsets,
4119                         displayWidth, displayHeight);
4120             }
4121             return mForceShowSystemBars;
4122         }
4123         outContentInsets.setEmpty();
4124         outStableInsets.setEmpty();
4125         return mForceShowSystemBars;
4126     }
4127
4128     /**
4129      * For any given task bounds, the insets relevant for these bounds given the insets relevant
4130      * for the entire display.
4131      */
4132     private void calculateRelevantTaskInsets(Rect taskBounds, Rect inOutInsets, int displayWidth,
4133             int displayHeight) {
4134         mTmpRect.set(0, 0, displayWidth, displayHeight);
4135         mTmpRect.inset(inOutInsets);
4136         mTmpRect.intersect(taskBounds);
4137         int leftInset = mTmpRect.left - taskBounds.left;
4138         int topInset = mTmpRect.top - taskBounds.top;
4139         int rightInset = taskBounds.right - mTmpRect.right;
4140         int bottomInset = taskBounds.bottom - mTmpRect.bottom;
4141         inOutInsets.set(leftInset, topInset, rightInset, bottomInset);
4142     }
4143
4144     private boolean shouldUseOutsets(WindowManager.LayoutParams attrs, int fl) {
4145         return attrs.type == TYPE_WALLPAPER || (fl & (WindowManager.LayoutParams.FLAG_FULLSCREEN
4146                 | WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN)) != 0;
4147     }
4148
4149     /** {@inheritDoc} */
4150     @Override
4151     public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
4152                               int displayRotation, int uiMode) {
4153         mDisplayRotation = displayRotation;
4154         final int overscanLeft, overscanTop, overscanRight, overscanBottom;
4155         if (isDefaultDisplay) {
4156             switch (displayRotation) {
4157                 case Surface.ROTATION_90:
4158                     overscanLeft = mOverscanTop;
4159                     overscanTop = mOverscanRight;
4160                     overscanRight = mOverscanBottom;
4161                     overscanBottom = mOverscanLeft;
4162                     break;
4163                 case Surface.ROTATION_180:
4164                     overscanLeft = mOverscanRight;
4165                     overscanTop = mOverscanBottom;
4166                     overscanRight = mOverscanLeft;
4167                     overscanBottom = mOverscanTop;
4168                     break;
4169                 case Surface.ROTATION_270:
4170                     overscanLeft = mOverscanBottom;
4171                     overscanTop = mOverscanLeft;
4172                     overscanRight = mOverscanTop;
4173                     overscanBottom = mOverscanRight;
4174                     break;
4175                 default:
4176                     overscanLeft = mOverscanLeft;
4177                     overscanTop = mOverscanTop;
4178                     overscanRight = mOverscanRight;
4179                     overscanBottom = mOverscanBottom;
4180                     break;
4181             }
4182         } else {
4183             overscanLeft = 0;
4184             overscanTop = 0;
4185             overscanRight = 0;
4186             overscanBottom = 0;
4187         }
4188         mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
4189         mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
4190         mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
4191         mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
4192         mSystemLeft = 0;
4193         mSystemTop = 0;
4194         mSystemRight = displayWidth;
4195         mSystemBottom = displayHeight;
4196         mUnrestrictedScreenLeft = overscanLeft;
4197         mUnrestrictedScreenTop = overscanTop;
4198         mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
4199         mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
4200         mRestrictedScreenLeft = mUnrestrictedScreenLeft;
4201         mRestrictedScreenTop = mUnrestrictedScreenTop;
4202         mRestrictedScreenWidth = mSystemGestures.screenWidth = mUnrestrictedScreenWidth;
4203         mRestrictedScreenHeight = mSystemGestures.screenHeight = mUnrestrictedScreenHeight;
4204         mDockLeft = mContentLeft = mVoiceContentLeft = mStableLeft = mStableFullscreenLeft
4205                 = mCurLeft = mUnrestrictedScreenLeft;
4206         mDockTop = mContentTop = mVoiceContentTop = mStableTop = mStableFullscreenTop
4207                 = mCurTop = mUnrestrictedScreenTop;
4208         mDockRight = mContentRight = mVoiceContentRight = mStableRight = mStableFullscreenRight
4209                 = mCurRight = displayWidth - overscanRight;
4210         mDockBottom = mContentBottom = mVoiceContentBottom = mStableBottom = mStableFullscreenBottom
4211                 = mCurBottom = displayHeight - overscanBottom;
4212         mDockLayer = 0x10000000;
4213         mStatusBarLayer = -1;
4214
4215         // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
4216         final Rect pf = mTmpParentFrame;
4217         final Rect df = mTmpDisplayFrame;
4218         final Rect of = mTmpOverscanFrame;
4219         final Rect vf = mTmpVisibleFrame;
4220         final Rect dcf = mTmpDecorFrame;
4221         pf.left = df.left = of.left = vf.left = mDockLeft;
4222         pf.top = df.top = of.top = vf.top = mDockTop;
4223         pf.right = df.right = of.right = vf.right = mDockRight;
4224         pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
4225         dcf.setEmpty();  // Decor frame N/A for system bars.
4226
4227         if (isDefaultDisplay) {
4228             // For purposes of putting out fake window up to steal focus, we will
4229             // drive nav being hidden only by whether it is requested.
4230             final int sysui = mLastSystemUiFlags;
4231             boolean navVisible = (sysui & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
4232             boolean navTranslucent = (sysui
4233                     & (View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT)) != 0;
4234             boolean immersive = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
4235             boolean immersiveSticky = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
4236             boolean navAllowedHidden = immersive || immersiveSticky;
4237             navTranslucent &= !immersiveSticky;  // transient trumps translucent
4238             boolean isKeyguardShowing = isStatusBarKeyguard() && !mHideLockScreen;
4239             if (!isKeyguardShowing) {
4240                 navTranslucent &= areTranslucentBarsAllowed();
4241             }
4242             boolean statusBarExpandedNotKeyguard = !isKeyguardShowing && mStatusBar != null
4243                     && mStatusBar.getAttrs().height == MATCH_PARENT
4244                     && mStatusBar.getAttrs().width == MATCH_PARENT;
4245
4246             // When the navigation bar isn't visible, we put up a fake
4247             // input window to catch all touch events.  This way we can
4248             // detect when the user presses anywhere to bring back the nav
4249             // bar and ensure the application doesn't see the event.
4250             if (navVisible || navAllowedHidden) {
4251                 if (mInputConsumer != null) {
4252                     mHandler.sendMessage(
4253                             mHandler.obtainMessage(MSG_DISPOSE_INPUT_CONSUMER, mInputConsumer));
4254                     mInputConsumer = null;
4255                 }
4256             } else if (mInputConsumer == null) {
4257                 mInputConsumer = mWindowManagerFuncs.addInputConsumer(mHandler.getLooper(),
4258                         mHideNavInputEventReceiverFactory);
4259             }
4260
4261             // For purposes of positioning and showing the nav bar, if we have
4262             // decided that it can't be hidden (because of the screen aspect ratio),
4263             // then take that into account.
4264             navVisible |= !canHideNavigationBar();
4265
4266             boolean updateSysUiVisibility = layoutNavigationBar(displayWidth, displayHeight,
4267                     displayRotation, uiMode, overscanRight, overscanBottom, dcf, navVisible, navTranslucent,
4268                     navAllowedHidden, statusBarExpandedNotKeyguard);
4269             if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
4270                     mDockLeft, mDockTop, mDockRight, mDockBottom));
4271             updateSysUiVisibility |= layoutStatusBar(pf, df, of, vf, dcf, sysui, isKeyguardShowing);
4272             if (updateSysUiVisibility) {
4273                 updateSystemUiVisibilityLw();
4274             }
4275         }
4276     }
4277
4278     private boolean layoutStatusBar(Rect pf, Rect df, Rect of, Rect vf, Rect dcf, int sysui,
4279             boolean isKeyguardShowing) {
4280         // decide where the status bar goes ahead of time
4281         if (mStatusBar != null) {
4282             // apply any navigation bar insets
4283             pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4284             pf.top = df.top = of.top = mUnrestrictedScreenTop;
4285             pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
4286             pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
4287                     + mUnrestrictedScreenTop;
4288             vf.left = mStableLeft;
4289             vf.top = mStableTop;
4290             vf.right = mStableRight;
4291             vf.bottom = mStableBottom;
4292
4293             mStatusBarLayer = mStatusBar.getSurfaceLayer();
4294
4295             // Let the status bar determine its size.
4296             mStatusBar.computeFrameLw(pf /* parentFrame */, df /* displayFrame */,
4297                     vf /* overlayFrame */, vf /* contentFrame */, vf /* visibleFrame */,
4298                     dcf /* decorFrame */, vf /* stableFrame */, vf /* outsetFrame */);
4299
4300             // For layout, the status bar is always at the top with our fixed height.
4301             mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
4302
4303             boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
4304             boolean statusBarTranslucent = (sysui
4305                     & (View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT)) != 0;
4306             if (!isKeyguardShowing) {
4307                 statusBarTranslucent &= areTranslucentBarsAllowed();
4308             }
4309
4310             // If the status bar is hidden, we don't want to cause
4311             // windows behind it to scroll.
4312             if (mStatusBar.isVisibleLw() && !statusBarTransient) {
4313                 // Status bar may go away, so the screen area it occupies
4314                 // is available to apps but just covering them when the
4315                 // status bar is visible.
4316                 mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
4317
4318                 mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4319                 mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4320                 mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4321                 mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4322
4323                 if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
4324                         String.format(
4325                                 "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
4326                                 mDockLeft, mDockTop, mDockRight, mDockBottom,
4327                                 mContentLeft, mContentTop, mContentRight, mContentBottom,
4328                                 mCurLeft, mCurTop, mCurRight, mCurBottom));
4329             }
4330             if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
4331                     && !statusBarTransient && !statusBarTranslucent
4332                     && !mStatusBarController.wasRecentlyTranslucent()) {
4333                 // If the opaque status bar is currently requested to be visible,
4334                 // and not in the process of animating on or off, then
4335                 // we can tell the app that it is covered by it.
4336                 mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
4337             }
4338             if (mStatusBarController.checkHiddenLw()) {
4339                 return true;
4340             }
4341         }
4342         return false;
4343     }
4344
4345     private boolean layoutNavigationBar(int displayWidth, int displayHeight, int displayRotation,
4346             int uiMode, int overscanRight, int overscanBottom, Rect dcf, boolean navVisible,
4347             boolean navTranslucent, boolean navAllowedHidden,
4348             boolean statusBarExpandedNotKeyguard) {
4349         if (mNavigationBar != null) {
4350             boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
4351             // Force the navigation bar to its appropriate place and
4352             // size.  We need to do this directly, instead of relying on
4353             // it to bubble up from the nav bar, because this needs to
4354             // change atomically with screen rotations.
4355             mNavigationBarOnBottom = isNavigationBarOnBottom(displayWidth, displayHeight);
4356             if (mNavigationBarOnBottom) {
4357                 // It's a system nav bar or a portrait screen; nav bar goes on bottom.
4358                 int top = displayHeight - overscanBottom
4359                         - getNavigationBarHeight(displayRotation, uiMode);
4360                 mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
4361                 mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
4362                 if (transientNavBarShowing) {
4363                     mNavigationBarController.setBarShowingLw(true);
4364                 } else if (navVisible) {
4365                     mNavigationBarController.setBarShowingLw(true);
4366                     mDockBottom = mTmpNavigationFrame.top;
4367                     mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
4368                     mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
4369                 } else {
4370                     // We currently want to hide the navigation UI - unless we expanded the status
4371                     // bar.
4372                     mNavigationBarController.setBarShowingLw(statusBarExpandedNotKeyguard);
4373                 }
4374                 if (navVisible && !navTranslucent && !navAllowedHidden
4375                         && !mNavigationBar.isAnimatingLw()
4376                         && !mNavigationBarController.wasRecentlyTranslucent()) {
4377                     // If the opaque nav bar is currently requested to be visible,
4378                     // and not in the process of animating on or off, then
4379                     // we can tell the app that it is covered by it.
4380                     mSystemBottom = mTmpNavigationFrame.top;
4381                 }
4382             } else {
4383                 // Landscape screen; nav bar goes to the right.
4384                 int left = displayWidth - overscanRight
4385                         - getNavigationBarWidth(displayRotation, uiMode);
4386                 mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
4387                 mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
4388                 if (transientNavBarShowing) {
4389                     mNavigationBarController.setBarShowingLw(true);
4390                 } else if (navVisible) {
4391                     mNavigationBarController.setBarShowingLw(true);
4392                     mDockRight = mTmpNavigationFrame.left;
4393                     mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
4394                     mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
4395                 } else {
4396                     // We currently want to hide the navigation UI - unless we expanded the status
4397                     // bar.
4398                     mNavigationBarController.setBarShowingLw(statusBarExpandedNotKeyguard);
4399                 }
4400                 if (navVisible && !navTranslucent && !navAllowedHidden
4401                         && !mNavigationBar.isAnimatingLw()
4402                         && !mNavigationBarController.wasRecentlyTranslucent()) {
4403                     // If the nav bar is currently requested to be visible,
4404                     // and not in the process of animating on or off, then
4405                     // we can tell the app that it is covered by it.
4406                     mSystemRight = mTmpNavigationFrame.left;
4407                 }
4408             }
4409             // Make sure the content and current rectangles are updated to
4410             // account for the restrictions from the navigation bar.
4411             mContentTop = mVoiceContentTop = mCurTop = mDockTop;
4412             mContentBottom = mVoiceContentBottom = mCurBottom = mDockBottom;
4413             mContentLeft = mVoiceContentLeft = mCurLeft = mDockLeft;
4414             mContentRight = mVoiceContentRight = mCurRight = mDockRight;
4415             mStatusBarLayer = mNavigationBar.getSurfaceLayer();
4416             // And compute the final frame.
4417             mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
4418                     mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf,
4419                     mTmpNavigationFrame, mTmpNavigationFrame);
4420             if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
4421             if (mNavigationBarController.checkHiddenLw()) {
4422                 return true;
4423             }
4424         }
4425         return false;
4426     }
4427
4428     private boolean isNavigationBarOnBottom(int displayWidth, int displayHeight) {
4429         return !mNavigationBarCanMove || displayWidth < displayHeight;
4430     }
4431
4432     /** {@inheritDoc} */
4433     @Override
4434     public int getSystemDecorLayerLw() {
4435         if (mStatusBar != null && mStatusBar.isVisibleLw()) {
4436             return mStatusBar.getSurfaceLayer();
4437         }
4438
4439         if (mNavigationBar != null && mNavigationBar.isVisibleLw()) {
4440             return mNavigationBar.getSurfaceLayer();
4441         }
4442
4443         return 0;
4444     }
4445
4446     @Override
4447     public void getContentRectLw(Rect r) {
4448         r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
4449     }
4450
4451     void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
4452             boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
4453         if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
4454             // Here's a special case: if this attached window is a panel that is
4455             // above the dock window, and the window it is attached to is below
4456             // the dock window, then the frames we computed for the window it is
4457             // attached to can not be used because the dock is effectively part
4458             // of the underlying window and the attached window is floating on top
4459             // of the whole thing.  So, we ignore the attached window and explicitly
4460             // compute the frames that would be appropriate without the dock.
4461             df.left = of.left = cf.left = vf.left = mDockLeft;
4462             df.top = of.top = cf.top = vf.top = mDockTop;
4463             df.right = of.right = cf.right = vf.right = mDockRight;
4464             df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
4465         } else {
4466             // The effective display frame of the attached window depends on
4467             // whether it is taking care of insetting its content.  If not,
4468             // we need to use the parent's content frame so that the entire
4469             // window is positioned within that content.  Otherwise we can use
4470             // the overscan frame and let the attached window take care of
4471             // positioning its content appropriately.
4472             if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4473                 // Set the content frame of the attached window to the parent's decor frame
4474                 // (same as content frame when IME isn't present) if specifically requested by
4475                 // setting {@link WindowManager.LayoutParams#FLAG_LAYOUT_ATTACHED_IN_DECOR} flag.
4476                 // Otherwise, use the overscan frame.
4477                 cf.set((fl & FLAG_LAYOUT_ATTACHED_IN_DECOR) != 0
4478                         ? attached.getContentFrameLw() : attached.getOverscanFrameLw());
4479             } else {
4480                 // If the window is resizing, then we want to base the content
4481                 // frame on our attached content frame to resize...  however,
4482                 // things can be tricky if the attached window is NOT in resize
4483                 // mode, in which case its content frame will be larger.
4484                 // Ungh.  So to deal with that, make sure the content frame
4485                 // we end up using is not covering the IM dock.
4486                 cf.set(attached.getContentFrameLw());
4487                 if (attached.isVoiceInteraction()) {
4488                     if (cf.left < mVoiceContentLeft) cf.left = mVoiceContentLeft;
4489                     if (cf.top < mVoiceContentTop) cf.top = mVoiceContentTop;
4490                     if (cf.right > mVoiceContentRight) cf.right = mVoiceContentRight;
4491                     if (cf.bottom > mVoiceContentBottom) cf.bottom = mVoiceContentBottom;
4492                 } else if (attached.getSurfaceLayer() < mDockLayer) {
4493                     if (cf.left < mContentLeft) cf.left = mContentLeft;
4494                     if (cf.top < mContentTop) cf.top = mContentTop;
4495                     if (cf.right > mContentRight) cf.right = mContentRight;
4496                     if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
4497                 }
4498             }
4499             df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
4500             of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
4501             vf.set(attached.getVisibleFrameLw());
4502         }
4503         // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
4504         // window should be positioned relative to its parent or the entire
4505         // screen.
4506         pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
4507                 ? attached.getFrameLw() : df);
4508     }
4509
4510     private void applyStableConstraints(int sysui, int fl, Rect r) {
4511         if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
4512             // If app is requesting a stable layout, don't let the
4513             // content insets go below the stable values.
4514             if ((fl & FLAG_FULLSCREEN) != 0) {
4515                 if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
4516                 if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
4517                 if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
4518                 if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
4519             } else {
4520                 if (r.left < mStableLeft) r.left = mStableLeft;
4521                 if (r.top < mStableTop) r.top = mStableTop;
4522                 if (r.right > mStableRight) r.right = mStableRight;
4523                 if (r.bottom > mStableBottom) r.bottom = mStableBottom;
4524             }
4525         }
4526     }
4527
4528     private boolean canReceiveInput(WindowState win) {
4529         boolean notFocusable =
4530                 (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) != 0;
4531         boolean altFocusableIm =
4532                 (win.getAttrs().flags & WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM) != 0;
4533         boolean notFocusableForIm = notFocusable ^ altFocusableIm;
4534         return !notFocusableForIm;
4535     }
4536
4537     /** {@inheritDoc} */
4538     @Override
4539     public void layoutWindowLw(WindowState win, WindowState attached) {
4540         // We've already done the navigation bar and status bar. If the status bar can receive
4541         // input, we need to layout it again to accomodate for the IME window.
4542         if ((win == mStatusBar && !canReceiveInput(win)) || win == mNavigationBar) {
4543             return;
4544         }
4545         final WindowManager.LayoutParams attrs = win.getAttrs();
4546         final boolean isDefaultDisplay = win.isDefaultDisplay();
4547         final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
4548                 (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
4549         if (needsToOffsetInputMethodTarget) {
4550             if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
4551             offsetInputMethodWindowLw(mLastInputMethodWindow);
4552         }
4553
4554         final int fl = PolicyControl.getWindowFlags(win, attrs);
4555         final int pfl = attrs.privateFlags;
4556         final int sim = attrs.softInputMode;
4557         final int sysUiFl = PolicyControl.getSystemUiVisibility(win, null);
4558
4559         final Rect pf = mTmpParentFrame;
4560         final Rect df = mTmpDisplayFrame;
4561         final Rect of = mTmpOverscanFrame;
4562         final Rect cf = mTmpContentFrame;
4563         final Rect vf = mTmpVisibleFrame;
4564         final Rect dcf = mTmpDecorFrame;
4565         final Rect sf = mTmpStableFrame;
4566         Rect osf = null;
4567         dcf.setEmpty();
4568
4569         final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
4570                 && mNavigationBar != null && mNavigationBar.isVisibleLw());
4571
4572         final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
4573
4574         if (isDefaultDisplay) {
4575             sf.set(mStableLeft, mStableTop, mStableRight, mStableBottom);
4576         } else {
4577             sf.set(mOverscanLeft, mOverscanTop, mOverscanRight, mOverscanBottom);
4578         }
4579
4580         if (!isDefaultDisplay) {
4581             if (attached != null) {
4582                 // If this window is attached to another, our display
4583                 // frame is the same as the one we are attached to.
4584                 setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4585             } else {
4586                 // Give the window full screen.
4587                 pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4588                 pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4589                 pf.right = df.right = of.right = cf.right
4590                         = mOverscanScreenLeft + mOverscanScreenWidth;
4591                 pf.bottom = df.bottom = of.bottom = cf.bottom
4592                         = mOverscanScreenTop + mOverscanScreenHeight;
4593             }
4594         } else if (attrs.type == TYPE_INPUT_METHOD) {
4595             pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
4596             pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
4597             pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
4598             // IM dock windows layout below the nav bar...
4599             pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4600             // ...with content insets above the nav bar
4601             cf.bottom = vf.bottom = mStableBottom;
4602             if (mStatusBar != null && mFocusedWindow == mStatusBar && canReceiveInput(mStatusBar)) {
4603                 // The status bar forces the navigation bar while it's visible. Make sure the IME
4604                 // avoids the navigation bar in that case.
4605                 pf.right = df.right = of.right = cf.right = vf.right = mStableRight;
4606             }
4607             // IM dock windows always go to the bottom of the screen.
4608             attrs.gravity = Gravity.BOTTOM;
4609             mDockLayer = win.getSurfaceLayer();
4610         } else if (attrs.type == TYPE_VOICE_INTERACTION) {
4611             pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4612             pf.top = df.top = of.top = mUnrestrictedScreenTop;
4613             pf.right = df.right = of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4614             pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4615             if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4616                 cf.left = mDockLeft;
4617                 cf.top = mDockTop;
4618                 cf.right = mDockRight;
4619                 cf.bottom = mDockBottom;
4620             } else {
4621                 cf.left = mContentLeft;
4622                 cf.top = mContentTop;
4623                 cf.right = mContentRight;
4624                 cf.bottom = mContentBottom;
4625             }
4626             if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4627                 vf.left = mCurLeft;
4628                 vf.top = mCurTop;
4629                 vf.right = mCurRight;
4630                 vf.bottom = mCurBottom;
4631             } else {
4632                 vf.set(cf);
4633             }
4634         } else if (win == mStatusBar) {
4635             pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4636             pf.top = df.top = of.top = mUnrestrictedScreenTop;
4637             pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
4638             pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight + mUnrestrictedScreenTop;
4639             cf.left = vf.left = mStableLeft;
4640             cf.top = vf.top = mStableTop;
4641             cf.right = vf.right = mStableRight;
4642             vf.bottom = mStableBottom;
4643
4644             if (adjust == SOFT_INPUT_ADJUST_RESIZE) {
4645                 cf.bottom = mContentBottom;
4646             } else {
4647                 cf.bottom = mDockBottom;
4648                 vf.bottom = mContentBottom;
4649             }
4650         } else {
4651
4652             // Default policy decor for the default display
4653             dcf.left = mSystemLeft;
4654             dcf.top = mSystemTop;
4655             dcf.right = mSystemRight;
4656             dcf.bottom = mSystemBottom;
4657             final boolean inheritTranslucentDecor = (attrs.privateFlags
4658                     & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
4659             final boolean isAppWindow =
4660                     attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
4661                     attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
4662             final boolean topAtRest =
4663                     win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
4664             if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
4665                 if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
4666                         && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
4667                         && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0
4668                         && (fl & WindowManager.LayoutParams.
4669                                 FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0
4670                         && (pfl & PRIVATE_FLAG_FORCE_DRAW_STATUS_BAR_BACKGROUND) == 0) {
4671                     // Ensure policy decor includes status bar
4672                     dcf.top = mStableTop;
4673                 }
4674                 if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
4675                         && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
4676                         && (fl & WindowManager.LayoutParams.
4677                                 FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0) {
4678                     // Ensure policy decor includes navigation bar
4679                     dcf.bottom = mStableBottom;
4680                     dcf.right = mStableRight;
4681                 }
4682             }
4683
4684             if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
4685                     == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
4686                 if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
4687                             + "): IN_SCREEN, INSET_DECOR");
4688                 // This is the case for a normal activity window: we want it
4689                 // to cover all of the screen space, and it can take care of
4690                 // moving its contents to account for screen decorations that
4691                 // intrude into that space.
4692                 if (attached != null) {
4693                     // If this window is attached to another, our display
4694                     // frame is the same as the one we are attached to.
4695                     setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
4696                 } else {
4697                     if (attrs.type == TYPE_STATUS_BAR_PANEL
4698                             || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
4699                         // Status bar panels are the only windows who can go on top of
4700                         // the status bar.  They are protected by the STATUS_BAR_SERVICE
4701                         // permission, so they have the same privileges as the status
4702                         // bar itself.
4703                         //
4704                         // However, they should still dodge the navigation bar if it exists.
4705
4706                         pf.left = df.left = of.left = hasNavBar
4707                                 ? mDockLeft : mUnrestrictedScreenLeft;
4708                         pf.top = df.top = of.top = mUnrestrictedScreenTop;
4709                         pf.right = df.right = of.right = hasNavBar
4710                                 ? mRestrictedScreenLeft+mRestrictedScreenWidth
4711                                 : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4712                         pf.bottom = df.bottom = of.bottom = hasNavBar
4713                                 ? mRestrictedScreenTop+mRestrictedScreenHeight
4714                                 : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4715
4716                         if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4717                                         "Laying out status bar window: (%d,%d - %d,%d)",
4718                                         pf.left, pf.top, pf.right, pf.bottom));
4719                     } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4720                             && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4721                             && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4722                         // Asking to layout into the overscan region, so give it that pure
4723                         // unrestricted area.
4724                         pf.left = df.left = of.left = mOverscanScreenLeft;
4725                         pf.top = df.top = of.top = mOverscanScreenTop;
4726                         pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
4727                         pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
4728                                 + mOverscanScreenHeight;
4729                     } else if (canHideNavigationBar()
4730                             && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4731                             && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4732                             && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4733                         // Asking for layout as if the nav bar is hidden, lets the
4734                         // application extend into the unrestricted overscan screen area.  We
4735                         // only do this for application windows to ensure no window that
4736                         // can be above the nav bar can do this.
4737                         pf.left = df.left = mOverscanScreenLeft;
4738                         pf.top = df.top = mOverscanScreenTop;
4739                         pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4740                         pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4741                         // We need to tell the app about where the frame inside the overscan
4742                         // is, so it can inset its content by that amount -- it didn't ask
4743                         // to actually extend itself into the overscan region.
4744                         of.left = mUnrestrictedScreenLeft;
4745                         of.top = mUnrestrictedScreenTop;
4746                         of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4747                         of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4748                     } else {
4749                         pf.left = df.left = mRestrictedOverscanScreenLeft;
4750                         pf.top = df.top = mRestrictedOverscanScreenTop;
4751                         pf.right = df.right = mRestrictedOverscanScreenLeft
4752                                 + mRestrictedOverscanScreenWidth;
4753                         pf.bottom = df.bottom = mRestrictedOverscanScreenTop
4754                                 + mRestrictedOverscanScreenHeight;
4755                         // We need to tell the app about where the frame inside the overscan
4756                         // is, so it can inset its content by that amount -- it didn't ask
4757                         // to actually extend itself into the overscan region.
4758                         of.left = mUnrestrictedScreenLeft;
4759                         of.top = mUnrestrictedScreenTop;
4760                         of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4761                         of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4762                     }
4763
4764                     if ((fl & FLAG_FULLSCREEN) == 0) {
4765                         if (win.isVoiceInteraction()) {
4766                             cf.left = mVoiceContentLeft;
4767                             cf.top = mVoiceContentTop;
4768                             cf.right = mVoiceContentRight;
4769                             cf.bottom = mVoiceContentBottom;
4770                         } else {
4771                             if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4772                                 cf.left = mDockLeft;
4773                                 cf.top = mDockTop;
4774                                 cf.right = mDockRight;
4775                                 cf.bottom = mDockBottom;
4776                             } else {
4777                                 cf.left = mContentLeft;
4778                                 cf.top = mContentTop;
4779                                 cf.right = mContentRight;
4780                                 cf.bottom = mContentBottom;
4781                             }
4782                         }
4783                     } else {
4784                         // Full screen windows are always given a layout that is as if the
4785                         // status bar and other transient decors are gone.  This is to avoid
4786                         // bad states when moving from a window that is not hding the
4787                         // status bar to one that is.
4788                         cf.left = mRestrictedScreenLeft;
4789                         cf.top = mRestrictedScreenTop;
4790                         cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4791                         cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
4792                     }
4793                     applyStableConstraints(sysUiFl, fl, cf);
4794                     if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4795                         vf.left = mCurLeft;
4796                         vf.top = mCurTop;
4797                         vf.right = mCurRight;
4798                         vf.bottom = mCurBottom;
4799                     } else {
4800                         vf.set(cf);
4801                     }
4802                 }
4803             } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
4804                     & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
4805                             | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
4806                 if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4807                         "): IN_SCREEN");
4808                 // A window that has requested to fill the entire screen just
4809                 // gets everything, period.
4810                 if (attrs.type == TYPE_STATUS_BAR_PANEL
4811                         || attrs.type == TYPE_STATUS_BAR_SUB_PANEL
4812                         || attrs.type == TYPE_VOLUME_OVERLAY) {
4813                     pf.left = df.left = of.left = cf.left = hasNavBar
4814                             ? mDockLeft : mUnrestrictedScreenLeft;
4815                     pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4816                     pf.right = df.right = of.right = cf.right = hasNavBar
4817                                         ? mRestrictedScreenLeft+mRestrictedScreenWidth
4818                                         : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4819                     pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
4820                                           ? mRestrictedScreenTop+mRestrictedScreenHeight
4821                                           : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4822                     if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4823                                     "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
4824                                     pf.left, pf.top, pf.right, pf.bottom));
4825                 } else if (attrs.type == TYPE_NAVIGATION_BAR
4826                         || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
4827                     // The navigation bar has Real Ultimate Power.
4828                     pf.left = df.left = of.left = mUnrestrictedScreenLeft;
4829                     pf.top = df.top = of.top = mUnrestrictedScreenTop;
4830                     pf.right = df.right = of.right = mUnrestrictedScreenLeft
4831                             + mUnrestrictedScreenWidth;
4832                     pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
4833                             + mUnrestrictedScreenHeight;
4834                     if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
4835                                     "Laying out navigation bar window: (%d,%d - %d,%d)",
4836                                     pf.left, pf.top, pf.right, pf.bottom));
4837                 } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
4838                                 || attrs.type == TYPE_BOOT_PROGRESS
4839                                 || attrs.type == TYPE_SCREENSHOT)
4840                         && ((fl & FLAG_FULLSCREEN) != 0)) {
4841                     // Fullscreen secure system overlays get what they ask for. Screenshot region
4842                     // selection overlay should also expand to full screen.
4843                     pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4844                     pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4845                     pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4846                             + mOverscanScreenWidth;
4847                     pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4848                             + mOverscanScreenHeight;
4849                 } else if (attrs.type == TYPE_BOOT_PROGRESS) {
4850                     // Boot progress screen always covers entire display.
4851                     pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4852                     pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4853                     pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
4854                             + mOverscanScreenWidth;
4855                     pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
4856                             + mOverscanScreenHeight;
4857                 } else if (attrs.type == TYPE_WALLPAPER) {
4858                     // The wallpaper also has Real Ultimate Power, but we want to tell
4859                     // it about the overscan area.
4860                     pf.left = df.left = mOverscanScreenLeft;
4861                     pf.top = df.top = mOverscanScreenTop;
4862                     pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
4863                     pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
4864                     of.left = cf.left = mUnrestrictedScreenLeft;
4865                     of.top = cf.top = mUnrestrictedScreenTop;
4866                     of.right = cf.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
4867                     of.bottom = cf.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
4868                 } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
4869                         && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4870                         && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
4871                     // Asking to layout into the overscan region, so give it that pure
4872                     // unrestricted area.
4873                     pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
4874                     pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
4875                     pf.right = df.right = of.right = cf.right
4876                             = mOverscanScreenLeft + mOverscanScreenWidth;
4877                     pf.bottom = df.bottom = of.bottom = cf.bottom
4878                             = mOverscanScreenTop + mOverscanScreenHeight;
4879                 } else if (canHideNavigationBar()
4880                         && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
4881                         && (attrs.type == TYPE_STATUS_BAR
4882                             || attrs.type == TYPE_TOAST
4883                             || attrs.type == TYPE_DOCK_DIVIDER
4884                             || attrs.type == TYPE_VOICE_INTERACTION_STARTING
4885                             || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
4886                             && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
4887                     // Asking for layout as if the nav bar is hidden, lets the
4888                     // application extend into the unrestricted screen area.  We
4889                     // only do this for application windows (or toasts) to ensure no window that
4890                     // can be above the nav bar can do this.
4891                     // XXX This assumes that an app asking for this will also
4892                     // ask for layout in only content.  We can't currently figure out
4893                     // what the screen would be if only laying out to hide the nav bar.
4894                     pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
4895                     pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
4896                     pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
4897                             + mUnrestrictedScreenWidth;
4898                     pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
4899                             + mUnrestrictedScreenHeight;
4900                 } else if ((sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) != 0) {
4901                     pf.left = df.left = of.left = mRestrictedScreenLeft;
4902                     pf.top = df.top = of.top  = mRestrictedScreenTop;
4903                     pf.right = df.right = of.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
4904                     pf.bottom = df.bottom = of.bottom = mRestrictedScreenTop
4905                             + mRestrictedScreenHeight;
4906                     if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4907                         cf.left = mDockLeft;
4908                         cf.top = mDockTop;
4909                         cf.right = mDockRight;
4910                         cf.bottom = mDockBottom;
4911                     } else {
4912                         cf.left = mContentLeft;
4913                         cf.top = mContentTop;
4914                         cf.right = mContentRight;
4915                         cf.bottom = mContentBottom;
4916                     }
4917                 } else {
4918                     pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4919                     pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4920                     pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4921                             + mRestrictedScreenWidth;
4922                     pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4923                             + mRestrictedScreenHeight;
4924                 }
4925
4926                 applyStableConstraints(sysUiFl, fl, cf);
4927
4928                 if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4929                     vf.left = mCurLeft;
4930                     vf.top = mCurTop;
4931                     vf.right = mCurRight;
4932                     vf.bottom = mCurBottom;
4933                 } else {
4934                     vf.set(cf);
4935                 }
4936             } else if (attached != null) {
4937                 if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4938                         "): attached to " + attached);
4939                 // A child window should be placed inside of the same visible
4940                 // frame that its parent had.
4941                 setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
4942             } else {
4943                 if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
4944                         "): normal window");
4945                 // Otherwise, a normal window must be placed inside the content
4946                 // of all screen decorations.
4947                 if (attrs.type == TYPE_STATUS_BAR_PANEL || attrs.type == TYPE_VOLUME_OVERLAY) {
4948                     // Status bar panels and the volume dialog are the only windows who can go on
4949                     // top of the status bar.  They are protected by the STATUS_BAR_SERVICE
4950                     // permission, so they have the same privileges as the status
4951                     // bar itself.
4952                     pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
4953                     pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
4954                     pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
4955                             + mRestrictedScreenWidth;
4956                     pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
4957                             + mRestrictedScreenHeight;
4958                 } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT) {
4959                     // These dialogs are stable to interim decor changes.
4960                     pf.left = df.left = of.left = cf.left = mStableLeft;
4961                     pf.top = df.top = of.top = cf.top = mStableTop;
4962                     pf.right = df.right = of.right = cf.right = mStableRight;
4963                     pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
4964                 } else {
4965                     pf.left = mContentLeft;
4966                     pf.top = mContentTop;
4967                     pf.right = mContentRight;
4968                     pf.bottom = mContentBottom;
4969                     if (win.isVoiceInteraction()) {
4970                         df.left = of.left = cf.left = mVoiceContentLeft;
4971                         df.top = of.top = cf.top = mVoiceContentTop;
4972                         df.right = of.right = cf.right = mVoiceContentRight;
4973                         df.bottom = of.bottom = cf.bottom = mVoiceContentBottom;
4974                     } else if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
4975                         df.left = of.left = cf.left = mDockLeft;
4976                         df.top = of.top = cf.top = mDockTop;
4977                         df.right = of.right = cf.right = mDockRight;
4978                         df.bottom = of.bottom = cf.bottom = mDockBottom;
4979                     } else {
4980                         df.left = of.left = cf.left = mContentLeft;
4981                         df.top = of.top = cf.top = mContentTop;
4982                         df.right = of.right = cf.right = mContentRight;
4983                         df.bottom = of.bottom = cf.bottom = mContentBottom;
4984                     }
4985                     if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
4986                         vf.left = mCurLeft;
4987                         vf.top = mCurTop;
4988                         vf.right = mCurRight;
4989                         vf.bottom = mCurBottom;
4990                     } else {
4991                         vf.set(cf);
4992                     }
4993                 }
4994             }
4995         }
4996
4997         // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
4998         // Also, we don't allow windows in multi-window mode to extend out of the screen.
4999         if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR
5000                 && !win.isInMultiWindowMode()) {
5001             df.left = df.top = -10000;
5002             df.right = df.bottom = 10000;
5003             if (attrs.type != TYPE_WALLPAPER) {
5004                 of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
5005                 of.right = of.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
5006             }
5007         }
5008
5009         // If the device has a chin (e.g. some watches), a dead area at the bottom of the screen we
5010         // need to provide information to the clients that want to pretend that you can draw there.
5011         // We only want to apply outsets to certain types of windows. For example, we never want to
5012         // apply the outsets to floating dialogs, because they wouldn't make sense there.
5013         final boolean useOutsets = shouldUseOutsets(attrs, fl);
5014         if (isDefaultDisplay && useOutsets) {
5015             osf = mTmpOutsetFrame;
5016             osf.set(cf.left, cf.top, cf.right, cf.bottom);
5017             int outset = ScreenShapeHelper.getWindowOutsetBottomPx(mContext.getResources());
5018             if (outset > 0) {
5019                 int rotation = mDisplayRotation;
5020                 if (rotation == Surface.ROTATION_0) {
5021                     osf.bottom += outset;
5022                 } else if (rotation == Surface.ROTATION_90) {
5023                     osf.right += outset;
5024                 } else if (rotation == Surface.ROTATION_180) {
5025                     osf.top -= outset;
5026                 } else if (rotation == Surface.ROTATION_270) {
5027                     osf.left -= outset;
5028                 }
5029                 if (DEBUG_LAYOUT) Slog.v(TAG, "applying bottom outset of " + outset
5030                         + " with rotation " + rotation + ", result: " + osf);
5031             }
5032         }
5033
5034         if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
5035                 + ": sim=#" + Integer.toHexString(sim)
5036                 + " attach=" + attached + " type=" + attrs.type
5037                 + String.format(" flags=0x%08x", fl)
5038                 + " pf=" + pf.toShortString() + " df=" + df.toShortString()
5039                 + " of=" + of.toShortString()
5040                 + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
5041                 + " dcf=" + dcf.toShortString()
5042                 + " sf=" + sf.toShortString()
5043                 + " osf=" + (osf == null ? "null" : osf.toShortString()));
5044
5045         win.computeFrameLw(pf, df, of, cf, vf, dcf, sf, osf);
5046
5047         // Dock windows carve out the bottom of the screen, so normal windows
5048         // can't appear underneath them.
5049         if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
5050                 && win.isDisplayedLw() && !win.getGivenInsetsPendingLw()) {
5051             setLastInputMethodWindowLw(null, null);
5052             offsetInputMethodWindowLw(win);
5053         }
5054         if (attrs.type == TYPE_VOICE_INTERACTION && win.isVisibleOrBehindKeyguardLw()
5055                 && !win.getGivenInsetsPendingLw()) {
5056             offsetVoiceInputWindowLw(win);
5057         }
5058     }
5059
5060     private void offsetInputMethodWindowLw(WindowState win) {
5061         int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
5062         top += win.getGivenContentInsetsLw().top;
5063         if (mContentBottom > top) {
5064             mContentBottom = top;
5065         }
5066         if (mVoiceContentBottom > top) {
5067             mVoiceContentBottom = top;
5068         }
5069         top = win.getVisibleFrameLw().top;
5070         top += win.getGivenVisibleInsetsLw().top;
5071         if (mCurBottom > top) {
5072             mCurBottom = top;
5073         }
5074         if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
5075                 + mDockBottom + " mContentBottom="
5076                 + mContentBottom + " mCurBottom=" + mCurBottom);
5077     }
5078
5079     private void offsetVoiceInputWindowLw(WindowState win) {
5080         int top = Math.max(win.getDisplayFrameLw().top, win.getContentFrameLw().top);
5081         top += win.getGivenContentInsetsLw().top;
5082         if (mVoiceContentBottom > top) {
5083             mVoiceContentBottom = top;
5084         }
5085     }
5086
5087     /** {@inheritDoc} */
5088     @Override
5089     public void finishLayoutLw() {
5090         return;
5091     }
5092
5093     /** {@inheritDoc} */
5094     @Override
5095     public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
5096         mTopFullscreenOpaqueWindowState = null;
5097         mTopFullscreenOpaqueOrDimmingWindowState = null;
5098         mTopDockedOpaqueWindowState = null;
5099         mTopDockedOpaqueOrDimmingWindowState = null;
5100         mAppsToBeHidden.clear();
5101         mAppsThatDismissKeyguard.clear();
5102         mForceStatusBar = false;
5103         mForceStatusBarFromKeyguard = false;
5104         mForceStatusBarTransparent = false;
5105         mForcingShowNavBar = false;
5106         mForcingShowNavBarLayer = -1;
5107
5108         mHideLockScreen = false;
5109         mAllowLockscreenWhenOn = false;
5110         mDismissKeyguard = DISMISS_KEYGUARD_NONE;
5111         mShowingLockscreen = false;
5112         mShowingDream = false;
5113         mWinShowWhenLocked = null;
5114         mKeyguardSecure = isKeyguardSecure(mCurrentUserId);
5115         mKeyguardSecureIncludingHidden = mKeyguardSecure
5116                 && (mKeyguardDelegate != null && mKeyguardDelegate.isShowing());
5117     }
5118
5119     /** {@inheritDoc} */
5120     @Override
5121     public void applyPostLayoutPolicyLw(WindowState win, WindowManager.LayoutParams attrs,
5122             WindowState attached) {
5123         if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
5124                 + win.isVisibleOrBehindKeyguardLw());
5125         final int fl = PolicyControl.getWindowFlags(win, attrs);
5126         if (mTopFullscreenOpaqueWindowState == null
5127                 && win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD) {
5128             mForcingShowNavBar = true;
5129             mForcingShowNavBarLayer = win.getSurfaceLayer();
5130         }
5131         if (attrs.type == TYPE_STATUS_BAR) {
5132             if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
5133                 mForceStatusBarFromKeyguard = true;
5134                 mShowingLockscreen = true;
5135             }
5136             if ((attrs.privateFlags & PRIVATE_FLAG_FORCE_STATUS_BAR_VISIBLE_TRANSPARENT) != 0) {
5137                 mForceStatusBarTransparent = true;
5138             }
5139         }
5140
5141         boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
5142                 && attrs.type < FIRST_SYSTEM_WINDOW;
5143         final boolean showWhenLocked = (fl & FLAG_SHOW_WHEN_LOCKED) != 0;
5144         final boolean dismissKeyguard = (fl & FLAG_DISMISS_KEYGUARD) != 0;
5145         final int stackId = win.getStackId();
5146         if (mTopFullscreenOpaqueWindowState == null &&
5147                 win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
5148             if ((fl & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
5149                 if ((attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
5150                     mForceStatusBarFromKeyguard = true;
5151                 } else {
5152                     mForceStatusBar = true;
5153                 }
5154             }
5155             if (attrs.type == TYPE_DREAM) {
5156                 // If the lockscreen was showing when the dream started then wait
5157                 // for the dream to draw before hiding the lockscreen.
5158                 if (!mDreamingLockscreen
5159                         || (win.isVisibleLw() && win.hasDrawnLw())) {
5160                     mShowingDream = true;
5161                     appWindow = true;
5162                 }
5163             }
5164
5165             final IApplicationToken appToken = win.getAppToken();
5166
5167             // For app windows that are not attached, we decide if all windows in the app they
5168             // represent should be hidden or if we should hide the lockscreen. For attached app
5169             // windows we defer the decision to the window it is attached to.
5170             if (appWindow && attached == null) {
5171                 if (showWhenLocked) {
5172                     // Remove any previous windows with the same appToken.
5173                     mAppsToBeHidden.remove(appToken);
5174                     mAppsThatDismissKeyguard.remove(appToken);
5175                     if (mAppsToBeHidden.isEmpty()) {
5176                         if (dismissKeyguard && !mKeyguardSecure) {
5177                             mAppsThatDismissKeyguard.add(appToken);
5178                         } else if (win.isDrawnLw() || win.hasAppShownWindows()) {
5179                             mWinShowWhenLocked = win;
5180                             mHideLockScreen = true;
5181                             mForceStatusBarFromKeyguard = false;
5182                         }
5183                     }
5184                 } else if (dismissKeyguard) {
5185                     if (mKeyguardSecure) {
5186                         mAppsToBeHidden.add(appToken);
5187                     } else {
5188                         mAppsToBeHidden.remove(appToken);
5189                     }
5190                     mAppsThatDismissKeyguard.add(appToken);
5191                 } else {
5192                     mAppsToBeHidden.add(appToken);
5193                 }
5194                 if (isFullscreen(attrs) && StackId.normallyFullscreenWindows(stackId)) {
5195                     if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
5196                     mTopFullscreenOpaqueWindowState = win;
5197                     if (mTopFullscreenOpaqueOrDimmingWindowState == null) {
5198                         mTopFullscreenOpaqueOrDimmingWindowState = win;
5199                     }
5200                     if (!mAppsThatDismissKeyguard.isEmpty() &&
5201                             mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
5202                         if (DEBUG_LAYOUT) Slog.v(TAG,
5203                                 "Setting mDismissKeyguard true by win " + win);
5204                         mDismissKeyguard = (mWinDismissingKeyguard == win
5205                                 && mSecureDismissingKeyguard == mKeyguardSecure)
5206                                 ? DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
5207                         mWinDismissingKeyguard = win;
5208                         mSecureDismissingKeyguard = mKeyguardSecure;
5209                         mForceStatusBarFromKeyguard = mShowingLockscreen && mKeyguardSecure;
5210                     } else if (mAppsToBeHidden.isEmpty() && showWhenLocked
5211                             && (win.isDrawnLw() || win.hasAppShownWindows())) {
5212                         if (DEBUG_LAYOUT) Slog.v(TAG,
5213                                 "Setting mHideLockScreen to true by win " + win);
5214                         mHideLockScreen = true;
5215                         mForceStatusBarFromKeyguard = false;
5216                     }
5217                     if ((fl & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
5218                         mAllowLockscreenWhenOn = true;
5219                     }
5220                 }
5221
5222                 if (!mKeyguardHidden && mWinShowWhenLocked != null &&
5223                         mWinShowWhenLocked.getAppToken() != win.getAppToken() &&
5224                         (attrs.flags & FLAG_SHOW_WHEN_LOCKED) == 0) {
5225                     win.hideLw(false);
5226                 }
5227             }
5228         } else if (mTopFullscreenOpaqueWindowState == null && mWinShowWhenLocked == null) {
5229             // No TopFullscreenOpaqueWindow is showing, but we found a SHOW_WHEN_LOCKED window
5230             // that is being hidden in an animation - keep the
5231             // keyguard hidden until the new window shows up and
5232             // we know whether to show the keyguard or not.
5233             if (win.isAnimatingLw() && appWindow && showWhenLocked && mKeyguardHidden) {
5234                 mHideLockScreen = true;
5235                 mWinShowWhenLocked = win;
5236             }
5237         }
5238
5239         // Keep track of the window if it's dimming but not necessarily fullscreen.
5240         final boolean reallyVisible = win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw();
5241         if (mTopFullscreenOpaqueOrDimmingWindowState == null &&  reallyVisible
5242                 && win.isDimming() && StackId.normallyFullscreenWindows(stackId)) {
5243             mTopFullscreenOpaqueOrDimmingWindowState = win;
5244         }
5245
5246         // We need to keep track of the top "fullscreen" opaque window for the docked stack
5247         // separately, because both the "real fullscreen" opaque window and the one for the docked
5248         // stack can control View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.
5249         if (mTopDockedOpaqueWindowState == null && reallyVisible && appWindow && attached == null
5250                 && isFullscreen(attrs) && stackId == DOCKED_STACK_ID) {
5251             mTopDockedOpaqueWindowState = win;
5252             if (mTopDockedOpaqueOrDimmingWindowState == null) {
5253                 mTopDockedOpaqueOrDimmingWindowState = win;
5254             }
5255         }
5256
5257         // Also keep track of any windows that are dimming but not necessarily fullscreen in the
5258         // docked stack.
5259         if (mTopDockedOpaqueOrDimmingWindowState == null && reallyVisible && win.isDimming()
5260                 && stackId == DOCKED_STACK_ID) {
5261             mTopDockedOpaqueOrDimmingWindowState = win;
5262         }
5263     }
5264
5265     private boolean isFullscreen(WindowManager.LayoutParams attrs) {
5266         return attrs.x == 0 && attrs.y == 0
5267                 && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
5268                 && attrs.height == WindowManager.LayoutParams.MATCH_PARENT;
5269     }
5270
5271     /** {@inheritDoc} */
5272     @Override
5273     public int finishPostLayoutPolicyLw() {
5274         if (mWinShowWhenLocked != null && mTopFullscreenOpaqueWindowState != null &&
5275                 mWinShowWhenLocked.getAppToken() != mTopFullscreenOpaqueWindowState.getAppToken()
5276                 && isKeyguardLocked()) {
5277             // A dialog is dismissing the keyguard. Put the wallpaper behind it and hide the
5278             // fullscreen window.
5279             // TODO: Make sure FLAG_SHOW_WALLPAPER is restored when dialog is dismissed. Or not.
5280             mWinShowWhenLocked.getAttrs().flags |= FLAG_SHOW_WALLPAPER;
5281             mTopFullscreenOpaqueWindowState.hideLw(false);
5282             mTopFullscreenOpaqueWindowState = mWinShowWhenLocked;
5283         }
5284
5285         int changes = 0;
5286         boolean topIsFullscreen = false;
5287
5288         final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
5289                 ? mTopFullscreenOpaqueWindowState.getAttrs()
5290                 : null;
5291
5292         // If we are not currently showing a dream then remember the current
5293         // lockscreen state.  We will use this to determine whether the dream
5294         // started while the lockscreen was showing and remember this state
5295         // while the dream is showing.
5296         if (!mShowingDream) {
5297             mDreamingLockscreen = mShowingLockscreen;
5298             if (mDreamingSleepTokenNeeded) {
5299                 mDreamingSleepTokenNeeded = false;
5300                 mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 0, 1).sendToTarget();
5301             }
5302         } else {
5303             if (!mDreamingSleepTokenNeeded) {
5304                 mDreamingSleepTokenNeeded = true;
5305                 mHandler.obtainMessage(MSG_UPDATE_DREAMING_SLEEP_TOKEN, 1, 1).sendToTarget();
5306             }
5307         }
5308
5309         if (mStatusBar != null) {
5310             if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
5311                     + " forcefkg=" + mForceStatusBarFromKeyguard
5312                     + " top=" + mTopFullscreenOpaqueWindowState);
5313             boolean shouldBeTransparent = mForceStatusBarTransparent
5314                     && !mForceStatusBar
5315                     && !mForceStatusBarFromKeyguard;
5316             if (!shouldBeTransparent) {
5317                 mStatusBarController.setShowTransparent(false /* transparent */);
5318             } else if (!mStatusBar.isVisibleLw()) {
5319                 mStatusBarController.setShowTransparent(true /* transparent */);
5320             }
5321
5322             WindowManager.LayoutParams statusBarAttrs = mStatusBar.getAttrs();
5323             boolean statusBarExpanded = statusBarAttrs.height == MATCH_PARENT
5324                     && statusBarAttrs.width == MATCH_PARENT;
5325             if (mForceStatusBar || mForceStatusBarFromKeyguard || mForceStatusBarTransparent
5326                     || statusBarExpanded) {
5327                 if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
5328                 if (mStatusBarController.setBarShowingLw(true)) {
5329                     changes |= FINISH_LAYOUT_REDO_LAYOUT;
5330                 }
5331                 // Maintain fullscreen layout until incoming animation is complete.
5332                 topIsFullscreen = mTopIsFullscreen && mStatusBar.isAnimatingLw();
5333                 // Transient status bar on the lockscreen is not allowed
5334                 if (mForceStatusBarFromKeyguard && mStatusBarController.isTransientShowing()) {
5335                     mStatusBarController.updateVisibilityLw(false /*transientAllowed*/,
5336                             mLastSystemUiFlags, mLastSystemUiFlags);
5337                 }
5338                 if (statusBarExpanded && mNavigationBar != null) {
5339                     if (mNavigationBarController.setBarShowingLw(true)) {
5340                         changes |= FINISH_LAYOUT_REDO_LAYOUT;
5341                     }
5342                 }
5343             } else if (mTopFullscreenOpaqueWindowState != null) {
5344                 final int fl = PolicyControl.getWindowFlags(null, lp);
5345                 if (localLOGV) {
5346                     Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
5347                             + " shown position: "
5348                             + mTopFullscreenOpaqueWindowState.getShownPositionLw());
5349                     Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
5350                             + " lp.flags=0x" + Integer.toHexString(fl));
5351                 }
5352                 topIsFullscreen = (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
5353                         || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
5354                 // The subtle difference between the window for mTopFullscreenOpaqueWindowState
5355                 // and mTopIsFullscreen is that mTopIsFullscreen is set only if the window
5356                 // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
5357                 // case though.
5358                 if (mStatusBarController.isTransientShowing()) {
5359                     if (mStatusBarController.setBarShowingLw(true)) {
5360                         changes |= FINISH_LAYOUT_REDO_LAYOUT;
5361                     }
5362                 } else if (topIsFullscreen
5363                         && !mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID)
5364                         && !mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID)) {
5365                     if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
5366                     if (mStatusBarController.setBarShowingLw(false)) {
5367                         changes |= FINISH_LAYOUT_REDO_LAYOUT;
5368                     } else {
5369                         if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
5370                     }
5371                 } else {
5372                     if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
5373                     if (mStatusBarController.setBarShowingLw(true)) {
5374                         changes |= FINISH_LAYOUT_REDO_LAYOUT;
5375                     }
5376                 }
5377             }
5378         }
5379
5380         if (mTopIsFullscreen != topIsFullscreen) {
5381             if (!topIsFullscreen) {
5382                 // Force another layout when status bar becomes fully shown.
5383                 changes |= FINISH_LAYOUT_REDO_LAYOUT;
5384             }
5385             mTopIsFullscreen = topIsFullscreen;
5386         }
5387
5388         // Hide the key guard if a visible window explicitly specifies that it wants to be
5389         // displayed when the screen is locked.
5390         if (mKeyguardDelegate != null && mStatusBar != null) {
5391             if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
5392                     + mHideLockScreen);
5393             if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardSecure) {
5394                 mKeyguardHidden = true;
5395                 if (setKeyguardOccludedLw(true)) {
5396                     changes |= FINISH_LAYOUT_REDO_LAYOUT
5397                             | FINISH_LAYOUT_REDO_CONFIG
5398                             | FINISH_LAYOUT_REDO_WALLPAPER;
5399                 }
5400                 if (mKeyguardDelegate.isShowing()) {
5401                     mHandler.post(new Runnable() {
5402                         @Override
5403                         public void run() {
5404                             mKeyguardDelegate.keyguardDone(false, false);
5405                         }
5406                     });
5407                 }
5408             } else if (mHideLockScreen) {
5409                 mKeyguardHidden = true;
5410                 mWinDismissingKeyguard = null;
5411                 if (setKeyguardOccludedLw(true)) {
5412                     changes |= FINISH_LAYOUT_REDO_LAYOUT
5413                             | FINISH_LAYOUT_REDO_CONFIG
5414                             | FINISH_LAYOUT_REDO_WALLPAPER;
5415                 }
5416             } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
5417                 mKeyguardHidden = false;
5418                 if (setKeyguardOccludedLw(false)) {
5419                     changes |= FINISH_LAYOUT_REDO_LAYOUT
5420                             | FINISH_LAYOUT_REDO_CONFIG
5421                             | FINISH_LAYOUT_REDO_WALLPAPER;
5422                 }
5423                 if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
5424                     // Only launch the next keyguard unlock window once per window.
5425                     mHandler.post(new Runnable() {
5426                         @Override
5427                         public void run() {
5428                             mKeyguardDelegate.dismiss();
5429                         }
5430                     });
5431                 }
5432             } else {
5433                 mWinDismissingKeyguard = null;
5434                 mSecureDismissingKeyguard = false;
5435                 mKeyguardHidden = false;
5436                 if (setKeyguardOccludedLw(false)) {
5437                     changes |= FINISH_LAYOUT_REDO_LAYOUT
5438                             | FINISH_LAYOUT_REDO_CONFIG
5439                             | FINISH_LAYOUT_REDO_WALLPAPER;
5440                 }
5441             }
5442         }
5443
5444         if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
5445             // If the navigation bar has been hidden or shown, we need to do another
5446             // layout pass to update that window.
5447             changes |= FINISH_LAYOUT_REDO_LAYOUT;
5448         }
5449
5450         // update since mAllowLockscreenWhenOn might have changed
5451         updateLockScreenTimeout();
5452         return changes;
5453     }
5454
5455     /**
5456      * Updates the occluded state of the Keyguard.
5457      *
5458      * @return Whether the flags have changed and we have to redo the layout.
5459      */
5460     private boolean setKeyguardOccludedLw(boolean isOccluded) {
5461         boolean wasOccluded = mKeyguardOccluded;
5462         boolean showing = mKeyguardDelegate.isShowing();
5463         if (wasOccluded && !isOccluded && showing) {
5464             mKeyguardOccluded = false;
5465             mKeyguardDelegate.setOccluded(false);
5466             mStatusBar.getAttrs().privateFlags |= PRIVATE_FLAG_KEYGUARD;
5467             return true;
5468         } else if (!wasOccluded && isOccluded && showing) {
5469             mKeyguardOccluded = true;
5470             mKeyguardDelegate.setOccluded(true);
5471             mStatusBar.getAttrs().privateFlags &= ~PRIVATE_FLAG_KEYGUARD;
5472             mStatusBar.getAttrs().flags &= ~FLAG_SHOW_WALLPAPER;
5473             return true;
5474         } else {
5475             return false;
5476         }
5477     }
5478
5479     private boolean isStatusBarKeyguard() {
5480         return mStatusBar != null
5481                 && (mStatusBar.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0;
5482     }
5483
5484     @Override
5485     public boolean allowAppAnimationsLw() {
5486         if (isStatusBarKeyguard() || mShowingDream) {
5487             // If keyguard or dreams is currently visible, no reason to animate behind it.
5488             return false;
5489         }
5490         return true;
5491     }
5492
5493     @Override
5494     public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
5495         mFocusedWindow = newFocus;
5496         if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
5497             // If the navigation bar has been hidden or shown, we need to do another
5498             // layout pass to update that window.
5499             return FINISH_LAYOUT_REDO_LAYOUT;
5500         }
5501         return 0;
5502     }
5503
5504     /** {@inheritDoc} */
5505     @Override
5506     public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
5507         // lid changed state
5508         final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
5509         if (newLidState == mLidState) {
5510             return;
5511         }
5512
5513         mLidState = newLidState;
5514         applyLidSwitchState();
5515         updateRotation(true);
5516
5517         if (lidOpen) {
5518             wakeUp(SystemClock.uptimeMillis(), mAllowTheaterModeWakeFromLidSwitch,
5519                     "android.policy:LID");
5520         } else if (!mLidControlsSleep) {
5521             mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5522         }
5523     }
5524
5525     @Override
5526     public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered) {
5527         int lensCoverState = lensCovered ? CAMERA_LENS_COVERED : CAMERA_LENS_UNCOVERED;
5528         if (mCameraLensCoverState == lensCoverState) {
5529             return;
5530         }
5531         if (mCameraLensCoverState == CAMERA_LENS_COVERED &&
5532                 lensCoverState == CAMERA_LENS_UNCOVERED) {
5533             Intent intent;
5534             final boolean keyguardActive = mKeyguardDelegate == null ? false :
5535                     mKeyguardDelegate.isShowing();
5536             if (keyguardActive) {
5537                 intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE);
5538             } else {
5539                 intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
5540             }
5541             wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromCameraLens,
5542                     "android.policy:CAMERA_COVER");
5543             startActivityAsUser(intent, UserHandle.CURRENT_OR_SELF);
5544         }
5545         mCameraLensCoverState = lensCoverState;
5546     }
5547
5548     void setHdmiPlugged(boolean plugged) {
5549         if (mHdmiPlugged != plugged) {
5550             mHdmiPlugged = plugged;
5551             updateRotation(true, true);
5552             Intent intent = new Intent(ACTION_HDMI_PLUGGED);
5553             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5554             intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
5555             mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
5556         }
5557     }
5558
5559     void initializeHdmiState() {
5560         boolean plugged = false;
5561         // watch for HDMI plug messages if the hdmi switch exists
5562         if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
5563             mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
5564
5565             final String filename = "/sys/class/switch/hdmi/state";
5566             FileReader reader = null;
5567             try {
5568                 reader = new FileReader(filename);
5569                 char[] buf = new char[15];
5570                 int n = reader.read(buf);
5571                 if (n > 1) {
5572                     plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
5573                 }
5574             } catch (IOException ex) {
5575                 Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
5576             } catch (NumberFormatException ex) {
5577                 Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
5578             } finally {
5579                 if (reader != null) {
5580                     try {
5581                         reader.close();
5582                     } catch (IOException ex) {
5583                     }
5584                 }
5585             }
5586         }
5587         // This dance forces the code in setHdmiPlugged to run.
5588         // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
5589         mHdmiPlugged = !plugged;
5590         setHdmiPlugged(!mHdmiPlugged);
5591     }
5592
5593     final Object mScreenshotLock = new Object();
5594     ServiceConnection mScreenshotConnection = null;
5595
5596     final Runnable mScreenshotTimeout = new Runnable() {
5597         @Override public void run() {
5598             synchronized (mScreenshotLock) {
5599                 if (mScreenshotConnection != null) {
5600                     mContext.unbindService(mScreenshotConnection);
5601                     mScreenshotConnection = null;
5602                     notifyScreenshotError();
5603                 }
5604             }
5605         }
5606     };
5607
5608     // Assume this is called from the Handler thread.
5609     private void takeScreenshot(final int screenshotType) {
5610         synchronized (mScreenshotLock) {
5611             if (mScreenshotConnection != null) {
5612                 return;
5613             }
5614             final ComponentName serviceComponent = new ComponentName(SYSUI_PACKAGE,
5615                     SYSUI_SCREENSHOT_SERVICE);
5616             final Intent serviceIntent = new Intent();
5617             serviceIntent.setComponent(serviceComponent);
5618             ServiceConnection conn = new ServiceConnection() {
5619                 @Override
5620                 public void onServiceConnected(ComponentName name, IBinder service) {
5621                     synchronized (mScreenshotLock) {
5622                         if (mScreenshotConnection != this) {
5623                             return;
5624                         }
5625                         Messenger messenger = new Messenger(service);
5626                         Message msg = Message.obtain(null, screenshotType);
5627                         final ServiceConnection myConn = this;
5628                         Handler h = new Handler(mHandler.getLooper()) {
5629                             @Override
5630                             public void handleMessage(Message msg) {
5631                                 synchronized (mScreenshotLock) {
5632                                     if (mScreenshotConnection == myConn) {
5633                                         mContext.unbindService(mScreenshotConnection);
5634                                         mScreenshotConnection = null;
5635                                         mHandler.removeCallbacks(mScreenshotTimeout);
5636                                     }
5637                                 }
5638                             }
5639                         };
5640                         msg.replyTo = new Messenger(h);
5641                         msg.arg1 = msg.arg2 = 0;
5642                         if (mStatusBar != null && mStatusBar.isVisibleLw())
5643                             msg.arg1 = 1;
5644                         if (mNavigationBar != null && mNavigationBar.isVisibleLw())
5645                             msg.arg2 = 1;
5646                         try {
5647                             messenger.send(msg);
5648                         } catch (RemoteException e) {
5649                         }
5650                     }
5651                 }
5652
5653                 @Override
5654                 public void onServiceDisconnected(ComponentName name) {
5655                     notifyScreenshotError();
5656                 }
5657             };
5658             if (mContext.bindServiceAsUser(serviceIntent, conn,
5659                     Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE,
5660                     UserHandle.CURRENT)) {
5661                 mScreenshotConnection = conn;
5662                 mHandler.postDelayed(mScreenshotTimeout, 10000);
5663             }
5664         }
5665     }
5666
5667     /**
5668      * Notifies the screenshot service to show an error.
5669      */
5670     private void notifyScreenshotError() {
5671         // If the service process is killed, then ask it to clean up after itself
5672         final ComponentName errorComponent = new ComponentName(SYSUI_PACKAGE,
5673                 SYSUI_SCREENSHOT_ERROR_RECEIVER);
5674         Intent errorIntent = new Intent(Intent.ACTION_USER_PRESENT);
5675         errorIntent.setComponent(errorComponent);
5676         errorIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT |
5677                 Intent.FLAG_RECEIVER_FOREGROUND);
5678         mContext.sendBroadcastAsUser(errorIntent, UserHandle.CURRENT);
5679     }
5680
5681     /** {@inheritDoc} */
5682     @Override
5683     public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
5684         if (!mSystemBooted) {
5685             // If we have not yet booted, don't let key events do anything.
5686             return 0;
5687         }
5688
5689         final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;
5690         final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
5691         final boolean canceled = event.isCanceled();
5692         final int keyCode = event.getKeyCode();
5693
5694         final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
5695
5696         // If screen is off then we treat the case where the keyguard is open but hidden
5697         // the same as if it were open and in front.
5698         // This will prevent any keys other than the power button from waking the screen
5699         // when the keyguard is hidden by another activity.
5700         final boolean keyguardActive = (mKeyguardDelegate == null ? false :
5701                                             (interactive ?
5702                                                 isKeyguardShowingAndNotOccluded() :
5703                                                 mKeyguardDelegate.isShowing()));
5704
5705         if (DEBUG_INPUT) {
5706             Log.d(TAG, "interceptKeyTq keycode=" + keyCode
5707                     + " interactive=" + interactive + " keyguardActive=" + keyguardActive
5708                     + " policyFlags=" + Integer.toHexString(policyFlags));
5709         }
5710
5711         // Basic policy based on interactive state.
5712         int result;
5713         boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0
5714                 || event.isWakeKey();
5715         if (interactive || (isInjected && !isWakeKey)) {
5716             // When the device is interactive or the key is injected pass the
5717             // key to the application.
5718             result = ACTION_PASS_TO_USER;
5719             isWakeKey = false;
5720         } else if (!interactive && shouldDispatchInputWhenNonInteractive()) {
5721             // If we're currently dozing with the screen on and the keyguard showing, pass the key
5722             // to the application but preserve its wake key status to make sure we still move
5723             // from dozing to fully interactive if we would normally go from off to fully
5724             // interactive.
5725             result = ACTION_PASS_TO_USER;
5726         } else {
5727             // When the screen is off and the key is not injected, determine whether
5728             // to wake the device but don't pass the key to the application.
5729             result = 0;
5730             if (isWakeKey && (!down || !isWakeKeyWhenScreenOff(keyCode))) {
5731                 isWakeKey = false;
5732             }
5733         }
5734
5735         // If the key would be handled globally, just return the result, don't worry about special
5736         // key processing.
5737         if (isValidGlobalKey(keyCode)
5738                 && mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
5739             if (isWakeKey) {
5740                 wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
5741             }
5742             return result;
5743         }
5744
5745         boolean useHapticFeedback = down
5746                 && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
5747                 && event.getRepeatCount() == 0;
5748
5749         // Handle special keys.
5750         switch (keyCode) {
5751             case KeyEvent.KEYCODE_BACK: {
5752                 if (down) {
5753                     mBackKeyHandled = false;
5754                     if (hasLongPressOnBackBehavior()) {
5755                         Message msg = mHandler.obtainMessage(MSG_BACK_LONG_PRESS);
5756                         msg.setAsynchronous(true);
5757                         mHandler.sendMessageDelayed(msg,
5758                                 ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5759                     }
5760                 } else {
5761                     boolean handled = mBackKeyHandled;
5762
5763                     // Reset back key state
5764                     cancelPendingBackKeyAction();
5765
5766                     // Don't pass back press to app if we've already handled it
5767                     if (handled) {
5768                         result &= ~ACTION_PASS_TO_USER;
5769                     }
5770                 }
5771                 break;
5772             }
5773
5774             case KeyEvent.KEYCODE_VOLUME_DOWN:
5775             case KeyEvent.KEYCODE_VOLUME_UP:
5776             case KeyEvent.KEYCODE_VOLUME_MUTE: {
5777                 if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
5778                     if (down) {
5779                         if (interactive && !mScreenshotChordVolumeDownKeyTriggered
5780                                 && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5781                             mScreenshotChordVolumeDownKeyTriggered = true;
5782                             mScreenshotChordVolumeDownKeyTime = event.getDownTime();
5783                             mScreenshotChordVolumeDownKeyConsumed = false;
5784                             cancelPendingPowerKeyAction();
5785                             interceptScreenshotChord();
5786                         }
5787                     } else {
5788                         mScreenshotChordVolumeDownKeyTriggered = false;
5789                         cancelPendingScreenshotChordAction();
5790                     }
5791                 } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
5792                     if (down) {
5793                         if (interactive && !mScreenshotChordVolumeUpKeyTriggered
5794                                 && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
5795                             mScreenshotChordVolumeUpKeyTriggered = true;
5796                             cancelPendingPowerKeyAction();
5797                             cancelPendingScreenshotChordAction();
5798                         }
5799                     } else {
5800                         mScreenshotChordVolumeUpKeyTriggered = false;
5801                         cancelPendingScreenshotChordAction();
5802                     }
5803                 }
5804                 if (down) {
5805                     TelecomManager telecomManager = getTelecommService();
5806                     if (telecomManager != null) {
5807                         if (telecomManager.isRinging()) {
5808                             // If an incoming call is ringing, either VOLUME key means
5809                             // "silence ringer".  We handle these keys here, rather than
5810                             // in the InCallScreen, to make sure we'll respond to them
5811                             // even if the InCallScreen hasn't come to the foreground yet.
5812                             // Look for the DOWN event here, to agree with the "fallback"
5813                             // behavior in the InCallScreen.
5814                             Log.i(TAG, "interceptKeyBeforeQueueing:"
5815                                   + " VOLUME key-down while ringing: Silence ringer!");
5816
5817                             // Silence the ringer.  (It's safe to call this
5818                             // even if the ringer has already been silenced.)
5819                             telecomManager.silenceRinger();
5820
5821                             // And *don't* pass this key thru to the current activity
5822                             // (which is probably the InCallScreen.)
5823                             result &= ~ACTION_PASS_TO_USER;
5824                             break;
5825                         }
5826                         if (telecomManager.isInCall()
5827                                 && (result & ACTION_PASS_TO_USER) == 0) {
5828                             // If we are in call but we decided not to pass the key to
5829                             // the application, just pass it to the session service.
5830
5831                             MediaSessionLegacyHelper.getHelper(mContext)
5832                                     .sendVolumeKeyEvent(event, false);
5833                             break;
5834                         }
5835                     }
5836                 }
5837                 if (mUseTvRouting) {
5838                     // On TVs, defer special key handlings to
5839                     // {@link interceptKeyBeforeDispatching()}.
5840                     result |= ACTION_PASS_TO_USER;
5841                 } else if ((result & ACTION_PASS_TO_USER) == 0) {
5842                     // If we aren't passing to the user and no one else
5843                     // handled it send it to the session manager to
5844                     // figure out.
5845                     MediaSessionLegacyHelper.getHelper(mContext)
5846                             .sendVolumeKeyEvent(event, true);
5847                 }
5848                 break;
5849             }
5850
5851             case KeyEvent.KEYCODE_ENDCALL: {
5852                 result &= ~ACTION_PASS_TO_USER;
5853                 if (down) {
5854                     TelecomManager telecomManager = getTelecommService();
5855                     boolean hungUp = false;
5856                     if (telecomManager != null) {
5857                         hungUp = telecomManager.endCall();
5858                     }
5859                     if (interactive && !hungUp) {
5860                         mEndCallKeyHandled = false;
5861                         mHandler.postDelayed(mEndCallLongPress,
5862                                 ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());
5863                     } else {
5864                         mEndCallKeyHandled = true;
5865                     }
5866                 } else {
5867                     if (!mEndCallKeyHandled) {
5868                         mHandler.removeCallbacks(mEndCallLongPress);
5869                         if (!canceled) {
5870                             if ((mEndcallBehavior
5871                                     & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
5872                                 if (goHome()) {
5873                                     break;
5874                                 }
5875                             }
5876                             if ((mEndcallBehavior
5877                                     & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
5878                                 mPowerManager.goToSleep(event.getEventTime(),
5879                                         PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
5880                                 isWakeKey = false;
5881                             }
5882                         }
5883                     }
5884                 }
5885                 break;
5886             }
5887
5888             case KeyEvent.KEYCODE_POWER: {
5889                 result &= ~ACTION_PASS_TO_USER;
5890                 isWakeKey = false; // wake-up will be handled separately
5891                 if (down) {
5892                     interceptPowerKeyDown(event, interactive);
5893                 } else {
5894                     interceptPowerKeyUp(event, interactive, canceled);
5895                 }
5896                 break;
5897             }
5898
5899             case KeyEvent.KEYCODE_SLEEP: {
5900                 result &= ~ACTION_PASS_TO_USER;
5901                 isWakeKey = false;
5902                 if (!mPowerManager.isInteractive()) {
5903                     useHapticFeedback = false; // suppress feedback if already non-interactive
5904                 }
5905                 if (down) {
5906                     sleepPress(event.getEventTime());
5907                 } else {
5908                     sleepRelease(event.getEventTime());
5909                 }
5910                 break;
5911             }
5912
5913             case KeyEvent.KEYCODE_SOFT_SLEEP: {
5914                 result &= ~ACTION_PASS_TO_USER;
5915                 isWakeKey = false;
5916                 if (!down) {
5917                     mPowerManagerInternal.setUserInactiveOverrideFromWindowManager();
5918                 }
5919                 break;
5920             }
5921
5922             case KeyEvent.KEYCODE_WAKEUP: {
5923                 result &= ~ACTION_PASS_TO_USER;
5924                 isWakeKey = true;
5925                 break;
5926             }
5927
5928             case KeyEvent.KEYCODE_MEDIA_PLAY:
5929             case KeyEvent.KEYCODE_MEDIA_PAUSE:
5930             case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
5931             case KeyEvent.KEYCODE_HEADSETHOOK:
5932             case KeyEvent.KEYCODE_MUTE:
5933             case KeyEvent.KEYCODE_MEDIA_STOP:
5934             case KeyEvent.KEYCODE_MEDIA_NEXT:
5935             case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
5936             case KeyEvent.KEYCODE_MEDIA_REWIND:
5937             case KeyEvent.KEYCODE_MEDIA_RECORD:
5938             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
5939             case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
5940                 if (MediaSessionLegacyHelper.getHelper(mContext).isGlobalPriorityActive()) {
5941                     // If the global session is active pass all media keys to it
5942                     // instead of the active window.
5943                     result &= ~ACTION_PASS_TO_USER;
5944                 }
5945                 if ((result & ACTION_PASS_TO_USER) == 0) {
5946                     // Only do this if we would otherwise not pass it to the user. In that
5947                     // case, the PhoneWindow class will do the same thing, except it will
5948                     // only do it if the showing app doesn't process the key on its own.
5949                     // Note that we need to make a copy of the key event here because the
5950                     // original key event will be recycled when we return.
5951                     mBroadcastWakeLock.acquire();
5952                     Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
5953                             new KeyEvent(event));
5954                     msg.setAsynchronous(true);
5955                     msg.sendToTarget();
5956                 }
5957                 break;
5958             }
5959
5960             case KeyEvent.KEYCODE_CALL: {
5961                 if (down) {
5962                     TelecomManager telecomManager = getTelecommService();
5963                     if (telecomManager != null) {
5964                         if (telecomManager.isRinging()) {
5965                             Log.i(TAG, "interceptKeyBeforeQueueing:"
5966                                   + " CALL key-down while ringing: Answer the call!");
5967                             telecomManager.acceptRingingCall();
5968
5969                             // And *don't* pass this key thru to the current activity
5970                             // (which is presumably the InCallScreen.)
5971                             result &= ~ACTION_PASS_TO_USER;
5972                         }
5973                     }
5974                 }
5975                 break;
5976             }
5977             case KeyEvent.KEYCODE_VOICE_ASSIST: {
5978                 // Only do this if we would otherwise not pass it to the user. In that case,
5979                 // interceptKeyBeforeDispatching would apply a similar but different policy in
5980                 // order to invoke voice assist actions. Note that we need to make a copy of the
5981                 // key event here because the original key event will be recycled when we return.
5982                 if ((result & ACTION_PASS_TO_USER) == 0 && !down) {
5983                     mBroadcastWakeLock.acquire();
5984                     Message msg = mHandler.obtainMessage(MSG_LAUNCH_VOICE_ASSIST_WITH_WAKE_LOCK,
5985                             keyguardActive ? 1 : 0, 0);
5986                     msg.setAsynchronous(true);
5987                     msg.sendToTarget();
5988                 }
5989                 break;
5990             }
5991             case KeyEvent.KEYCODE_WINDOW: {
5992                 if (mShortPressWindowBehavior == SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE) {
5993                     if (mTvPictureInPictureVisible) {
5994                         // Consumes the key only if picture-in-picture is visible
5995                         // to show picture-in-picture control menu.
5996                         // This gives a chance to the foreground activity
5997                         // to customize PIP key behavior.
5998                         if (!down) {
5999                             showTvPictureInPictureMenu(event);
6000                         }
6001                         result &= ~ACTION_PASS_TO_USER;
6002                     }
6003                 }
6004                 break;
6005             }
6006         }
6007
6008         if (useHapticFeedback) {
6009             performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
6010         }
6011
6012         if (isWakeKey) {
6013             wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey, "android.policy:KEY");
6014         }
6015
6016         return result;
6017     }
6018
6019     /**
6020      * Returns true if the key can have global actions attached to it.
6021      * We reserve all power management keys for the system since they require
6022      * very careful handling.
6023      */
6024     private static boolean isValidGlobalKey(int keyCode) {
6025         switch (keyCode) {
6026             case KeyEvent.KEYCODE_POWER:
6027             case KeyEvent.KEYCODE_WAKEUP:
6028             case KeyEvent.KEYCODE_SLEEP:
6029                 return false;
6030             default:
6031                 return true;
6032         }
6033     }
6034
6035     /**
6036      * When the screen is off we ignore some keys that might otherwise typically
6037      * be considered wake keys.  We filter them out here.
6038      *
6039      * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
6040      * is always considered a wake key.
6041      */
6042     private boolean isWakeKeyWhenScreenOff(int keyCode) {
6043         switch (keyCode) {
6044             // ignore volume keys unless docked
6045             case KeyEvent.KEYCODE_VOLUME_UP:
6046             case KeyEvent.KEYCODE_VOLUME_DOWN:
6047             case KeyEvent.KEYCODE_VOLUME_MUTE:
6048                 return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
6049
6050             // ignore media and camera keys
6051             case KeyEvent.KEYCODE_MUTE:
6052             case KeyEvent.KEYCODE_HEADSETHOOK:
6053             case KeyEvent.KEYCODE_MEDIA_PLAY:
6054             case KeyEvent.KEYCODE_MEDIA_PAUSE:
6055             case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
6056             case KeyEvent.KEYCODE_MEDIA_STOP:
6057             case KeyEvent.KEYCODE_MEDIA_NEXT:
6058             case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
6059             case KeyEvent.KEYCODE_MEDIA_REWIND:
6060             case KeyEvent.KEYCODE_MEDIA_RECORD:
6061             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
6062             case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
6063             case KeyEvent.KEYCODE_CAMERA:
6064                 return false;
6065         }
6066         return true;
6067     }
6068
6069
6070     /** {@inheritDoc} */
6071     @Override
6072     public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
6073         if ((policyFlags & FLAG_WAKE) != 0) {
6074             if (wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotion,
6075                     "android.policy:MOTION")) {
6076                 return 0;
6077             }
6078         }
6079
6080         if (shouldDispatchInputWhenNonInteractive()) {
6081             return ACTION_PASS_TO_USER;
6082         }
6083
6084         // If we have not passed the action up and we are in theater mode without dreaming,
6085         // there will be no dream to intercept the touch and wake into ambient.  The device should
6086         // wake up in this case.
6087         if (isTheaterModeEnabled() && (policyFlags & FLAG_WAKE) != 0) {
6088             wakeUp(whenNanos / 1000000, mAllowTheaterModeWakeFromMotionWhenNotDreaming,
6089                     "android.policy:MOTION");
6090         }
6091
6092         return 0;
6093     }
6094
6095     private boolean shouldDispatchInputWhenNonInteractive() {
6096         final boolean displayOff = (mDisplay == null || mDisplay.getState() == Display.STATE_OFF);
6097
6098         if (displayOff && !mHasFeatureWatch) {
6099             return false;
6100         }
6101
6102         // Send events to keyguard while the screen is on and it's showing.
6103         if (isKeyguardShowingAndNotOccluded() && !displayOff) {
6104             return true;
6105         }
6106
6107         // Send events to a dozing dream even if the screen is off since the dream
6108         // is in control of the state of the screen.
6109         IDreamManager dreamManager = getDreamManager();
6110
6111         try {
6112             if (dreamManager != null && dreamManager.isDreaming()) {
6113                 return true;
6114             }
6115         } catch (RemoteException e) {
6116             Slog.e(TAG, "RemoteException when checking if dreaming", e);
6117         }
6118
6119         // Otherwise, consume events since the user can't see what is being
6120         // interacted with.
6121         return false;
6122     }
6123
6124     private void dispatchDirectAudioEvent(KeyEvent event) {
6125         if (event.getAction() != KeyEvent.ACTION_DOWN) {
6126             return;
6127         }
6128         int keyCode = event.getKeyCode();
6129         int flags = AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_PLAY_SOUND
6130                 | AudioManager.FLAG_FROM_KEY;
6131         String pkgName = mContext.getOpPackageName();
6132         switch (keyCode) {
6133             case KeyEvent.KEYCODE_VOLUME_UP:
6134                 try {
6135                     getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE,
6136                             AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
6137                 } catch (RemoteException e) {
6138                     Log.e(TAG, "Error dispatching volume up in dispatchTvAudioEvent.", e);
6139                 }
6140                 break;
6141             case KeyEvent.KEYCODE_VOLUME_DOWN:
6142                 try {
6143                     getAudioService().adjustSuggestedStreamVolume(AudioManager.ADJUST_LOWER,
6144                             AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
6145                 } catch (RemoteException e) {
6146                     Log.e(TAG, "Error dispatching volume down in dispatchTvAudioEvent.", e);
6147                 }
6148                 break;
6149             case KeyEvent.KEYCODE_VOLUME_MUTE:
6150                 try {
6151                     if (event.getRepeatCount() == 0) {
6152                         getAudioService().adjustSuggestedStreamVolume(
6153                                 AudioManager.ADJUST_TOGGLE_MUTE,
6154                                 AudioManager.USE_DEFAULT_STREAM_TYPE, flags, pkgName, TAG);
6155                     }
6156                 } catch (RemoteException e) {
6157                     Log.e(TAG, "Error dispatching mute in dispatchTvAudioEvent.", e);
6158                 }
6159                 break;
6160         }
6161     }
6162
6163     void dispatchMediaKeyWithWakeLock(KeyEvent event) {
6164         if (DEBUG_INPUT) {
6165             Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
6166         }
6167
6168         if (mHavePendingMediaKeyRepeatWithWakeLock) {
6169             if (DEBUG_INPUT) {
6170                 Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
6171             }
6172
6173             mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
6174             mHavePendingMediaKeyRepeatWithWakeLock = false;
6175             mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
6176         }
6177
6178         dispatchMediaKeyWithWakeLockToAudioService(event);
6179
6180         if (event.getAction() == KeyEvent.ACTION_DOWN
6181                 && event.getRepeatCount() == 0) {
6182             mHavePendingMediaKeyRepeatWithWakeLock = true;
6183
6184             Message msg = mHandler.obtainMessage(
6185                     MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
6186             msg.setAsynchronous(true);
6187             mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
6188         } else {
6189             mBroadcastWakeLock.release();
6190         }
6191     }
6192
6193     void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
6194         mHavePendingMediaKeyRepeatWithWakeLock = false;
6195
6196         KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
6197                 SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
6198         if (DEBUG_INPUT) {
6199             Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
6200         }
6201
6202         dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
6203         mBroadcastWakeLock.release();
6204     }
6205
6206     void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
6207         if (ActivityManagerNative.isSystemReady()) {
6208             MediaSessionLegacyHelper.getHelper(mContext).sendMediaButtonEvent(event, true);
6209         }
6210     }
6211
6212     void launchVoiceAssistWithWakeLock(boolean keyguardActive) {
6213         IDeviceIdleController dic = IDeviceIdleController.Stub.asInterface(
6214                 ServiceManager.getService(Context.DEVICE_IDLE_CONTROLLER));
6215         if (dic != null) {
6216             try {
6217                 dic.exitIdle("voice-search");
6218             } catch (RemoteException e) {
6219             }
6220         }
6221         Intent voiceIntent =
6222             new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
6223         voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE, keyguardActive);
6224         startActivityAsUser(voiceIntent, UserHandle.CURRENT_OR_SELF);
6225         mBroadcastWakeLock.release();
6226     }
6227
6228     BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
6229         @Override
6230         public void onReceive(Context context, Intent intent) {
6231             if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
6232                 mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
6233                         Intent.EXTRA_DOCK_STATE_UNDOCKED);
6234             } else {
6235                 try {
6236                     IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
6237                             ServiceManager.getService(Context.UI_MODE_SERVICE));
6238                     mUiMode = uiModeService.getCurrentModeType();
6239                 } catch (RemoteException e) {
6240                 }
6241             }
6242             updateRotation(true);
6243             synchronized (mLock) {
6244                 updateOrientationListenerLp();
6245             }
6246         }
6247     };
6248
6249     BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
6250         @Override
6251         public void onReceive(Context context, Intent intent) {
6252             if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
6253                 if (mKeyguardDelegate != null) {
6254                     mKeyguardDelegate.onDreamingStarted();
6255                 }
6256             } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
6257                 if (mKeyguardDelegate != null) {
6258                     mKeyguardDelegate.onDreamingStopped();
6259                 }
6260             }
6261         }
6262     };
6263
6264     BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
6265         @Override
6266         public void onReceive(Context context, Intent intent) {
6267             if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
6268                 // tickle the settings observer: this first ensures that we're
6269                 // observing the relevant settings for the newly-active user,
6270                 // and then updates our own bookkeeping based on the now-
6271                 // current user.
6272                 mSettingsObserver.onChange(false);
6273
6274                 // force a re-application of focused window sysui visibility.
6275                 // the window may never have been shown for this user
6276                 // e.g. the keyguard when going through the new-user setup flow
6277                 synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
6278                     mLastSystemUiFlags = 0;
6279                     updateSystemUiVisibilityLw();
6280                 }
6281             }
6282         }
6283     };
6284
6285     private final Runnable mHiddenNavPanic = new Runnable() {
6286         @Override
6287         public void run() {
6288             synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
6289                 if (!isUserSetupComplete()) {
6290                     // Swipe-up for navigation bar is disabled during setup
6291                     return;
6292                 }
6293                 mPendingPanicGestureUptime = SystemClock.uptimeMillis();
6294                 mNavigationBarController.showTransient();
6295             }
6296         }
6297     };
6298
6299     private void requestTransientBars(WindowState swipeTarget) {
6300         synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
6301             if (!isUserSetupComplete()) {
6302                 // Swipe-up for navigation bar is disabled during setup
6303                 return;
6304             }
6305             boolean sb = mStatusBarController.checkShowTransientBarLw();
6306             boolean nb = mNavigationBarController.checkShowTransientBarLw();
6307             if (sb || nb) {
6308                 // Don't show status bar when swiping on already visible navigation bar
6309                 if (!nb && swipeTarget == mNavigationBar) {
6310                     if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
6311                     return;
6312                 }
6313                 if (sb) mStatusBarController.showTransient();
6314                 if (nb) mNavigationBarController.showTransient();
6315                 mImmersiveModeConfirmation.confirmCurrentPrompt();
6316                 updateSystemUiVisibilityLw();
6317             }
6318         }
6319     }
6320
6321
6322     BroadcastReceiver mWifiDisplayReceiver = new BroadcastReceiver() {
6323         public void onReceive(Context context, Intent intent) {
6324         String action = intent.getAction();
6325             if (action.equals(ACTION_WIFI_DISPLAY_VIDEO)) {
6326                 int state = intent.getIntExtra("state", 0);
6327                 if(state == 1) {
6328                     mWifiDisplayConnected = true;
6329                 } else {
6330                     mWifiDisplayConnected = false;
6331                 }
6332                 mWifiDisplayCustomRotation =
6333                     intent.getIntExtra("wfd_UIBC_rot", -1);
6334                 updateRotation(true);
6335             }
6336         }
6337     };
6338
6339     // Called on the PowerManager's Notifier thread.
6340     @Override
6341     public void startedGoingToSleep(int why) {
6342         if (DEBUG_WAKEUP) Slog.i(TAG, "Started going to sleep... (why=" + why + ")");
6343         mCameraGestureTriggeredDuringGoingToSleep = false;
6344         mGoingToSleep = true;
6345         if (mKeyguardDelegate != null) {
6346             mKeyguardDelegate.onStartedGoingToSleep(why);
6347         }
6348     }
6349
6350     // Called on the PowerManager's Notifier thread.
6351     @Override
6352     public void finishedGoingToSleep(int why) {
6353         EventLog.writeEvent(70000, 0);
6354         if (DEBUG_WAKEUP) Slog.i(TAG, "Finished going to sleep... (why=" + why + ")");
6355         MetricsLogger.histogram(mContext, "screen_timeout", mLockScreenTimeout / 1000);
6356
6357         mGoingToSleep = false;
6358
6359         // We must get this work done here because the power manager will drop
6360         // the wake lock and let the system suspend once this function returns.
6361         synchronized (mLock) {
6362             mAwake = false;
6363             updateWakeGestureListenerLp();
6364             updateOrientationListenerLp();
6365             updateLockScreenTimeout();
6366         }
6367         if (mKeyguardDelegate != null) {
6368             mKeyguardDelegate.onFinishedGoingToSleep(why,
6369                     mCameraGestureTriggeredDuringGoingToSleep);
6370         }
6371         mCameraGestureTriggeredDuringGoingToSleep = false;
6372     }
6373
6374     // Called on the PowerManager's Notifier thread.
6375     @Override
6376     public void startedWakingUp() {
6377         EventLog.writeEvent(70000, 1);
6378         if (DEBUG_WAKEUP) Slog.i(TAG, "Started waking up...");
6379
6380         // Since goToSleep performs these functions synchronously, we must
6381         // do the same here.  We cannot post this work to a handler because
6382         // that might cause it to become reordered with respect to what
6383         // may happen in a future call to goToSleep.
6384         synchronized (mLock) {
6385             mAwake = true;
6386
6387             updateWakeGestureListenerLp();
6388             updateOrientationListenerLp();
6389             updateLockScreenTimeout();
6390         }
6391
6392         if (mKeyguardDelegate != null) {
6393             mKeyguardDelegate.onStartedWakingUp();
6394         }
6395     }
6396
6397     // Called on the PowerManager's Notifier thread.
6398     @Override
6399     public void finishedWakingUp() {
6400         if (DEBUG_WAKEUP) Slog.i(TAG, "Finished waking up...");
6401     }
6402
6403     private void wakeUpFromPowerKey(long eventTime) {
6404         wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey, "android.policy:POWER");
6405     }
6406
6407     private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode, String reason) {
6408         final boolean theaterModeEnabled = isTheaterModeEnabled();
6409         if (!wakeInTheaterMode && theaterModeEnabled) {
6410             return false;
6411         }
6412
6413         if (theaterModeEnabled) {
6414             Settings.Global.putInt(mContext.getContentResolver(),
6415                     Settings.Global.THEATER_MODE_ON, 0);
6416         }
6417
6418         mPowerManager.wakeUp(wakeTime, reason);
6419         return true;
6420     }
6421
6422     private void finishKeyguardDrawn() {
6423         synchronized (mLock) {
6424             if (!mScreenOnEarly || mKeyguardDrawComplete) {
6425                 return; // We are not awake yet or we have already informed of this event.
6426             }
6427
6428             mKeyguardDrawComplete = true;
6429             if (mKeyguardDelegate != null) {
6430                 mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
6431             }
6432             mWindowManagerDrawComplete = false;
6433         }
6434
6435         // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
6436         // as well as enabling the orientation change logic/sensor.
6437         mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
6438                 WAITING_FOR_DRAWN_TIMEOUT);
6439     }
6440
6441     // Called on the DisplayManager's DisplayPowerController thread.
6442     @Override
6443     public void screenTurnedOff() {
6444         if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turned off...");
6445
6446         updateScreenOffSleepToken(true);
6447         synchronized (mLock) {
6448             mScreenOnEarly = false;
6449             mScreenOnFully = false;
6450             mKeyguardDrawComplete = false;
6451             mWindowManagerDrawComplete = false;
6452             mScreenOnListener = null;
6453             updateOrientationListenerLp();
6454
6455             if (mKeyguardDelegate != null) {
6456                 mKeyguardDelegate.onScreenTurnedOff();
6457             }
6458         }
6459     }
6460
6461     // Called on the DisplayManager's DisplayPowerController thread.
6462     @Override
6463     public void screenTurningOn(final ScreenOnListener screenOnListener) {
6464         if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
6465
6466         updateScreenOffSleepToken(false);
6467         synchronized (mLock) {
6468             mScreenOnEarly = true;
6469             mScreenOnFully = false;
6470             mKeyguardDrawComplete = false;
6471             mWindowManagerDrawComplete = false;
6472             mScreenOnListener = screenOnListener;
6473
6474             if (mKeyguardDelegate != null) {
6475                 mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
6476                 mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);
6477                 mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
6478             } else {
6479                 if (DEBUG_WAKEUP) Slog.d(TAG,
6480                         "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
6481                 finishKeyguardDrawn();
6482             }
6483         }
6484     }
6485
6486     // Called on the DisplayManager's DisplayPowerController thread.
6487     @Override
6488     public void screenTurnedOn() {
6489         synchronized (mLock) {
6490             if (mKeyguardDelegate != null) {
6491                 mKeyguardDelegate.onScreenTurnedOn();
6492             }
6493         }
6494     }
6495
6496     private void finishWindowsDrawn() {
6497         synchronized (mLock) {
6498             if (!mScreenOnEarly || mWindowManagerDrawComplete) {
6499                 return; // Screen is not turned on or we did already handle this case earlier.
6500             }
6501
6502             mWindowManagerDrawComplete = true;
6503         }
6504
6505         finishScreenTurningOn();
6506     }
6507
6508     private void finishScreenTurningOn() {
6509         synchronized (mLock) {
6510             // We have just finished drawing screen content. Since the orientation listener
6511             // gets only installed when all windows are drawn, we try to install it again.
6512             updateOrientationListenerLp();
6513         }
6514         final ScreenOnListener listener;
6515         final boolean enableScreen;
6516         synchronized (mLock) {
6517             if (DEBUG_WAKEUP) Slog.d(TAG,
6518                     "finishScreenTurningOn: mAwake=" + mAwake
6519                             + ", mScreenOnEarly=" + mScreenOnEarly
6520                             + ", mScreenOnFully=" + mScreenOnFully
6521                             + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
6522                             + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
6523
6524             if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
6525                     || (mAwake && !mKeyguardDrawComplete)) {
6526                 return; // spurious or not ready yet
6527             }
6528
6529             if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
6530             listener = mScreenOnListener;
6531             mScreenOnListener = null;
6532             mScreenOnFully = true;
6533
6534             // Remember the first time we draw the keyguard so we know when we're done with
6535             // the main part of booting and can enable the screen and hide boot messages.
6536             if (!mKeyguardDrawnOnce && mAwake) {
6537                 mKeyguardDrawnOnce = true;
6538                 enableScreen = true;
6539                 if (mBootMessageNeedsHiding) {
6540                     mBootMessageNeedsHiding = false;
6541                     hideBootMessages();
6542                 }
6543             } else {
6544                 enableScreen = false;
6545             }
6546         }
6547
6548         if (listener != null) {
6549             listener.onScreenOn();
6550         }
6551
6552         if (enableScreen) {
6553             try {
6554                 mWindowManager.enableScreenIfNeeded();
6555             } catch (RemoteException unhandled) {
6556             }
6557         }
6558     }
6559
6560     private void handleHideBootMessage() {
6561         synchronized (mLock) {
6562             if (!mKeyguardDrawnOnce) {
6563                 mBootMessageNeedsHiding = true;
6564                 return; // keyguard hasn't drawn the first time yet, not done booting
6565             }
6566         }
6567
6568         if (mBootMsgDialog != null) {
6569             if (DEBUG_WAKEUP) Slog.d(TAG, "handleHideBootMessage: dismissing");
6570             mBootMsgDialog.dismiss();
6571             mBootMsgDialog = null;
6572         }
6573     }
6574
6575     @Override
6576     public boolean isScreenOn() {
6577         return mScreenOnFully;
6578     }
6579
6580     /** {@inheritDoc} */
6581     @Override
6582     public void enableKeyguard(boolean enabled) {
6583         if (mKeyguardDelegate != null) {
6584             mKeyguardDelegate.setKeyguardEnabled(enabled);
6585         }
6586     }
6587
6588     /** {@inheritDoc} */
6589     @Override
6590     public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
6591         if (mKeyguardDelegate != null) {
6592             mKeyguardDelegate.verifyUnlock(callback);
6593         }
6594     }
6595
6596     private boolean isKeyguardShowingAndNotOccluded() {
6597         if (mKeyguardDelegate == null) return false;
6598         return mKeyguardDelegate.isShowing() && !mKeyguardOccluded;
6599     }
6600
6601     /** {@inheritDoc} */
6602     @Override
6603     public boolean isKeyguardLocked() {
6604         return keyguardOn();
6605     }
6606
6607     /** {@inheritDoc} */
6608     @Override
6609     public boolean isKeyguardSecure(int userId) {
6610         if (mKeyguardDelegate == null) return false;
6611         return mKeyguardDelegate.isSecure(userId);
6612     }
6613
6614     /** {@inheritDoc} */
6615     @Override
6616     public boolean isKeyguardShowingOrOccluded() {
6617         return mKeyguardDelegate == null ? false : mKeyguardDelegate.isShowing();
6618     }
6619
6620     /** {@inheritDoc} */
6621     @Override
6622     public boolean inKeyguardRestrictedKeyInputMode() {
6623         if (mKeyguardDelegate == null) return false;
6624         return mKeyguardDelegate.isInputRestricted();
6625     }
6626
6627     @Override
6628     public void dismissKeyguardLw() {
6629         if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
6630             if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.dismissKeyguardLw");
6631             mHandler.post(new Runnable() {
6632                 @Override
6633                 public void run() {
6634                     // ask the keyguard to prompt the user to authenticate if necessary
6635                     mKeyguardDelegate.dismiss();
6636                 }
6637             });
6638         }
6639     }
6640
6641     @Override
6642     public void notifyActivityDrawnForKeyguardLw() {
6643         if (mKeyguardDelegate != null) {
6644             mHandler.post(new Runnable() {
6645                 @Override
6646                 public void run() {
6647                     mKeyguardDelegate.onActivityDrawn();
6648                 }
6649             });
6650         }
6651     }
6652
6653     @Override
6654     public boolean isKeyguardDrawnLw() {
6655         synchronized (mLock) {
6656             return mKeyguardDrawnOnce;
6657         }
6658     }
6659
6660     @Override
6661     public void startKeyguardExitAnimation(long startTime, long fadeoutDuration) {
6662         if (mKeyguardDelegate != null) {
6663             if (DEBUG_KEYGUARD) Slog.d(TAG, "PWM.startKeyguardExitAnimation");
6664             mKeyguardDelegate.startKeyguardExitAnimation(startTime, fadeoutDuration);
6665         }
6666     }
6667
6668     @Override
6669     public void getStableInsetsLw(int displayRotation, int displayWidth, int displayHeight,
6670             Rect outInsets) {
6671         outInsets.setEmpty();
6672
6673         // Navigation bar and status bar.
6674         getNonDecorInsetsLw(displayRotation, displayWidth, displayHeight, outInsets);
6675         if (mStatusBar != null) {
6676             outInsets.top = mStatusBarHeight;
6677         }
6678     }
6679
6680     @Override
6681     public void getNonDecorInsetsLw(int displayRotation, int displayWidth, int displayHeight,
6682             Rect outInsets) {
6683         outInsets.setEmpty();
6684
6685         // Only navigation bar
6686         if (mNavigationBar != null) {
6687             if (isNavigationBarOnBottom(displayWidth, displayHeight)) {
6688                 outInsets.bottom = getNavigationBarHeight(displayRotation, mUiMode);
6689             } else {
6690                 outInsets.right = getNavigationBarWidth(displayRotation, mUiMode);
6691             }
6692         }
6693     }
6694
6695     @Override
6696     public boolean isNavBarForcedShownLw(WindowState windowState) {
6697         return mForceShowSystemBars;
6698     }
6699
6700     @Override
6701     public boolean isDockSideAllowed(int dockSide) {
6702
6703         // We do not allow all dock sides at which the navigation bar touches the docked stack.
6704         if (!mNavigationBarCanMove) {
6705             return dockSide == DOCKED_TOP || dockSide == DOCKED_LEFT || dockSide == DOCKED_RIGHT;
6706         } else {
6707             return dockSide == DOCKED_TOP || dockSide == DOCKED_LEFT;
6708         }
6709     }
6710
6711     void sendCloseSystemWindows() {
6712         PhoneWindow.sendCloseSystemWindows(mContext, null);
6713     }
6714
6715     void sendCloseSystemWindows(String reason) {
6716         PhoneWindow.sendCloseSystemWindows(mContext, reason);
6717     }
6718
6719     @Override
6720     public int rotationForOrientationLw(int orientation, int lastRotation) {
6721         if (false) {
6722             Slog.v(TAG, "rotationForOrientationLw(orient="
6723                         + orientation + ", last=" + lastRotation
6724                         + "); user=" + mUserRotation + " "
6725                         + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
6726                             ? "USER_ROTATION_LOCKED" : "")
6727                         );
6728         }
6729
6730         if (mForceDefaultOrientation) {
6731             return Surface.ROTATION_0;
6732         }
6733
6734         synchronized (mLock) {
6735             int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
6736             if (sensorRotation < 0) {
6737                 sensorRotation = lastRotation;
6738             }
6739
6740             final int preferredRotation;
6741             if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
6742                 // Ignore sensor when lid switch is open and rotation is forced.
6743                 preferredRotation = mLidOpenRotation;
6744             } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
6745                     && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
6746                 // Ignore sensor when in car dock unless explicitly enabled.
6747                 // This case can override the behavior of NOSENSOR, and can also
6748                 // enable 180 degree rotation while docked.
6749                 preferredRotation = mCarDockEnablesAccelerometer
6750                         ? sensorRotation : mCarDockRotation;
6751             } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
6752                     || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
6753                     || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
6754                     && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
6755                 // Ignore sensor when in desk dock unless explicitly enabled.
6756                 // This case can override the behavior of NOSENSOR, and can also
6757                 // enable 180 degree rotation while docked.
6758                 preferredRotation = mDeskDockEnablesAccelerometer
6759                         ? sensorRotation : mDeskDockRotation;
6760             } else if ((mHdmiPlugged || mWifiDisplayConnected) && mDemoHdmiRotationLock) {
6761                 // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
6762                 // Note that the dock orientation overrides the HDMI orientation.
6763                 preferredRotation = mDemoHdmiRotation;
6764             } else if (mWifiDisplayConnected && (mWifiDisplayCustomRotation > -1)) {
6765                 // Ignore sensor when WFD is active and UIBC rotation is enabled
6766                  preferredRotation = mWifiDisplayCustomRotation;
6767             } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
6768                     && mUndockedHdmiRotation >= 0) {
6769                 // Ignore sensor when plugged into HDMI and an undocked orientation has
6770                 // been specified in the configuration (only for legacy devices without
6771                 // full multi-display support).
6772                 // Note that the dock orientation overrides the HDMI orientation.
6773                 preferredRotation = mUndockedHdmiRotation;
6774             } else if (mDemoRotationLock) {
6775                 // Ignore sensor when demo rotation lock is enabled.
6776                 // Note that the dock orientation and HDMI rotation lock override this.
6777                 preferredRotation = mDemoRotation;
6778             } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
6779                 // Application just wants to remain locked in the last rotation.
6780                 preferredRotation = lastRotation;
6781             } else if (!mSupportAutoRotation) {
6782                 // If we don't support auto-rotation then bail out here and ignore
6783                 // the sensor and any rotation lock settings.
6784                 preferredRotation = -1;
6785             } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
6786                             && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
6787                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
6788                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
6789                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
6790                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
6791                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
6792                     || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6793                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
6794                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
6795                 // Otherwise, use sensor only if requested by the application or enabled
6796                 // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
6797                 if (mAllowAllRotations < 0) {
6798                     // Can't read this during init() because the context doesn't
6799                     // have display metrics at that time so we cannot determine
6800                     // tablet vs. phone then.
6801                     mAllowAllRotations = mContext.getResources().getBoolean(
6802                             com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
6803                 }
6804                 if (sensorRotation != Surface.ROTATION_180
6805                         || mAllowAllRotations == 1
6806                         || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
6807                         || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
6808                     preferredRotation = sensorRotation;
6809                 } else {
6810                     preferredRotation = lastRotation;
6811                 }
6812             } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
6813                     && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
6814                 // Apply rotation lock.  Does not apply to NOSENSOR.
6815                 // The idea is that the user rotation expresses a weak preference for the direction
6816                 // of gravity and as NOSENSOR is never affected by gravity, then neither should
6817                 // NOSENSOR be affected by rotation lock (although it will be affected by docks).
6818                 preferredRotation = mUserRotation;
6819             } else {
6820                 // No overriding preference.
6821                 // We will do exactly what the application asked us to do.
6822                 preferredRotation = -1;
6823             }
6824
6825             switch (orientation) {
6826                 case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6827                     // Return portrait unless overridden.
6828                     if (isAnyPortrait(preferredRotation)) {
6829                         return preferredRotation;
6830                     }
6831                     return mPortraitRotation;
6832
6833                 case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6834                     // Return landscape unless overridden.
6835                     if (isLandscapeOrSeascape(preferredRotation)) {
6836                         return preferredRotation;
6837                     }
6838                     return mLandscapeRotation;
6839
6840                 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6841                     // Return reverse portrait unless overridden.
6842                     if (isAnyPortrait(preferredRotation)) {
6843                         return preferredRotation;
6844                     }
6845                     return mUpsideDownRotation;
6846
6847                 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6848                     // Return seascape unless overridden.
6849                     if (isLandscapeOrSeascape(preferredRotation)) {
6850                         return preferredRotation;
6851                     }
6852                     return mSeascapeRotation;
6853
6854                 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6855                 case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
6856                     // Return either landscape rotation.
6857                     if (isLandscapeOrSeascape(preferredRotation)) {
6858                         return preferredRotation;
6859                     }
6860                     if (isLandscapeOrSeascape(lastRotation)) {
6861                         return lastRotation;
6862                     }
6863                     return mLandscapeRotation;
6864
6865                 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6866                 case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
6867                     // Return either portrait rotation.
6868                     if (isAnyPortrait(preferredRotation)) {
6869                         return preferredRotation;
6870                     }
6871                     if (isAnyPortrait(lastRotation)) {
6872                         return lastRotation;
6873                     }
6874                     return mPortraitRotation;
6875
6876                 default:
6877                     // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
6878                     // just return the preferred orientation we already calculated.
6879                     if (preferredRotation >= 0) {
6880                         return preferredRotation;
6881                     }
6882                     return Surface.ROTATION_0;
6883             }
6884         }
6885     }
6886
6887     @Override
6888     public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
6889         switch (orientation) {
6890             case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
6891             case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
6892             case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
6893                 return isAnyPortrait(rotation);
6894
6895             case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
6896             case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
6897             case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
6898                 return isLandscapeOrSeascape(rotation);
6899
6900             default:
6901                 return true;
6902         }
6903     }
6904
6905     @Override
6906     public void setRotationLw(int rotation) {
6907         mOrientationListener.setCurrentRotation(rotation);
6908     }
6909
6910     private boolean isLandscapeOrSeascape(int rotation) {
6911         return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
6912     }
6913
6914     private boolean isAnyPortrait(int rotation) {
6915         return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
6916     }
6917
6918     @Override
6919     public int getUserRotationMode() {
6920         return Settings.System.getIntForUser(mContext.getContentResolver(),
6921                 Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
6922                         WindowManagerPolicy.USER_ROTATION_FREE :
6923                                 WindowManagerPolicy.USER_ROTATION_LOCKED;
6924     }
6925
6926     // User rotation: to be used when all else fails in assigning an orientation to the device
6927     @Override
6928     public void setUserRotationMode(int mode, int rot) {
6929         ContentResolver res = mContext.getContentResolver();
6930
6931         // mUserRotationMode and mUserRotation will be assigned by the content observer
6932         if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
6933             Settings.System.putIntForUser(res,
6934                     Settings.System.USER_ROTATION,
6935                     rot,
6936                     UserHandle.USER_CURRENT);
6937             Settings.System.putIntForUser(res,
6938                     Settings.System.ACCELEROMETER_ROTATION,
6939                     0,
6940                     UserHandle.USER_CURRENT);
6941         } else {
6942             Settings.System.putIntForUser(res,
6943                     Settings.System.ACCELEROMETER_ROTATION,
6944                     1,
6945                     UserHandle.USER_CURRENT);
6946         }
6947     }
6948
6949     @Override
6950     public void setSafeMode(boolean safeMode) {
6951         mSafeMode = safeMode;
6952         performHapticFeedbackLw(null, safeMode
6953                 ? HapticFeedbackConstants.SAFE_MODE_ENABLED
6954                 : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
6955     }
6956
6957     static long[] getLongIntArray(Resources r, int resid) {
6958         int[] ar = r.getIntArray(resid);
6959         if (ar == null) {
6960             return null;
6961         }
6962         long[] out = new long[ar.length];
6963         for (int i=0; i<ar.length; i++) {
6964             out[i] = ar[i];
6965         }
6966         return out;
6967     }
6968
6969     /** {@inheritDoc} */
6970     @Override
6971     public void systemReady() {
6972         mKeyguardDelegate = new KeyguardServiceDelegate(mContext);
6973         mKeyguardDelegate.onSystemReady();
6974
6975         readCameraLensCoverState();
6976         updateUiMode();
6977         boolean bindKeyguardNow;
6978         synchronized (mLock) {
6979             updateOrientationListenerLp();
6980             mSystemReady = true;
6981             mHandler.post(new Runnable() {
6982                 @Override
6983                 public void run() {
6984                     updateSettings();
6985                 }
6986             });
6987
6988             bindKeyguardNow = mDeferBindKeyguard;
6989             if (bindKeyguardNow) {
6990                 // systemBooted ran but wasn't able to bind to the Keyguard, we'll do it now.
6991                 mDeferBindKeyguard = false;
6992             }
6993         }
6994
6995         if (bindKeyguardNow) {
6996             mKeyguardDelegate.bindService(mContext);
6997             mKeyguardDelegate.onBootCompleted();
6998         }
6999         mSystemGestures.systemReady();
7000         mImmersiveModeConfirmation.systemReady();
7001     }
7002
7003     /** {@inheritDoc} */
7004     @Override
7005     public void systemBooted() {
7006         boolean bindKeyguardNow = false;
7007         synchronized (mLock) {
7008             // Time to bind Keyguard; take care to only bind it once, either here if ready or
7009             // in systemReady if not.
7010             if (mKeyguardDelegate != null) {
7011                 bindKeyguardNow = true;
7012             } else {
7013                 // Because mKeyguardDelegate is null, we know that the synchronized block in
7014                 // systemReady didn't run yet and setting this will actually have an effect.
7015                 mDeferBindKeyguard = true;
7016             }
7017         }
7018         if (bindKeyguardNow) {
7019             mKeyguardDelegate.bindService(mContext);
7020             mKeyguardDelegate.onBootCompleted();
7021         }
7022         synchronized (mLock) {
7023             mSystemBooted = true;
7024         }
7025         startedWakingUp();
7026         screenTurningOn(null);
7027         screenTurnedOn();
7028     }
7029
7030     ProgressDialog mBootMsgDialog = null;
7031
7032     /** {@inheritDoc} */
7033     @Override
7034     public void showBootMessage(final CharSequence msg, final boolean always) {
7035         mHandler.post(new Runnable() {
7036             @Override public void run() {
7037                 if (mBootMsgDialog == null) {
7038                     int theme;
7039                     if (mHasFeatureWatch) {
7040                         theme = com.android.internal.R.style.Theme_Micro_Dialog_Alert;
7041                     } else if (mContext.getPackageManager().hasSystemFeature(FEATURE_TELEVISION)) {
7042                         theme = com.android.internal.R.style.Theme_Leanback_Dialog_Alert;
7043                     } else {
7044                         theme = 0;
7045                     }
7046
7047                     mBootMsgDialog = new ProgressDialog(mContext, theme) {
7048                         // This dialog will consume all events coming in to
7049                         // it, to avoid it trying to do things too early in boot.
7050                         @Override public boolean dispatchKeyEvent(KeyEvent event) {
7051                             return true;
7052                         }
7053                         @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7054                             return true;
7055                         }
7056                         @Override public boolean dispatchTouchEvent(MotionEvent ev) {
7057                             return true;
7058                         }
7059                         @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
7060                             return true;
7061                         }
7062                         @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
7063                             return true;
7064                         }
7065                         @Override public boolean dispatchPopulateAccessibilityEvent(
7066                                 AccessibilityEvent event) {
7067                             return true;
7068                         }
7069                     };
7070                     if (mContext.getPackageManager().isUpgrade()) {
7071                         mBootMsgDialog.setTitle(R.string.android_upgrading_title);
7072                     } else {
7073                         mBootMsgDialog.setTitle(R.string.android_start_title);
7074                     }
7075                     mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
7076                     mBootMsgDialog.setIndeterminate(true);
7077                     mBootMsgDialog.getWindow().setType(
7078                             WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
7079                     mBootMsgDialog.getWindow().addFlags(
7080                             WindowManager.LayoutParams.FLAG_DIM_BEHIND
7081                             | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
7082                     mBootMsgDialog.getWindow().setDimAmount(1);
7083                     WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
7084                     lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
7085                     mBootMsgDialog.getWindow().setAttributes(lp);
7086                     mBootMsgDialog.setCancelable(false);
7087                     mBootMsgDialog.show();
7088                 }
7089                 mBootMsgDialog.setMessage(msg);
7090             }
7091         });
7092     }
7093
7094     /** {@inheritDoc} */
7095     @Override
7096     public void hideBootMessages() {
7097         mHandler.sendEmptyMessage(MSG_HIDE_BOOT_MESSAGE);
7098     }
7099
7100     /** {@inheritDoc} */
7101     @Override
7102     public void userActivity() {
7103         // ***************************************
7104         // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
7105         // ***************************************
7106         // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
7107         // WITH ITS LOCKS HELD.
7108         //
7109         // This code must be VERY careful about the locks
7110         // it acquires.
7111         // In fact, the current code acquires way too many,
7112         // and probably has lurking deadlocks.
7113
7114         synchronized (mScreenLockTimeout) {
7115             if (mLockScreenTimerActive) {
7116                 // reset the timer
7117                 mHandler.removeCallbacks(mScreenLockTimeout);
7118                 mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
7119             }
7120         }
7121     }
7122
7123     class ScreenLockTimeout implements Runnable {
7124         Bundle options;
7125
7126         @Override
7127         public void run() {
7128             synchronized (this) {
7129                 if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
7130                 if (mKeyguardDelegate != null) {
7131                     mKeyguardDelegate.doKeyguardTimeout(options);
7132                 }
7133                 mLockScreenTimerActive = false;
7134                 options = null;
7135             }
7136         }
7137
7138         public void setLockOptions(Bundle options) {
7139             this.options = options;
7140         }
7141     }
7142
7143     ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
7144
7145     @Override
7146     public void lockNow(Bundle options) {
7147         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
7148         mHandler.removeCallbacks(mScreenLockTimeout);
7149         if (options != null) {
7150             // In case multiple calls are made to lockNow, we don't wipe out the options
7151             // until the runnable actually executes.
7152             mScreenLockTimeout.setLockOptions(options);
7153         }
7154         mHandler.post(mScreenLockTimeout);
7155     }
7156
7157     private void updateLockScreenTimeout() {
7158         synchronized (mScreenLockTimeout) {
7159             boolean enable = (mAllowLockscreenWhenOn && mAwake &&
7160                     mKeyguardDelegate != null && mKeyguardDelegate.isSecure(mCurrentUserId));
7161             if (mLockScreenTimerActive != enable) {
7162                 if (enable) {
7163                     if (localLOGV) Log.v(TAG, "setting lockscreen timer");
7164                     mHandler.removeCallbacks(mScreenLockTimeout); // remove any pending requests
7165                     mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
7166                 } else {
7167                     if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
7168                     mHandler.removeCallbacks(mScreenLockTimeout);
7169                 }
7170                 mLockScreenTimerActive = enable;
7171             }
7172         }
7173     }
7174
7175     private void updateDreamingSleepToken(boolean acquire) {
7176         if (acquire) {
7177             if (mDreamingSleepToken == null) {
7178                 mDreamingSleepToken = mActivityManagerInternal.acquireSleepToken("Dream");
7179             }
7180         } else {
7181             if (mDreamingSleepToken != null) {
7182                 mDreamingSleepToken.release();
7183                 mDreamingSleepToken = null;
7184             }
7185         }
7186     }
7187
7188     private void updateScreenOffSleepToken(boolean acquire) {
7189         if (acquire) {
7190             if (mScreenOffSleepToken == null) {
7191                 mScreenOffSleepToken = mActivityManagerInternal.acquireSleepToken("ScreenOff");
7192             }
7193         } else {
7194             if (mScreenOffSleepToken != null) {
7195                 mScreenOffSleepToken.release();
7196                 mScreenOffSleepToken = null;
7197             }
7198         }
7199     }
7200
7201     /** {@inheritDoc} */
7202     @Override
7203     public void enableScreenAfterBoot() {
7204         readLidState();
7205         applyLidSwitchState();
7206         updateRotation(true);
7207     }
7208
7209     private void applyLidSwitchState() {
7210         mPowerManager.setKeyboardVisibility(isBuiltInKeyboardVisible());
7211
7212         if (mLidState == LID_CLOSED && mLidControlsSleep) {
7213             mPowerManager.goToSleep(SystemClock.uptimeMillis(),
7214                     PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH,
7215                     PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
7216         } else if (mLidState == LID_CLOSED && mLidControlsScreenLock) {
7217             mWindowManagerFuncs.lockDeviceNow();
7218         }
7219
7220         synchronized (mLock) {
7221             updateWakeGestureListenerLp();
7222         }
7223     }
7224
7225     void updateUiMode() {
7226         if (mUiModeManager == null) {
7227             mUiModeManager = IUiModeManager.Stub.asInterface(
7228                     ServiceManager.getService(Context.UI_MODE_SERVICE));
7229         }
7230         try {
7231             mUiMode = mUiModeManager.getCurrentModeType();
7232         } catch (RemoteException e) {
7233         }
7234     }
7235
7236     void updateRotation(boolean alwaysSendConfiguration) {
7237         try {
7238             //set orientation on WindowManager
7239             mWindowManager.updateRotation(alwaysSendConfiguration, false);
7240         } catch (RemoteException e) {
7241             // Ignore
7242         }
7243     }
7244
7245     void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
7246         try {
7247             //set orientation on WindowManager
7248             mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
7249         } catch (RemoteException e) {
7250             // Ignore
7251         }
7252     }
7253
7254     /**
7255      * Return an Intent to launch the currently active dock app as home.  Returns
7256      * null if the standard home should be launched, which is the case if any of the following is
7257      * true:
7258      * <ul>
7259      *  <li>The device is not in either car mode or desk mode
7260      *  <li>The device is in car mode but mEnableCarDockHomeCapture is false
7261      *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
7262      *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
7263      *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
7264      * </ul>
7265      * @return A dock intent.
7266      */
7267     Intent createHomeDockIntent() {
7268         Intent intent = null;
7269
7270         // What home does is based on the mode, not the dock state.  That
7271         // is, when in car mode you should be taken to car home regardless
7272         // of whether we are actually in a car dock.
7273         if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
7274             if (mEnableCarDockHomeCapture) {
7275                 intent = mCarDockIntent;
7276             }
7277         } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
7278             if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
7279                 intent = mDeskDockIntent;
7280             }
7281         } else if (mUiMode == Configuration.UI_MODE_TYPE_WATCH
7282                 && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
7283                         || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK
7284                         || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK)) {
7285             // Always launch dock home from home when watch is docked, if it exists.
7286             intent = mDeskDockIntent;
7287         }
7288
7289         if (intent == null) {
7290             return null;
7291         }
7292
7293         ActivityInfo ai = null;
7294         ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
7295                 intent,
7296                 PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
7297                 mCurrentUserId);
7298         if (info != null) {
7299             ai = info.activityInfo;
7300         }
7301         if (ai != null
7302                 && ai.metaData != null
7303                 && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
7304             intent = new Intent(intent);
7305             intent.setClassName(ai.packageName, ai.name);
7306             return intent;
7307         }
7308
7309         return null;
7310     }
7311
7312     void startDockOrHome(boolean fromHomeKey, boolean awakenFromDreams) {
7313         if (awakenFromDreams) {
7314             awakenDreams();
7315         }
7316
7317         Intent dock = createHomeDockIntent();
7318         if (dock != null) {
7319             try {
7320                 if (fromHomeKey) {
7321                     dock.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
7322                 }
7323                 startActivityAsUser(dock, UserHandle.CURRENT);
7324                 return;
7325             } catch (ActivityNotFoundException e) {
7326             }
7327         }
7328
7329         Intent intent;
7330
7331         if (fromHomeKey) {
7332             intent = new Intent(mHomeIntent);
7333             intent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, fromHomeKey);
7334         } else {
7335             intent = mHomeIntent;
7336         }
7337
7338         startActivityAsUser(intent, UserHandle.CURRENT);
7339     }
7340
7341     /**
7342      * goes to the home screen
7343      * @return whether it did anything
7344      */
7345     boolean goHome() {
7346         if (!isUserSetupComplete()) {
7347             Slog.i(TAG, "Not going home because user setup is in progress.");
7348             return false;
7349         }
7350         if (false) {
7351             // This code always brings home to the front.
7352             try {
7353                 ActivityManagerNative.getDefault().stopAppSwitches();
7354             } catch (RemoteException e) {
7355             }
7356             sendCloseSystemWindows();
7357             startDockOrHome(false /*fromHomeKey*/, true /* awakenFromDreams */);
7358         } else {
7359             // This code brings home to the front or, if it is already
7360             // at the front, puts the device to sleep.
7361             try {
7362                 if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
7363                     /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
7364                     Log.d(TAG, "UTS-TEST-MODE");
7365                 } else {
7366                     ActivityManagerNative.getDefault().stopAppSwitches();
7367                     sendCloseSystemWindows();
7368                     Intent dock = createHomeDockIntent();
7369                     if (dock != null) {
7370                         int result = ActivityManagerNative.getDefault()
7371                                 .startActivityAsUser(null, null, dock,
7372                                         dock.resolveTypeIfNeeded(mContext.getContentResolver()),
7373                                         null, null, 0,
7374                                         ActivityManager.START_FLAG_ONLY_IF_NEEDED,
7375                                         null, null, UserHandle.USER_CURRENT);
7376                         if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
7377                             return false;
7378                         }
7379                     }
7380                 }
7381                 int result = ActivityManagerNative.getDefault()
7382                         .startActivityAsUser(null, null, mHomeIntent,
7383                                 mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
7384                                 null, null, 0,
7385                                 ActivityManager.START_FLAG_ONLY_IF_NEEDED,
7386                                 null, null, UserHandle.USER_CURRENT);
7387                 if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
7388                     return false;
7389                 }
7390             } catch (RemoteException ex) {
7391                 // bummer, the activity manager, which is in this process, is dead
7392             }
7393         }
7394         return true;
7395     }
7396
7397     @Override
7398     public void setCurrentOrientationLw(int newOrientation) {
7399         synchronized (mLock) {
7400             if (newOrientation != mCurrentAppOrientation) {
7401                 mCurrentAppOrientation = newOrientation;
7402                 updateOrientationListenerLp();
7403             }
7404         }
7405     }
7406
7407     private void performAuditoryFeedbackForAccessibilityIfNeed() {
7408         if (!isGlobalAccessibilityGestureEnabled()) {
7409             return;
7410         }
7411         AudioManager audioManager = (AudioManager) mContext.getSystemService(
7412                 Context.AUDIO_SERVICE);
7413         if (audioManager.isSilentMode()) {
7414             return;
7415         }
7416         Ringtone ringTone = RingtoneManager.getRingtone(mContext,
7417                 Settings.System.DEFAULT_NOTIFICATION_URI);
7418         ringTone.setStreamType(AudioManager.STREAM_MUSIC);
7419         ringTone.play();
7420     }
7421
7422     private boolean isTheaterModeEnabled() {
7423         return Settings.Global.getInt(mContext.getContentResolver(),
7424                 Settings.Global.THEATER_MODE_ON, 0) == 1;
7425     }
7426
7427     private boolean isGlobalAccessibilityGestureEnabled() {
7428         return Settings.Global.getInt(mContext.getContentResolver(),
7429                 Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
7430     }
7431
7432     @Override
7433     public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
7434         if (!mVibrator.hasVibrator()) {
7435             return false;
7436         }
7437         final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
7438                 Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
7439         if (hapticsDisabled && !always) {
7440             return false;
7441         }
7442         long[] pattern = null;
7443         switch (effectId) {
7444             case HapticFeedbackConstants.LONG_PRESS:
7445                 pattern = mLongPressVibePattern;
7446                 break;
7447             case HapticFeedbackConstants.VIRTUAL_KEY:
7448                 pattern = mVirtualKeyVibePattern;
7449                 break;
7450             case HapticFeedbackConstants.KEYBOARD_TAP:
7451                 pattern = mKeyboardTapVibePattern;
7452                 break;
7453             case HapticFeedbackConstants.CLOCK_TICK:
7454                 pattern = mClockTickVibePattern;
7455                 break;
7456             case HapticFeedbackConstants.CALENDAR_DATE:
7457                 pattern = mCalendarDateVibePattern;
7458                 break;
7459             case HapticFeedbackConstants.SAFE_MODE_DISABLED:
7460                 pattern = mSafeModeDisabledVibePattern;
7461                 break;
7462             case HapticFeedbackConstants.SAFE_MODE_ENABLED:
7463                 pattern = mSafeModeEnabledVibePattern;
7464                 break;
7465             case HapticFeedbackConstants.CONTEXT_CLICK:
7466                 pattern = mContextClickVibePattern;
7467                 break;
7468             default:
7469                 return false;
7470         }
7471         int owningUid;
7472         String owningPackage;
7473         if (win != null) {
7474             owningUid = win.getOwningUid();
7475             owningPackage = win.getOwningPackage();
7476         } else {
7477             owningUid = android.os.Process.myUid();
7478             owningPackage = mContext.getOpPackageName();
7479         }
7480         if (pattern.length == 1) {
7481             // One-shot vibration
7482             mVibrator.vibrate(owningUid, owningPackage, pattern[0], VIBRATION_ATTRIBUTES);
7483         } else {
7484             // Pattern vibration
7485             mVibrator.vibrate(owningUid, owningPackage, pattern, -1, VIBRATION_ATTRIBUTES);
7486         }
7487         return true;
7488     }
7489
7490     @Override
7491     public void keepScreenOnStartedLw() {
7492     }
7493
7494     @Override
7495     public void keepScreenOnStoppedLw() {
7496         if (isKeyguardShowingAndNotOccluded()) {
7497             mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
7498         }
7499     }
7500
7501     private int updateSystemUiVisibilityLw() {
7502         // If there is no window focused, there will be nobody to handle the events
7503         // anyway, so just hang on in whatever state we're in until things settle down.
7504         final WindowState win = mFocusedWindow != null ? mFocusedWindow
7505                 : mTopFullscreenOpaqueWindowState;
7506         if (win == null) {
7507             return 0;
7508         }
7509         if ((win.getAttrs().privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 && mHideLockScreen == true) {
7510             // We are updating at a point where the keyguard has gotten
7511             // focus, but we were last in a state where the top window is
7512             // hiding it.  This is probably because the keyguard as been
7513             // shown while the top window was displayed, so we want to ignore
7514             // it here because this is just a very transient change and it
7515             // will quickly lose focus once it correctly gets hidden.
7516             return 0;
7517         }
7518
7519         int tmpVisibility = PolicyControl.getSystemUiVisibility(win, null)
7520                 & ~mResettingSystemUiFlags
7521                 & ~mForceClearedSystemUiFlags;
7522         if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
7523             tmpVisibility &= ~PolicyControl.adjustClearableFlags(win, View.SYSTEM_UI_CLEARABLE_FLAGS);
7524         }
7525
7526         final int fullscreenVisibility = updateLightStatusBarLw(0 /* vis */,
7527                 mTopFullscreenOpaqueWindowState, mTopFullscreenOpaqueOrDimmingWindowState);
7528         final int dockedVisibility = updateLightStatusBarLw(0 /* vis */,
7529                 mTopDockedOpaqueWindowState, mTopDockedOpaqueOrDimmingWindowState);
7530         mWindowManagerFuncs.getStackBounds(HOME_STACK_ID, mNonDockedStackBounds);
7531         mWindowManagerFuncs.getStackBounds(DOCKED_STACK_ID, mDockedStackBounds);
7532         final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
7533         final int diff = visibility ^ mLastSystemUiFlags;
7534         final int fullscreenDiff = fullscreenVisibility ^ mLastFullscreenStackSysUiFlags;
7535         final int dockedDiff = dockedVisibility ^ mLastDockedStackSysUiFlags;
7536         final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
7537         if (diff == 0 && fullscreenDiff == 0 && dockedDiff == 0 && mLastFocusNeedsMenu == needsMenu
7538                 && mFocusedApp == win.getAppToken()
7539                 && mLastNonDockedStackBounds.equals(mNonDockedStackBounds)
7540                 && mLastDockedStackBounds.equals(mDockedStackBounds)) {
7541             return 0;
7542         }
7543         mLastSystemUiFlags = visibility;
7544         mLastFullscreenStackSysUiFlags = fullscreenVisibility;
7545         mLastDockedStackSysUiFlags = dockedVisibility;
7546         mLastFocusNeedsMenu = needsMenu;
7547         mFocusedApp = win.getAppToken();
7548         final Rect fullscreenStackBounds = new Rect(mNonDockedStackBounds);
7549         final Rect dockedStackBounds = new Rect(mDockedStackBounds);
7550         mHandler.post(new Runnable() {
7551                 @Override
7552                 public void run() {
7553                     StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
7554                     if (statusbar != null) {
7555                         statusbar.setSystemUiVisibility(visibility, fullscreenVisibility,
7556                                 dockedVisibility, 0xffffffff, fullscreenStackBounds,
7557                                 dockedStackBounds, win.toString());
7558                         statusbar.topAppWindowChanged(needsMenu);
7559                     }
7560                 }
7561             });
7562         return diff;
7563     }
7564
7565     private int updateLightStatusBarLw(int vis, WindowState opaque, WindowState opaqueOrDimming) {
7566         WindowState statusColorWin = isStatusBarKeyguard() && !mHideLockScreen
7567                 ? mStatusBar
7568                 : opaqueOrDimming;
7569
7570         if (statusColorWin != null) {
7571             if (statusColorWin == opaque) {
7572                 // If the top fullscreen-or-dimming window is also the top fullscreen, respect
7573                 // its light flag.
7574                 vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7575                 vis |= PolicyControl.getSystemUiVisibility(statusColorWin, null)
7576                         & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7577             } else if (statusColorWin != null && statusColorWin.isDimming()) {
7578                 // Otherwise if it's dimming, clear the light flag.
7579                 vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7580             }
7581         }
7582         return vis;
7583     }
7584
7585     private boolean drawsSystemBarBackground(WindowState win) {
7586         return win == null || (win.getAttrs().flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0;
7587     }
7588
7589     private boolean forcesDrawStatusBarBackground(WindowState win) {
7590         return win == null || (win.getAttrs().privateFlags
7591                 & PRIVATE_FLAG_FORCE_DRAW_STATUS_BAR_BACKGROUND) != 0;
7592     }
7593
7594     private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
7595         final boolean dockedStackVisible = mWindowManagerInternal.isStackVisible(DOCKED_STACK_ID);
7596         final boolean freeformStackVisible =
7597                 mWindowManagerInternal.isStackVisible(FREEFORM_WORKSPACE_STACK_ID);
7598         final boolean resizing = mWindowManagerInternal.isDockedDividerResizing();
7599
7600         // We need to force system bars when the docked stack is visible, when the freeform stack
7601         // is visible but also when we are resizing for the transitions when docked stack
7602         // visibility changes.
7603         mForceShowSystemBars = dockedStackVisible || freeformStackVisible || resizing;
7604         final boolean forceOpaqueStatusBar = mForceShowSystemBars && !mForceStatusBarFromKeyguard;
7605
7606         // apply translucent bar vis flags
7607         WindowState fullscreenTransWin = isStatusBarKeyguard() && !mHideLockScreen
7608                 ? mStatusBar
7609                 : mTopFullscreenOpaqueWindowState;
7610         vis = mStatusBarController.applyTranslucentFlagLw(fullscreenTransWin, vis, oldVis);
7611         vis = mNavigationBarController.applyTranslucentFlagLw(fullscreenTransWin, vis, oldVis);
7612         final int dockedVis = mStatusBarController.applyTranslucentFlagLw(
7613                 mTopDockedOpaqueWindowState, 0, 0);
7614
7615         final boolean fullscreenDrawsStatusBarBackground =
7616                 (drawsSystemBarBackground(mTopFullscreenOpaqueWindowState)
7617                         && (vis & View.STATUS_BAR_TRANSLUCENT) == 0)
7618                 || forcesDrawStatusBarBackground(mTopFullscreenOpaqueWindowState);
7619         final boolean dockedDrawsStatusBarBackground =
7620                 (drawsSystemBarBackground(mTopDockedOpaqueWindowState)
7621                         && (dockedVis & View.STATUS_BAR_TRANSLUCENT) == 0)
7622                 || forcesDrawStatusBarBackground(mTopDockedOpaqueWindowState);
7623
7624         // prevent status bar interaction from clearing certain flags
7625         int type = win.getAttrs().type;
7626         boolean statusBarHasFocus = type == TYPE_STATUS_BAR;
7627         if (statusBarHasFocus && !isStatusBarKeyguard()) {
7628             int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
7629                     | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
7630                     | View.SYSTEM_UI_FLAG_IMMERSIVE
7631                     | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
7632                     | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
7633             if (mHideLockScreen) {
7634                 flags |= View.STATUS_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSLUCENT;
7635             }
7636             vis = (vis & ~flags) | (oldVis & flags);
7637         }
7638
7639         if (fullscreenDrawsStatusBarBackground && dockedDrawsStatusBarBackground) {
7640             vis |= View.STATUS_BAR_TRANSPARENT;
7641             vis &= ~View.STATUS_BAR_TRANSLUCENT;
7642         } else if ((!areTranslucentBarsAllowed() && fullscreenTransWin != mStatusBar)
7643                 || forceOpaqueStatusBar) {
7644             vis &= ~(View.STATUS_BAR_TRANSLUCENT | View.STATUS_BAR_TRANSPARENT);
7645         }
7646
7647         vis = configureNavBarOpacity(vis, dockedStackVisible, freeformStackVisible, resizing);
7648
7649         // update status bar
7650         boolean immersiveSticky =
7651                 (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7652         final boolean hideStatusBarWM =
7653                 mTopFullscreenOpaqueWindowState != null
7654                 && (PolicyControl.getWindowFlags(mTopFullscreenOpaqueWindowState, null)
7655                         & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
7656         final boolean hideStatusBarSysui =
7657                 (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
7658         final boolean hideNavBarSysui =
7659                 (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
7660
7661         final boolean transientStatusBarAllowed = mStatusBar != null
7662                 && (statusBarHasFocus || (!mForceShowSystemBars
7663                         && (hideStatusBarWM || (hideStatusBarSysui && immersiveSticky))));
7664
7665         final boolean transientNavBarAllowed = mNavigationBar != null
7666                 && !mForceShowSystemBars && hideNavBarSysui && immersiveSticky;
7667
7668         final long now = SystemClock.uptimeMillis();
7669         final boolean pendingPanic = mPendingPanicGestureUptime != 0
7670                 && now - mPendingPanicGestureUptime <= PANIC_GESTURE_EXPIRATION;
7671         if (pendingPanic && hideNavBarSysui && !isStatusBarKeyguard() && mKeyguardDrawComplete) {
7672             // The user performed the panic gesture recently, we're about to hide the bars,
7673             // we're no longer on the Keyguard and the screen is ready. We can now request the bars.
7674             mPendingPanicGestureUptime = 0;
7675             mStatusBarController.showTransient();
7676             mNavigationBarController.showTransient();
7677         }
7678
7679         final boolean denyTransientStatus = mStatusBarController.isTransientShowRequested()
7680                 && !transientStatusBarAllowed && hideStatusBarSysui;
7681         final boolean denyTransientNav = mNavigationBarController.isTransientShowRequested()
7682                 && !transientNavBarAllowed;
7683         if (denyTransientStatus || denyTransientNav || mForceShowSystemBars) {
7684             // clear the clearable flags instead
7685             clearClearableFlagsLw();
7686             vis &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
7687         }
7688
7689         final boolean immersive = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
7690         immersiveSticky = (vis & View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) != 0;
7691         final boolean navAllowedHidden = immersive || immersiveSticky;
7692
7693         if (hideNavBarSysui && !navAllowedHidden && windowTypeToLayerLw(win.getBaseType())
7694                 > windowTypeToLayerLw(TYPE_INPUT_CONSUMER)) {
7695             // We can't hide the navbar from this window otherwise the input consumer would not get
7696             // the input events.
7697             vis = (vis & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
7698         }
7699
7700         vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
7701
7702         // update navigation bar
7703         boolean oldImmersiveMode = isImmersiveMode(oldVis);
7704         boolean newImmersiveMode = isImmersiveMode(vis);
7705         if (win != null && oldImmersiveMode != newImmersiveMode) {
7706             final String pkg = win.getOwningPackage();
7707             mImmersiveModeConfirmation.immersiveModeChangedLw(pkg, newImmersiveMode,
7708                     isUserSetupComplete());
7709         }
7710
7711         vis = mNavigationBarController.updateVisibilityLw(transientNavBarAllowed, oldVis, vis);
7712
7713         return vis;
7714     }
7715
7716     /**
7717      * @return the current visibility flags with the nav-bar opacity related flags toggled based
7718      *         on the nav bar opacity rules chosen by {@link #mNavBarOpacityMode}.
7719      */
7720     private int configureNavBarOpacity(int visibility, boolean dockedStackVisible,
7721             boolean freeformStackVisible, boolean isDockedDividerResizing) {
7722         if (mNavBarOpacityMode == NAV_BAR_OPAQUE_WHEN_FREEFORM_OR_DOCKED) {
7723             if (dockedStackVisible || freeformStackVisible || isDockedDividerResizing) {
7724                 visibility = setNavBarOpaqueFlag(visibility);
7725             }
7726         } else if (mNavBarOpacityMode == NAV_BAR_TRANSLUCENT_WHEN_FREEFORM_OPAQUE_OTHERWISE) {
7727             if (isDockedDividerResizing) {
7728                 visibility = setNavBarOpaqueFlag(visibility);
7729             } else if (freeformStackVisible) {
7730                 visibility = setNavBarTranslucentFlag(visibility);
7731             } else {
7732                 visibility = setNavBarOpaqueFlag(visibility);
7733             }
7734         }
7735
7736         if (!areTranslucentBarsAllowed()) {
7737             visibility &= ~View.NAVIGATION_BAR_TRANSLUCENT;
7738         }
7739         return visibility;
7740     }
7741
7742     private int setNavBarOpaqueFlag(int visibility) {
7743         return visibility &= ~(View.NAVIGATION_BAR_TRANSLUCENT | View.NAVIGATION_BAR_TRANSPARENT);
7744     }
7745
7746     private int setNavBarTranslucentFlag(int visibility) {
7747         visibility &= ~View.NAVIGATION_BAR_TRANSPARENT;
7748         return visibility |= View.NAVIGATION_BAR_TRANSLUCENT;
7749     }
7750
7751     private void clearClearableFlagsLw() {
7752         int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
7753         if (newVal != mResettingSystemUiFlags) {
7754             mResettingSystemUiFlags = newVal;
7755             mWindowManagerFuncs.reevaluateStatusBarVisibility();
7756         }
7757     }
7758
7759     private boolean isImmersiveMode(int vis) {
7760         final int flags = View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
7761         return mNavigationBar != null
7762                 && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
7763                 && (vis & flags) != 0
7764                 && canHideNavigationBar();
7765     }
7766
7767     /**
7768      * @return whether the navigation or status bar can be made translucent
7769      *
7770      * This should return true unless touch exploration is not enabled or
7771      * R.boolean.config_enableTranslucentDecor is false.
7772      */
7773     private boolean areTranslucentBarsAllowed() {
7774         return mTranslucentDecorEnabled;
7775     }
7776
7777     // Use this instead of checking config_showNavigationBar so that it can be consistently
7778     // overridden by qemu.hw.mainkeys in the emulator.
7779     @Override
7780     public boolean hasNavigationBar() {
7781         return mHasNavigationBar;
7782     }
7783
7784     @Override
7785     public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
7786         mLastInputMethodWindow = ime;
7787         mLastInputMethodTargetWindow = target;
7788     }
7789
7790     @Override
7791     public int getInputMethodWindowVisibleHeightLw() {
7792         return mDockBottom - mCurBottom;
7793     }
7794
7795     @Override
7796     public void setCurrentUserLw(int newUserId) {
7797         mCurrentUserId = newUserId;
7798         if (mKeyguardDelegate != null) {
7799             mKeyguardDelegate.setCurrentUser(newUserId);
7800         }
7801         StatusBarManagerInternal statusBar = getStatusBarManagerInternal();
7802         if (statusBar != null) {
7803             statusBar.setCurrentUser(newUserId);
7804         }
7805         setLastInputMethodWindowLw(null, null);
7806     }
7807
7808     @Override
7809     public boolean canMagnifyWindow(int windowType) {
7810         switch (windowType) {
7811             case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
7812             case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
7813             case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
7814             case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
7815                 return false;
7816             }
7817         }
7818         return true;
7819     }
7820
7821     @Override
7822     public boolean isTopLevelWindow(int windowType) {
7823         if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
7824                 && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
7825             return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
7826         }
7827         return true;
7828     }
7829
7830     @Override
7831     public void dump(String prefix, PrintWriter pw, String[] args) {
7832         pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
7833                 pw.print(" mSystemReady="); pw.print(mSystemReady);
7834                 pw.print(" mSystemBooted="); pw.println(mSystemBooted);
7835         pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
7836                 pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
7837                 pw.print(" mCameraLensCoverState="); pw.print(mCameraLensCoverState);
7838                 pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
7839         if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
7840                 || mForceClearedSystemUiFlags != 0) {
7841             pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
7842                     pw.print(Integer.toHexString(mLastSystemUiFlags));
7843                     pw.print(" mResettingSystemUiFlags=0x");
7844                     pw.print(Integer.toHexString(mResettingSystemUiFlags));
7845                     pw.print(" mForceClearedSystemUiFlags=0x");
7846                     pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
7847         }
7848         if (mLastFocusNeedsMenu) {
7849             pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
7850                     pw.println(mLastFocusNeedsMenu);
7851         }
7852         pw.print(prefix); pw.print("mWakeGestureEnabledSetting=");
7853                 pw.println(mWakeGestureEnabledSetting);
7854
7855         pw.print(prefix); pw.print("mSupportAutoRotation="); pw.println(mSupportAutoRotation);
7856         pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
7857                 pw.print(" mDockMode="); pw.print(mDockMode);
7858                 pw.print(" mEnableCarDockHomeCapture="); pw.print(mEnableCarDockHomeCapture);
7859                 pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
7860                 pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
7861         pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
7862                 pw.print(" mUserRotation="); pw.print(mUserRotation);
7863                 pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
7864         pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
7865         pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
7866                 pw.print(mCarDockEnablesAccelerometer);
7867                 pw.print(" mDeskDockEnablesAccelerometer=");
7868                 pw.println(mDeskDockEnablesAccelerometer);
7869         pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
7870                 pw.print(mLidKeyboardAccessibility);
7871                 pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
7872                 pw.print(" mLidControlsScreenLock="); pw.println(mLidControlsScreenLock);
7873                 pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
7874         pw.print(prefix);
7875                 pw.print(" mLongPressOnBackBehavior="); pw.println(mLongPressOnBackBehavior);
7876         pw.print(prefix);
7877                 pw.print("mShortPressOnPowerBehavior="); pw.print(mShortPressOnPowerBehavior);
7878                 pw.print(" mLongPressOnPowerBehavior="); pw.println(mLongPressOnPowerBehavior);
7879         pw.print(prefix);
7880                 pw.print("mDoublePressOnPowerBehavior="); pw.print(mDoublePressOnPowerBehavior);
7881                 pw.print(" mTriplePressOnPowerBehavior="); pw.println(mTriplePressOnPowerBehavior);
7882         pw.print(prefix); pw.print("mHasSoftInput="); pw.println(mHasSoftInput);
7883         pw.print(prefix); pw.print("mAwake="); pw.println(mAwake);
7884         pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
7885                 pw.print(" mScreenOnFully="); pw.println(mScreenOnFully);
7886         pw.print(prefix); pw.print("mKeyguardDrawComplete="); pw.print(mKeyguardDrawComplete);
7887                 pw.print(" mWindowManagerDrawComplete="); pw.println(mWindowManagerDrawComplete);
7888         pw.print(prefix); pw.print("mOrientationSensorEnabled=");
7889                 pw.println(mOrientationSensorEnabled);
7890         pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
7891                 pw.print(","); pw.print(mOverscanScreenTop);
7892                 pw.print(") "); pw.print(mOverscanScreenWidth);
7893                 pw.print("x"); pw.println(mOverscanScreenHeight);
7894         if (mOverscanLeft != 0 || mOverscanTop != 0
7895                 || mOverscanRight != 0 || mOverscanBottom != 0) {
7896             pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
7897                     pw.print(" top="); pw.print(mOverscanTop);
7898                     pw.print(" right="); pw.print(mOverscanRight);
7899                     pw.print(" bottom="); pw.println(mOverscanBottom);
7900         }
7901         pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
7902                 pw.print(mRestrictedOverscanScreenLeft);
7903                 pw.print(","); pw.print(mRestrictedOverscanScreenTop);
7904                 pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
7905                 pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
7906         pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
7907                 pw.print(","); pw.print(mUnrestrictedScreenTop);
7908                 pw.print(") "); pw.print(mUnrestrictedScreenWidth);
7909                 pw.print("x"); pw.println(mUnrestrictedScreenHeight);
7910         pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
7911                 pw.print(","); pw.print(mRestrictedScreenTop);
7912                 pw.print(") "); pw.print(mRestrictedScreenWidth);
7913                 pw.print("x"); pw.println(mRestrictedScreenHeight);
7914         pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
7915                 pw.print(","); pw.print(mStableFullscreenTop);
7916                 pw.print(")-("); pw.print(mStableFullscreenRight);
7917                 pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
7918         pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
7919                 pw.print(","); pw.print(mStableTop);
7920                 pw.print(")-("); pw.print(mStableRight);
7921                 pw.print(","); pw.print(mStableBottom); pw.println(")");
7922         pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
7923                 pw.print(","); pw.print(mSystemTop);
7924                 pw.print(")-("); pw.print(mSystemRight);
7925                 pw.print(","); pw.print(mSystemBottom); pw.println(")");
7926         pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
7927                 pw.print(","); pw.print(mCurTop);
7928                 pw.print(")-("); pw.print(mCurRight);
7929                 pw.print(","); pw.print(mCurBottom); pw.println(")");
7930         pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
7931                 pw.print(","); pw.print(mContentTop);
7932                 pw.print(")-("); pw.print(mContentRight);
7933                 pw.print(","); pw.print(mContentBottom); pw.println(")");
7934         pw.print(prefix); pw.print("mVoiceContent=("); pw.print(mVoiceContentLeft);
7935                 pw.print(","); pw.print(mVoiceContentTop);
7936                 pw.print(")-("); pw.print(mVoiceContentRight);
7937                 pw.print(","); pw.print(mVoiceContentBottom); pw.println(")");
7938         pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
7939                 pw.print(","); pw.print(mDockTop);
7940                 pw.print(")-("); pw.print(mDockRight);
7941                 pw.print(","); pw.print(mDockBottom); pw.println(")");
7942         pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
7943                 pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
7944         pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
7945                 pw.print(" mShowingDream="); pw.print(mShowingDream);
7946                 pw.print(" mDreamingLockscreen="); pw.print(mDreamingLockscreen);
7947                 pw.print(" mDreamingSleepToken="); pw.println(mDreamingSleepToken);
7948         if (mLastInputMethodWindow != null) {
7949             pw.print(prefix); pw.print("mLastInputMethodWindow=");
7950                     pw.println(mLastInputMethodWindow);
7951         }
7952         if (mLastInputMethodTargetWindow != null) {
7953             pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
7954                     pw.println(mLastInputMethodTargetWindow);
7955         }
7956         if (mStatusBar != null) {
7957             pw.print(prefix); pw.print("mStatusBar=");
7958                     pw.print(mStatusBar); pw.print(" isStatusBarKeyguard=");
7959                     pw.println(isStatusBarKeyguard());
7960         }
7961         if (mNavigationBar != null) {
7962             pw.print(prefix); pw.print("mNavigationBar=");
7963                     pw.println(mNavigationBar);
7964         }
7965         if (mFocusedWindow != null) {
7966             pw.print(prefix); pw.print("mFocusedWindow=");
7967                     pw.println(mFocusedWindow);
7968         }
7969         if (mFocusedApp != null) {
7970             pw.print(prefix); pw.print("mFocusedApp=");
7971                     pw.println(mFocusedApp);
7972         }
7973         if (mWinDismissingKeyguard != null) {
7974             pw.print(prefix); pw.print("mWinDismissingKeyguard=");
7975                     pw.println(mWinDismissingKeyguard);
7976         }
7977         if (mTopFullscreenOpaqueWindowState != null) {
7978             pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
7979                     pw.println(mTopFullscreenOpaqueWindowState);
7980         }
7981         if (mTopFullscreenOpaqueOrDimmingWindowState != null) {
7982             pw.print(prefix); pw.print("mTopFullscreenOpaqueOrDimmingWindowState=");
7983                     pw.println(mTopFullscreenOpaqueOrDimmingWindowState);
7984         }
7985         if (mForcingShowNavBar) {
7986             pw.print(prefix); pw.print("mForcingShowNavBar=");
7987                     pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
7988                     pw.println(mForcingShowNavBarLayer);
7989         }
7990         pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
7991                 pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
7992         pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
7993                 pw.print(" mForceStatusBarFromKeyguard=");
7994                 pw.println(mForceStatusBarFromKeyguard);
7995         pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
7996                 pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
7997                 pw.print(" mHomePressed="); pw.println(mHomePressed);
7998         pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
7999                 pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
8000                 pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
8001         pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
8002                 pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
8003                 pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
8004         pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
8005                 pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
8006         pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
8007                 pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
8008         pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
8009                 pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
8010         pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
8011
8012         mGlobalKeyManager.dump(prefix, pw);
8013         mStatusBarController.dump(pw, prefix);
8014         mNavigationBarController.dump(pw, prefix);
8015         PolicyControl.dump(prefix, pw);
8016
8017         if (mWakeGestureListener != null) {
8018             mWakeGestureListener.dump(pw, prefix);
8019         }
8020         if (mOrientationListener != null) {
8021             mOrientationListener.dump(pw, prefix);
8022         }
8023         if (mBurnInProtectionHelper != null) {
8024             mBurnInProtectionHelper.dump(prefix, pw);
8025         }
8026         if (mKeyguardDelegate != null) {
8027             mKeyguardDelegate.dump(prefix, pw);
8028         }
8029     }
8030 }