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