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