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