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