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