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