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