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