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