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