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