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