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