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