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