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