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