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