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