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