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