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