PhoneWindowManager.java revision fca1e603236b8d1681f784e77e3719d1d59c1428
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.TRANSIENT_NAV_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 TransientNavigationConfirmation mTransientNavigationConfirmation;
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        mTransientNavigationConfirmation = new TransientNavigationConfirmation(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 (mTransientNavigationConfirmation != null) {
1173                mTransientNavigationConfirmation.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 transientAllowed = (sysui & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
2703            navTranslucent &= !transientAllowed;  // transient trumps translucent
2704            navTranslucent &= isTranslucentNavigationAllowed();
2705
2706            // When the navigation bar isn't visible, we put up a fake
2707            // input window to catch all touch events.  This way we can
2708            // detect when the user presses anywhere to bring back the nav
2709            // bar and ensure the application doesn't see the event.
2710            if (navVisible || transientAllowed) {
2711                if (mHideNavFakeWindow != null) {
2712                    mHideNavFakeWindow.dismiss();
2713                    mHideNavFakeWindow = null;
2714                }
2715            } else if (mHideNavFakeWindow == null) {
2716                mHideNavFakeWindow = mWindowManagerFuncs.addFakeWindow(
2717                        mHandler.getLooper(), mHideNavInputEventReceiverFactory,
2718                        "hidden nav", WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER, 0,
2719                        0, false, false, true);
2720            }
2721
2722            // For purposes of positioning and showing the nav bar, if we have
2723            // decided that it can't be hidden (because of the screen aspect ratio),
2724            // then take that into account.
2725            navVisible |= !canHideNavigationBar();
2726
2727            boolean updateSysUiVisibility = false;
2728            if (mNavigationBar != null) {
2729                boolean transientNavBarShowing = mNavigationBarController.isTransientShowing();
2730                // Force the navigation bar to its appropriate place and
2731                // size.  We need to do this directly, instead of relying on
2732                // it to bubble up from the nav bar, because this needs to
2733                // change atomically with screen rotations.
2734                mNavigationBarOnBottom = (!mNavigationBarCanMove || displayWidth < displayHeight);
2735                if (mNavigationBarOnBottom) {
2736                    // It's a system nav bar or a portrait screen; nav bar goes on bottom.
2737                    int top = displayHeight - overscanBottom
2738                            - mNavigationBarHeightForRotation[displayRotation];
2739                    mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
2740                    mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
2741                    if (transientNavBarShowing || navTranslucent) {
2742                        mNavigationBarController.setBarShowingLw(true);
2743                    } else if (navVisible) {
2744                        mNavigationBarController.setBarShowingLw(true);
2745                        mDockBottom = mTmpNavigationFrame.top;
2746                        mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
2747                        mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
2748                    } else {
2749                        // We currently want to hide the navigation UI.
2750                        mNavigationBarController.setBarShowingLw(false);
2751                    }
2752                    if (navVisible && !navTranslucent && !mNavigationBar.isAnimatingLw()
2753                            && !mNavigationBarController.wasRecentlyTranslucent()) {
2754                        // If the opaque nav bar is currently requested to be visible,
2755                        // and not in the process of animating on or off, then
2756                        // we can tell the app that it is covered by it.
2757                        mSystemBottom = mTmpNavigationFrame.top;
2758                    }
2759                } else {
2760                    // Landscape screen; nav bar goes to the right.
2761                    int left = displayWidth - overscanRight
2762                            - mNavigationBarWidthForRotation[displayRotation];
2763                    mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
2764                    mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
2765                    if (transientNavBarShowing || navTranslucent) {
2766                        mNavigationBarController.setBarShowingLw(true);
2767                    } else if (navVisible) {
2768                        mNavigationBarController.setBarShowingLw(true);
2769                        mDockRight = mTmpNavigationFrame.left;
2770                        mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
2771                        mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
2772                    } else {
2773                        // We currently want to hide the navigation UI.
2774                        mNavigationBarController.setBarShowingLw(false);
2775                    }
2776                    if (navVisible && !navTranslucent && !mNavigationBar.isAnimatingLw()
2777                            && !mNavigationBarController.wasRecentlyTranslucent()) {
2778                        // If the nav bar is currently requested to be visible,
2779                        // and not in the process of animating on or off, then
2780                        // we can tell the app that it is covered by it.
2781                        mSystemRight = mTmpNavigationFrame.left;
2782                    }
2783                }
2784                // Make sure the content and current rectangles are updated to
2785                // account for the restrictions from the navigation bar.
2786                mContentTop = mCurTop = mDockTop;
2787                mContentBottom = mCurBottom = mDockBottom;
2788                mContentLeft = mCurLeft = mDockLeft;
2789                mContentRight = mCurRight = mDockRight;
2790                mStatusBarLayer = mNavigationBar.getSurfaceLayer();
2791                // And compute the final frame.
2792                mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
2793                        mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame, dcf);
2794                if (DEBUG_LAYOUT) Slog.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
2795                if (mNavigationBarController.checkHiddenLw()) {
2796                    updateSysUiVisibility = true;
2797                }
2798            }
2799            if (DEBUG_LAYOUT) Slog.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
2800                    mDockLeft, mDockTop, mDockRight, mDockBottom));
2801
2802            // decide where the status bar goes ahead of time
2803            if (mStatusBar != null) {
2804                // apply any navigation bar insets
2805                pf.left = df.left = of.left = mUnrestrictedScreenLeft;
2806                pf.top = df.top = of.top = mUnrestrictedScreenTop;
2807                pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
2808                pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
2809                        + mUnrestrictedScreenTop;
2810                vf.left = mStableLeft;
2811                vf.top = mStableTop;
2812                vf.right = mStableRight;
2813                vf.bottom = mStableBottom;
2814
2815                mStatusBarLayer = mStatusBar.getSurfaceLayer();
2816
2817                // Let the status bar determine its size.
2818                mStatusBar.computeFrameLw(pf, df, vf, vf, vf, dcf);
2819
2820                // For layout, the status bar is always at the top with our fixed height.
2821                mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
2822
2823                boolean statusBarTransient = (sysui & View.STATUS_BAR_TRANSIENT) != 0;
2824                boolean statusBarTranslucent = (sysui & View.STATUS_BAR_TRANSLUCENT) != 0;
2825
2826                // If the status bar is hidden, we don't want to cause
2827                // windows behind it to scroll.
2828                if (mStatusBar.isVisibleLw() && !statusBarTransient) {
2829                    // Status bar may go away, so the screen area it occupies
2830                    // is available to apps but just covering them when the
2831                    // status bar is visible.
2832                    mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
2833
2834                    mContentTop = mCurTop = mDockTop;
2835                    mContentBottom = mCurBottom = mDockBottom;
2836                    mContentLeft = mCurLeft = mDockLeft;
2837                    mContentRight = mCurRight = mDockRight;
2838
2839                    if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar: " +
2840                        String.format(
2841                            "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
2842                            mDockLeft, mDockTop, mDockRight, mDockBottom,
2843                            mContentLeft, mContentTop, mContentRight, mContentBottom,
2844                            mCurLeft, mCurTop, mCurRight, mCurBottom));
2845                }
2846                if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()
2847                        && !statusBarTransient && !statusBarTranslucent
2848                        && !mStatusBarController.wasRecentlyTranslucent()) {
2849                    // If the opaque status bar is currently requested to be visible,
2850                    // and not in the process of animating on or off, then
2851                    // we can tell the app that it is covered by it.
2852                    mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
2853                }
2854                if (mStatusBarController.checkHiddenLw()) {
2855                    updateSysUiVisibility = true;
2856                }
2857            }
2858            if (updateSysUiVisibility) {
2859                updateSystemUiVisibilityLw();
2860            }
2861        }
2862    }
2863
2864    /** {@inheritDoc} */
2865    @Override
2866    public int getSystemDecorLayerLw() {
2867        if (mStatusBar != null) return mStatusBar.getSurfaceLayer();
2868        if (mNavigationBar != null) return mNavigationBar.getSurfaceLayer();
2869        return 0;
2870    }
2871
2872    @Override
2873    public void getContentRectLw(Rect r) {
2874        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
2875    }
2876
2877    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
2878            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
2879        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
2880            // Here's a special case: if this attached window is a panel that is
2881            // above the dock window, and the window it is attached to is below
2882            // the dock window, then the frames we computed for the window it is
2883            // attached to can not be used because the dock is effectively part
2884            // of the underlying window and the attached window is floating on top
2885            // of the whole thing.  So, we ignore the attached window and explicitly
2886            // compute the frames that would be appropriate without the dock.
2887            df.left = of.left = cf.left = vf.left = mDockLeft;
2888            df.top = of.top = cf.top = vf.top = mDockTop;
2889            df.right = of.right = cf.right = vf.right = mDockRight;
2890            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
2891        } else {
2892            // The effective display frame of the attached window depends on
2893            // whether it is taking care of insetting its content.  If not,
2894            // we need to use the parent's content frame so that the entire
2895            // window is positioned within that content.  Otherwise we can use
2896            // the display frame and let the attached window take care of
2897            // positioning its content appropriately.
2898            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2899                cf.set(attached.getOverscanFrameLw());
2900            } else {
2901                // If the window is resizing, then we want to base the content
2902                // frame on our attached content frame to resize...  however,
2903                // things can be tricky if the attached window is NOT in resize
2904                // mode, in which case its content frame will be larger.
2905                // Ungh.  So to deal with that, make sure the content frame
2906                // we end up using is not covering the IM dock.
2907                cf.set(attached.getContentFrameLw());
2908                if (attached.getSurfaceLayer() < mDockLayer) {
2909                    if (cf.left < mContentLeft) cf.left = mContentLeft;
2910                    if (cf.top < mContentTop) cf.top = mContentTop;
2911                    if (cf.right > mContentRight) cf.right = mContentRight;
2912                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
2913                }
2914            }
2915            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
2916            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
2917            vf.set(attached.getVisibleFrameLw());
2918        }
2919        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
2920        // window should be positioned relative to its parent or the entire
2921        // screen.
2922        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
2923                ? attached.getFrameLw() : df);
2924    }
2925
2926    private void applyStableConstraints(int sysui, int fl, Rect r) {
2927        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
2928            // If app is requesting a stable layout, don't let the
2929            // content insets go below the stable values.
2930            if ((fl & FLAG_FULLSCREEN) != 0) {
2931                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
2932                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
2933                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
2934                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
2935            } else {
2936                if (r.left < mStableLeft) r.left = mStableLeft;
2937                if (r.top < mStableTop) r.top = mStableTop;
2938                if (r.right > mStableRight) r.right = mStableRight;
2939                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
2940            }
2941        }
2942    }
2943
2944    /** {@inheritDoc} */
2945    @Override
2946    public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
2947            WindowState attached) {
2948        // we've already done the status bar
2949        if (win == mStatusBar || win == mNavigationBar) {
2950            return;
2951        }
2952        final boolean isDefaultDisplay = win.isDefaultDisplay();
2953        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
2954                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
2955        if (needsToOffsetInputMethodTarget) {
2956            if (DEBUG_LAYOUT) Slog.i(TAG, "Offset ime target window by the last ime window state");
2957            offsetInputMethodWindowLw(mLastInputMethodWindow);
2958        }
2959
2960        final int fl = attrs.flags;
2961        final int sim = attrs.softInputMode;
2962        final int sysUiFl = win.getSystemUiVisibility();
2963
2964        final Rect pf = mTmpParentFrame;
2965        final Rect df = mTmpDisplayFrame;
2966        final Rect of = mTmpOverscanFrame;
2967        final Rect cf = mTmpContentFrame;
2968        final Rect vf = mTmpVisibleFrame;
2969        final Rect dcf = mTmpDecorFrame;
2970        dcf.setEmpty();
2971
2972        final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
2973                && mNavigationBar != null && mNavigationBar.isVisibleLw());
2974
2975        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
2976
2977        if (!isDefaultDisplay) {
2978            if (attached != null) {
2979                // If this window is attached to another, our display
2980                // frame is the same as the one we are attached to.
2981                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
2982            } else {
2983                // Give the window full screen.
2984                pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
2985                pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
2986                pf.right = df.right = of.right = cf.right
2987                        = mOverscanScreenLeft + mOverscanScreenWidth;
2988                pf.bottom = df.bottom = of.bottom = cf.bottom
2989                        = mOverscanScreenTop + mOverscanScreenHeight;
2990            }
2991        } else  if (attrs.type == TYPE_INPUT_METHOD) {
2992            pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
2993            pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
2994            pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
2995            // IM dock windows layout below the nav bar...
2996            pf.bottom = df.bottom = of.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
2997            // ...with content insets above the nav bar
2998            cf.bottom = vf.bottom = mStableBottom;
2999            // IM dock windows always go to the bottom of the screen.
3000            attrs.gravity = Gravity.BOTTOM;
3001            mDockLayer = win.getSurfaceLayer();
3002        } else {
3003
3004            // Default policy decor for the default display
3005            dcf.left = mSystemLeft;
3006            dcf.top = mSystemTop;
3007            dcf.right = mSystemRight;
3008            dcf.bottom = mSystemBottom;
3009            final boolean inheritTranslucentDecor = (attrs.privateFlags
3010                    & WindowManager.LayoutParams.PRIVATE_FLAG_INHERIT_TRANSLUCENT_DECOR) != 0;
3011            final boolean isAppWindow =
3012                    attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW &&
3013                    attrs.type <= WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
3014            final boolean topAtRest =
3015                    win == mTopFullscreenOpaqueWindowState && !win.isAnimatingLw();
3016            if (isAppWindow && !inheritTranslucentDecor && !topAtRest) {
3017                if ((sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0
3018                        && (fl & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0
3019                        && (fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) == 0) {
3020                    // Ensure policy decor includes status bar
3021                    dcf.top = mStableTop;
3022                }
3023                if ((fl & WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION) == 0
3024                        && (sysUiFl & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
3025                    // Ensure policy decor includes navigation bar
3026                    dcf.bottom = mStableBottom;
3027                    dcf.right = mStableRight;
3028                }
3029            }
3030
3031            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
3032                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
3033                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle()
3034                            + "): IN_SCREEN, INSET_DECOR");
3035                // This is the case for a normal activity window: we want it
3036                // to cover all of the screen space, and it can take care of
3037                // moving its contents to account for screen decorations that
3038                // intrude into that space.
3039                if (attached != null) {
3040                    // If this window is attached to another, our display
3041                    // frame is the same as the one we are attached to.
3042                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
3043                } else {
3044                    if (attrs.type == TYPE_STATUS_BAR_PANEL
3045                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
3046                        // Status bar panels are the only windows who can go on top of
3047                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
3048                        // permission, so they have the same privileges as the status
3049                        // bar itself.
3050                        //
3051                        // However, they should still dodge the navigation bar if it exists.
3052
3053                        pf.left = df.left = of.left = hasNavBar
3054                                ? mDockLeft : mUnrestrictedScreenLeft;
3055                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
3056                        pf.right = df.right = of.right = hasNavBar
3057                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
3058                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3059                        pf.bottom = df.bottom = of.bottom = hasNavBar
3060                                ? mRestrictedScreenTop+mRestrictedScreenHeight
3061                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3062
3063                        if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3064                                        "Laying out status bar window: (%d,%d - %d,%d)",
3065                                        pf.left, pf.top, pf.right, pf.bottom));
3066                    } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
3067                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3068                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3069                        // Asking to layout into the overscan region, so give it that pure
3070                        // unrestricted area.
3071                        pf.left = df.left = of.left = mOverscanScreenLeft;
3072                        pf.top = df.top = of.top = mOverscanScreenTop;
3073                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
3074                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
3075                                + mOverscanScreenHeight;
3076                    } else if (canHideNavigationBar()
3077                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
3078                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3079                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3080                        // Asking for layout as if the nav bar is hidden, lets the
3081                        // application extend into the unrestricted overscan screen area.  We
3082                        // only do this for application windows to ensure no window that
3083                        // can be above the nav bar can do this.
3084                        pf.left = df.left = mOverscanScreenLeft;
3085                        pf.top = df.top = mOverscanScreenTop;
3086                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
3087                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
3088                        // We need to tell the app about where the frame inside the overscan
3089                        // is, so it can inset its content by that amount -- it didn't ask
3090                        // to actually extend itself into the overscan region.
3091                        of.left = mUnrestrictedScreenLeft;
3092                        of.top = mUnrestrictedScreenTop;
3093                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3094                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3095                    } else {
3096                        pf.left = df.left = mRestrictedOverscanScreenLeft;
3097                        pf.top = df.top = mRestrictedOverscanScreenTop;
3098                        pf.right = df.right = mRestrictedOverscanScreenLeft
3099                                + mRestrictedOverscanScreenWidth;
3100                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
3101                                + mRestrictedOverscanScreenHeight;
3102                        // We need to tell the app about where the frame inside the overscan
3103                        // is, so it can inset its content by that amount -- it didn't ask
3104                        // to actually extend itself into the overscan region.
3105                        of.left = mUnrestrictedScreenLeft;
3106                        of.top = mUnrestrictedScreenTop;
3107                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3108                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3109                    }
3110
3111                    if ((fl & FLAG_FULLSCREEN) == 0) {
3112                        if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3113                            cf.left = mDockLeft;
3114                            cf.top = mDockTop;
3115                            cf.right = mDockRight;
3116                            cf.bottom = mDockBottom;
3117                        } else {
3118                            cf.left = mContentLeft;
3119                            cf.top = mContentTop;
3120                            cf.right = mContentRight;
3121                            cf.bottom = mContentBottom;
3122                        }
3123                    } else {
3124                        // Full screen windows are always given a layout that is as if the
3125                        // status bar and other transient decors are gone.  This is to avoid
3126                        // bad states when moving from a window that is not hding the
3127                        // status bar to one that is.
3128                        cf.left = mRestrictedScreenLeft;
3129                        cf.top = mRestrictedScreenTop;
3130                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
3131                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3132                    }
3133                    applyStableConstraints(sysUiFl, fl, cf);
3134                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3135                        vf.left = mCurLeft;
3136                        vf.top = mCurTop;
3137                        vf.right = mCurRight;
3138                        vf.bottom = mCurBottom;
3139                    } else {
3140                        vf.set(cf);
3141                    }
3142                }
3143            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
3144                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
3145                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
3146                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
3147                        "): IN_SCREEN");
3148                // A window that has requested to fill the entire screen just
3149                // gets everything, period.
3150                if (attrs.type == TYPE_STATUS_BAR_PANEL
3151                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
3152                    pf.left = df.left = of.left = cf.left = hasNavBar
3153                            ? mDockLeft : mUnrestrictedScreenLeft;
3154                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
3155                    pf.right = df.right = of.right = cf.right = hasNavBar
3156                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
3157                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3158                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
3159                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
3160                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3161                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3162                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
3163                                    pf.left, pf.top, pf.right, pf.bottom));
3164                } else if (attrs.type == TYPE_NAVIGATION_BAR
3165                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
3166                    // The navigation bar has Real Ultimate Power.
3167                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3168                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
3169                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
3170                            + mUnrestrictedScreenWidth;
3171                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
3172                            + mUnrestrictedScreenHeight;
3173                    if (DEBUG_LAYOUT) Slog.v(TAG, String.format(
3174                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
3175                                    pf.left, pf.top, pf.right, pf.bottom));
3176                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
3177                                || attrs.type == TYPE_BOOT_PROGRESS)
3178                        && ((fl & FLAG_FULLSCREEN) != 0)) {
3179                    // Fullscreen secure system overlays get what they ask for.
3180                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3181                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3182                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
3183                            + mOverscanScreenWidth;
3184                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
3185                            + mOverscanScreenHeight;
3186                } else if (attrs.type == TYPE_BOOT_PROGRESS
3187                        || attrs.type == TYPE_UNIVERSE_BACKGROUND) {
3188                    // Boot progress screen always covers entire display.
3189                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3190                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3191                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
3192                            + mOverscanScreenWidth;
3193                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
3194                            + mOverscanScreenHeight;
3195                } else if (attrs.type == TYPE_WALLPAPER) {
3196                    // The wallpaper also has Real Ultimate Power.
3197                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
3198                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
3199                    pf.right = df.right = of.right = cf.right
3200                            = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3201                    pf.bottom = df.bottom = of.bottom = cf.bottom
3202                            = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3203                } else if ((fl & FLAG_LAYOUT_IN_OVERSCAN) != 0
3204                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3205                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3206                    // Asking to layout into the overscan region, so give it that pure
3207                    // unrestricted area.
3208                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3209                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3210                    pf.right = df.right = of.right = cf.right
3211                            = mOverscanScreenLeft + mOverscanScreenWidth;
3212                    pf.bottom = df.bottom = of.bottom = cf.bottom
3213                            = mOverscanScreenTop + mOverscanScreenHeight;
3214                } else if (canHideNavigationBar()
3215                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
3216                        && (attrs.type == TYPE_TOAST
3217                            || (attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3218                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW))) {
3219                    // Asking for layout as if the nav bar is hidden, lets the
3220                    // application extend into the unrestricted screen area.  We
3221                    // only do this for application windows (or toasts) to ensure no window that
3222                    // can be above the nav bar can do this.
3223                    // XXX This assumes that an app asking for this will also
3224                    // ask for layout in only content.  We can't currently figure out
3225                    // what the screen would be if only laying out to hide the nav bar.
3226                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
3227                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
3228                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
3229                            + mUnrestrictedScreenWidth;
3230                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
3231                            + mUnrestrictedScreenHeight;
3232                } else {
3233                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
3234                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
3235                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
3236                            + mRestrictedScreenWidth;
3237                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
3238                            + mRestrictedScreenHeight;
3239                }
3240
3241                applyStableConstraints(sysUiFl, fl, cf);
3242
3243                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3244                    vf.left = mCurLeft;
3245                    vf.top = mCurTop;
3246                    vf.right = mCurRight;
3247                    vf.bottom = mCurBottom;
3248                } else {
3249                    vf.set(cf);
3250                }
3251            } else if (attached != null) {
3252                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
3253                        "): attached to " + attached);
3254                // A child window should be placed inside of the same visible
3255                // frame that its parent had.
3256                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
3257            } else {
3258                if (DEBUG_LAYOUT) Slog.v(TAG, "layoutWindowLw(" + attrs.getTitle() +
3259                        "): normal window");
3260                // Otherwise, a normal window must be placed inside the content
3261                // of all screen decorations.
3262                if (attrs.type == TYPE_STATUS_BAR_PANEL) {
3263                    // Status bar panels are the only windows who can go on top of
3264                    // the status bar.  They are protected by the STATUS_BAR_SERVICE
3265                    // permission, so they have the same privileges as the status
3266                    // bar itself.
3267                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
3268                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
3269                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
3270                            + mRestrictedScreenWidth;
3271                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
3272                            + mRestrictedScreenHeight;
3273                } else if (attrs.type == TYPE_TOAST || attrs.type == TYPE_SYSTEM_ALERT) {
3274                    // Toasts are stable to interim decor changes.
3275                    pf.left = df.left = of.left = cf.left = mStableLeft;
3276                    pf.top = df.top = of.top = cf.top = mStableTop;
3277                    pf.right = df.right = of.right = cf.right = mStableRight;
3278                    pf.bottom = df.bottom = of.bottom = cf.bottom = mStableBottom;
3279                } else {
3280                    pf.left = mContentLeft;
3281                    pf.top = mContentTop;
3282                    pf.right = mContentRight;
3283                    pf.bottom = mContentBottom;
3284                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3285                        df.left = of.left = cf.left = mDockLeft;
3286                        df.top = of.top = cf.top = mDockTop;
3287                        df.right = of.right = cf.right = mDockRight;
3288                        df.bottom = of.bottom = cf.bottom = mDockBottom;
3289                    } else {
3290                        df.left = of.left = cf.left = mContentLeft;
3291                        df.top = of.top = cf.top = mContentTop;
3292                        df.right = of.right = cf.right = mContentRight;
3293                        df.bottom = of.bottom = cf.bottom = mContentBottom;
3294                    }
3295                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3296                        vf.left = mCurLeft;
3297                        vf.top = mCurTop;
3298                        vf.right = mCurRight;
3299                        vf.bottom = mCurBottom;
3300                    } else {
3301                        vf.set(cf);
3302                    }
3303                }
3304            }
3305        }
3306
3307        // TYPE_SYSTEM_ERROR is above the NavigationBar so it can't be allowed to extend over it.
3308        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0 && attrs.type != TYPE_SYSTEM_ERROR) {
3309            df.left = df.top = of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
3310            df.right = df.bottom = of.right = of.bottom = cf.right = cf.bottom
3311                    = vf.right = vf.bottom = 10000;
3312        }
3313
3314        if (DEBUG_LAYOUT) Slog.v(TAG, "Compute frame " + attrs.getTitle()
3315                + ": sim=#" + Integer.toHexString(sim)
3316                + " attach=" + attached + " type=" + attrs.type
3317                + String.format(" flags=0x%08x", fl)
3318                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
3319                + " of=" + of.toShortString()
3320                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString()
3321                + " dcf=" + dcf.toShortString());
3322
3323        win.computeFrameLw(pf, df, of, cf, vf, dcf);
3324
3325        // Dock windows carve out the bottom of the screen, so normal windows
3326        // can't appear underneath them.
3327        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
3328                && !win.getGivenInsetsPendingLw()) {
3329            setLastInputMethodWindowLw(null, null);
3330            offsetInputMethodWindowLw(win);
3331        }
3332    }
3333
3334    private void offsetInputMethodWindowLw(WindowState win) {
3335        int top = win.getContentFrameLw().top;
3336        top += win.getGivenContentInsetsLw().top;
3337        if (mContentBottom > top) {
3338            mContentBottom = top;
3339        }
3340        top = win.getVisibleFrameLw().top;
3341        top += win.getGivenVisibleInsetsLw().top;
3342        if (mCurBottom > top) {
3343            mCurBottom = top;
3344        }
3345        if (DEBUG_LAYOUT) Slog.v(TAG, "Input method: mDockBottom="
3346                + mDockBottom + " mContentBottom="
3347                + mContentBottom + " mCurBottom=" + mCurBottom);
3348    }
3349
3350    /** {@inheritDoc} */
3351    @Override
3352    public void finishLayoutLw() {
3353        return;
3354    }
3355
3356    /** {@inheritDoc} */
3357    @Override
3358    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
3359        mTopFullscreenOpaqueWindowState = null;
3360        mForceStatusBar = false;
3361        mForceStatusBarFromKeyguard = false;
3362        mForcingShowNavBar = false;
3363        mForcingShowNavBarLayer = -1;
3364
3365        mHideLockScreen = false;
3366        mAllowLockscreenWhenOn = false;
3367        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
3368        mShowingLockscreen = false;
3369        mShowingDream = false;
3370    }
3371
3372    /** {@inheritDoc} */
3373    @Override
3374    public void applyPostLayoutPolicyLw(WindowState win,
3375                                WindowManager.LayoutParams attrs) {
3376        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
3377                + win.isVisibleOrBehindKeyguardLw());
3378        if (mTopFullscreenOpaqueWindowState == null && (win.getAttrs().privateFlags
3379                &WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_SHOW_NAV_BAR) != 0
3380                || (win.isVisibleLw() && attrs.type == TYPE_INPUT_METHOD)) {
3381            if (mForcingShowNavBarLayer < 0) {
3382                mForcingShowNavBar = true;
3383                mForcingShowNavBarLayer = win.getSurfaceLayer();
3384            }
3385        }
3386        if (mTopFullscreenOpaqueWindowState == null &&
3387                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
3388            if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
3389                if (attrs.type == TYPE_KEYGUARD) {
3390                    mForceStatusBarFromKeyguard = true;
3391                } else {
3392                    mForceStatusBar = true;
3393                }
3394            }
3395            if (attrs.type == TYPE_KEYGUARD) {
3396                mShowingLockscreen = true;
3397            }
3398            boolean applyWindow = attrs.type >= FIRST_APPLICATION_WINDOW
3399                    && attrs.type <= LAST_APPLICATION_WINDOW;
3400            if (attrs.type == TYPE_DREAM) {
3401                // If the lockscreen was showing when the dream started then wait
3402                // for the dream to draw before hiding the lockscreen.
3403                if (!mDreamingLockscreen
3404                        || (win.isVisibleLw() && win.hasDrawnLw())) {
3405                    mShowingDream = true;
3406                    applyWindow = true;
3407                }
3408            }
3409            if (applyWindow
3410                    && attrs.x == 0 && attrs.y == 0
3411                    && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
3412                    && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
3413                if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
3414                mTopFullscreenOpaqueWindowState = win;
3415                if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
3416                    if (DEBUG_LAYOUT) Slog.v(TAG, "Setting mHideLockScreen to true by win " + win);
3417                    mHideLockScreen = true;
3418                    mForceStatusBarFromKeyguard = false;
3419                }
3420                if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0
3421                        && mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
3422                    if (DEBUG_LAYOUT) Slog.v(TAG, "Setting mDismissKeyguard true by win " + win);
3423                    mDismissKeyguard = mWinDismissingKeyguard == win ?
3424                            DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
3425                    mWinDismissingKeyguard = win;
3426                    mForceStatusBarFromKeyguard = mShowingLockscreen && isKeyguardSecure();
3427                }
3428                if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
3429                    mAllowLockscreenWhenOn = true;
3430                }
3431            }
3432        }
3433    }
3434
3435    /** {@inheritDoc} */
3436    @Override
3437    public int finishPostLayoutPolicyLw() {
3438        int changes = 0;
3439        boolean topIsFullscreen = false;
3440
3441        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
3442                ? mTopFullscreenOpaqueWindowState.getAttrs()
3443                : null;
3444
3445        // If we are not currently showing a dream then remember the current
3446        // lockscreen state.  We will use this to determine whether the dream
3447        // started while the lockscreen was showing and remember this state
3448        // while the dream is showing.
3449        if (!mShowingDream) {
3450            mDreamingLockscreen = mShowingLockscreen;
3451        }
3452
3453        if (mStatusBar != null) {
3454            if (DEBUG_LAYOUT) Slog.i(TAG, "force=" + mForceStatusBar
3455                    + " forcefkg=" + mForceStatusBarFromKeyguard
3456                    + " top=" + mTopFullscreenOpaqueWindowState);
3457            if (mForceStatusBar || mForceStatusBarFromKeyguard) {
3458                if (DEBUG_LAYOUT) Slog.v(TAG, "Showing status bar: forced");
3459                if (mStatusBarController.setBarShowingLw(true)) {
3460                    changes |= FINISH_LAYOUT_REDO_LAYOUT;
3461                }
3462            } else if (mTopFullscreenOpaqueWindowState != null) {
3463                if (localLOGV) {
3464                    Slog.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
3465                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
3466                    Slog.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
3467                            + " lp.flags=0x" + Integer.toHexString(lp.flags));
3468                }
3469                topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
3470                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
3471                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
3472                // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window
3473                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
3474                // case though.
3475                if (mStatusBarController.isTransientShowing()) {
3476                    if (mStatusBarController.setBarShowingLw(true)) {
3477                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
3478                    }
3479                } else if (topIsFullscreen) {
3480                    if (DEBUG_LAYOUT) Slog.v(TAG, "** HIDING status bar");
3481                    if (mStatusBarController.setBarShowingLw(false)) {
3482                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
3483                    } else {
3484                        if (DEBUG_LAYOUT) Slog.v(TAG, "Status bar already hiding");
3485                    }
3486                } else {
3487                    if (DEBUG_LAYOUT) Slog.v(TAG, "** SHOWING status bar: top is not fullscreen");
3488                    if (mStatusBarController.setBarShowingLw(true)) {
3489                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
3490                    }
3491                }
3492            }
3493        }
3494
3495        mTopIsFullscreen = topIsFullscreen;
3496
3497        // Hide the key guard if a visible window explicitly specifies that it wants to be
3498        // displayed when the screen is locked.
3499        if (mKeyguard != null) {
3500            if (localLOGV) Slog.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
3501                    + mHideLockScreen);
3502            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardDelegate.isSecure()) {
3503                if (mKeyguard.hideLw(true)) {
3504                    changes |= FINISH_LAYOUT_REDO_LAYOUT
3505                            | FINISH_LAYOUT_REDO_CONFIG
3506                            | FINISH_LAYOUT_REDO_WALLPAPER;
3507                }
3508                if (mKeyguardDelegate.isShowing()) {
3509                    mHandler.post(new Runnable() {
3510                        @Override
3511                        public void run() {
3512                            mKeyguardDelegate.keyguardDone(false, false);
3513                        }
3514                    });
3515                }
3516            } else if (mHideLockScreen) {
3517                if (mKeyguard.hideLw(true)) {
3518                    changes |= FINISH_LAYOUT_REDO_LAYOUT
3519                            | FINISH_LAYOUT_REDO_CONFIG
3520                            | FINISH_LAYOUT_REDO_WALLPAPER;
3521                }
3522                mKeyguardDelegate.setHidden(true);
3523            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
3524                // This is the case of keyguard isSecure() and not mHideLockScreen.
3525                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
3526                    // Only launch the next keyguard unlock window once per window.
3527                    if (mKeyguard.showLw(true)) {
3528                        changes |= FINISH_LAYOUT_REDO_LAYOUT
3529                                | FINISH_LAYOUT_REDO_CONFIG
3530                                | FINISH_LAYOUT_REDO_WALLPAPER;
3531                    }
3532                    mKeyguardDelegate.setHidden(false);
3533                    mHandler.post(new Runnable() {
3534                        @Override
3535                        public void run() {
3536                            mKeyguardDelegate.dismiss();
3537                        }
3538                    });
3539                }
3540            } else {
3541                mWinDismissingKeyguard = null;
3542                if (mKeyguard.showLw(true)) {
3543                    changes |= FINISH_LAYOUT_REDO_LAYOUT
3544                            | FINISH_LAYOUT_REDO_CONFIG
3545                            | FINISH_LAYOUT_REDO_WALLPAPER;
3546                }
3547                mKeyguardDelegate.setHidden(false);
3548            }
3549        }
3550
3551        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
3552            // If the navigation bar has been hidden or shown, we need to do another
3553            // layout pass to update that window.
3554            changes |= FINISH_LAYOUT_REDO_LAYOUT;
3555        }
3556
3557        // update since mAllowLockscreenWhenOn might have changed
3558        updateLockScreenTimeout();
3559        return changes;
3560    }
3561
3562    public boolean allowAppAnimationsLw() {
3563        if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) {
3564            // If keyguard is currently visible, no reason to animate
3565            // behind it.
3566            return false;
3567        }
3568        return true;
3569    }
3570
3571    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
3572        mFocusedWindow = newFocus;
3573        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
3574            // If the navigation bar has been hidden or shown, we need to do another
3575            // layout pass to update that window.
3576            return FINISH_LAYOUT_REDO_LAYOUT;
3577        }
3578        return 0;
3579    }
3580
3581    /** {@inheritDoc} */
3582    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
3583        // do nothing if headless
3584        if (mHeadless) return;
3585
3586        // lid changed state
3587        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
3588        if (newLidState == mLidState) {
3589            return;
3590        }
3591
3592        mLidState = newLidState;
3593        applyLidSwitchState();
3594        updateRotation(true);
3595
3596        if (lidOpen) {
3597            mPowerManager.wakeUp(SystemClock.uptimeMillis());
3598        } else if (!mLidControlsSleep) {
3599            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3600        }
3601    }
3602
3603    void setHdmiPlugged(boolean plugged) {
3604        if (mHdmiPlugged != plugged) {
3605            mHdmiPlugged = plugged;
3606            updateRotation(true, true);
3607            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
3608            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3609            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
3610            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3611        }
3612    }
3613
3614    void initializeHdmiState() {
3615        boolean plugged = false;
3616        // watch for HDMI plug messages if the hdmi switch exists
3617        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
3618            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
3619
3620            final String filename = "/sys/class/switch/hdmi/state";
3621            FileReader reader = null;
3622            try {
3623                reader = new FileReader(filename);
3624                char[] buf = new char[15];
3625                int n = reader.read(buf);
3626                if (n > 1) {
3627                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
3628                }
3629            } catch (IOException ex) {
3630                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3631            } catch (NumberFormatException ex) {
3632                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3633            } finally {
3634                if (reader != null) {
3635                    try {
3636                        reader.close();
3637                    } catch (IOException ex) {
3638                    }
3639                }
3640            }
3641        }
3642        // This dance forces the code in setHdmiPlugged to run.
3643        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
3644        mHdmiPlugged = !plugged;
3645        setHdmiPlugged(!mHdmiPlugged);
3646    }
3647
3648    /**
3649     * @return Whether music is being played right now "locally" (e.g. on the device's speakers
3650     *    or wired headphones) or "remotely" (e.g. on a device using the Cast protocol and
3651     *    controlled by this device, or through remote submix).
3652     */
3653    boolean isMusicActive() {
3654        final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
3655        if (am == null) {
3656            Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
3657            return false;
3658        }
3659        return am.isLocalOrRemoteMusicActive();
3660    }
3661
3662    /**
3663     * Tell the audio service to adjust the volume appropriate to the event.
3664     * @param keycode
3665     */
3666    void handleVolumeKey(int stream, int keycode) {
3667        IAudioService audioService = getAudioService();
3668        if (audioService == null) {
3669            return;
3670        }
3671        try {
3672            // when audio is playing locally, we shouldn't have to hold a wake lock
3673            // during the call, but we do it as a precaution for the rare possibility
3674            // that the music stops right before we call this.
3675            // Otherwise we might also be in a remote playback case.
3676            // TODO: Actually handle MUTE.
3677            mBroadcastWakeLock.acquire();
3678            if (stream == AudioSystem.STREAM_MUSIC) {
3679                audioService.adjustLocalOrRemoteStreamVolume(stream,
3680                        keycode == KeyEvent.KEYCODE_VOLUME_UP
3681                                ? AudioManager.ADJUST_RAISE
3682                                : AudioManager.ADJUST_LOWER,
3683                        mContext.getOpPackageName());
3684            } else {
3685                audioService.adjustStreamVolume(stream,
3686                        keycode == KeyEvent.KEYCODE_VOLUME_UP
3687                                ? AudioManager.ADJUST_RAISE
3688                                : AudioManager.ADJUST_LOWER,
3689                        0,
3690                        mContext.getOpPackageName());
3691            }
3692        } catch (RemoteException e) {
3693            Log.w(TAG, "IAudioService.adjust*StreamVolume() threw RemoteException " + e);
3694        } finally {
3695            mBroadcastWakeLock.release();
3696        }
3697    }
3698
3699    final Object mScreenshotLock = new Object();
3700    ServiceConnection mScreenshotConnection = null;
3701
3702    final Runnable mScreenshotTimeout = new Runnable() {
3703        @Override public void run() {
3704            synchronized (mScreenshotLock) {
3705                if (mScreenshotConnection != null) {
3706                    mContext.unbindService(mScreenshotConnection);
3707                    mScreenshotConnection = null;
3708                }
3709            }
3710        }
3711    };
3712
3713    // Assume this is called from the Handler thread.
3714    private void takeScreenshot() {
3715        synchronized (mScreenshotLock) {
3716            if (mScreenshotConnection != null) {
3717                return;
3718            }
3719            ComponentName cn = new ComponentName("com.android.systemui",
3720                    "com.android.systemui.screenshot.TakeScreenshotService");
3721            Intent intent = new Intent();
3722            intent.setComponent(cn);
3723            ServiceConnection conn = new ServiceConnection() {
3724                @Override
3725                public void onServiceConnected(ComponentName name, IBinder service) {
3726                    synchronized (mScreenshotLock) {
3727                        if (mScreenshotConnection != this) {
3728                            return;
3729                        }
3730                        Messenger messenger = new Messenger(service);
3731                        Message msg = Message.obtain(null, 1);
3732                        final ServiceConnection myConn = this;
3733                        Handler h = new Handler(mHandler.getLooper()) {
3734                            @Override
3735                            public void handleMessage(Message msg) {
3736                                synchronized (mScreenshotLock) {
3737                                    if (mScreenshotConnection == myConn) {
3738                                        mContext.unbindService(mScreenshotConnection);
3739                                        mScreenshotConnection = null;
3740                                        mHandler.removeCallbacks(mScreenshotTimeout);
3741                                    }
3742                                }
3743                            }
3744                        };
3745                        msg.replyTo = new Messenger(h);
3746                        msg.arg1 = msg.arg2 = 0;
3747                        if (mStatusBar != null && mStatusBar.isVisibleLw())
3748                            msg.arg1 = 1;
3749                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
3750                            msg.arg2 = 1;
3751                        try {
3752                            messenger.send(msg);
3753                        } catch (RemoteException e) {
3754                        }
3755                    }
3756                }
3757                @Override
3758                public void onServiceDisconnected(ComponentName name) {}
3759            };
3760            if (mContext.bindServiceAsUser(
3761                    intent, conn, Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
3762                mScreenshotConnection = conn;
3763                mHandler.postDelayed(mScreenshotTimeout, 10000);
3764            }
3765        }
3766    }
3767
3768    /** {@inheritDoc} */
3769    @Override
3770    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
3771        if (!mSystemBooted) {
3772            // If we have not yet booted, don't let key events do anything.
3773            return 0;
3774        }
3775
3776        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
3777        final boolean canceled = event.isCanceled();
3778        final int keyCode = event.getKeyCode();
3779
3780        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
3781
3782        // If screen is off then we treat the case where the keyguard is open but hidden
3783        // the same as if it were open and in front.
3784        // This will prevent any keys other than the power button from waking the screen
3785        // when the keyguard is hidden by another activity.
3786        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
3787                                            (isScreenOn ?
3788                                                mKeyguardDelegate.isShowingAndNotHidden() :
3789                                                mKeyguardDelegate.isShowing()));
3790
3791        if (keyCode == KeyEvent.KEYCODE_POWER) {
3792            policyFlags |= WindowManagerPolicy.FLAG_WAKE;
3793        }
3794        final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE
3795                | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3796
3797        if (DEBUG_INPUT) {
3798            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
3799                    + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive
3800                    + " policyFlags=" + Integer.toHexString(policyFlags)
3801                    + " isWakeKey=" + isWakeKey);
3802        }
3803
3804        if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
3805                && event.getRepeatCount() == 0) {
3806            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
3807        }
3808
3809        // Basic policy based on screen state and keyguard.
3810        // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
3811        //        is on or off, really.  We should care about whether the device is in an
3812        //        interactive state or is in suspend pretending to be "off".
3813        //        The primary screen might be turned off due to proximity sensor or
3814        //        because we are presenting media on an auxiliary screen or remotely controlling
3815        //        the device some other way (which is why we have an exemption here for injected
3816        //        events).
3817        int result;
3818        if ((isScreenOn && !mHeadless) || (isInjected && !isWakeKey)) {
3819            // When the screen is on or if the key is injected pass the key to the application.
3820            result = ACTION_PASS_TO_USER;
3821        } else {
3822            // When the screen is off and the key is not injected, determine whether
3823            // to wake the device but don't pass the key to the application.
3824            result = 0;
3825            if (down && isWakeKey && isWakeKeyWhenScreenOff(keyCode)) {
3826                result |= ACTION_WAKE_UP;
3827            }
3828        }
3829
3830        // If the key would be handled globally, just return the result, don't worry about special
3831        // key processing.
3832        if (mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
3833            return result;
3834        }
3835
3836        // Handle special keys.
3837        switch (keyCode) {
3838            case KeyEvent.KEYCODE_VOLUME_DOWN:
3839            case KeyEvent.KEYCODE_VOLUME_UP:
3840            case KeyEvent.KEYCODE_VOLUME_MUTE: {
3841                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
3842                    if (down) {
3843                        if (isScreenOn && !mVolumeDownKeyTriggered
3844                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3845                            mVolumeDownKeyTriggered = true;
3846                            mVolumeDownKeyTime = event.getDownTime();
3847                            mVolumeDownKeyConsumedByScreenshotChord = false;
3848                            cancelPendingPowerKeyAction();
3849                            interceptScreenshotChord();
3850                        }
3851                    } else {
3852                        mVolumeDownKeyTriggered = false;
3853                        cancelPendingScreenshotChordAction();
3854                    }
3855                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
3856                    if (down) {
3857                        if (isScreenOn && !mVolumeUpKeyTriggered
3858                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3859                            mVolumeUpKeyTriggered = true;
3860                            cancelPendingPowerKeyAction();
3861                            cancelPendingScreenshotChordAction();
3862                        }
3863                    } else {
3864                        mVolumeUpKeyTriggered = false;
3865                        cancelPendingScreenshotChordAction();
3866                    }
3867                }
3868                if (down) {
3869                    ITelephony telephonyService = getTelephonyService();
3870                    if (telephonyService != null) {
3871                        try {
3872                            if (telephonyService.isRinging()) {
3873                                // If an incoming call is ringing, either VOLUME key means
3874                                // "silence ringer".  We handle these keys here, rather than
3875                                // in the InCallScreen, to make sure we'll respond to them
3876                                // even if the InCallScreen hasn't come to the foreground yet.
3877                                // Look for the DOWN event here, to agree with the "fallback"
3878                                // behavior in the InCallScreen.
3879                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3880                                      + " VOLUME key-down while ringing: Silence ringer!");
3881
3882                                // Silence the ringer.  (It's safe to call this
3883                                // even if the ringer has already been silenced.)
3884                                telephonyService.silenceRinger();
3885
3886                                // And *don't* pass this key thru to the current activity
3887                                // (which is probably the InCallScreen.)
3888                                result &= ~ACTION_PASS_TO_USER;
3889                                break;
3890                            }
3891                            if (telephonyService.isOffhook()
3892                                    && (result & ACTION_PASS_TO_USER) == 0) {
3893                                // If we are in call but we decided not to pass the key to
3894                                // the application, handle the volume change here.
3895                                handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
3896                                break;
3897                            }
3898                        } catch (RemoteException ex) {
3899                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3900                        }
3901                    }
3902
3903                    if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
3904                        // If music is playing but we decided not to pass the key to the
3905                        // application, handle the volume change here.
3906                        handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
3907                        break;
3908                    }
3909                }
3910                break;
3911            }
3912
3913            case KeyEvent.KEYCODE_ENDCALL: {
3914                result &= ~ACTION_PASS_TO_USER;
3915                if (down) {
3916                    ITelephony telephonyService = getTelephonyService();
3917                    boolean hungUp = false;
3918                    if (telephonyService != null) {
3919                        try {
3920                            hungUp = telephonyService.endCall();
3921                        } catch (RemoteException ex) {
3922                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3923                        }
3924                    }
3925                    interceptPowerKeyDown(!isScreenOn || hungUp);
3926                } else {
3927                    if (interceptPowerKeyUp(canceled)) {
3928                        if ((mEndcallBehavior
3929                                & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
3930                            if (goHome()) {
3931                                break;
3932                            }
3933                        }
3934                        if ((mEndcallBehavior
3935                                & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
3936                            result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3937                        }
3938                    }
3939                }
3940                break;
3941            }
3942
3943            case KeyEvent.KEYCODE_POWER: {
3944                result &= ~ACTION_PASS_TO_USER;
3945                if (down) {
3946                    mTransientNavigationConfirmation.onPowerKeyDown(isScreenOn, event.getDownTime(),
3947                            isTransientNavigationAllowed(mLastSystemUiFlags));
3948                    if (isScreenOn && !mPowerKeyTriggered
3949                            && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3950                        mPowerKeyTriggered = true;
3951                        mPowerKeyTime = event.getDownTime();
3952                        interceptScreenshotChord();
3953                    }
3954
3955                    ITelephony telephonyService = getTelephonyService();
3956                    boolean hungUp = false;
3957                    if (telephonyService != null) {
3958                        try {
3959                            if (telephonyService.isRinging()) {
3960                                // Pressing Power while there's a ringing incoming
3961                                // call should silence the ringer.
3962                                telephonyService.silenceRinger();
3963                            } else if ((mIncallPowerBehavior
3964                                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
3965                                    && telephonyService.isOffhook()) {
3966                                // Otherwise, if "Power button ends call" is enabled,
3967                                // the Power button will hang up any current active call.
3968                                hungUp = telephonyService.endCall();
3969                            }
3970                        } catch (RemoteException ex) {
3971                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3972                        }
3973                    }
3974                    interceptPowerKeyDown(!isScreenOn || hungUp
3975                            || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered);
3976                } else {
3977                    mPowerKeyTriggered = false;
3978                    cancelPendingScreenshotChordAction();
3979                    if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) {
3980                        result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3981                    }
3982                    mPendingPowerKeyUpCanceled = false;
3983                }
3984                break;
3985            }
3986
3987            case KeyEvent.KEYCODE_MEDIA_PLAY:
3988            case KeyEvent.KEYCODE_MEDIA_PAUSE:
3989            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3990                if (down) {
3991                    ITelephony telephonyService = getTelephonyService();
3992                    if (telephonyService != null) {
3993                        try {
3994                            if (!telephonyService.isIdle()) {
3995                                // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
3996                                // to avoid music playback.
3997                                break;
3998                            }
3999                        } catch (RemoteException ex) {
4000                            Log.w(TAG, "ITelephony threw RemoteException", ex);
4001                        }
4002                    }
4003                }
4004            case KeyEvent.KEYCODE_HEADSETHOOK:
4005            case KeyEvent.KEYCODE_MUTE:
4006            case KeyEvent.KEYCODE_MEDIA_STOP:
4007            case KeyEvent.KEYCODE_MEDIA_NEXT:
4008            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
4009            case KeyEvent.KEYCODE_MEDIA_REWIND:
4010            case KeyEvent.KEYCODE_MEDIA_RECORD:
4011            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
4012            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK: {
4013                if ((result & ACTION_PASS_TO_USER) == 0) {
4014                    // Only do this if we would otherwise not pass it to the user. In that
4015                    // case, the PhoneWindow class will do the same thing, except it will
4016                    // only do it if the showing app doesn't process the key on its own.
4017                    // Note that we need to make a copy of the key event here because the
4018                    // original key event will be recycled when we return.
4019                    mBroadcastWakeLock.acquire();
4020                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
4021                            new KeyEvent(event));
4022                    msg.setAsynchronous(true);
4023                    msg.sendToTarget();
4024                }
4025                break;
4026            }
4027
4028            case KeyEvent.KEYCODE_CALL: {
4029                if (down) {
4030                    ITelephony telephonyService = getTelephonyService();
4031                    if (telephonyService != null) {
4032                        try {
4033                            if (telephonyService.isRinging()) {
4034                                Log.i(TAG, "interceptKeyBeforeQueueing:"
4035                                      + " CALL key-down while ringing: Answer the call!");
4036                                telephonyService.answerRingingCall();
4037
4038                                // And *don't* pass this key thru to the current activity
4039                                // (which is presumably the InCallScreen.)
4040                                result &= ~ACTION_PASS_TO_USER;
4041                            }
4042                        } catch (RemoteException ex) {
4043                            Log.w(TAG, "ITelephony threw RemoteException", ex);
4044                        }
4045                    }
4046                }
4047                break;
4048            }
4049        }
4050        return result;
4051    }
4052
4053    /**
4054     * When the screen is off we ignore some keys that might otherwise typically
4055     * be considered wake keys.  We filter them out here.
4056     *
4057     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
4058     * is always considered a wake key.
4059     */
4060    private boolean isWakeKeyWhenScreenOff(int keyCode) {
4061        switch (keyCode) {
4062            // ignore volume keys unless docked
4063            case KeyEvent.KEYCODE_VOLUME_UP:
4064            case KeyEvent.KEYCODE_VOLUME_DOWN:
4065            case KeyEvent.KEYCODE_VOLUME_MUTE:
4066                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
4067
4068            // ignore media and camera keys
4069            case KeyEvent.KEYCODE_MUTE:
4070            case KeyEvent.KEYCODE_HEADSETHOOK:
4071            case KeyEvent.KEYCODE_MEDIA_PLAY:
4072            case KeyEvent.KEYCODE_MEDIA_PAUSE:
4073            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
4074            case KeyEvent.KEYCODE_MEDIA_STOP:
4075            case KeyEvent.KEYCODE_MEDIA_NEXT:
4076            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
4077            case KeyEvent.KEYCODE_MEDIA_REWIND:
4078            case KeyEvent.KEYCODE_MEDIA_RECORD:
4079            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
4080            case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
4081            case KeyEvent.KEYCODE_CAMERA:
4082                return false;
4083        }
4084        return true;
4085    }
4086
4087
4088    /** {@inheritDoc} */
4089    @Override
4090    public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
4091        int result = 0;
4092
4093        final boolean isWakeMotion = (policyFlags
4094                & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
4095        if (isWakeMotion) {
4096            result |= ACTION_WAKE_UP;
4097        }
4098        return result;
4099    }
4100
4101    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
4102        if (DEBUG_INPUT) {
4103            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
4104        }
4105
4106        if (mHavePendingMediaKeyRepeatWithWakeLock) {
4107            if (DEBUG_INPUT) {
4108                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
4109            }
4110
4111            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
4112            mHavePendingMediaKeyRepeatWithWakeLock = false;
4113            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
4114        }
4115
4116        dispatchMediaKeyWithWakeLockToAudioService(event);
4117
4118        if (event.getAction() == KeyEvent.ACTION_DOWN
4119                && event.getRepeatCount() == 0) {
4120            mHavePendingMediaKeyRepeatWithWakeLock = true;
4121
4122            Message msg = mHandler.obtainMessage(
4123                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
4124            msg.setAsynchronous(true);
4125            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
4126        } else {
4127            mBroadcastWakeLock.release();
4128        }
4129    }
4130
4131    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
4132        mHavePendingMediaKeyRepeatWithWakeLock = false;
4133
4134        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
4135                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
4136        if (DEBUG_INPUT) {
4137            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
4138        }
4139
4140        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
4141        mBroadcastWakeLock.release();
4142    }
4143
4144    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
4145        if (ActivityManagerNative.isSystemReady()) {
4146            IAudioService audioService = getAudioService();
4147            if (audioService != null) {
4148                try {
4149                    audioService.dispatchMediaKeyEventUnderWakelock(event);
4150                } catch (RemoteException e) {
4151                    Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e);
4152                }
4153            }
4154        }
4155    }
4156
4157    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
4158        @Override
4159        public void onReceive(Context context, Intent intent) {
4160            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
4161                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
4162                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
4163            } else {
4164                try {
4165                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
4166                            ServiceManager.getService(Context.UI_MODE_SERVICE));
4167                    mUiMode = uiModeService.getCurrentModeType();
4168                } catch (RemoteException e) {
4169                }
4170            }
4171            updateRotation(true);
4172            synchronized (mLock) {
4173                updateOrientationListenerLp();
4174            }
4175        }
4176    };
4177
4178    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
4179        @Override
4180        public void onReceive(Context context, Intent intent) {
4181            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
4182                if (mKeyguardDelegate != null) {
4183                    mKeyguardDelegate.onDreamingStarted();
4184                }
4185            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
4186                if (mKeyguardDelegate != null) {
4187                    mKeyguardDelegate.onDreamingStopped();
4188                }
4189            }
4190        }
4191    };
4192
4193    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
4194        @Override
4195        public void onReceive(Context context, Intent intent) {
4196            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
4197                // tickle the settings observer: this first ensures that we're
4198                // observing the relevant settings for the newly-active user,
4199                // and then updates our own bookkeeping based on the now-
4200                // current user.
4201                mSettingsObserver.onChange(false);
4202
4203                // force a re-application of focused window sysui visibility.
4204                // the window may never have been shown for this user
4205                // e.g. the keyguard when going through the new-user setup flow
4206                synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
4207                    mLastSystemUiFlags = 0;
4208                    updateSystemUiVisibilityLw();
4209                }
4210            }
4211        }
4212    };
4213
4214    private void requestTransientBars(WindowState swipeTarget) {
4215        synchronized (mWindowManagerFuncs.getWindowManagerLock()) {
4216            boolean sb = mStatusBarController.checkShowTransientBarLw();
4217            boolean nb = mNavigationBarController.checkShowTransientBarLw();
4218            if (sb || nb) {
4219                WindowState barTarget = sb ? mStatusBar : mNavigationBar;
4220                if (sb ^ nb && barTarget != swipeTarget) {
4221                    if (DEBUG) Slog.d(TAG, "Not showing transient bar, wrong swipe target");
4222                    return;
4223                }
4224                if (sb) mStatusBarController.showTransient();
4225                if (nb) mNavigationBarController.showTransient();
4226                mTransientNavigationConfirmation.confirmCurrentPrompt();
4227                updateSystemUiVisibilityLw();
4228            }
4229        }
4230    }
4231
4232    @Override
4233    public void screenTurnedOff(int why) {
4234        EventLog.writeEvent(70000, 0);
4235        synchronized (mLock) {
4236            mScreenOnEarly = false;
4237            mScreenOnFully = false;
4238        }
4239        if (mKeyguardDelegate != null) {
4240            mKeyguardDelegate.onScreenTurnedOff(why);
4241        }
4242        synchronized (mLock) {
4243            updateOrientationListenerLp();
4244            updateLockScreenTimeout();
4245        }
4246    }
4247
4248    @Override
4249    public void screenTurningOn(final ScreenOnListener screenOnListener) {
4250        EventLog.writeEvent(70000, 1);
4251        if (false) {
4252            RuntimeException here = new RuntimeException("here");
4253            here.fillInStackTrace();
4254            Slog.i(TAG, "Screen turning on...", here);
4255        }
4256
4257        synchronized (mLock) {
4258            mScreenOnEarly = true;
4259            updateOrientationListenerLp();
4260            updateLockScreenTimeout();
4261        }
4262
4263        waitForKeyguard(screenOnListener);
4264    }
4265
4266    private void waitForKeyguard(final ScreenOnListener screenOnListener) {
4267        if (mKeyguardDelegate != null) {
4268            if (screenOnListener != null) {
4269                mKeyguardDelegate.onScreenTurnedOn(new KeyguardServiceDelegate.ShowListener() {
4270                    @Override
4271                    public void onShown(IBinder windowToken) {
4272                        waitForKeyguardWindowDrawn(windowToken, screenOnListener);
4273                    }
4274                });
4275                return;
4276            } else {
4277                mKeyguardDelegate.onScreenTurnedOn(null);
4278            }
4279        } else {
4280            Slog.i(TAG, "No keyguard interface!");
4281        }
4282        finishScreenTurningOn(screenOnListener);
4283    }
4284
4285    private void waitForKeyguardWindowDrawn(IBinder windowToken,
4286            final ScreenOnListener screenOnListener) {
4287        if (windowToken != null) {
4288            try {
4289                if (mWindowManager.waitForWindowDrawn(
4290                        windowToken, new IRemoteCallback.Stub() {
4291                    @Override
4292                    public void sendResult(Bundle data) {
4293                        Slog.i(TAG, "Lock screen displayed!");
4294                        finishScreenTurningOn(screenOnListener);
4295                    }
4296                })) {
4297                    return;
4298                }
4299                Slog.i(TAG, "No lock screen! waitForWindowDrawn false");
4300
4301            } catch (RemoteException ex) {
4302                // Can't happen in system process.
4303            }
4304        }
4305
4306        Slog.i(TAG, "No lock screen! windowToken=" + windowToken);
4307        finishScreenTurningOn(screenOnListener);
4308    }
4309
4310    private void finishScreenTurningOn(ScreenOnListener screenOnListener) {
4311        synchronized (mLock) {
4312            mScreenOnFully = true;
4313        }
4314
4315        try {
4316            mWindowManager.setEventDispatching(true);
4317        } catch (RemoteException unhandled) {
4318        }
4319
4320        if (screenOnListener != null) {
4321            screenOnListener.onScreenOn();
4322        }
4323    }
4324
4325    @Override
4326    public boolean isScreenOnEarly() {
4327        return mScreenOnEarly;
4328    }
4329
4330    @Override
4331    public boolean isScreenOnFully() {
4332        return mScreenOnFully;
4333    }
4334
4335    /** {@inheritDoc} */
4336    public void enableKeyguard(boolean enabled) {
4337        if (mKeyguardDelegate != null) {
4338            mKeyguardDelegate.setKeyguardEnabled(enabled);
4339        }
4340    }
4341
4342    /** {@inheritDoc} */
4343    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
4344        if (mKeyguardDelegate != null) {
4345            mKeyguardDelegate.verifyUnlock(callback);
4346        }
4347    }
4348
4349    private boolean keyguardIsShowingTq() {
4350        if (mKeyguardDelegate == null) return false;
4351        return mKeyguardDelegate.isShowingAndNotHidden();
4352    }
4353
4354
4355    /** {@inheritDoc} */
4356    public boolean isKeyguardLocked() {
4357        return keyguardOn();
4358    }
4359
4360    /** {@inheritDoc} */
4361    public boolean isKeyguardSecure() {
4362        if (mKeyguardDelegate == null) return false;
4363        return mKeyguardDelegate.isSecure();
4364    }
4365
4366    /** {@inheritDoc} */
4367    public boolean inKeyguardRestrictedKeyInputMode() {
4368        if (mKeyguardDelegate == null) return false;
4369        return mKeyguardDelegate.isInputRestricted();
4370    }
4371
4372    public void dismissKeyguardLw() {
4373        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
4374            mHandler.post(new Runnable() {
4375                public void run() {
4376                    if (mKeyguardDelegate.isDismissable()) {
4377                        // Can we just finish the keyguard straight away?
4378                        mKeyguardDelegate.keyguardDone(false, true);
4379                    } else {
4380                        // ask the keyguard to prompt the user to authenticate if necessary
4381                        mKeyguardDelegate.dismiss();
4382                    }
4383                }
4384            });
4385        }
4386    }
4387
4388    void sendCloseSystemWindows() {
4389        sendCloseSystemWindows(mContext, null);
4390    }
4391
4392    void sendCloseSystemWindows(String reason) {
4393        sendCloseSystemWindows(mContext, reason);
4394    }
4395
4396    static void sendCloseSystemWindows(Context context, String reason) {
4397        if (ActivityManagerNative.isSystemReady()) {
4398            try {
4399                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
4400            } catch (RemoteException e) {
4401            }
4402        }
4403    }
4404
4405    @Override
4406    public int rotationForOrientationLw(int orientation, int lastRotation) {
4407        if (false) {
4408            Slog.v(TAG, "rotationForOrientationLw(orient="
4409                        + orientation + ", last=" + lastRotation
4410                        + "); user=" + mUserRotation + " "
4411                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
4412                            ? "USER_ROTATION_LOCKED" : "")
4413                        );
4414        }
4415
4416        if (mForceDefaultOrientation) {
4417            return Surface.ROTATION_0;
4418        }
4419
4420        synchronized (mLock) {
4421            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
4422            if (sensorRotation < 0) {
4423                sensorRotation = lastRotation;
4424            }
4425
4426            final int preferredRotation;
4427            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
4428                // Ignore sensor when lid switch is open and rotation is forced.
4429                preferredRotation = mLidOpenRotation;
4430            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
4431                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
4432                // Ignore sensor when in car dock unless explicitly enabled.
4433                // This case can override the behavior of NOSENSOR, and can also
4434                // enable 180 degree rotation while docked.
4435                preferredRotation = mCarDockEnablesAccelerometer
4436                        ? sensorRotation : mCarDockRotation;
4437            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
4438                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
4439                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
4440                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
4441                // Ignore sensor when in desk dock unless explicitly enabled.
4442                // This case can override the behavior of NOSENSOR, and can also
4443                // enable 180 degree rotation while docked.
4444                preferredRotation = mDeskDockEnablesAccelerometer
4445                        ? sensorRotation : mDeskDockRotation;
4446            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
4447                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
4448                // Note that the dock orientation overrides the HDMI orientation.
4449                preferredRotation = mDemoHdmiRotation;
4450            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
4451                    && mUndockedHdmiRotation >= 0) {
4452                // Ignore sensor when plugged into HDMI and an undocked orientation has
4453                // been specified in the configuration (only for legacy devices without
4454                // full multi-display support).
4455                // Note that the dock orientation overrides the HDMI orientation.
4456                preferredRotation = mUndockedHdmiRotation;
4457            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
4458                // Application just wants to remain locked in the last rotation.
4459                preferredRotation = lastRotation;
4460            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
4461                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
4462                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
4463                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
4464                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
4465                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
4466                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
4467                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
4468                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
4469                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
4470                // Otherwise, use sensor only if requested by the application or enabled
4471                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
4472                if (mAllowAllRotations < 0) {
4473                    // Can't read this during init() because the context doesn't
4474                    // have display metrics at that time so we cannot determine
4475                    // tablet vs. phone then.
4476                    mAllowAllRotations = mContext.getResources().getBoolean(
4477                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
4478                }
4479                if (sensorRotation != Surface.ROTATION_180
4480                        || mAllowAllRotations == 1
4481                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
4482                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
4483                    preferredRotation = sensorRotation;
4484                } else {
4485                    preferredRotation = lastRotation;
4486                }
4487            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
4488                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
4489                // Apply rotation lock.  Does not apply to NOSENSOR.
4490                // The idea is that the user rotation expresses a weak preference for the direction
4491                // of gravity and as NOSENSOR is never affected by gravity, then neither should
4492                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
4493                preferredRotation = mUserRotation;
4494            } else {
4495                // No overriding preference.
4496                // We will do exactly what the application asked us to do.
4497                preferredRotation = -1;
4498            }
4499
4500            switch (orientation) {
4501                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
4502                    // Return portrait unless overridden.
4503                    if (isAnyPortrait(preferredRotation)) {
4504                        return preferredRotation;
4505                    }
4506                    return mPortraitRotation;
4507
4508                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
4509                    // Return landscape unless overridden.
4510                    if (isLandscapeOrSeascape(preferredRotation)) {
4511                        return preferredRotation;
4512                    }
4513                    return mLandscapeRotation;
4514
4515                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
4516                    // Return reverse portrait unless overridden.
4517                    if (isAnyPortrait(preferredRotation)) {
4518                        return preferredRotation;
4519                    }
4520                    return mUpsideDownRotation;
4521
4522                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
4523                    // Return seascape unless overridden.
4524                    if (isLandscapeOrSeascape(preferredRotation)) {
4525                        return preferredRotation;
4526                    }
4527                    return mSeascapeRotation;
4528
4529                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
4530                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
4531                    // Return either landscape rotation.
4532                    if (isLandscapeOrSeascape(preferredRotation)) {
4533                        return preferredRotation;
4534                    }
4535                    if (isLandscapeOrSeascape(lastRotation)) {
4536                        return lastRotation;
4537                    }
4538                    return mLandscapeRotation;
4539
4540                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
4541                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
4542                    // Return either portrait rotation.
4543                    if (isAnyPortrait(preferredRotation)) {
4544                        return preferredRotation;
4545                    }
4546                    if (isAnyPortrait(lastRotation)) {
4547                        return lastRotation;
4548                    }
4549                    return mPortraitRotation;
4550
4551                default:
4552                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
4553                    // just return the preferred orientation we already calculated.
4554                    if (preferredRotation >= 0) {
4555                        return preferredRotation;
4556                    }
4557                    return Surface.ROTATION_0;
4558            }
4559        }
4560    }
4561
4562    @Override
4563    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
4564        switch (orientation) {
4565            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
4566            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
4567            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
4568                return isAnyPortrait(rotation);
4569
4570            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
4571            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
4572            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
4573                return isLandscapeOrSeascape(rotation);
4574
4575            default:
4576                return true;
4577        }
4578    }
4579
4580    @Override
4581    public void setRotationLw(int rotation) {
4582        mOrientationListener.setCurrentRotation(rotation);
4583    }
4584
4585    private boolean isLandscapeOrSeascape(int rotation) {
4586        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
4587    }
4588
4589    private boolean isAnyPortrait(int rotation) {
4590        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
4591    }
4592
4593    public int getUserRotationMode() {
4594        return Settings.System.getIntForUser(mContext.getContentResolver(),
4595                Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
4596                        WindowManagerPolicy.USER_ROTATION_FREE :
4597                                WindowManagerPolicy.USER_ROTATION_LOCKED;
4598    }
4599
4600    // User rotation: to be used when all else fails in assigning an orientation to the device
4601    public void setUserRotationMode(int mode, int rot) {
4602        ContentResolver res = mContext.getContentResolver();
4603
4604        // mUserRotationMode and mUserRotation will be assigned by the content observer
4605        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
4606            Settings.System.putIntForUser(res,
4607                    Settings.System.USER_ROTATION,
4608                    rot,
4609                    UserHandle.USER_CURRENT);
4610            Settings.System.putIntForUser(res,
4611                    Settings.System.ACCELEROMETER_ROTATION,
4612                    0,
4613                    UserHandle.USER_CURRENT);
4614        } else {
4615            Settings.System.putIntForUser(res,
4616                    Settings.System.ACCELEROMETER_ROTATION,
4617                    1,
4618                    UserHandle.USER_CURRENT);
4619        }
4620    }
4621
4622    public void setSafeMode(boolean safeMode) {
4623        mSafeMode = safeMode;
4624        performHapticFeedbackLw(null, safeMode
4625                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
4626                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
4627    }
4628
4629    static long[] getLongIntArray(Resources r, int resid) {
4630        int[] ar = r.getIntArray(resid);
4631        if (ar == null) {
4632            return null;
4633        }
4634        long[] out = new long[ar.length];
4635        for (int i=0; i<ar.length; i++) {
4636            out[i] = ar[i];
4637        }
4638        return out;
4639    }
4640
4641    /** {@inheritDoc} */
4642    @Override
4643    public void systemReady() {
4644        if (!mHeadless) {
4645            mKeyguardDelegate = new KeyguardServiceDelegate(mContext, null);
4646            mKeyguardDelegate.onSystemReady();
4647        }
4648        synchronized (mLock) {
4649            updateOrientationListenerLp();
4650            mSystemReady = true;
4651            mHandler.post(new Runnable() {
4652                @Override
4653                public void run() {
4654                    updateSettings();
4655                }
4656            });
4657        }
4658    }
4659
4660    /** {@inheritDoc} */
4661    public void systemBooted() {
4662        synchronized (mLock) {
4663            mSystemBooted = true;
4664        }
4665    }
4666
4667    ProgressDialog mBootMsgDialog = null;
4668
4669    /** {@inheritDoc} */
4670    public void showBootMessage(final CharSequence msg, final boolean always) {
4671        if (mHeadless) return;
4672        mHandler.post(new Runnable() {
4673            @Override public void run() {
4674                if (mBootMsgDialog == null) {
4675                    mBootMsgDialog = new ProgressDialog(mContext) {
4676                        // This dialog will consume all events coming in to
4677                        // it, to avoid it trying to do things too early in boot.
4678                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
4679                            return true;
4680                        }
4681                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4682                            return true;
4683                        }
4684                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
4685                            return true;
4686                        }
4687                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
4688                            return true;
4689                        }
4690                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
4691                            return true;
4692                        }
4693                        @Override public boolean dispatchPopulateAccessibilityEvent(
4694                                AccessibilityEvent event) {
4695                            return true;
4696                        }
4697                    };
4698                    mBootMsgDialog.setTitle(R.string.android_upgrading_title);
4699                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
4700                    mBootMsgDialog.setIndeterminate(true);
4701                    mBootMsgDialog.getWindow().setType(
4702                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
4703                    mBootMsgDialog.getWindow().addFlags(
4704                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
4705                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
4706                    mBootMsgDialog.getWindow().setDimAmount(1);
4707                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
4708                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
4709                    mBootMsgDialog.getWindow().setAttributes(lp);
4710                    mBootMsgDialog.setCancelable(false);
4711                    mBootMsgDialog.show();
4712                }
4713                mBootMsgDialog.setMessage(msg);
4714            }
4715        });
4716    }
4717
4718    /** {@inheritDoc} */
4719    public void hideBootMessages() {
4720        mHandler.post(new Runnable() {
4721            @Override public void run() {
4722                if (mBootMsgDialog != null) {
4723                    mBootMsgDialog.dismiss();
4724                    mBootMsgDialog = null;
4725                }
4726            }
4727        });
4728    }
4729
4730    /** {@inheritDoc} */
4731    public void userActivity() {
4732        // ***************************************
4733        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
4734        // ***************************************
4735        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
4736        // WITH ITS LOCKS HELD.
4737        //
4738        // This code must be VERY careful about the locks
4739        // it acquires.
4740        // In fact, the current code acquires way too many,
4741        // and probably has lurking deadlocks.
4742
4743        synchronized (mScreenLockTimeout) {
4744            if (mLockScreenTimerActive) {
4745                // reset the timer
4746                mHandler.removeCallbacks(mScreenLockTimeout);
4747                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4748            }
4749        }
4750    }
4751
4752    class ScreenLockTimeout implements Runnable {
4753        Bundle options;
4754
4755        @Override
4756        public void run() {
4757            synchronized (this) {
4758                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
4759                if (mKeyguardDelegate != null) {
4760                    mKeyguardDelegate.doKeyguardTimeout(options);
4761                }
4762                mLockScreenTimerActive = false;
4763                options = null;
4764            }
4765        }
4766
4767        public void setLockOptions(Bundle options) {
4768            this.options = options;
4769        }
4770    }
4771
4772    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
4773
4774    public void lockNow(Bundle options) {
4775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
4776        mHandler.removeCallbacks(mScreenLockTimeout);
4777        if (options != null) {
4778            // In case multiple calls are made to lockNow, we don't wipe out the options
4779            // until the runnable actually executes.
4780            mScreenLockTimeout.setLockOptions(options);
4781        }
4782        mHandler.post(mScreenLockTimeout);
4783    }
4784
4785    private void updateLockScreenTimeout() {
4786        synchronized (mScreenLockTimeout) {
4787            boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly &&
4788                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
4789            if (mLockScreenTimerActive != enable) {
4790                if (enable) {
4791                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
4792                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4793                } else {
4794                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
4795                    mHandler.removeCallbacks(mScreenLockTimeout);
4796                }
4797                mLockScreenTimerActive = enable;
4798            }
4799        }
4800    }
4801
4802    /** {@inheritDoc} */
4803    @Override
4804    public void enableScreenAfterBoot() {
4805        readLidState();
4806        applyLidSwitchState();
4807        updateRotation(true);
4808    }
4809
4810    private void applyLidSwitchState() {
4811        if (mLidState == LID_CLOSED && mLidControlsSleep) {
4812            mPowerManager.goToSleep(SystemClock.uptimeMillis());
4813        }
4814    }
4815
4816    void updateRotation(boolean alwaysSendConfiguration) {
4817        try {
4818            //set orientation on WindowManager
4819            mWindowManager.updateRotation(alwaysSendConfiguration, false);
4820        } catch (RemoteException e) {
4821            // Ignore
4822        }
4823    }
4824
4825    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
4826        try {
4827            //set orientation on WindowManager
4828            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
4829        } catch (RemoteException e) {
4830            // Ignore
4831        }
4832    }
4833
4834    /**
4835     * Return an Intent to launch the currently active dock app as home.  Returns
4836     * null if the standard home should be launched, which is the case if any of the following is
4837     * true:
4838     * <ul>
4839     *  <li>The device is not in either car mode or desk mode
4840     *  <li>The device is in car mode but ENABLE_CAR_DOCK_HOME_CAPTURE is false
4841     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
4842     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
4843     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
4844     * </ul>
4845     * @return A dock intent.
4846     */
4847    Intent createHomeDockIntent() {
4848        Intent intent = null;
4849
4850        // What home does is based on the mode, not the dock state.  That
4851        // is, when in car mode you should be taken to car home regardless
4852        // of whether we are actually in a car dock.
4853        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
4854            if (ENABLE_CAR_DOCK_HOME_CAPTURE) {
4855                intent = mCarDockIntent;
4856            }
4857        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
4858            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
4859                intent = mDeskDockIntent;
4860            }
4861        }
4862
4863        if (intent == null) {
4864            return null;
4865        }
4866
4867        ActivityInfo ai = null;
4868        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
4869                intent,
4870                PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_META_DATA,
4871                mCurrentUserId);
4872        if (info != null) {
4873            ai = info.activityInfo;
4874        }
4875        if (ai != null
4876                && ai.metaData != null
4877                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
4878            intent = new Intent(intent);
4879            intent.setClassName(ai.packageName, ai.name);
4880            return intent;
4881        }
4882
4883        return null;
4884    }
4885
4886    void startDockOrHome() {
4887        awakenDreams();
4888
4889        Intent dock = createHomeDockIntent();
4890        if (dock != null) {
4891            try {
4892                mContext.startActivityAsUser(dock, UserHandle.CURRENT);
4893                return;
4894            } catch (ActivityNotFoundException e) {
4895            }
4896        }
4897
4898        mContext.startActivityAsUser(mHomeIntent, UserHandle.CURRENT);
4899    }
4900
4901    /**
4902     * goes to the home screen
4903     * @return whether it did anything
4904     */
4905    boolean goHome() {
4906        if (false) {
4907            // This code always brings home to the front.
4908            try {
4909                ActivityManagerNative.getDefault().stopAppSwitches();
4910            } catch (RemoteException e) {
4911            }
4912            sendCloseSystemWindows();
4913            startDockOrHome();
4914        } else {
4915            // This code brings home to the front or, if it is already
4916            // at the front, puts the device to sleep.
4917            try {
4918                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
4919                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
4920                    Log.d(TAG, "UTS-TEST-MODE");
4921                } else {
4922                    ActivityManagerNative.getDefault().stopAppSwitches();
4923                    sendCloseSystemWindows();
4924                    Intent dock = createHomeDockIntent();
4925                    if (dock != null) {
4926                        int result = ActivityManagerNative.getDefault()
4927                                .startActivityAsUser(null, null, dock,
4928                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
4929                                        null, null, 0,
4930                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4931                                        null, null, null, UserHandle.USER_CURRENT);
4932                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4933                            return false;
4934                        }
4935                    }
4936                }
4937                int result = ActivityManagerNative.getDefault()
4938                        .startActivityAsUser(null, null, mHomeIntent,
4939                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
4940                                null, null, 0,
4941                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4942                                null, null, null, UserHandle.USER_CURRENT);
4943                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4944                    return false;
4945                }
4946            } catch (RemoteException ex) {
4947                // bummer, the activity manager, which is in this process, is dead
4948            }
4949        }
4950        return true;
4951    }
4952
4953    @Override
4954    public void setCurrentOrientationLw(int newOrientation) {
4955        synchronized (mLock) {
4956            if (newOrientation != mCurrentAppOrientation) {
4957                mCurrentAppOrientation = newOrientation;
4958                updateOrientationListenerLp();
4959            }
4960        }
4961    }
4962
4963    private void performAuditoryFeedbackForAccessibilityIfNeed() {
4964        if (!isGlobalAccessibilityGestureEnabled()) {
4965            return;
4966        }
4967        AudioManager audioManager = (AudioManager) mContext.getSystemService(
4968                Context.AUDIO_SERVICE);
4969        if (audioManager.isSilentMode()) {
4970            return;
4971        }
4972        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
4973                Settings.System.DEFAULT_NOTIFICATION_URI);
4974        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
4975        ringTone.play();
4976    }
4977
4978    private boolean isGlobalAccessibilityGestureEnabled() {
4979        return Settings.Global.getInt(mContext.getContentResolver(),
4980                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
4981    }
4982
4983    @Override
4984    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
4985        if (!mVibrator.hasVibrator()) {
4986            return false;
4987        }
4988        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
4989                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
4990        if (!always && (hapticsDisabled || mKeyguardDelegate.isShowingAndNotHidden())) {
4991            return false;
4992        }
4993        long[] pattern = null;
4994        switch (effectId) {
4995            case HapticFeedbackConstants.LONG_PRESS:
4996                pattern = mLongPressVibePattern;
4997                break;
4998            case HapticFeedbackConstants.VIRTUAL_KEY:
4999                pattern = mVirtualKeyVibePattern;
5000                break;
5001            case HapticFeedbackConstants.KEYBOARD_TAP:
5002                pattern = mKeyboardTapVibePattern;
5003                break;
5004            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
5005                pattern = mSafeModeDisabledVibePattern;
5006                break;
5007            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
5008                pattern = mSafeModeEnabledVibePattern;
5009                break;
5010            default:
5011                return false;
5012        }
5013        int owningUid;
5014        String owningPackage;
5015        if (win != null) {
5016            owningUid = win.getOwningUid();
5017            owningPackage = win.getOwningPackage();
5018        } else {
5019            owningUid = android.os.Process.myUid();
5020            owningPackage = mContext.getOpPackageName();
5021        }
5022        if (pattern.length == 1) {
5023            // One-shot vibration
5024            mVibrator.vibrate(owningUid, owningPackage, pattern[0]);
5025        } else {
5026            // Pattern vibration
5027            mVibrator.vibrate(owningUid, owningPackage, pattern, -1);
5028        }
5029        return true;
5030    }
5031
5032    @Override
5033    public void keepScreenOnStartedLw() {
5034    }
5035
5036    @Override
5037    public void keepScreenOnStoppedLw() {
5038        if (mKeyguardDelegate != null && !mKeyguardDelegate.isShowingAndNotHidden()) {
5039            long curTime = SystemClock.uptimeMillis();
5040            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
5041        }
5042    }
5043
5044    private int updateSystemUiVisibilityLw() {
5045        // If there is no window focused, there will be nobody to handle the events
5046        // anyway, so just hang on in whatever state we're in until things settle down.
5047        WindowState win = mFocusedWindow != null ? mFocusedWindow : mTopFullscreenOpaqueWindowState;
5048        if (win == null) {
5049            return 0;
5050        }
5051        if (win.getAttrs().type == TYPE_KEYGUARD && mHideLockScreen == true) {
5052            // We are updating at a point where the keyguard has gotten
5053            // focus, but we were last in a state where the top window is
5054            // hiding it.  This is probably because the keyguard as been
5055            // shown while the top window was displayed, so we want to ignore
5056            // it here because this is just a very transient change and it
5057            // will quickly lose focus once it correctly gets hidden.
5058            return 0;
5059        }
5060
5061        int tmpVisibility = win.getSystemUiVisibility()
5062                & ~mResettingSystemUiFlags
5063                & ~mForceClearedSystemUiFlags;
5064        if (mForcingShowNavBar && win.getSurfaceLayer() < mForcingShowNavBarLayer) {
5065            tmpVisibility &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
5066        }
5067        final int visibility = updateSystemBarsLw(win, mLastSystemUiFlags, tmpVisibility);
5068        final int diff = visibility ^ mLastSystemUiFlags;
5069        final boolean needsMenu = win.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
5070        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
5071                && mFocusedApp == win.getAppToken()) {
5072            return 0;
5073        }
5074        mLastSystemUiFlags = visibility;
5075        mLastFocusNeedsMenu = needsMenu;
5076        mFocusedApp = win.getAppToken();
5077        mHandler.post(new Runnable() {
5078                @Override
5079                public void run() {
5080                    try {
5081                        IStatusBarService statusbar = getStatusBarService();
5082                        if (statusbar != null) {
5083                            statusbar.setSystemUiVisibility(visibility, 0xffffffff);
5084                            statusbar.topAppWindowChanged(needsMenu);
5085                        }
5086                    } catch (RemoteException e) {
5087                        // re-acquire status bar service next time it is needed.
5088                        mStatusBarService = null;
5089                    }
5090                }
5091            });
5092        return diff;
5093    }
5094
5095    private int updateSystemBarsLw(WindowState win, int oldVis, int vis) {
5096        // apply translucent bar vis flags
5097        WindowState transWin = mKeyguard != null && mKeyguard.isVisibleLw() && !mHideLockScreen
5098                ? mKeyguard
5099                : mTopFullscreenOpaqueWindowState;
5100        vis = mStatusBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
5101        vis = mNavigationBarController.applyTranslucentFlagLw(transWin, vis, oldVis);
5102
5103        // prevent status bar interaction from clearing certain flags
5104        boolean statusBarHasFocus = win.getAttrs().type == TYPE_STATUS_BAR;
5105        if (statusBarHasFocus) {
5106            int flags = View.SYSTEM_UI_FLAG_FULLSCREEN
5107                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
5108                    | View.SYSTEM_UI_FLAG_IMMERSIVE
5109                    | View.STATUS_BAR_TRANSLUCENT
5110                    | View.NAVIGATION_BAR_TRANSLUCENT;
5111            vis = (vis & ~flags) | (oldVis & flags);
5112        }
5113
5114        if (!isTranslucentNavigationAllowed()) {
5115            vis &= ~View.NAVIGATION_BAR_TRANSLUCENT;
5116        }
5117
5118        // update status bar
5119        boolean transientAllowed =
5120                (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
5121        boolean hideStatusBarWM =
5122                mTopFullscreenOpaqueWindowState != null &&
5123                (mTopFullscreenOpaqueWindowState.getAttrs().flags
5124                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
5125        boolean hideStatusBarSysui =
5126                (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
5127
5128        boolean transientStatusBarAllowed =
5129                mStatusBar != null && (
5130                hideStatusBarWM
5131                || (hideStatusBarSysui && transientAllowed)
5132                || statusBarHasFocus);
5133
5134        if (mStatusBarController.isTransientShowing()
5135                && !transientStatusBarAllowed && hideStatusBarSysui) {
5136            // clear the clearable flags instead
5137            int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
5138            if (newVal != mResettingSystemUiFlags) {
5139                mResettingSystemUiFlags = newVal;
5140                mWindowManagerFuncs.reevaluateStatusBarVisibility();
5141            }
5142        }
5143
5144        vis = mStatusBarController.updateVisibilityLw(transientStatusBarAllowed, oldVis, vis);
5145
5146        // update navigation bar
5147        boolean oldTransientNav = isTransientNavigationAllowed(oldVis);
5148        boolean isTransientNav = isTransientNavigationAllowed(vis);
5149        if (win != null && oldTransientNav != isTransientNav) {
5150            final String pkg = win.getOwningPackage();
5151            mTransientNavigationConfirmation.transientNavigationChanged(pkg, isTransientNav);
5152        }
5153        vis = mNavigationBarController.updateVisibilityLw(isTransientNav, oldVis, vis);
5154
5155        // don't send low profile updates if the system bars are hidden
5156        if (mStatusBarController.isHidden() && mNavigationBarController.isHidden()) {
5157            vis &= ~View.SYSTEM_UI_FLAG_LOW_PROFILE;
5158        }
5159        return vis;
5160    }
5161
5162    private boolean isTransientNavigationAllowed(int vis) {
5163        return mNavigationBar != null
5164                && (vis & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0
5165                && (vis & View.SYSTEM_UI_FLAG_IMMERSIVE) != 0;
5166    }
5167
5168    /**
5169     * @return whether the navigation bar can be made translucent, e.g. touch
5170     *         exploration is not enabled
5171     */
5172    private boolean isTranslucentNavigationAllowed() {
5173        return !mTouchExplorationEnabled;
5174    }
5175
5176    // Use this instead of checking config_showNavigationBar so that it can be consistently
5177    // overridden by qemu.hw.mainkeys in the emulator.
5178    @Override
5179    public boolean hasNavigationBar() {
5180        return mHasNavigationBar;
5181    }
5182
5183    @Override
5184    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
5185        mLastInputMethodWindow = ime;
5186        mLastInputMethodTargetWindow = target;
5187    }
5188
5189    @Override
5190    public void setCurrentUserLw(int newUserId) {
5191        mCurrentUserId = newUserId;
5192        if (mKeyguardDelegate != null) {
5193            mKeyguardDelegate.setCurrentUser(newUserId);
5194        }
5195        if (mStatusBarService != null) {
5196            try {
5197                mStatusBarService.setCurrentUser(newUserId);
5198            } catch (RemoteException e) {
5199                // oh well
5200            }
5201        }
5202        setLastInputMethodWindowLw(null, null);
5203    }
5204
5205    @Override
5206    public boolean canMagnifyWindow(int windowType) {
5207        switch (windowType) {
5208            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
5209            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
5210            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
5211            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
5212                return false;
5213            }
5214        }
5215        return true;
5216    }
5217
5218    @Override
5219    public void setTouchExplorationEnabled(boolean enabled) {
5220        mTouchExplorationEnabled = enabled;
5221    }
5222
5223    @Override
5224    public boolean isTopLevelWindow(int windowType) {
5225        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
5226                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
5227            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
5228        }
5229        return true;
5230    }
5231
5232    @Override
5233    public void dump(String prefix, PrintWriter pw, String[] args) {
5234        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
5235                pw.print(" mSystemReady="); pw.print(mSystemReady);
5236                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
5237        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
5238                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
5239                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
5240        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
5241                || mForceClearedSystemUiFlags != 0) {
5242            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
5243                    pw.print(Integer.toHexString(mLastSystemUiFlags));
5244                    pw.print(" mResettingSystemUiFlags=0x");
5245                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
5246                    pw.print(" mForceClearedSystemUiFlags=0x");
5247                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
5248        }
5249        if (mLastFocusNeedsMenu) {
5250            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
5251                    pw.println(mLastFocusNeedsMenu);
5252        }
5253        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
5254                pw.print(" mDockMode="); pw.print(mDockMode);
5255                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
5256                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
5257        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
5258                pw.print(" mUserRotation="); pw.print(mUserRotation);
5259                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
5260        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
5261        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
5262                pw.print(mCarDockEnablesAccelerometer);
5263                pw.print(" mDeskDockEnablesAccelerometer=");
5264                pw.println(mDeskDockEnablesAccelerometer);
5265        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
5266                pw.print(mLidKeyboardAccessibility);
5267                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
5268                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
5269        pw.print(prefix); pw.print("mLongPressOnPowerBehavior=");
5270                pw.print(mLongPressOnPowerBehavior);
5271                pw.print(" mHasSoftInput="); pw.println(mHasSoftInput);
5272        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
5273                pw.print(" mScreenOnFully="); pw.print(mScreenOnFully);
5274                pw.print(" mOrientationSensorEnabled="); pw.println(mOrientationSensorEnabled);
5275        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
5276                pw.print(","); pw.print(mOverscanScreenTop);
5277                pw.print(") "); pw.print(mOverscanScreenWidth);
5278                pw.print("x"); pw.println(mOverscanScreenHeight);
5279        if (mOverscanLeft != 0 || mOverscanTop != 0
5280                || mOverscanRight != 0 || mOverscanBottom != 0) {
5281            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
5282                    pw.print(" top="); pw.print(mOverscanTop);
5283                    pw.print(" right="); pw.print(mOverscanRight);
5284                    pw.print(" bottom="); pw.println(mOverscanBottom);
5285        }
5286        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
5287                pw.print(mRestrictedOverscanScreenLeft);
5288                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
5289                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
5290                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
5291        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
5292                pw.print(","); pw.print(mUnrestrictedScreenTop);
5293                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
5294                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
5295        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
5296                pw.print(","); pw.print(mRestrictedScreenTop);
5297                pw.print(") "); pw.print(mRestrictedScreenWidth);
5298                pw.print("x"); pw.println(mRestrictedScreenHeight);
5299        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
5300                pw.print(","); pw.print(mStableFullscreenTop);
5301                pw.print(")-("); pw.print(mStableFullscreenRight);
5302                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
5303        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
5304                pw.print(","); pw.print(mStableTop);
5305                pw.print(")-("); pw.print(mStableRight);
5306                pw.print(","); pw.print(mStableBottom); pw.println(")");
5307        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
5308                pw.print(","); pw.print(mSystemTop);
5309                pw.print(")-("); pw.print(mSystemRight);
5310                pw.print(","); pw.print(mSystemBottom); pw.println(")");
5311        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
5312                pw.print(","); pw.print(mCurTop);
5313                pw.print(")-("); pw.print(mCurRight);
5314                pw.print(","); pw.print(mCurBottom); pw.println(")");
5315        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
5316                pw.print(","); pw.print(mContentTop);
5317                pw.print(")-("); pw.print(mContentRight);
5318                pw.print(","); pw.print(mContentBottom); pw.println(")");
5319        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
5320                pw.print(","); pw.print(mDockTop);
5321                pw.print(")-("); pw.print(mDockRight);
5322                pw.print(","); pw.print(mDockBottom); pw.println(")");
5323        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
5324                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
5325        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
5326                pw.print(" mShowingDream="); pw.print(mShowingDream);
5327                pw.print(" mDreamingLockscreen="); pw.println(mDreamingLockscreen);
5328        if (mLastInputMethodWindow != null) {
5329            pw.print(prefix); pw.print("mLastInputMethodWindow=");
5330                    pw.println(mLastInputMethodWindow);
5331        }
5332        if (mLastInputMethodTargetWindow != null) {
5333            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
5334                    pw.println(mLastInputMethodTargetWindow);
5335        }
5336        if (mStatusBar != null) {
5337            pw.print(prefix); pw.print("mStatusBar=");
5338                    pw.println(mStatusBar);
5339        }
5340        if (mNavigationBar != null) {
5341            pw.print(prefix); pw.print("mNavigationBar=");
5342                    pw.println(mNavigationBar);
5343        }
5344        if (mKeyguard != null) {
5345            pw.print(prefix); pw.print("mKeyguard=");
5346                    pw.println(mKeyguard);
5347        }
5348        if (mFocusedWindow != null) {
5349            pw.print(prefix); pw.print("mFocusedWindow=");
5350                    pw.println(mFocusedWindow);
5351        }
5352        if (mFocusedApp != null) {
5353            pw.print(prefix); pw.print("mFocusedApp=");
5354                    pw.println(mFocusedApp);
5355        }
5356        if (mWinDismissingKeyguard != null) {
5357            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
5358                    pw.println(mWinDismissingKeyguard);
5359        }
5360        if (mTopFullscreenOpaqueWindowState != null) {
5361            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
5362                    pw.println(mTopFullscreenOpaqueWindowState);
5363        }
5364        if (mForcingShowNavBar) {
5365            pw.print(prefix); pw.print("mForcingShowNavBar=");
5366                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
5367                    pw.println(mForcingShowNavBarLayer);
5368        }
5369        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
5370                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
5371        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
5372                pw.print(" mForceStatusBarFromKeyguard=");
5373                pw.println(mForceStatusBarFromKeyguard);
5374        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
5375                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
5376                pw.print(" mHomePressed="); pw.println(mHomePressed);
5377        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
5378                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
5379                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
5380        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
5381                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
5382                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
5383        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
5384                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
5385        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
5386                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
5387        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
5388                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
5389        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
5390        mStatusBarController.dump(pw, prefix);
5391        mNavigationBarController.dump(pw, prefix);
5392    }
5393}
5394