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