OSDN Git Service

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