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