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