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