PhoneWindowManager.java revision f752202bee88e31ce765483ba2efa6999ae9c9ad
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        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
2577
2578        if (!isDefaultDisplay) {
2579            if (attached != null) {
2580                // If this window is attached to another, our display
2581                // frame is the same as the one we are attached to.
2582                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, cf, vf);
2583            } else {
2584                // Give the window full screen.
2585                pf.left = df.left = cf.left = mUnrestrictedScreenLeft;
2586                pf.top = df.top = cf.top = mUnrestrictedScreenTop;
2587                pf.right = df.right = cf.right
2588                        = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
2589                pf.bottom = df.bottom = cf.bottom
2590                        = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
2591            }
2592        } else  if (attrs.type == TYPE_INPUT_METHOD) {
2593            pf.left = df.left = cf.left = vf.left = mDockLeft;
2594            pf.top = df.top = cf.top = vf.top = mDockTop;
2595            pf.right = df.right = cf.right = vf.right = mDockRight;
2596            pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom;
2597            // IM dock windows always go to the bottom of the screen.
2598            attrs.gravity = Gravity.BOTTOM;
2599            mDockLayer = win.getSurfaceLayer();
2600        } else {
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, adjust, 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.isVisibleOrBehindKeyguardLw()
2830                && !win.getGivenInsetsPendingLw()) {
2831            setLastInputMethodWindowLw(null, null);
2832            offsetInputMethodWindowLw(win);
2833        }
2834    }
2835
2836    private void offsetInputMethodWindowLw(WindowState win) {
2837        int top = win.getContentFrameLw().top;
2838        top += win.getGivenContentInsetsLw().top;
2839        if (mContentBottom > top) {
2840            mContentBottom = top;
2841        }
2842        top = win.getVisibleFrameLw().top;
2843        top += win.getGivenVisibleInsetsLw().top;
2844        if (mCurBottom > top) {
2845            mCurBottom = top;
2846        }
2847        if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
2848                + mDockBottom + " mContentBottom="
2849                + mContentBottom + " mCurBottom=" + mCurBottom);
2850    }
2851
2852    /** {@inheritDoc} */
2853    @Override
2854    public void finishLayoutLw() {
2855        return;
2856    }
2857
2858    /** {@inheritDoc} */
2859    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
2860        mTopFullscreenOpaqueWindowState = null;
2861        mForceStatusBar = false;
2862
2863        mHideLockScreen = false;
2864        mAllowLockscreenWhenOn = false;
2865        mDismissKeyguard = false;
2866    }
2867
2868    /** {@inheritDoc} */
2869    public void applyPostLayoutPolicyLw(WindowState win,
2870                                WindowManager.LayoutParams attrs) {
2871        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
2872                + win.isVisibleOrBehindKeyguardLw());
2873        if (mTopFullscreenOpaqueWindowState == null &&
2874                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
2875            if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
2876                mForceStatusBar = true;
2877            }
2878            if (((attrs.type >= FIRST_APPLICATION_WINDOW && attrs.type <= LAST_APPLICATION_WINDOW)
2879                        || attrs.type == TYPE_DREAM)
2880                    && attrs.x == 0 && attrs.y == 0
2881                    && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
2882                    && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
2883                if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
2884                mTopFullscreenOpaqueWindowState = win;
2885                if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
2886                    if (localLOGV) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
2887                    mHideLockScreen = true;
2888                }
2889                if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0) {
2890                    if (localLOGV) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
2891                    mDismissKeyguard = true;
2892                }
2893                if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
2894                    mAllowLockscreenWhenOn = true;
2895                }
2896            }
2897        }
2898    }
2899
2900    /** {@inheritDoc} */
2901    public int finishPostLayoutPolicyLw() {
2902        int changes = 0;
2903        boolean topIsFullscreen = false;
2904
2905        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
2906                ? mTopFullscreenOpaqueWindowState.getAttrs()
2907                : null;
2908
2909        if (mStatusBar != null) {
2910            if (DEBUG_LAYOUT) Log.i(TAG, "force=" + mForceStatusBar
2911                    + " top=" + mTopFullscreenOpaqueWindowState);
2912            if (mForceStatusBar) {
2913                if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar: forced");
2914                if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
2915            } else if (mTopFullscreenOpaqueWindowState != null) {
2916                if (localLOGV) {
2917                    Log.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
2918                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
2919                    Log.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
2920                            + " lp.flags=0x" + Integer.toHexString(lp.flags));
2921                }
2922                topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
2923                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
2924                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
2925                // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window
2926                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
2927                // case though.
2928                if (topIsFullscreen) {
2929                    if (DEBUG_LAYOUT) Log.v(TAG, "** HIDING status bar");
2930                    if (mStatusBar.hideLw(true)) {
2931                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
2932
2933                        mHandler.post(new Runnable() { public void run() {
2934                            try {
2935                                IStatusBarService statusbar = getStatusBarService();
2936                                if (statusbar != null) {
2937                                    statusbar.collapsePanels();
2938                                }
2939                            } catch (RemoteException ex) {
2940                                // re-acquire status bar service next time it is needed.
2941                                mStatusBarService = null;
2942                            }
2943                        }});
2944                    } else if (DEBUG_LAYOUT) {
2945                        Log.v(TAG, "Preventing status bar from hiding by policy");
2946                    }
2947                } else {
2948                    if (DEBUG_LAYOUT) Log.v(TAG, "** SHOWING status bar: top is not fullscreen");
2949                    if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
2950                }
2951            }
2952        }
2953
2954        mTopIsFullscreen = topIsFullscreen;
2955
2956        // Hide the key guard if a visible window explicitly specifies that it wants to be
2957        // displayed when the screen is locked.
2958        if (mKeyguard != null) {
2959            if (localLOGV) Log.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
2960                    + mHideLockScreen);
2961            if (mDismissKeyguard && !mKeyguardMediator.isSecure()) {
2962                if (mKeyguard.hideLw(true)) {
2963                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2964                            | FINISH_LAYOUT_REDO_CONFIG
2965                            | FINISH_LAYOUT_REDO_WALLPAPER;
2966                }
2967                if (mKeyguardMediator.isShowing()) {
2968                    mHandler.post(new Runnable() {
2969                        public void run() {
2970                            mKeyguardMediator.keyguardDone(false, false);
2971                        }
2972                    });
2973                }
2974            } else if (mHideLockScreen) {
2975                if (mKeyguard.hideLw(true)) {
2976                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2977                            | FINISH_LAYOUT_REDO_CONFIG
2978                            | FINISH_LAYOUT_REDO_WALLPAPER;
2979                }
2980                mKeyguardMediator.setHidden(true);
2981            } else {
2982                if (mKeyguard.showLw(true)) {
2983                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2984                            | FINISH_LAYOUT_REDO_CONFIG
2985                            | FINISH_LAYOUT_REDO_WALLPAPER;
2986                }
2987                mKeyguardMediator.setHidden(false);
2988            }
2989        }
2990
2991        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
2992            // If the navigation bar has been hidden or shown, we need to do another
2993            // layout pass to update that window.
2994            changes |= FINISH_LAYOUT_REDO_LAYOUT;
2995        }
2996
2997        // update since mAllowLockscreenWhenOn might have changed
2998        updateLockScreenTimeout();
2999        return changes;
3000    }
3001
3002    public boolean allowAppAnimationsLw() {
3003        if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) {
3004            // If keyguard is currently visible, no reason to animate
3005            // behind it.
3006            return false;
3007        }
3008        return true;
3009    }
3010
3011    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
3012        mFocusedWindow = newFocus;
3013        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
3014            // If the navigation bar has been hidden or shown, we need to do another
3015            // layout pass to update that window.
3016            return FINISH_LAYOUT_REDO_LAYOUT;
3017        }
3018        return 0;
3019    }
3020
3021    /** {@inheritDoc} */
3022    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
3023        // do nothing if headless
3024        if (mHeadless) return;
3025
3026        // lid changed state
3027        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
3028        if (newLidState == mLidState) {
3029            return;
3030        }
3031
3032        mLidState = newLidState;
3033        applyLidSwitchState();
3034        updateRotation(true);
3035
3036        if (lidOpen) {
3037            if (keyguardIsShowingTq()) {
3038                mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(
3039                        KeyEvent.KEYCODE_POWER, mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED);
3040            } else {
3041                mPowerManager.wakeUp(SystemClock.uptimeMillis());
3042            }
3043        } else if (!mLidControlsSleep) {
3044            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3045        }
3046    }
3047
3048    void setHdmiPlugged(boolean plugged) {
3049        if (mHdmiPlugged != plugged) {
3050            mHdmiPlugged = plugged;
3051            updateRotation(true, true);
3052            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
3053            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3054            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
3055            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3056        }
3057    }
3058
3059    void initializeHdmiState() {
3060        boolean plugged = false;
3061        // watch for HDMI plug messages if the hdmi switch exists
3062        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
3063            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
3064
3065            final String filename = "/sys/class/switch/hdmi/state";
3066            FileReader reader = null;
3067            try {
3068                reader = new FileReader(filename);
3069                char[] buf = new char[15];
3070                int n = reader.read(buf);
3071                if (n > 1) {
3072                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
3073                }
3074            } catch (IOException ex) {
3075                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3076            } catch (NumberFormatException ex) {
3077                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3078            } finally {
3079                if (reader != null) {
3080                    try {
3081                        reader.close();
3082                    } catch (IOException ex) {
3083                    }
3084                }
3085            }
3086        }
3087        // This dance forces the code in setHdmiPlugged to run.
3088        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
3089        mHdmiPlugged = !plugged;
3090        setHdmiPlugged(!mHdmiPlugged);
3091    }
3092
3093    /**
3094     * @return Whether music is being played right now.
3095     */
3096    boolean isMusicActive() {
3097        final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
3098        if (am == null) {
3099            Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
3100            return false;
3101        }
3102        return am.isMusicActive();
3103    }
3104
3105    /**
3106     * Tell the audio service to adjust the volume appropriate to the event.
3107     * @param keycode
3108     */
3109    void handleVolumeKey(int stream, int keycode) {
3110        IAudioService audioService = getAudioService();
3111        if (audioService == null) {
3112            return;
3113        }
3114        try {
3115            // since audio is playing, we shouldn't have to hold a wake lock
3116            // during the call, but we do it as a precaution for the rare possibility
3117            // that the music stops right before we call this
3118            // TODO: Actually handle MUTE.
3119            mBroadcastWakeLock.acquire();
3120            audioService.adjustStreamVolume(stream,
3121                keycode == KeyEvent.KEYCODE_VOLUME_UP
3122                            ? AudioManager.ADJUST_RAISE
3123                            : AudioManager.ADJUST_LOWER,
3124                    0);
3125        } catch (RemoteException e) {
3126            Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
3127        } finally {
3128            mBroadcastWakeLock.release();
3129        }
3130    }
3131
3132    final Object mScreenshotLock = new Object();
3133    ServiceConnection mScreenshotConnection = null;
3134
3135    final Runnable mScreenshotTimeout = new Runnable() {
3136        @Override public void run() {
3137            synchronized (mScreenshotLock) {
3138                if (mScreenshotConnection != null) {
3139                    mContext.unbindService(mScreenshotConnection);
3140                    mScreenshotConnection = null;
3141                }
3142            }
3143        }
3144    };
3145
3146    // Assume this is called from the Handler thread.
3147    private void takeScreenshot() {
3148        synchronized (mScreenshotLock) {
3149            if (mScreenshotConnection != null) {
3150                return;
3151            }
3152            ComponentName cn = new ComponentName("com.android.systemui",
3153                    "com.android.systemui.screenshot.TakeScreenshotService");
3154            Intent intent = new Intent();
3155            intent.setComponent(cn);
3156            ServiceConnection conn = new ServiceConnection() {
3157                @Override
3158                public void onServiceConnected(ComponentName name, IBinder service) {
3159                    synchronized (mScreenshotLock) {
3160                        if (mScreenshotConnection != this) {
3161                            return;
3162                        }
3163                        Messenger messenger = new Messenger(service);
3164                        Message msg = Message.obtain(null, 1);
3165                        final ServiceConnection myConn = this;
3166                        Handler h = new Handler(mHandler.getLooper()) {
3167                            @Override
3168                            public void handleMessage(Message msg) {
3169                                synchronized (mScreenshotLock) {
3170                                    if (mScreenshotConnection == myConn) {
3171                                        mContext.unbindService(mScreenshotConnection);
3172                                        mScreenshotConnection = null;
3173                                        mHandler.removeCallbacks(mScreenshotTimeout);
3174                                    }
3175                                }
3176                            }
3177                        };
3178                        msg.replyTo = new Messenger(h);
3179                        msg.arg1 = msg.arg2 = 0;
3180                        if (mStatusBar != null && mStatusBar.isVisibleLw())
3181                            msg.arg1 = 1;
3182                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
3183                            msg.arg2 = 1;
3184                        try {
3185                            messenger.send(msg);
3186                        } catch (RemoteException e) {
3187                        }
3188                    }
3189                }
3190                @Override
3191                public void onServiceDisconnected(ComponentName name) {}
3192            };
3193            if (mContext.bindService(
3194                    intent, conn, Context.BIND_AUTO_CREATE, UserHandle.USER_CURRENT)) {
3195                mScreenshotConnection = conn;
3196                mHandler.postDelayed(mScreenshotTimeout, 10000);
3197            }
3198        }
3199    }
3200
3201    /** {@inheritDoc} */
3202    @Override
3203    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
3204        if (!mSystemBooted) {
3205            // If we have not yet booted, don't let key events do anything.
3206            return 0;
3207        }
3208
3209        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
3210        final boolean canceled = event.isCanceled();
3211        final int keyCode = event.getKeyCode();
3212
3213        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
3214
3215        // If screen is off then we treat the case where the keyguard is open but hidden
3216        // the same as if it were open and in front.
3217        // This will prevent any keys other than the power button from waking the screen
3218        // when the keyguard is hidden by another activity.
3219        final boolean keyguardActive = (mKeyguardMediator == null ? false :
3220                                            (isScreenOn ?
3221                                                mKeyguardMediator.isShowingAndNotHidden() :
3222                                                mKeyguardMediator.isShowing()));
3223
3224        if (keyCode == KeyEvent.KEYCODE_POWER) {
3225            policyFlags |= WindowManagerPolicy.FLAG_WAKE;
3226        }
3227        final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE
3228                | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3229
3230        if (DEBUG_INPUT) {
3231            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
3232                    + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive
3233                    + " policyFlags=" + Integer.toHexString(policyFlags)
3234                    + " isWakeKey=" + isWakeKey);
3235        }
3236
3237        if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
3238                && event.getRepeatCount() == 0) {
3239            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
3240        }
3241
3242        // Basic policy based on screen state and keyguard.
3243        // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
3244        //        is on or off, really.  We should care about whether the device is in an
3245        //        interactive state or is in suspend pretending to be "off".
3246        //        The primary screen might be turned off due to proximity sensor or
3247        //        because we are presenting media on an auxiliary screen or remotely controlling
3248        //        the device some other way (which is why we have an exemption here for injected
3249        //        events).
3250        int result;
3251        if ((isScreenOn && !mHeadless) || (isInjected && !isWakeKey)) {
3252            // When the screen is on or if the key is injected pass the key to the application.
3253            result = ACTION_PASS_TO_USER;
3254        } else {
3255            // When the screen is off and the key is not injected, determine whether
3256            // to wake the device but don't pass the key to the application.
3257            result = 0;
3258            if (down && isWakeKey) {
3259                if (keyguardActive) {
3260                    // If the keyguard is showing, let it decide what to do with the wake key.
3261                    mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode,
3262                            mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED);
3263                } else {
3264                    // Otherwise, wake the device ourselves.
3265                    result |= ACTION_WAKE_UP;
3266                }
3267            }
3268        }
3269
3270        // Handle special keys.
3271        switch (keyCode) {
3272            case KeyEvent.KEYCODE_VOLUME_DOWN:
3273            case KeyEvent.KEYCODE_VOLUME_UP:
3274            case KeyEvent.KEYCODE_VOLUME_MUTE: {
3275                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
3276                    if (down) {
3277                        if (isScreenOn && !mVolumeDownKeyTriggered
3278                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3279                            mVolumeDownKeyTriggered = true;
3280                            mVolumeDownKeyTime = event.getDownTime();
3281                            mVolumeDownKeyConsumedByScreenshotChord = false;
3282                            cancelPendingPowerKeyAction();
3283                            interceptScreenshotChord();
3284                        }
3285                    } else {
3286                        mVolumeDownKeyTriggered = false;
3287                        cancelPendingScreenshotChordAction();
3288                    }
3289                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
3290                    if (down) {
3291                        if (isScreenOn && !mVolumeUpKeyTriggered
3292                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3293                            mVolumeUpKeyTriggered = true;
3294                            cancelPendingPowerKeyAction();
3295                            cancelPendingScreenshotChordAction();
3296                        }
3297                    } else {
3298                        mVolumeUpKeyTriggered = false;
3299                        cancelPendingScreenshotChordAction();
3300                    }
3301                }
3302                if (down) {
3303                    ITelephony telephonyService = getTelephonyService();
3304                    if (telephonyService != null) {
3305                        try {
3306                            if (telephonyService.isRinging()) {
3307                                // If an incoming call is ringing, either VOLUME key means
3308                                // "silence ringer".  We handle these keys here, rather than
3309                                // in the InCallScreen, to make sure we'll respond to them
3310                                // even if the InCallScreen hasn't come to the foreground yet.
3311                                // Look for the DOWN event here, to agree with the "fallback"
3312                                // behavior in the InCallScreen.
3313                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3314                                      + " VOLUME key-down while ringing: Silence ringer!");
3315
3316                                // Silence the ringer.  (It's safe to call this
3317                                // even if the ringer has already been silenced.)
3318                                telephonyService.silenceRinger();
3319
3320                                // And *don't* pass this key thru to the current activity
3321                                // (which is probably the InCallScreen.)
3322                                result &= ~ACTION_PASS_TO_USER;
3323                                break;
3324                            }
3325                            if (telephonyService.isOffhook()
3326                                    && (result & ACTION_PASS_TO_USER) == 0) {
3327                                // If we are in call but we decided not to pass the key to
3328                                // the application, handle the volume change here.
3329                                handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
3330                                break;
3331                            }
3332                        } catch (RemoteException ex) {
3333                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3334                        }
3335                    }
3336
3337                    if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
3338                        // If music is playing but we decided not to pass the key to the
3339                        // application, handle the volume change here.
3340                        handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
3341                        break;
3342                    }
3343                }
3344                break;
3345            }
3346
3347            case KeyEvent.KEYCODE_ENDCALL: {
3348                result &= ~ACTION_PASS_TO_USER;
3349                if (down) {
3350                    ITelephony telephonyService = getTelephonyService();
3351                    boolean hungUp = false;
3352                    if (telephonyService != null) {
3353                        try {
3354                            hungUp = telephonyService.endCall();
3355                        } catch (RemoteException ex) {
3356                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3357                        }
3358                    }
3359                    interceptPowerKeyDown(!isScreenOn || hungUp);
3360                } else {
3361                    if (interceptPowerKeyUp(canceled)) {
3362                        if ((mEndcallBehavior
3363                                & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
3364                            if (goHome()) {
3365                                break;
3366                            }
3367                        }
3368                        if ((mEndcallBehavior
3369                                & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
3370                            result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3371                        }
3372                    }
3373                }
3374                break;
3375            }
3376
3377            case KeyEvent.KEYCODE_POWER: {
3378                result &= ~ACTION_PASS_TO_USER;
3379                if (down) {
3380                    if (isScreenOn && !mPowerKeyTriggered
3381                            && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3382                        mPowerKeyTriggered = true;
3383                        mPowerKeyTime = event.getDownTime();
3384                        interceptScreenshotChord();
3385                    }
3386
3387                    ITelephony telephonyService = getTelephonyService();
3388                    boolean hungUp = false;
3389                    if (telephonyService != null) {
3390                        try {
3391                            if (telephonyService.isRinging()) {
3392                                // Pressing Power while there's a ringing incoming
3393                                // call should silence the ringer.
3394                                telephonyService.silenceRinger();
3395                            } else if ((mIncallPowerBehavior
3396                                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
3397                                    && telephonyService.isOffhook()) {
3398                                // Otherwise, if "Power button ends call" is enabled,
3399                                // the Power button will hang up any current active call.
3400                                hungUp = telephonyService.endCall();
3401                            }
3402                        } catch (RemoteException ex) {
3403                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3404                        }
3405                    }
3406                    interceptPowerKeyDown(!isScreenOn || hungUp
3407                            || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered);
3408                } else {
3409                    mPowerKeyTriggered = false;
3410                    cancelPendingScreenshotChordAction();
3411                    if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) {
3412                        result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3413                    }
3414                    mPendingPowerKeyUpCanceled = false;
3415                }
3416                break;
3417            }
3418
3419            case KeyEvent.KEYCODE_MEDIA_PLAY:
3420            case KeyEvent.KEYCODE_MEDIA_PAUSE:
3421            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3422                if (down) {
3423                    ITelephony telephonyService = getTelephonyService();
3424                    if (telephonyService != null) {
3425                        try {
3426                            if (!telephonyService.isIdle()) {
3427                                // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
3428                                // to avoid music playback.
3429                                break;
3430                            }
3431                        } catch (RemoteException ex) {
3432                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3433                        }
3434                    }
3435                }
3436            case KeyEvent.KEYCODE_HEADSETHOOK:
3437            case KeyEvent.KEYCODE_MUTE:
3438            case KeyEvent.KEYCODE_MEDIA_STOP:
3439            case KeyEvent.KEYCODE_MEDIA_NEXT:
3440            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
3441            case KeyEvent.KEYCODE_MEDIA_REWIND:
3442            case KeyEvent.KEYCODE_MEDIA_RECORD:
3443            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
3444                if ((result & ACTION_PASS_TO_USER) == 0) {
3445                    // Only do this if we would otherwise not pass it to the user. In that
3446                    // case, the PhoneWindow class will do the same thing, except it will
3447                    // only do it if the showing app doesn't process the key on its own.
3448                    // Note that we need to make a copy of the key event here because the
3449                    // original key event will be recycled when we return.
3450                    mBroadcastWakeLock.acquire();
3451                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
3452                            new KeyEvent(event));
3453                    msg.setAsynchronous(true);
3454                    msg.sendToTarget();
3455                }
3456                break;
3457            }
3458
3459            case KeyEvent.KEYCODE_CALL: {
3460                if (down) {
3461                    ITelephony telephonyService = getTelephonyService();
3462                    if (telephonyService != null) {
3463                        try {
3464                            if (telephonyService.isRinging()) {
3465                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3466                                      + " CALL key-down while ringing: Answer the call!");
3467                                telephonyService.answerRingingCall();
3468
3469                                // And *don't* pass this key thru to the current activity
3470                                // (which is presumably the InCallScreen.)
3471                                result &= ~ACTION_PASS_TO_USER;
3472                            }
3473                        } catch (RemoteException ex) {
3474                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3475                        }
3476                    }
3477                }
3478                break;
3479            }
3480        }
3481        return result;
3482    }
3483
3484    /** {@inheritDoc} */
3485    @Override
3486    public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
3487        int result = 0;
3488
3489        final boolean isWakeMotion = (policyFlags
3490                & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3491        if (isWakeMotion) {
3492            if (mKeyguardMediator != null && mKeyguardMediator.isShowing()) {
3493                // If the keyguard is showing, let it decide what to do with the wake motion.
3494                mKeyguardMediator.onWakeMotionWhenKeyguardShowingTq();
3495            } else {
3496                // Otherwise, wake the device ourselves.
3497                result |= ACTION_WAKE_UP;
3498            }
3499        }
3500        return result;
3501    }
3502
3503    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
3504        if (DEBUG_INPUT) {
3505            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
3506        }
3507
3508        if (mHavePendingMediaKeyRepeatWithWakeLock) {
3509            if (DEBUG_INPUT) {
3510                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
3511            }
3512
3513            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
3514            mHavePendingMediaKeyRepeatWithWakeLock = false;
3515            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
3516        }
3517
3518        dispatchMediaKeyWithWakeLockToAudioService(event);
3519
3520        if (event.getAction() == KeyEvent.ACTION_DOWN
3521                && event.getRepeatCount() == 0) {
3522            mHavePendingMediaKeyRepeatWithWakeLock = true;
3523
3524            Message msg = mHandler.obtainMessage(
3525                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
3526            msg.setAsynchronous(true);
3527            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
3528        } else {
3529            mBroadcastWakeLock.release();
3530        }
3531    }
3532
3533    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
3534        mHavePendingMediaKeyRepeatWithWakeLock = false;
3535
3536        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
3537                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
3538        if (DEBUG_INPUT) {
3539            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
3540        }
3541
3542        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
3543        mBroadcastWakeLock.release();
3544    }
3545
3546    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
3547        if (ActivityManagerNative.isSystemReady()) {
3548            IAudioService audioService = getAudioService();
3549            if (audioService != null) {
3550                try {
3551                    audioService.dispatchMediaKeyEventUnderWakelock(event);
3552                } catch (RemoteException e) {
3553                    Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e);
3554                }
3555            }
3556        }
3557    }
3558
3559    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
3560        public void onReceive(Context context, Intent intent) {
3561            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
3562                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3563                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
3564            }
3565            updateRotation(true);
3566            updateOrientationListenerLp();
3567        }
3568    };
3569
3570    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
3571        @Override
3572        public void onReceive(Context context, Intent intent) {
3573            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
3574                // tickle the settings observer: this first ensures that we're
3575                // observing the relevant settings for the newly-active user,
3576                // and then updates our own bookkeeping based on the now-
3577                // current user.
3578                mSettingsObserver.onChange(false);
3579            }
3580        }
3581    };
3582
3583    /** {@inheritDoc} */
3584    public void screenTurnedOff(int why) {
3585        EventLog.writeEvent(70000, 0);
3586        synchronized (mLock) {
3587            mScreenOnEarly = false;
3588            mScreenOnFully = false;
3589        }
3590        if (mKeyguardMediator != null) {
3591            mKeyguardMediator.onScreenTurnedOff(why);
3592        }
3593        synchronized (mLock) {
3594            updateOrientationListenerLp();
3595            updateLockScreenTimeout();
3596        }
3597    }
3598
3599    /** {@inheritDoc} */
3600    public void screenTurningOn(final ScreenOnListener screenOnListener) {
3601        EventLog.writeEvent(70000, 1);
3602        if (false) {
3603            RuntimeException here = new RuntimeException("here");
3604            here.fillInStackTrace();
3605            Slog.i(TAG, "Screen turning on...", here);
3606        }
3607        if (screenOnListener != null) {
3608            if (mKeyguardMediator != null) {
3609                try {
3610                    mWindowManager.setEventDispatching(true);
3611                } catch (RemoteException unhandled) {
3612                }
3613                mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() {
3614                    @Override public void onShown(IBinder windowToken) {
3615                        if (windowToken != null) {
3616                            try {
3617                                mWindowManager.waitForWindowDrawn(windowToken,
3618                                        new IRemoteCallback.Stub() {
3619                                    @Override public void sendResult(Bundle data) {
3620                                        Slog.i(TAG, "Lock screen displayed!");
3621                                        screenOnListener.onScreenOn();
3622                                        synchronized (mLock) {
3623                                            mScreenOnFully = true;
3624                                        }
3625                                    }
3626                                });
3627                            } catch (RemoteException e) {
3628                            }
3629                        } else {
3630                            Slog.i(TAG, "No lock screen!");
3631                            screenOnListener.onScreenOn();
3632                            synchronized (mLock) {
3633                                mScreenOnFully = true;
3634                            }
3635                        }
3636                    }
3637                });
3638            }
3639        } else {
3640            if (mKeyguardMediator != null) {
3641                // Must set mScreenOn = true.
3642                mKeyguardMediator.onScreenTurnedOn(null);
3643            }
3644            synchronized (mLock) {
3645                mScreenOnFully = true;
3646            }
3647        }
3648        synchronized (mLock) {
3649            mScreenOnEarly = true;
3650            updateOrientationListenerLp();
3651            updateLockScreenTimeout();
3652        }
3653    }
3654
3655    /** {@inheritDoc} */
3656    public boolean isScreenOnEarly() {
3657        return mScreenOnEarly;
3658    }
3659
3660    /** {@inheritDoc} */
3661    public boolean isScreenOnFully() {
3662        return mScreenOnFully;
3663    }
3664
3665    /** {@inheritDoc} */
3666    public void enableKeyguard(boolean enabled) {
3667        if (mKeyguardMediator != null) {
3668            mKeyguardMediator.setKeyguardEnabled(enabled);
3669        }
3670    }
3671
3672    /** {@inheritDoc} */
3673    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
3674        if (mKeyguardMediator != null) {
3675            mKeyguardMediator.verifyUnlock(callback);
3676        }
3677    }
3678
3679    private boolean keyguardIsShowingTq() {
3680        if (mKeyguardMediator == null) return false;
3681        return mKeyguardMediator.isShowingAndNotHidden();
3682    }
3683
3684
3685    /** {@inheritDoc} */
3686    public boolean isKeyguardLocked() {
3687        return keyguardOn();
3688    }
3689
3690    /** {@inheritDoc} */
3691    public boolean isKeyguardSecure() {
3692        if (mKeyguardMediator == null) return false;
3693        return mKeyguardMediator.isSecure();
3694    }
3695
3696    /** {@inheritDoc} */
3697    public boolean inKeyguardRestrictedKeyInputMode() {
3698        if (mKeyguardMediator == null) return false;
3699        return mKeyguardMediator.isInputRestricted();
3700    }
3701
3702    public void dismissKeyguardLw() {
3703        if (!mKeyguardMediator.isSecure()) {
3704            if (mKeyguardMediator.isShowing()) {
3705                mHandler.post(new Runnable() {
3706                    public void run() {
3707                        mKeyguardMediator.keyguardDone(false, true);
3708                    }
3709                });
3710            }
3711        }
3712    }
3713
3714    void sendCloseSystemWindows() {
3715        sendCloseSystemWindows(mContext, null);
3716    }
3717
3718    void sendCloseSystemWindows(String reason) {
3719        sendCloseSystemWindows(mContext, reason);
3720    }
3721
3722    static void sendCloseSystemWindows(Context context, String reason) {
3723        if (ActivityManagerNative.isSystemReady()) {
3724            try {
3725                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
3726            } catch (RemoteException e) {
3727            }
3728        }
3729    }
3730
3731    @Override
3732    public int rotationForOrientationLw(int orientation, int lastRotation) {
3733        if (false) {
3734            Slog.v(TAG, "rotationForOrientationLw(orient="
3735                        + orientation + ", last=" + lastRotation
3736                        + "); user=" + mUserRotation + " "
3737                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
3738                            ? "USER_ROTATION_LOCKED" : "")
3739                        );
3740        }
3741
3742        synchronized (mLock) {
3743            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
3744            if (sensorRotation < 0) {
3745                sensorRotation = lastRotation;
3746            }
3747
3748            final int preferredRotation;
3749            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
3750                // Ignore sensor when lid switch is open and rotation is forced.
3751                preferredRotation = mLidOpenRotation;
3752            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
3753                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
3754                // Ignore sensor when in car dock unless explicitly enabled.
3755                // This case can override the behavior of NOSENSOR, and can also
3756                // enable 180 degree rotation while docked.
3757                preferredRotation = mCarDockEnablesAccelerometer
3758                        ? sensorRotation : mCarDockRotation;
3759            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
3760                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
3761                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
3762                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
3763                // Ignore sensor when in desk dock unless explicitly enabled.
3764                // This case can override the behavior of NOSENSOR, and can also
3765                // enable 180 degree rotation while docked.
3766                preferredRotation = mDeskDockEnablesAccelerometer
3767                        ? sensorRotation : mDeskDockRotation;
3768            } else if (mHdmiPlugged) {
3769                // Ignore sensor when plugged into HDMI.
3770                // Note that the dock orientation overrides the HDMI orientation.
3771                preferredRotation = mHdmiRotation;
3772            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
3773                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
3774                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED))
3775                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
3776                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
3777                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
3778                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
3779                // Otherwise, use sensor only if requested by the application or enabled
3780                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
3781                if (mAllowAllRotations < 0) {
3782                    // Can't read this during init() because the context doesn't
3783                    // have display metrics at that time so we cannot determine
3784                    // tablet vs. phone then.
3785                    mAllowAllRotations = mContext.getResources().getBoolean(
3786                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
3787                }
3788                if (sensorRotation != Surface.ROTATION_180
3789                        || mAllowAllRotations == 1
3790                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
3791                    preferredRotation = sensorRotation;
3792                } else {
3793                    preferredRotation = lastRotation;
3794                }
3795            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
3796                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
3797                // Apply rotation lock.  Does not apply to NOSENSOR.
3798                // The idea is that the user rotation expresses a weak preference for the direction
3799                // of gravity and as NOSENSOR is never affected by gravity, then neither should
3800                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
3801                preferredRotation = mUserRotation;
3802            } else {
3803                // No overriding preference.
3804                // We will do exactly what the application asked us to do.
3805                preferredRotation = -1;
3806            }
3807
3808            switch (orientation) {
3809                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
3810                    // Return portrait unless overridden.
3811                    if (isAnyPortrait(preferredRotation)) {
3812                        return preferredRotation;
3813                    }
3814                    return mPortraitRotation;
3815
3816                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
3817                    // Return landscape unless overridden.
3818                    if (isLandscapeOrSeascape(preferredRotation)) {
3819                        return preferredRotation;
3820                    }
3821                    return mLandscapeRotation;
3822
3823                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
3824                    // Return reverse portrait unless overridden.
3825                    if (isAnyPortrait(preferredRotation)) {
3826                        return preferredRotation;
3827                    }
3828                    return mUpsideDownRotation;
3829
3830                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
3831                    // Return seascape unless overridden.
3832                    if (isLandscapeOrSeascape(preferredRotation)) {
3833                        return preferredRotation;
3834                    }
3835                    return mSeascapeRotation;
3836
3837                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
3838                    // Return either landscape rotation.
3839                    if (isLandscapeOrSeascape(preferredRotation)) {
3840                        return preferredRotation;
3841                    }
3842                    if (isLandscapeOrSeascape(lastRotation)) {
3843                        return lastRotation;
3844                    }
3845                    return mLandscapeRotation;
3846
3847                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
3848                    // Return either portrait rotation.
3849                    if (isAnyPortrait(preferredRotation)) {
3850                        return preferredRotation;
3851                    }
3852                    if (isAnyPortrait(lastRotation)) {
3853                        return lastRotation;
3854                    }
3855                    return mPortraitRotation;
3856
3857                default:
3858                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
3859                    // just return the preferred orientation we already calculated.
3860                    if (preferredRotation >= 0) {
3861                        return preferredRotation;
3862                    }
3863                    return Surface.ROTATION_0;
3864            }
3865        }
3866    }
3867
3868    @Override
3869    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
3870        switch (orientation) {
3871            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
3872            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
3873            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
3874                return isAnyPortrait(rotation);
3875
3876            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
3877            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
3878            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
3879                return isLandscapeOrSeascape(rotation);
3880
3881            default:
3882                return true;
3883        }
3884    }
3885
3886    @Override
3887    public void setRotationLw(int rotation) {
3888        mOrientationListener.setCurrentRotation(rotation);
3889    }
3890
3891    private boolean isLandscapeOrSeascape(int rotation) {
3892        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
3893    }
3894
3895    private boolean isAnyPortrait(int rotation) {
3896        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
3897    }
3898
3899
3900    // User rotation: to be used when all else fails in assigning an orientation to the device
3901    public void setUserRotationMode(int mode, int rot) {
3902        ContentResolver res = mContext.getContentResolver();
3903
3904        // mUserRotationMode and mUserRotation will be assigned by the content observer
3905        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
3906            Settings.System.putIntForUser(res,
3907                    Settings.System.USER_ROTATION,
3908                    rot,
3909                    UserHandle.USER_CURRENT);
3910            Settings.System.putIntForUser(res,
3911                    Settings.System.ACCELEROMETER_ROTATION,
3912                    0,
3913                    UserHandle.USER_CURRENT);
3914        } else {
3915            Settings.System.putIntForUser(res,
3916                    Settings.System.ACCELEROMETER_ROTATION,
3917                    1,
3918                    UserHandle.USER_CURRENT);
3919        }
3920    }
3921
3922    public void setSafeMode(boolean safeMode) {
3923        mSafeMode = safeMode;
3924        performHapticFeedbackLw(null, safeMode
3925                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
3926                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
3927    }
3928
3929    static long[] getLongIntArray(Resources r, int resid) {
3930        int[] ar = r.getIntArray(resid);
3931        if (ar == null) {
3932            return null;
3933        }
3934        long[] out = new long[ar.length];
3935        for (int i=0; i<ar.length; i++) {
3936            out[i] = ar[i];
3937        }
3938        return out;
3939    }
3940
3941    /** {@inheritDoc} */
3942    public void systemReady() {
3943        if (mKeyguardMediator != null) {
3944            // tell the keyguard
3945            mKeyguardMediator.onSystemReady();
3946        }
3947        synchronized (mLock) {
3948            updateOrientationListenerLp();
3949            mSystemReady = true;
3950            mHandler.post(new Runnable() {
3951                public void run() {
3952                    updateSettings();
3953                }
3954            });
3955        }
3956    }
3957
3958    /** {@inheritDoc} */
3959    public void systemBooted() {
3960        synchronized (mLock) {
3961            mSystemBooted = true;
3962        }
3963    }
3964
3965    ProgressDialog mBootMsgDialog = null;
3966
3967    /** {@inheritDoc} */
3968    public void showBootMessage(final CharSequence msg, final boolean always) {
3969        if (mHeadless) return;
3970        mHandler.post(new Runnable() {
3971            @Override public void run() {
3972                if (mBootMsgDialog == null) {
3973                    mBootMsgDialog = new ProgressDialog(mContext) {
3974                        // This dialog will consume all events coming in to
3975                        // it, to avoid it trying to do things too early in boot.
3976                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
3977                            return true;
3978                        }
3979                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3980                            return true;
3981                        }
3982                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
3983                            return true;
3984                        }
3985                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
3986                            return true;
3987                        }
3988                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
3989                            return true;
3990                        }
3991                        @Override public boolean dispatchPopulateAccessibilityEvent(
3992                                AccessibilityEvent event) {
3993                            return true;
3994                        }
3995                    };
3996                    mBootMsgDialog.setTitle(R.string.android_upgrading_title);
3997                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
3998                    mBootMsgDialog.setIndeterminate(true);
3999                    mBootMsgDialog.getWindow().setType(
4000                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
4001                    mBootMsgDialog.getWindow().addFlags(
4002                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
4003                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
4004                    mBootMsgDialog.getWindow().setDimAmount(1);
4005                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
4006                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
4007                    mBootMsgDialog.getWindow().setAttributes(lp);
4008                    mBootMsgDialog.setCancelable(false);
4009                    mBootMsgDialog.show();
4010                }
4011                mBootMsgDialog.setMessage(msg);
4012            }
4013        });
4014    }
4015
4016    /** {@inheritDoc} */
4017    public void hideBootMessages() {
4018        mHandler.post(new Runnable() {
4019            @Override public void run() {
4020                if (mBootMsgDialog != null) {
4021                    mBootMsgDialog.dismiss();
4022                    mBootMsgDialog = null;
4023                }
4024            }
4025        });
4026    }
4027
4028    /** {@inheritDoc} */
4029    public void userActivity() {
4030        // ***************************************
4031        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
4032        // ***************************************
4033        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
4034        // WITH ITS LOCKS HELD.
4035        //
4036        // This code must be VERY careful about the locks
4037        // it acquires.
4038        // In fact, the current code acquires way too many,
4039        // and probably has lurking deadlocks.
4040
4041        synchronized (mScreenLockTimeout) {
4042            if (mLockScreenTimerActive) {
4043                // reset the timer
4044                mHandler.removeCallbacks(mScreenLockTimeout);
4045                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4046            }
4047        }
4048    }
4049
4050    class ScreenLockTimeout implements Runnable {
4051        Bundle options;
4052
4053        @Override
4054        public void run() {
4055            synchronized (this) {
4056                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
4057                if (mKeyguardMediator != null) {
4058                    mKeyguardMediator.doKeyguardTimeout(options);
4059                }
4060                mLockScreenTimerActive = false;
4061                options = null;
4062            }
4063        }
4064
4065        public void setLockOptions(Bundle options) {
4066            this.options = options;
4067        }
4068    }
4069
4070    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
4071
4072    public void lockNow(Bundle options) {
4073        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
4074        mHandler.removeCallbacks(mScreenLockTimeout);
4075        if (options != null) {
4076            // In case multiple calls are made to lockNow, we don't wipe out the options
4077            // until the runnable actually executes.
4078            mScreenLockTimeout.setLockOptions(options);
4079        }
4080        mHandler.post(mScreenLockTimeout);
4081    }
4082
4083    private void updateLockScreenTimeout() {
4084        synchronized (mScreenLockTimeout) {
4085            boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly &&
4086                    mKeyguardMediator != null && mKeyguardMediator.isSecure());
4087            if (mLockScreenTimerActive != enable) {
4088                if (enable) {
4089                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
4090                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4091                } else {
4092                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
4093                    mHandler.removeCallbacks(mScreenLockTimeout);
4094                }
4095                mLockScreenTimerActive = enable;
4096            }
4097        }
4098    }
4099
4100    /** {@inheritDoc} */
4101    public void enableScreenAfterBoot() {
4102        readLidState();
4103        applyLidSwitchState();
4104        updateRotation(true);
4105    }
4106
4107    private void applyLidSwitchState() {
4108        if (mLidState == LID_CLOSED && mLidControlsSleep) {
4109            mPowerManager.goToSleep(SystemClock.uptimeMillis());
4110        }
4111    }
4112
4113    void updateRotation(boolean alwaysSendConfiguration) {
4114        try {
4115            //set orientation on WindowManager
4116            mWindowManager.updateRotation(alwaysSendConfiguration, false);
4117        } catch (RemoteException e) {
4118            // Ignore
4119        }
4120    }
4121
4122    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
4123        try {
4124            //set orientation on WindowManager
4125            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
4126        } catch (RemoteException e) {
4127            // Ignore
4128        }
4129    }
4130
4131    void startDockOrHome() {
4132        // We don't have dock home anymore. Home is home. If you lived here, you'd be home by now.
4133        mContext.startActivityAsUser(mHomeIntent, UserHandle.CURRENT);
4134    }
4135
4136    /**
4137     * goes to the home screen
4138     * @return whether it did anything
4139     */
4140    boolean goHome() {
4141        if (false) {
4142            // This code always brings home to the front.
4143            try {
4144                ActivityManagerNative.getDefault().stopAppSwitches();
4145            } catch (RemoteException e) {
4146            }
4147            sendCloseSystemWindows();
4148            startDockOrHome();
4149        } else {
4150            // This code brings home to the front or, if it is already
4151            // at the front, puts the device to sleep.
4152            try {
4153                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
4154                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
4155                    Log.d(TAG, "UTS-TEST-MODE");
4156                } else {
4157                    ActivityManagerNative.getDefault().stopAppSwitches();
4158                    sendCloseSystemWindows();
4159                }
4160                int result = ActivityManagerNative.getDefault()
4161                        .startActivityAsUser(null, mHomeIntent,
4162                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
4163                                null, null, 0,
4164                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4165                                null, null, null, UserHandle.USER_CURRENT);
4166                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4167                    return false;
4168                }
4169            } catch (RemoteException ex) {
4170                // bummer, the activity manager, which is in this process, is dead
4171            }
4172        }
4173        return true;
4174    }
4175
4176    public void setCurrentOrientationLw(int newOrientation) {
4177        synchronized (mLock) {
4178            if (newOrientation != mCurrentAppOrientation) {
4179                mCurrentAppOrientation = newOrientation;
4180                updateOrientationListenerLp();
4181            }
4182        }
4183    }
4184
4185    private void performAuditoryFeedbackForAccessibilityIfNeed() {
4186        if (!isGlobalAccessibilityGestureEnabled()) {
4187            return;
4188        }
4189        AudioManager audioManager = (AudioManager) mContext.getSystemService(
4190                Context.AUDIO_SERVICE);
4191        if (audioManager.isSilentMode()) {
4192            return;
4193        }
4194        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
4195                Settings.System.DEFAULT_NOTIFICATION_URI);
4196        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
4197        ringTone.play();
4198    }
4199    private boolean isGlobalAccessibilityGestureEnabled() {
4200        return Settings.Global.getInt(mContext.getContentResolver(),
4201                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
4202    }
4203
4204    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
4205        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
4206                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
4207        if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
4208            return false;
4209        }
4210        long[] pattern = null;
4211        switch (effectId) {
4212            case HapticFeedbackConstants.LONG_PRESS:
4213                pattern = mLongPressVibePattern;
4214                break;
4215            case HapticFeedbackConstants.VIRTUAL_KEY:
4216                pattern = mVirtualKeyVibePattern;
4217                break;
4218            case HapticFeedbackConstants.KEYBOARD_TAP:
4219                pattern = mKeyboardTapVibePattern;
4220                break;
4221            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
4222                pattern = mSafeModeDisabledVibePattern;
4223                break;
4224            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
4225                pattern = mSafeModeEnabledVibePattern;
4226                break;
4227            default:
4228                return false;
4229        }
4230        if (pattern.length == 1) {
4231            // One-shot vibration
4232            mVibrator.vibrate(pattern[0]);
4233        } else {
4234            // Pattern vibration
4235            mVibrator.vibrate(pattern, -1);
4236        }
4237        return true;
4238    }
4239
4240    public void screenOnStartedLw() {
4241    }
4242
4243    public void screenOnStoppedLw() {
4244        if (mPowerManager.isScreenOn()) {
4245            if (mKeyguardMediator != null && !mKeyguardMediator.isShowingAndNotHidden()) {
4246                long curTime = SystemClock.uptimeMillis();
4247                mPowerManager.userActivity(curTime, false);
4248            }
4249        }
4250    }
4251
4252    public boolean allowKeyRepeat() {
4253        // disable key repeat when screen is off
4254        return mScreenOnEarly;
4255    }
4256
4257    private int updateSystemUiVisibilityLw() {
4258        // If there is no window focused, there will be nobody to handle the events
4259        // anyway, so just hang on in whatever state we're in until things settle down.
4260        if (mFocusedWindow == null) {
4261            return 0;
4262        }
4263        final int visibility = mFocusedWindow.getSystemUiVisibility()
4264                & ~mResettingSystemUiFlags
4265                & ~mForceClearedSystemUiFlags;
4266        int diff = visibility ^ mLastSystemUiFlags;
4267        final boolean needsMenu = mFocusedWindow.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
4268        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
4269                && mFocusedApp == mFocusedWindow.getAppToken()) {
4270            return 0;
4271        }
4272        mLastSystemUiFlags = visibility;
4273        mLastFocusNeedsMenu = needsMenu;
4274        mFocusedApp = mFocusedWindow.getAppToken();
4275        mHandler.post(new Runnable() {
4276                public void run() {
4277                    try {
4278                        IStatusBarService statusbar = getStatusBarService();
4279                        if (statusbar != null) {
4280                            statusbar.setSystemUiVisibility(visibility, 0xffffffff);
4281                            statusbar.topAppWindowChanged(needsMenu);
4282                        }
4283                    } catch (RemoteException e) {
4284                        // re-acquire status bar service next time it is needed.
4285                        mStatusBarService = null;
4286                    }
4287                }
4288            });
4289        return diff;
4290    }
4291
4292    // Use this instead of checking config_showNavigationBar so that it can be consistently
4293    // overridden by qemu.hw.mainkeys in the emulator.
4294    public boolean hasNavigationBar() {
4295        return mHasNavigationBar;
4296    }
4297
4298    @Override
4299    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
4300        mLastInputMethodWindow = ime;
4301        mLastInputMethodTargetWindow = target;
4302    }
4303
4304    @Override
4305    public boolean canMagnifyWindowLw(WindowManager.LayoutParams attrs) {
4306        switch (attrs.type) {
4307            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
4308            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
4309            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
4310            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
4311                return false;
4312            }
4313        }
4314        return true;
4315    }
4316
4317    @Override
4318    public void setCurrentUserLw(int newUserId) {
4319        if (mKeyguardMediator != null) {
4320            mKeyguardMediator.setCurrentUser(newUserId);
4321        }
4322        if (mStatusBarService != null) {
4323            try {
4324                mStatusBarService.setCurrentUser(newUserId);
4325            } catch (RemoteException e) {
4326                // oh well
4327            }
4328        }
4329    }
4330
4331    @Override
4332    public void dump(String prefix, PrintWriter pw, String[] args) {
4333        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
4334                pw.print(" mSystemReady="); pw.print(mSystemReady);
4335                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
4336        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
4337                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
4338                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
4339        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
4340                || mForceClearedSystemUiFlags != 0) {
4341            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
4342                    pw.print(Integer.toHexString(mLastSystemUiFlags));
4343                    pw.print(" mResettingSystemUiFlags=0x");
4344                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
4345                    pw.print(" mForceClearedSystemUiFlags=0x");
4346                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
4347        }
4348        if (mLastFocusNeedsMenu) {
4349            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
4350                    pw.println(mLastFocusNeedsMenu);
4351        }
4352        pw.print(prefix); pw.print("mDockMode="); pw.print(mDockMode);
4353                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
4354                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
4355        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
4356                pw.print(" mUserRotation="); pw.print(mUserRotation);
4357                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
4358        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
4359        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
4360                pw.print(mCarDockEnablesAccelerometer);
4361                pw.print(" mDeskDockEnablesAccelerometer=");
4362                pw.println(mDeskDockEnablesAccelerometer);
4363        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
4364                pw.print(mLidKeyboardAccessibility);
4365                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
4366                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
4367        pw.print(prefix); pw.print("mLongPressOnPowerBehavior=");
4368                pw.print(mLongPressOnPowerBehavior);
4369                pw.print(" mHasSoftInput="); pw.println(mHasSoftInput);
4370        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
4371                pw.print(" mScreenOnFully="); pw.print(mScreenOnFully);
4372                pw.print(" mOrientationSensorEnabled="); pw.println(mOrientationSensorEnabled);
4373        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
4374                pw.print(","); pw.print(mUnrestrictedScreenTop);
4375                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
4376                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
4377        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
4378                pw.print(","); pw.print(mRestrictedScreenTop);
4379                pw.print(") "); pw.print(mRestrictedScreenWidth);
4380                pw.print("x"); pw.println(mRestrictedScreenHeight);
4381        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
4382                pw.print(","); pw.print(mStableFullscreenTop);
4383                pw.print(")-("); pw.print(mStableFullscreenRight);
4384                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
4385        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
4386                pw.print(","); pw.print(mStableTop);
4387                pw.print(")-("); pw.print(mStableRight);
4388                pw.print(","); pw.print(mStableBottom); pw.println(")");
4389        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
4390                pw.print(","); pw.print(mSystemTop);
4391                pw.print(")-("); pw.print(mSystemRight);
4392                pw.print(","); pw.print(mSystemBottom); pw.println(")");
4393        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
4394                pw.print(","); pw.print(mCurTop);
4395                pw.print(")-("); pw.print(mCurRight);
4396                pw.print(","); pw.print(mCurBottom); pw.println(")");
4397        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
4398                pw.print(","); pw.print(mContentTop);
4399                pw.print(")-("); pw.print(mContentRight);
4400                pw.print(","); pw.print(mContentBottom); pw.println(")");
4401        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
4402                pw.print(","); pw.print(mDockTop);
4403                pw.print(")-("); pw.print(mDockRight);
4404                pw.print(","); pw.print(mDockBottom); pw.println(")");
4405        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
4406                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
4407        pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
4408                pw.println(mTopFullscreenOpaqueWindowState);
4409        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
4410                pw.print(" mForceStatusBar="); pw.print(mForceStatusBar);
4411                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
4412        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
4413                pw.print(" mHomePressed="); pw.println(mHomePressed);
4414        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
4415                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
4416                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
4417        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
4418                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
4419                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
4420        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
4421                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
4422        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
4423                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
4424    }
4425}
4426