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