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