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