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