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