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