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