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