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