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