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