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