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