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