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