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_VOLUME_OVERLAY;
129import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
130import static android.view.WindowManager.LayoutParams.TYPE_POINTER;
131import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR;
132import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL;
133import static android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS;
134import android.view.WindowManagerImpl;
135import android.view.WindowManagerPolicy;
136import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_ABSENT;
137import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN;
138import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_CLOSED;
139import android.view.KeyCharacterMap.FallbackAction;
140import android.view.accessibility.AccessibilityEvent;
141import android.view.animation.Animation;
142import android.view.animation.AnimationUtils;
143
144import java.io.File;
145import java.io.FileReader;
146import java.io.IOException;
147import java.io.PrintWriter;
148
149/**
150 * WindowManagerPolicy implementation for the Android phone UI.  This
151 * introduces a new method suffix, Lp, for an internal lock of the
152 * PhoneWindowManager.  This is used to protect some internal state, and
153 * can be acquired with either thw Lw and Li lock held, so has the restrictions
154 * of both of those when held.
155 */
156public class PhoneWindowManager implements WindowManagerPolicy {
157    static final String TAG = "WindowManager";
158    static final boolean DEBUG = false;
159    static final boolean localLOGV = false;
160    static final boolean DEBUG_LAYOUT = false;
161    static final boolean DEBUG_INPUT = false;
162    static final boolean DEBUG_STARTING_WINDOW = false;
163    static final boolean SHOW_STARTING_ANIMATIONS = true;
164    static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
165
166    // Whether to allow dock apps with METADATA_DOCK_HOME to temporarily take over the Home key.
167    // No longer recommended for desk docks; still useful in car docks.
168    static final boolean ENABLE_CAR_DOCK_HOME_CAPTURE = true;
169    static final boolean ENABLE_DESK_DOCK_HOME_CAPTURE = false;
170
171    // Should screen savers use their own timeout, or the SCREEN_OFF_TIMEOUT?
172    static final boolean SEPARATE_TIMEOUT_FOR_SCREEN_SAVER = false;
173
174    static final int LONG_PRESS_POWER_NOTHING = 0;
175    static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
176    static final int LONG_PRESS_POWER_SHUT_OFF = 2;
177
178    // These need to match the documentation/constant in
179    // core/res/res/values/config.xml
180    static final int LONG_PRESS_HOME_NOTHING = 0;
181    static final int LONG_PRESS_HOME_RECENT_DIALOG = 1;
182    static final int LONG_PRESS_HOME_RECENT_SYSTEM_UI = 2;
183
184    // wallpaper is at the bottom, though the window manager may move it.
185    static final int WALLPAPER_LAYER = 2;
186    static final int APPLICATION_LAYER = 2;
187    static final int PHONE_LAYER = 3;
188    static final int SEARCH_BAR_LAYER = 4;
189    static final int SYSTEM_DIALOG_LAYER = 5;
190    // toasts and the plugged-in battery thing
191    static final int TOAST_LAYER = 6;
192    // SIM errors and unlock.  Not sure if this really should be in a high layer.
193    static final int PRIORITY_PHONE_LAYER = 7;
194    // like the ANR / app crashed dialogs
195    static final int SYSTEM_ALERT_LAYER = 8;
196    // on-screen keyboards and other such input method user interfaces go here.
197    static final int INPUT_METHOD_LAYER = 9;
198    // on-screen keyboards and other such input method user interfaces go here.
199    static final int INPUT_METHOD_DIALOG_LAYER = 10;
200    // the keyguard; nothing on top of these can take focus, since they are
201    // responsible for power management when displayed.
202    static final int KEYGUARD_LAYER = 11;
203    static final int KEYGUARD_DIALOG_LAYER = 12;
204    // used for Dreams (screensavers with TYPE_DREAM windows)
205    static final int SCREENSAVER_LAYER = 13;
206    static final int STATUS_BAR_SUB_PANEL_LAYER = 14;
207    static final int STATUS_BAR_LAYER = 15;
208    static final int STATUS_BAR_PANEL_LAYER = 16;
209    // the on-screen volume indicator and controller shown when the user
210    // changes the device volume
211    static final int VOLUME_OVERLAY_LAYER = 17;
212    // things in here CAN NOT take focus, but are shown on top of everything else.
213    static final int SYSTEM_OVERLAY_LAYER = 18;
214    // the navigation bar, if available, shows atop most things
215    static final int NAVIGATION_BAR_LAYER = 19;
216    // some panels (e.g. search) need to show on top of the navigation bar
217    static final int NAVIGATION_BAR_PANEL_LAYER = 20;
218    // system-level error dialogs
219    static final int SYSTEM_ERROR_LAYER = 21;
220    // the drag layer: input for drag-and-drop is associated with this window,
221    // which sits above all other focusable windows
222    static final int DRAG_LAYER = 22;
223    static final int SECURE_SYSTEM_OVERLAY_LAYER = 23;
224    static final int BOOT_PROGRESS_LAYER = 24;
225    // the (mouse) pointer layer
226    static final int POINTER_LAYER = 25;
227    static final int HIDDEN_NAV_CONSUMER_LAYER = 26;
228
229    static final int APPLICATION_MEDIA_SUBLAYER = -2;
230    static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
231    static final int APPLICATION_PANEL_SUBLAYER = 1;
232    static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
233
234    static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
235    static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
236    static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
237    static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
238    static public final String SYSTEM_DIALOG_REASON_ASSIST = "assist";
239
240    /**
241     * These are the system UI flags that, when changing, can cause the layout
242     * of the screen to change.
243     */
244    static final int SYSTEM_UI_CHANGING_LAYOUT =
245            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
246
247    /* Table of Application Launch keys.  Maps from key codes to intent categories.
248     *
249     * These are special keys that are used to launch particular kinds of applications,
250     * such as a web browser.  HID defines nearly a hundred of them in the Consumer (0x0C)
251     * usage page.  We don't support quite that many yet...
252     */
253    static SparseArray<String> sApplicationLaunchKeyCategories;
254    static {
255        sApplicationLaunchKeyCategories = new SparseArray<String>();
256        sApplicationLaunchKeyCategories.append(
257                KeyEvent.KEYCODE_EXPLORER, Intent.CATEGORY_APP_BROWSER);
258        sApplicationLaunchKeyCategories.append(
259                KeyEvent.KEYCODE_ENVELOPE, Intent.CATEGORY_APP_EMAIL);
260        sApplicationLaunchKeyCategories.append(
261                KeyEvent.KEYCODE_CONTACTS, Intent.CATEGORY_APP_CONTACTS);
262        sApplicationLaunchKeyCategories.append(
263                KeyEvent.KEYCODE_CALENDAR, Intent.CATEGORY_APP_CALENDAR);
264        sApplicationLaunchKeyCategories.append(
265                KeyEvent.KEYCODE_MUSIC, Intent.CATEGORY_APP_MUSIC);
266        sApplicationLaunchKeyCategories.append(
267                KeyEvent.KEYCODE_CALCULATOR, Intent.CATEGORY_APP_CALCULATOR);
268    }
269
270    /**
271     * Lock protecting internal state.  Must not call out into window
272     * manager with lock held.  (This lock will be acquired in places
273     * where the window manager is calling in with its own lock held.)
274     */
275    final Object mLock = new Object();
276
277    Context mContext;
278    IWindowManager mWindowManager;
279    WindowManagerFuncs mWindowManagerFuncs;
280    LocalPowerManager mPowerManager;
281    IStatusBarService mStatusBarService;
282    final Object mServiceAquireLock = new Object();
283    Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
284    SearchManager mSearchManager;
285
286    // Vibrator pattern for haptic feedback of a long press.
287    long[] mLongPressVibePattern;
288
289    // Vibrator pattern for haptic feedback of virtual key press.
290    long[] mVirtualKeyVibePattern;
291
292    // Vibrator pattern for a short vibration.
293    long[] mKeyboardTapVibePattern;
294
295    // Vibrator pattern for haptic feedback during boot when safe mode is disabled.
296    long[] mSafeModeDisabledVibePattern;
297
298    // Vibrator pattern for haptic feedback during boot when safe mode is enabled.
299    long[] mSafeModeEnabledVibePattern;
300
301    /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
302    boolean mEnableShiftMenuBugReports = false;
303
304    boolean mHeadless;
305    boolean mSafeMode;
306    WindowState mStatusBar = null;
307    boolean mHasSystemNavBar;
308    int mStatusBarHeight;
309    WindowState mNavigationBar = null;
310    boolean mHasNavigationBar = false;
311    boolean mCanHideNavigationBar = false;
312    boolean mNavigationBarCanMove = false; // can the navigation bar ever move to the side?
313    boolean mNavigationBarOnBottom = true; // is the navigation bar on the bottom *right now*?
314    int[] mNavigationBarHeightForRotation = new int[4];
315    int[] mNavigationBarWidthForRotation = new int[4];
316
317    WindowState mKeyguard = null;
318    KeyguardViewMediator mKeyguardMediator;
319    GlobalActions mGlobalActions;
320    volatile boolean mPowerKeyHandled; // accessed from input reader and handler thread
321    boolean mPendingPowerKeyUpCanceled;
322    Handler mHandler;
323    WindowState mLastInputMethodWindow = null;
324    WindowState mLastInputMethodTargetWindow = null;
325
326    static final int RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS = 0;
327    static final int RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW = 1;
328    static final int RECENT_APPS_BEHAVIOR_DISMISS = 2;
329    static final int RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH = 3;
330
331    RecentApplicationsDialog mRecentAppsDialog;
332    int mRecentAppsDialogHeldModifiers;
333    boolean mLanguageSwitchKeyPressed;
334
335    int mLidState = LID_ABSENT;
336    boolean mHaveBuiltInKeyboard;
337
338    boolean mSystemReady;
339    boolean mSystemBooted;
340    boolean mHdmiPlugged;
341    int mExternalDisplayWidth;
342    int mExternalDisplayHeight;
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        mExternalDisplayWidth = mDisplay.getRawExternalWidth();
1000        mExternalDisplayHeight = mDisplay.getRawExternalHeight();
1001
1002        mStatusBarHeight = mContext.getResources().getDimensionPixelSize(
1003                com.android.internal.R.dimen.status_bar_height);
1004
1005        // Height of the navigation bar when presented horizontally at bottom
1006        mNavigationBarHeightForRotation[mPortraitRotation] =
1007        mNavigationBarHeightForRotation[mUpsideDownRotation] =
1008                mContext.getResources().getDimensionPixelSize(
1009                        com.android.internal.R.dimen.navigation_bar_height);
1010        mNavigationBarHeightForRotation[mLandscapeRotation] =
1011        mNavigationBarHeightForRotation[mSeascapeRotation] =
1012                mContext.getResources().getDimensionPixelSize(
1013                        com.android.internal.R.dimen.navigation_bar_height_landscape);
1014
1015        // Width of the navigation bar when presented vertically along one side
1016        mNavigationBarWidthForRotation[mPortraitRotation] =
1017        mNavigationBarWidthForRotation[mUpsideDownRotation] =
1018        mNavigationBarWidthForRotation[mLandscapeRotation] =
1019        mNavigationBarWidthForRotation[mSeascapeRotation] =
1020                mContext.getResources().getDimensionPixelSize(
1021                        com.android.internal.R.dimen.navigation_bar_width);
1022
1023        // SystemUI (status bar) layout policy
1024        int shortSizeDp = shortSize
1025                * DisplayMetrics.DENSITY_DEFAULT
1026                / DisplayMetrics.DENSITY_DEVICE;
1027
1028        if (shortSizeDp < 600) {
1029            // 0-599dp: "phone" UI with a separate status & navigation bar
1030            mHasSystemNavBar = false;
1031            mNavigationBarCanMove = true;
1032        } else if (shortSizeDp < 720) {
1033            // 600-719dp: "phone" UI with modifications for larger screens
1034            mHasSystemNavBar = false;
1035            mNavigationBarCanMove = false;
1036        } else {
1037            // 720dp: "tablet" UI with a single combined status & navigation bar
1038            mHasSystemNavBar = true;
1039            mNavigationBarCanMove = false;
1040        }
1041
1042        if (!mHasSystemNavBar) {
1043            mHasNavigationBar = mContext.getResources().getBoolean(
1044                    com.android.internal.R.bool.config_showNavigationBar);
1045            // Allow a system property to override this. Used by the emulator.
1046            // See also hasNavigationBar().
1047            String navBarOverride = SystemProperties.get("qemu.hw.mainkeys");
1048            if (! "".equals(navBarOverride)) {
1049                if      (navBarOverride.equals("1")) mHasNavigationBar = false;
1050                else if (navBarOverride.equals("0")) mHasNavigationBar = true;
1051            }
1052        } else {
1053            mHasNavigationBar = false;
1054        }
1055
1056        if (mHasSystemNavBar) {
1057            // The system bar is always at the bottom.  If you are watching
1058            // a video in landscape, we don't need to hide it if we can still
1059            // show a 16:9 aspect ratio with it.
1060            int longSizeDp = longSize
1061                    * DisplayMetrics.DENSITY_DEFAULT
1062                    / DisplayMetrics.DENSITY_DEVICE;
1063            int barHeightDp = mNavigationBarHeightForRotation[mLandscapeRotation]
1064                    * DisplayMetrics.DENSITY_DEFAULT
1065                    / DisplayMetrics.DENSITY_DEVICE;
1066            int aspect = ((shortSizeDp-barHeightDp) * 16) / longSizeDp;
1067            // We have computed the aspect ratio with the bar height taken
1068            // out to be 16:aspect.  If this is less than 9, then hiding
1069            // the navigation bar will provide more useful space for wide
1070            // screen movies.
1071            mCanHideNavigationBar = aspect < 9;
1072        } else if (mHasNavigationBar) {
1073            // The navigation bar is at the right in landscape; it seems always
1074            // useful to hide it for showing a video.
1075            mCanHideNavigationBar = true;
1076        } else {
1077            mCanHideNavigationBar = false;
1078        }
1079
1080        if ("portrait".equals(SystemProperties.get("persist.demo.hdmirotation"))) {
1081            mHdmiRotation = mPortraitRotation;
1082        } else {
1083            mHdmiRotation = mLandscapeRotation;
1084        }
1085    }
1086
1087    public void updateSettings() {
1088        ContentResolver resolver = mContext.getContentResolver();
1089        boolean updateRotation = false;
1090        synchronized (mLock) {
1091            mEndcallBehavior = Settings.System.getInt(resolver,
1092                    Settings.System.END_BUTTON_BEHAVIOR,
1093                    Settings.System.END_BUTTON_BEHAVIOR_DEFAULT);
1094            mIncallPowerBehavior = Settings.Secure.getInt(resolver,
1095                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
1096                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT);
1097
1098            // Configure rotation lock.
1099            int userRotation = Settings.System.getInt(resolver,
1100                    Settings.System.USER_ROTATION, Surface.ROTATION_0);
1101            if (mUserRotation != userRotation) {
1102                mUserRotation = userRotation;
1103                updateRotation = true;
1104            }
1105            int userRotationMode = Settings.System.getInt(resolver,
1106                    Settings.System.ACCELEROMETER_ROTATION, 0) != 0 ?
1107                            WindowManagerPolicy.USER_ROTATION_FREE :
1108                                    WindowManagerPolicy.USER_ROTATION_LOCKED;
1109            if (mUserRotationMode != userRotationMode) {
1110                mUserRotationMode = userRotationMode;
1111                updateRotation = true;
1112                updateOrientationListenerLp();
1113            }
1114
1115            if (mSystemReady) {
1116                int pointerLocation = Settings.System.getInt(resolver,
1117                        Settings.System.POINTER_LOCATION, 0);
1118                if (mPointerLocationMode != pointerLocation) {
1119                    mPointerLocationMode = pointerLocation;
1120                    mHandler.sendEmptyMessage(pointerLocation != 0 ?
1121                            MSG_ENABLE_POINTER_LOCATION : MSG_DISABLE_POINTER_LOCATION);
1122                }
1123            }
1124            // use screen off timeout setting as the timeout for the lockscreen
1125            mLockScreenTimeout = Settings.System.getInt(resolver,
1126                    Settings.System.SCREEN_OFF_TIMEOUT, 0);
1127            String imId = Settings.Secure.getString(resolver,
1128                    Settings.Secure.DEFAULT_INPUT_METHOD);
1129            boolean hasSoftInput = imId != null && imId.length() > 0;
1130            if (mHasSoftInput != hasSoftInput) {
1131                mHasSoftInput = hasSoftInput;
1132                updateRotation = true;
1133            }
1134
1135            // dreams
1136            mScreenSaverFeatureAvailable = mContext.getResources().getBoolean(
1137                    com.android.internal.R.bool.config_enableDreams);
1138
1139            mScreenSaverEnabledByUser = 0 != Settings.Secure.getInt(resolver,
1140                    Settings.Secure.SCREENSAVER_ENABLED, 1);
1141
1142            if (SEPARATE_TIMEOUT_FOR_SCREEN_SAVER) {
1143                mScreenSaverTimeout = Settings.Secure.getInt(resolver,
1144                        "screensaver_timeout", 0);
1145            } else {
1146                mScreenSaverTimeout = Settings.System.getInt(resolver,
1147                        Settings.System.SCREEN_OFF_TIMEOUT, 0);
1148                if (mScreenSaverTimeout > 0) {
1149                    // We actually want to activate the screensaver just before the
1150                    // power manager's screen timeout
1151                    mScreenSaverTimeout -= 5000;
1152                }
1153            }
1154        }
1155        if (updateRotation) {
1156            updateRotation(true);
1157        }
1158    }
1159
1160    private void enablePointerLocation() {
1161        if (mPointerLocationView == null) {
1162            mPointerLocationView = new PointerLocationView(mContext);
1163            mPointerLocationView.setPrintCoords(false);
1164
1165            WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1166                    WindowManager.LayoutParams.MATCH_PARENT,
1167                    WindowManager.LayoutParams.MATCH_PARENT);
1168            lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
1169            lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
1170                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
1171                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1172                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
1173            lp.format = PixelFormat.TRANSLUCENT;
1174            lp.setTitle("PointerLocation");
1175            WindowManager wm = (WindowManager)
1176                    mContext.getSystemService(Context.WINDOW_SERVICE);
1177            lp.inputFeatures |= WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL;
1178            wm.addView(mPointerLocationView, lp);
1179
1180            mPointerLocationInputChannel =
1181                    mWindowManagerFuncs.monitorInput("PointerLocationView");
1182            mPointerLocationInputEventReceiver =
1183                    new PointerLocationInputEventReceiver(mPointerLocationInputChannel,
1184                            Looper.myLooper(), mPointerLocationView);
1185        }
1186    }
1187
1188    private void disablePointerLocation() {
1189        if (mPointerLocationInputEventReceiver != null) {
1190            mPointerLocationInputEventReceiver.dispose();
1191            mPointerLocationInputEventReceiver = null;
1192        }
1193
1194        if (mPointerLocationInputChannel != null) {
1195            mPointerLocationInputChannel.dispose();
1196            mPointerLocationInputChannel = null;
1197        }
1198
1199        if (mPointerLocationView != null) {
1200            WindowManager wm = (WindowManager)
1201                    mContext.getSystemService(Context.WINDOW_SERVICE);
1202            wm.removeView(mPointerLocationView);
1203            mPointerLocationView = null;
1204        }
1205    }
1206
1207    private int readRotation(int resID) {
1208        try {
1209            int rotation = mContext.getResources().getInteger(resID);
1210            switch (rotation) {
1211                case 0:
1212                    return Surface.ROTATION_0;
1213                case 90:
1214                    return Surface.ROTATION_90;
1215                case 180:
1216                    return Surface.ROTATION_180;
1217                case 270:
1218                    return Surface.ROTATION_270;
1219            }
1220        } catch (Resources.NotFoundException e) {
1221            // fall through
1222        }
1223        return -1;
1224    }
1225
1226    /** {@inheritDoc} */
1227    public int checkAddPermission(WindowManager.LayoutParams attrs) {
1228        int type = attrs.type;
1229
1230        if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
1231                || type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) {
1232            return WindowManagerImpl.ADD_OKAY;
1233        }
1234        String permission = null;
1235        switch (type) {
1236            case TYPE_TOAST:
1237                // XXX right now the app process has complete control over
1238                // this...  should introduce a token to let the system
1239                // monitor/control what they are doing.
1240                break;
1241            case TYPE_DREAM:
1242            case TYPE_INPUT_METHOD:
1243            case TYPE_WALLPAPER:
1244                // The window manager will check these.
1245                break;
1246            case TYPE_PHONE:
1247            case TYPE_PRIORITY_PHONE:
1248            case TYPE_SYSTEM_ALERT:
1249            case TYPE_SYSTEM_ERROR:
1250            case TYPE_SYSTEM_OVERLAY:
1251                permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
1252                break;
1253            default:
1254                permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
1255        }
1256        if (permission != null) {
1257            if (mContext.checkCallingOrSelfPermission(permission)
1258                    != PackageManager.PERMISSION_GRANTED) {
1259                return WindowManagerImpl.ADD_PERMISSION_DENIED;
1260            }
1261        }
1262        return WindowManagerImpl.ADD_OKAY;
1263    }
1264
1265    public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
1266        switch (attrs.type) {
1267            case TYPE_SYSTEM_OVERLAY:
1268            case TYPE_SECURE_SYSTEM_OVERLAY:
1269            case TYPE_TOAST:
1270                // These types of windows can't receive input events.
1271                attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1272                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
1273                attrs.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
1274                break;
1275        }
1276    }
1277
1278    void readLidState() {
1279        mLidState = mWindowManagerFuncs.getLidState();
1280    }
1281
1282    private boolean isHidden(int accessibilityMode) {
1283        switch (accessibilityMode) {
1284            case 1:
1285                return mLidState == LID_CLOSED;
1286            case 2:
1287                return mLidState == LID_OPEN;
1288            default:
1289                return false;
1290        }
1291    }
1292
1293    private boolean isBuiltInKeyboardVisible() {
1294        return mHaveBuiltInKeyboard && !isHidden(mLidKeyboardAccessibility);
1295    }
1296
1297    /** {@inheritDoc} */
1298    public void adjustConfigurationLw(Configuration config, int keyboardPresence,
1299            int navigationPresence) {
1300        mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
1301
1302        readLidState();
1303        applyLidSwitchState();
1304
1305        if (config.keyboard == Configuration.KEYBOARD_NOKEYS
1306                || (keyboardPresence == PRESENCE_INTERNAL
1307                        && isHidden(mLidKeyboardAccessibility))) {
1308            config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
1309            if (!mHasSoftInput) {
1310                config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES;
1311            }
1312        }
1313
1314        if (config.navigation == Configuration.NAVIGATION_NONAV
1315                || (navigationPresence == PRESENCE_INTERNAL
1316                        && isHidden(mLidNavigationAccessibility))) {
1317            config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
1318        }
1319    }
1320
1321    /** {@inheritDoc} */
1322    public int windowTypeToLayerLw(int type) {
1323        if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
1324            return APPLICATION_LAYER;
1325        }
1326        switch (type) {
1327        case TYPE_STATUS_BAR:
1328            return STATUS_BAR_LAYER;
1329        case TYPE_STATUS_BAR_PANEL:
1330            return STATUS_BAR_PANEL_LAYER;
1331        case TYPE_STATUS_BAR_SUB_PANEL:
1332            return STATUS_BAR_SUB_PANEL_LAYER;
1333        case TYPE_SYSTEM_DIALOG:
1334            return SYSTEM_DIALOG_LAYER;
1335        case TYPE_SEARCH_BAR:
1336            return SEARCH_BAR_LAYER;
1337        case TYPE_PHONE:
1338            return PHONE_LAYER;
1339        case TYPE_KEYGUARD:
1340            return KEYGUARD_LAYER;
1341        case TYPE_KEYGUARD_DIALOG:
1342            return KEYGUARD_DIALOG_LAYER;
1343        case TYPE_SYSTEM_ALERT:
1344            return SYSTEM_ALERT_LAYER;
1345        case TYPE_SYSTEM_ERROR:
1346            return SYSTEM_ERROR_LAYER;
1347        case TYPE_INPUT_METHOD:
1348            return INPUT_METHOD_LAYER;
1349        case TYPE_INPUT_METHOD_DIALOG:
1350            return INPUT_METHOD_DIALOG_LAYER;
1351        case TYPE_VOLUME_OVERLAY:
1352            return VOLUME_OVERLAY_LAYER;
1353        case TYPE_SYSTEM_OVERLAY:
1354            return SYSTEM_OVERLAY_LAYER;
1355        case TYPE_SECURE_SYSTEM_OVERLAY:
1356            return SECURE_SYSTEM_OVERLAY_LAYER;
1357        case TYPE_PRIORITY_PHONE:
1358            return PRIORITY_PHONE_LAYER;
1359        case TYPE_TOAST:
1360            return TOAST_LAYER;
1361        case TYPE_WALLPAPER:
1362            return WALLPAPER_LAYER;
1363        case TYPE_DRAG:
1364            return DRAG_LAYER;
1365        case TYPE_POINTER:
1366            return POINTER_LAYER;
1367        case TYPE_NAVIGATION_BAR:
1368            return NAVIGATION_BAR_LAYER;
1369        case TYPE_NAVIGATION_BAR_PANEL:
1370            return NAVIGATION_BAR_PANEL_LAYER;
1371        case TYPE_BOOT_PROGRESS:
1372            return BOOT_PROGRESS_LAYER;
1373        case TYPE_HIDDEN_NAV_CONSUMER:
1374            return HIDDEN_NAV_CONSUMER_LAYER;
1375        case TYPE_DREAM:
1376            return SCREENSAVER_LAYER;
1377        }
1378        Log.e(TAG, "Unknown window type: " + type);
1379        return APPLICATION_LAYER;
1380    }
1381
1382    /** {@inheritDoc} */
1383    public int subWindowTypeToLayerLw(int type) {
1384        switch (type) {
1385        case TYPE_APPLICATION_PANEL:
1386        case TYPE_APPLICATION_ATTACHED_DIALOG:
1387            return APPLICATION_PANEL_SUBLAYER;
1388        case TYPE_APPLICATION_MEDIA:
1389            return APPLICATION_MEDIA_SUBLAYER;
1390        case TYPE_APPLICATION_MEDIA_OVERLAY:
1391            return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
1392        case TYPE_APPLICATION_SUB_PANEL:
1393            return APPLICATION_SUB_PANEL_SUBLAYER;
1394        }
1395        Log.e(TAG, "Unknown sub-window type: " + type);
1396        return 0;
1397    }
1398
1399    public int getMaxWallpaperLayer() {
1400        return STATUS_BAR_LAYER;
1401    }
1402
1403    public boolean hasSystemNavBar() {
1404        return mHasSystemNavBar;
1405    }
1406
1407    public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation) {
1408        if (mHasNavigationBar) {
1409            // For a basic navigation bar, when we are in landscape mode we place
1410            // the navigation bar to the side.
1411            if (mNavigationBarCanMove && fullWidth > fullHeight) {
1412                return fullWidth - mNavigationBarWidthForRotation[rotation];
1413            }
1414        }
1415        return fullWidth;
1416    }
1417
1418    public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation) {
1419        if (mHasSystemNavBar) {
1420            // For the system navigation bar, we always place it at the bottom.
1421            return fullHeight - mNavigationBarHeightForRotation[rotation];
1422        }
1423        if (mHasNavigationBar) {
1424            // For a basic navigation bar, when we are in portrait mode we place
1425            // the navigation bar to the bottom.
1426            if (!mNavigationBarCanMove || fullWidth < fullHeight) {
1427                return fullHeight - mNavigationBarHeightForRotation[rotation];
1428            }
1429        }
1430        return fullHeight;
1431    }
1432
1433    public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation) {
1434        return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation);
1435    }
1436
1437    public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation) {
1438        // If we don't have a system nav bar, then there is a separate status
1439        // bar at the top of the display.  We don't count that as part of the
1440        // fixed decor, since it can hide; however, for purposes of configurations,
1441        // we do want to exclude it since applications can't generally use that part
1442        // of the screen.
1443        if (!mHasSystemNavBar) {
1444            return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation) - mStatusBarHeight;
1445        }
1446        return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation);
1447    }
1448
1449    public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) {
1450        return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD;
1451    }
1452
1453    public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
1454        return attrs.type != WindowManager.LayoutParams.TYPE_STATUS_BAR
1455                && attrs.type != WindowManager.LayoutParams.TYPE_NAVIGATION_BAR
1456                && attrs.type != WindowManager.LayoutParams.TYPE_WALLPAPER;
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                if (mHdmiPlugged) {
2374                    // Move the nav bar up if the external display is the same aspect ratio
2375                    // but shorter.  This avoids clipping on the external display.
2376                    boolean sameAspect = mExternalDisplayHeight > 0 && displayHeight > 0
2377                        && ((float) mExternalDisplayWidth / mExternalDisplayHeight > 1)
2378                        == ((float) displayWidth / displayHeight > 1);
2379                    if (sameAspect && top > mExternalDisplayHeight) {
2380                        top = mExternalDisplayHeight;
2381                    }
2382                }
2383                mTmpNavigationFrame.set(0, top, displayWidth, displayHeight);
2384                mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
2385                if (navVisible) {
2386                    mNavigationBar.showLw(true);
2387                    mDockBottom = mTmpNavigationFrame.top;
2388                    mRestrictedScreenHeight = mDockBottom - mDockTop;
2389                } else {
2390                    // We currently want to hide the navigation UI.
2391                    mNavigationBar.hideLw(true);
2392                }
2393                if (navVisible && !mNavigationBar.isAnimatingLw()) {
2394                    // If the nav bar is currently requested to be visible,
2395                    // and not in the process of animating on or off, then
2396                    // we can tell the app that it is covered by it.
2397                    mSystemBottom = mTmpNavigationFrame.top;
2398                }
2399            } else {
2400                // Landscape screen; nav bar goes to the right.
2401                int left = displayWidth - mNavigationBarWidthForRotation[displayRotation];
2402                if (mHdmiPlugged) {
2403                    if (left > mExternalDisplayWidth) {
2404                        left = mExternalDisplayWidth;
2405                    }
2406                }
2407                mTmpNavigationFrame.set(left, 0, displayWidth, displayHeight);
2408                mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
2409                if (navVisible) {
2410                    mNavigationBar.showLw(true);
2411                    mDockRight = mTmpNavigationFrame.left;
2412                    mRestrictedScreenWidth = mDockRight - mDockLeft;
2413                } else {
2414                    // We currently want to hide the navigation UI.
2415                    mNavigationBar.hideLw(true);
2416                }
2417                if (navVisible && !mNavigationBar.isAnimatingLw()) {
2418                    // If the nav bar is currently requested to be visible,
2419                    // and not in the process of animating on or off, then
2420                    // we can tell the app that it is covered by it.
2421                    mSystemRight = mTmpNavigationFrame.left;
2422                }
2423            }
2424            // Make sure the content and current rectangles are updated to
2425            // account for the restrictions from the navigation bar.
2426            mContentTop = mCurTop = mDockTop;
2427            mContentBottom = mCurBottom = mDockBottom;
2428            mContentLeft = mCurLeft = mDockLeft;
2429            mContentRight = mCurRight = mDockRight;
2430            mStatusBarLayer = mNavigationBar.getSurfaceLayer();
2431            // And compute the final frame.
2432            mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
2433                    mTmpNavigationFrame, mTmpNavigationFrame);
2434            if (DEBUG_LAYOUT) Log.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
2435        }
2436        if (DEBUG_LAYOUT) Log.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
2437                mDockLeft, mDockTop, mDockRight, mDockBottom));
2438
2439        // decide where the status bar goes ahead of time
2440        if (mStatusBar != null) {
2441            // apply any navigation bar insets
2442            pf.left = df.left = mUnrestrictedScreenLeft;
2443            pf.top = df.top = mUnrestrictedScreenTop;
2444            pf.right = df.right = mUnrestrictedScreenWidth - mUnrestrictedScreenLeft;
2445            pf.bottom = df.bottom = mUnrestrictedScreenHeight - mUnrestrictedScreenTop;
2446            vf.left = mStableLeft;
2447            vf.top = mStableTop;
2448            vf.right = mStableRight;
2449            vf.bottom = mStableBottom;
2450
2451            mStatusBarLayer = mStatusBar.getSurfaceLayer();
2452
2453            // Let the status bar determine its size.
2454            mStatusBar.computeFrameLw(pf, df, vf, vf);
2455
2456            // For layout, the status bar is always at the top with our fixed height.
2457            mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
2458
2459            // If the status bar is hidden, we don't want to cause
2460            // windows behind it to scroll.
2461            if (mStatusBar.isVisibleLw()) {
2462                // Status bar may go away, so the screen area it occupies
2463                // is available to apps but just covering them when the
2464                // status bar is visible.
2465                mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
2466
2467                mContentTop = mCurTop = mDockTop;
2468                mContentBottom = mCurBottom = mDockBottom;
2469                mContentLeft = mCurLeft = mDockLeft;
2470                mContentRight = mCurRight = mDockRight;
2471
2472                if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: " +
2473                    String.format(
2474                        "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
2475                        mDockLeft, mDockTop, mDockRight, mDockBottom,
2476                        mContentLeft, mContentTop, mContentRight, mContentBottom,
2477                        mCurLeft, mCurTop, mCurRight, mCurBottom));
2478            }
2479            if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()) {
2480                // If the status bar is currently requested to be visible,
2481                // and not in the process of animating on or off, then
2482                // we can tell the app that it is covered by it.
2483                mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
2484            }
2485        }
2486    }
2487
2488    /** {@inheritDoc} */
2489    public int getSystemDecorRectLw(Rect systemRect) {
2490        systemRect.left = mSystemLeft;
2491        systemRect.top = mSystemTop;
2492        systemRect.right = mSystemRight;
2493        systemRect.bottom = mSystemBottom;
2494        if (mStatusBar != null) return mStatusBar.getSurfaceLayer();
2495        if (mNavigationBar != null) return mNavigationBar.getSurfaceLayer();
2496        return 0;
2497    }
2498
2499    void setAttachedWindowFrames(WindowState win, int fl, int adjust,
2500            WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) {
2501        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
2502            // Here's a special case: if this attached window is a panel that is
2503            // above the dock window, and the window it is attached to is below
2504            // the dock window, then the frames we computed for the window it is
2505            // attached to can not be used because the dock is effectively part
2506            // of the underlying window and the attached window is floating on top
2507            // of the whole thing.  So, we ignore the attached window and explicitly
2508            // compute the frames that would be appropriate without the dock.
2509            df.left = cf.left = vf.left = mDockLeft;
2510            df.top = cf.top = vf.top = mDockTop;
2511            df.right = cf.right = vf.right = mDockRight;
2512            df.bottom = cf.bottom = vf.bottom = mDockBottom;
2513        } else {
2514            // The effective display frame of the attached window depends on
2515            // whether it is taking care of insetting its content.  If not,
2516            // we need to use the parent's content frame so that the entire
2517            // window is positioned within that content.  Otherwise we can use
2518            // the display frame and let the attached window take care of
2519            // positioning its content appropriately.
2520            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2521                cf.set(attached.getDisplayFrameLw());
2522            } else {
2523                // If the window is resizing, then we want to base the content
2524                // frame on our attached content frame to resize...  however,
2525                // things can be tricky if the attached window is NOT in resize
2526                // mode, in which case its content frame will be larger.
2527                // Ungh.  So to deal with that, make sure the content frame
2528                // we end up using is not covering the IM dock.
2529                cf.set(attached.getContentFrameLw());
2530                if (attached.getSurfaceLayer() < mDockLayer) {
2531                    if (cf.left < mContentLeft) cf.left = mContentLeft;
2532                    if (cf.top < mContentTop) cf.top = mContentTop;
2533                    if (cf.right > mContentRight) cf.right = mContentRight;
2534                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
2535                }
2536            }
2537            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
2538            vf.set(attached.getVisibleFrameLw());
2539        }
2540        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
2541        // window should be positioned relative to its parent or the entire
2542        // screen.
2543        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
2544                ? attached.getFrameLw() : df);
2545    }
2546
2547    private void applyStableConstraints(int sysui, int fl, Rect r) {
2548        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
2549            // If app is requesting a stable layout, don't let the
2550            // content insets go below the stable values.
2551            if ((fl & FLAG_FULLSCREEN) != 0) {
2552                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
2553                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
2554                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
2555                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
2556            } else {
2557                if (r.left < mStableLeft) r.left = mStableLeft;
2558                if (r.top < mStableTop) r.top = mStableTop;
2559                if (r.right > mStableRight) r.right = mStableRight;
2560                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
2561            }
2562        }
2563    }
2564
2565    /** {@inheritDoc} */
2566    public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
2567            WindowState attached) {
2568        // we've already done the status bar
2569        if (win == mStatusBar || win == mNavigationBar) {
2570            return;
2571        }
2572        final boolean needsToOffsetInputMethodTarget =
2573                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
2574        if (needsToOffsetInputMethodTarget) {
2575            if (DEBUG_LAYOUT) {
2576                Slog.i(TAG, "Offset ime target window by the last ime window state");
2577            }
2578            offsetInputMethodWindowLw(mLastInputMethodWindow);
2579        }
2580
2581        final int fl = attrs.flags;
2582        final int sim = attrs.softInputMode;
2583        final int sysUiFl = win.getSystemUiVisibility();
2584
2585        final Rect pf = mTmpParentFrame;
2586        final Rect df = mTmpDisplayFrame;
2587        final Rect cf = mTmpContentFrame;
2588        final Rect vf = mTmpVisibleFrame;
2589
2590        final boolean hasNavBar = (mHasNavigationBar
2591                && mNavigationBar != null && mNavigationBar.isVisibleLw());
2592
2593        if (attrs.type == TYPE_INPUT_METHOD) {
2594            pf.left = df.left = cf.left = vf.left = mDockLeft;
2595            pf.top = df.top = cf.top = vf.top = mDockTop;
2596            pf.right = df.right = cf.right = vf.right = mDockRight;
2597            pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom;
2598            // IM dock windows always go to the bottom of the screen.
2599            attrs.gravity = Gravity.BOTTOM;
2600            mDockLayer = win.getSurfaceLayer();
2601        } else {
2602            final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
2603
2604            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
2605                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)
2606                    && (sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
2607                if (DEBUG_LAYOUT)
2608                    Log.v(TAG, "layoutWindowLw(" + attrs.getTitle()
2609                            + "): IN_SCREEN, INSET_DECOR, !FULLSCREEN");
2610                // This is the case for a normal activity window: we want it
2611                // to cover all of the screen space, and it can take care of
2612                // moving its contents to account for screen decorations that
2613                // intrude into that space.
2614                if (attached != null) {
2615                    // If this window is attached to another, our display
2616                    // frame is the same as the one we are attached to.
2617                    setAttachedWindowFrames(win, fl, sim, attached, true, pf, df, cf, vf);
2618                } else {
2619                    if (attrs.type == TYPE_STATUS_BAR_PANEL
2620                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
2621                        // Status bar panels are the only windows who can go on top of
2622                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
2623                        // permission, so they have the same privileges as the status
2624                        // bar itself.
2625                        //
2626                        // However, they should still dodge the navigation bar if it exists.
2627
2628                        pf.left = df.left = hasNavBar ? mDockLeft : mUnrestrictedScreenLeft;
2629                        pf.top = df.top = mUnrestrictedScreenTop;
2630                        pf.right = df.right = hasNavBar
2631                                            ? mRestrictedScreenLeft+mRestrictedScreenWidth
2632                                            : mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2633                        pf.bottom = df.bottom = hasNavBar
2634                                              ? mRestrictedScreenTop+mRestrictedScreenHeight
2635                                              : mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2636
2637                        if (DEBUG_LAYOUT) {
2638                            Log.v(TAG, String.format(
2639                                        "Laying out status bar window: (%d,%d - %d,%d)",
2640                                        pf.left, pf.top, pf.right, pf.bottom));
2641                        }
2642                    } else if (mCanHideNavigationBar
2643                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
2644                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
2645                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
2646                        // Asking for layout as if the nav bar is hidden, lets the
2647                        // application extend into the unrestricted screen area.  We
2648                        // only do this for application windows to ensure no window that
2649                        // can be above the nav bar can do this.
2650                        pf.left = df.left = mUnrestrictedScreenLeft;
2651                        pf.top = df.top = mUnrestrictedScreenTop;
2652                        pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2653                        pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2654                    } else {
2655                        pf.left = df.left = mRestrictedScreenLeft;
2656                        pf.top = df.top = mRestrictedScreenTop;
2657                        pf.right = df.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
2658                        pf.bottom = df.bottom = mRestrictedScreenTop+mRestrictedScreenHeight;
2659                    }
2660                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2661                        cf.left = mDockLeft;
2662                        cf.top = mDockTop;
2663                        cf.right = mDockRight;
2664                        cf.bottom = mDockBottom;
2665                    } else {
2666                        cf.left = mContentLeft;
2667                        cf.top = mContentTop;
2668                        cf.right = mContentRight;
2669                        cf.bottom = mContentBottom;
2670                    }
2671                    applyStableConstraints(sysUiFl, fl, cf);
2672                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2673                        vf.left = mCurLeft;
2674                        vf.top = mCurTop;
2675                        vf.right = mCurRight;
2676                        vf.bottom = mCurBottom;
2677                    } else {
2678                        vf.set(cf);
2679                    }
2680                }
2681            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
2682                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
2683                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
2684                if (DEBUG_LAYOUT)
2685                    Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): IN_SCREEN");
2686                // A window that has requested to fill the entire screen just
2687                // gets everything, period.
2688                if (attrs.type == TYPE_STATUS_BAR_PANEL
2689                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
2690                    pf.left = df.left = cf.left = hasNavBar ? mDockLeft : mUnrestrictedScreenLeft;
2691                    pf.top = df.top = cf.top = mUnrestrictedScreenTop;
2692                    pf.right = df.right = cf.right = hasNavBar
2693                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
2694                                        : mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2695                    pf.bottom = df.bottom = cf.bottom = hasNavBar
2696                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
2697                                          : mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2698                    if (DEBUG_LAYOUT) {
2699                        Log.v(TAG, String.format(
2700                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
2701                                    pf.left, pf.top, pf.right, pf.bottom));
2702                    }
2703                } else if (attrs.type == TYPE_NAVIGATION_BAR
2704                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
2705                    // The navigation bar has Real Ultimate Power.
2706                    pf.left = df.left = mUnrestrictedScreenLeft;
2707                    pf.top = df.top = mUnrestrictedScreenTop;
2708                    pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2709                    pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2710                    if (DEBUG_LAYOUT) {
2711                        Log.v(TAG, String.format(
2712                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
2713                                    pf.left, pf.top, pf.right, pf.bottom));
2714                    }
2715                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
2716                                || attrs.type == TYPE_BOOT_PROGRESS)
2717                        && ((fl & FLAG_FULLSCREEN) != 0)) {
2718                    // Fullscreen secure system overlays get what they ask for.
2719                    pf.left = df.left = mUnrestrictedScreenLeft;
2720                    pf.top = df.top = mUnrestrictedScreenTop;
2721                    pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2722                    pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2723                } else if (attrs.type == TYPE_BOOT_PROGRESS) {
2724                    // Boot progress screen always covers entire display.
2725                    pf.left = df.left = cf.left = mUnrestrictedScreenLeft;
2726                    pf.top = df.top = cf.top = mUnrestrictedScreenTop;
2727                    pf.right = df.right = cf.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2728                    pf.bottom = df.bottom = cf.bottom
2729                            = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2730                } else if (mCanHideNavigationBar
2731                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
2732                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
2733                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
2734                    // Asking for layout as if the nav bar is hidden, lets the
2735                    // application extend into the unrestricted screen area.  We
2736                    // only do this for application windows to ensure no window that
2737                    // can be above the nav bar can do this.
2738                    // XXX This assumes that an app asking for this will also
2739                    // ask for layout in only content.  We can't currently figure out
2740                    // what the screen would be if only laying out to hide the nav bar.
2741                    pf.left = df.left = cf.left = mUnrestrictedScreenLeft;
2742                    pf.top = df.top = cf.top = mUnrestrictedScreenTop;
2743                    pf.right = df.right = cf.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2744                    pf.bottom = df.bottom = cf.bottom
2745                            = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2746                } else {
2747                    pf.left = df.left = cf.left = mRestrictedScreenLeft;
2748                    pf.top = df.top = cf.top = mRestrictedScreenTop;
2749                    pf.right = df.right = cf.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
2750                    pf.bottom = df.bottom = cf.bottom
2751                            = mRestrictedScreenTop+mRestrictedScreenHeight;
2752                }
2753                applyStableConstraints(sysUiFl, fl, cf);
2754                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2755                    vf.left = mCurLeft;
2756                    vf.top = mCurTop;
2757                    vf.right = mCurRight;
2758                    vf.bottom = mCurBottom;
2759                } else {
2760                    vf.set(cf);
2761                }
2762            } else if (attached != null) {
2763                if (DEBUG_LAYOUT)
2764                    Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): attached to " + attached);
2765                // A child window should be placed inside of the same visible
2766                // frame that its parent had.
2767                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, cf, vf);
2768            } else {
2769                if (DEBUG_LAYOUT)
2770                    Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): normal window");
2771                // Otherwise, a normal window must be placed inside the content
2772                // of all screen decorations.
2773                if (attrs.type == TYPE_STATUS_BAR_PANEL) {
2774                    // Status bar panels are the only windows who can go on top of
2775                    // the status bar.  They are protected by the STATUS_BAR_SERVICE
2776                    // permission, so they have the same privileges as the status
2777                    // bar itself.
2778                    pf.left = df.left = cf.left = mRestrictedScreenLeft;
2779                    pf.top = df.top = cf.top = mRestrictedScreenTop;
2780                    pf.right = df.right = cf.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
2781                    pf.bottom = df.bottom = cf.bottom
2782                            = mRestrictedScreenTop+mRestrictedScreenHeight;
2783                } else {
2784                    pf.left = mContentLeft;
2785                    pf.top = mContentTop;
2786                    pf.right = mContentRight;
2787                    pf.bottom = mContentBottom;
2788                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2789                        df.left = cf.left = mDockLeft;
2790                        df.top = cf.top = mDockTop;
2791                        df.right = cf.right = mDockRight;
2792                        df.bottom = cf.bottom = mDockBottom;
2793                    } else {
2794                        df.left = cf.left = mContentLeft;
2795                        df.top = cf.top = mContentTop;
2796                        df.right = cf.right = mContentRight;
2797                        df.bottom = cf.bottom = mContentBottom;
2798                    }
2799                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2800                        vf.left = mCurLeft;
2801                        vf.top = mCurTop;
2802                        vf.right = mCurRight;
2803                        vf.bottom = mCurBottom;
2804                    } else {
2805                        vf.set(cf);
2806                    }
2807                }
2808            }
2809        }
2810
2811        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
2812            df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000;
2813            df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
2814        }
2815
2816        if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
2817                + ": sim=#" + Integer.toHexString(sim)
2818                + " attach=" + attached + " type=" + attrs.type
2819                + String.format(" flags=0x%08x", fl)
2820                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
2821                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
2822
2823        win.computeFrameLw(pf, df, cf, vf);
2824
2825        // Dock windows carve out the bottom of the screen, so normal windows
2826        // can't appear underneath them.
2827        if (attrs.type == TYPE_INPUT_METHOD && !win.getGivenInsetsPendingLw()) {
2828            setLastInputMethodWindowLw(null, null);
2829            offsetInputMethodWindowLw(win);
2830        }
2831    }
2832
2833    private void offsetInputMethodWindowLw(WindowState win) {
2834        int top = win.getContentFrameLw().top;
2835        top += win.getGivenContentInsetsLw().top;
2836        if (mContentBottom > top) {
2837            mContentBottom = top;
2838        }
2839        top = win.getVisibleFrameLw().top;
2840        top += win.getGivenVisibleInsetsLw().top;
2841        if (mCurBottom > top) {
2842            mCurBottom = top;
2843        }
2844        if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
2845                + mDockBottom + " mContentBottom="
2846                + mContentBottom + " mCurBottom=" + mCurBottom);
2847    }
2848
2849    /** {@inheritDoc} */
2850    @Override
2851    public void finishLayoutLw() {
2852        return;
2853    }
2854
2855    /** {@inheritDoc} */
2856    public void beginAnimationLw(int displayWidth, int displayHeight) {
2857        mTopFullscreenOpaqueWindowState = null;
2858        mForceStatusBar = false;
2859
2860        mHideLockScreen = false;
2861        mAllowLockscreenWhenOn = false;
2862        mDismissKeyguard = false;
2863    }
2864
2865    /** {@inheritDoc} */
2866    public void animatingWindowLw(WindowState win,
2867                                WindowManager.LayoutParams attrs) {
2868        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
2869                + win.isVisibleOrBehindKeyguardLw());
2870        if (mTopFullscreenOpaqueWindowState == null &&
2871                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
2872            if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
2873                mForceStatusBar = true;
2874            }
2875            if (attrs.type >= FIRST_APPLICATION_WINDOW
2876                    && attrs.type <= LAST_APPLICATION_WINDOW
2877                    && attrs.x == 0 && attrs.y == 0
2878                    && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
2879                    && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
2880                if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
2881                mTopFullscreenOpaqueWindowState = win;
2882                if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
2883                    if (localLOGV) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
2884                    mHideLockScreen = true;
2885                }
2886                if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0) {
2887                    if (localLOGV) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
2888                    mDismissKeyguard = true;
2889                }
2890                if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
2891                    mAllowLockscreenWhenOn = true;
2892                }
2893            }
2894        }
2895    }
2896
2897    /** {@inheritDoc} */
2898    public int finishAnimationLw() {
2899        int changes = 0;
2900        boolean topIsFullscreen = false;
2901
2902        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
2903                ? mTopFullscreenOpaqueWindowState.getAttrs()
2904                : null;
2905
2906        if (mStatusBar != null) {
2907            if (DEBUG_LAYOUT) Log.i(TAG, "force=" + mForceStatusBar
2908                    + " top=" + mTopFullscreenOpaqueWindowState);
2909            if (mForceStatusBar) {
2910                if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar: forced");
2911                if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
2912            } else if (mTopFullscreenOpaqueWindowState != null) {
2913                if (localLOGV) {
2914                    Log.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
2915                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
2916                    Log.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
2917                            + " lp.flags=0x" + Integer.toHexString(lp.flags));
2918                }
2919                topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
2920                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
2921                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
2922                // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window
2923                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
2924                // case though.
2925                if (topIsFullscreen) {
2926                    if (DEBUG_LAYOUT) Log.v(TAG, "** HIDING status bar");
2927                    if (mStatusBar.hideLw(true)) {
2928                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
2929
2930                        mHandler.post(new Runnable() { public void run() {
2931                            try {
2932                                IStatusBarService statusbar = getStatusBarService();
2933                                if (statusbar != null) {
2934                                    statusbar.collapse();
2935                                }
2936                            } catch (RemoteException ex) {
2937                                // re-acquire status bar service next time it is needed.
2938                                mStatusBarService = null;
2939                            }
2940                        }});
2941                    } else if (DEBUG_LAYOUT) {
2942                        Log.v(TAG, "Preventing status bar from hiding by policy");
2943                    }
2944                } else {
2945                    if (DEBUG_LAYOUT) Log.v(TAG, "** SHOWING status bar: top is not fullscreen");
2946                    if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
2947                }
2948            }
2949        }
2950
2951        mTopIsFullscreen = topIsFullscreen;
2952
2953        // Hide the key guard if a visible window explicitly specifies that it wants to be displayed
2954        // when the screen is locked
2955        if (mKeyguard != null) {
2956            if (localLOGV) Log.v(TAG, "finishAnimationLw::mHideKeyguard="+mHideLockScreen);
2957            if (mDismissKeyguard && !mKeyguardMediator.isSecure()) {
2958                if (mKeyguard.hideLw(true)) {
2959                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2960                            | FINISH_LAYOUT_REDO_CONFIG
2961                            | FINISH_LAYOUT_REDO_WALLPAPER;
2962                }
2963                if (mKeyguardMediator.isShowing()) {
2964                    mHandler.post(new Runnable() {
2965                        public void run() {
2966                            mKeyguardMediator.keyguardDone(false, false);
2967                        }
2968                    });
2969                }
2970            } else if (mHideLockScreen) {
2971                if (mKeyguard.hideLw(true)) {
2972                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2973                            | FINISH_LAYOUT_REDO_CONFIG
2974                            | FINISH_LAYOUT_REDO_WALLPAPER;
2975                }
2976                mKeyguardMediator.setHidden(true);
2977            } else {
2978                if (mKeyguard.showLw(true)) {
2979                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2980                            | FINISH_LAYOUT_REDO_CONFIG
2981                            | FINISH_LAYOUT_REDO_WALLPAPER;
2982                }
2983                mKeyguardMediator.setHidden(false);
2984            }
2985        }
2986
2987        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
2988            // If the navigation bar has been hidden or shown, we need to do another
2989            // layout pass to update that window.
2990            changes |= FINISH_LAYOUT_REDO_LAYOUT;
2991        }
2992
2993        // update since mAllowLockscreenWhenOn might have changed
2994        updateLockScreenTimeout();
2995        return changes;
2996    }
2997
2998    public boolean allowAppAnimationsLw() {
2999        if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) {
3000            // If keyguard is currently visible, no reason to animate
3001            // behind it.
3002            return false;
3003        }
3004        return true;
3005    }
3006
3007    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
3008        mFocusedWindow = newFocus;
3009        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
3010            // If the navigation bar has been hidden or shown, we need to do another
3011            // layout pass to update that window.
3012            return FINISH_LAYOUT_REDO_LAYOUT;
3013        }
3014        return 0;
3015    }
3016
3017    /** {@inheritDoc} */
3018    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
3019        // do nothing if headless
3020        if (mHeadless) return;
3021
3022        // lid changed state
3023        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
3024        if (newLidState == mLidState) {
3025            return;
3026        }
3027
3028        mLidState = newLidState;
3029        applyLidSwitchState();
3030        updateRotation(true);
3031
3032        if (lidOpen) {
3033            if (keyguardIsShowingTq()) {
3034                mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(
3035                        KeyEvent.KEYCODE_POWER, mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED);
3036            } else {
3037                mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
3038                        LocalPowerManager.BUTTON_EVENT);
3039            }
3040        } else if (!mLidControlsSleep) {
3041            mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
3042                    LocalPowerManager.OTHER_EVENT);
3043        }
3044    }
3045
3046    void setHdmiPlugged(boolean plugged) {
3047        if (mHdmiPlugged != plugged) {
3048            mHdmiPlugged = plugged;
3049            if (plugged && mDisplay != null) {
3050                mExternalDisplayWidth = mDisplay.getRawExternalWidth();
3051                mExternalDisplayHeight = mDisplay.getRawExternalHeight();
3052            }
3053            updateRotation(true, true);
3054            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
3055            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3056            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
3057            mContext.sendStickyBroadcast(intent);
3058        }
3059    }
3060
3061    void initializeHdmiState() {
3062        boolean plugged = false;
3063        // watch for HDMI plug messages if the hdmi switch exists
3064        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
3065            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
3066
3067            final String filename = "/sys/class/switch/hdmi/state";
3068            FileReader reader = null;
3069            try {
3070                reader = new FileReader(filename);
3071                char[] buf = new char[15];
3072                int n = reader.read(buf);
3073                if (n > 1) {
3074                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
3075                }
3076            } catch (IOException ex) {
3077                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3078            } catch (NumberFormatException ex) {
3079                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3080            } finally {
3081                if (reader != null) {
3082                    try {
3083                        reader.close();
3084                    } catch (IOException ex) {
3085                    }
3086                }
3087            }
3088        }
3089        // This dance forces the code in setHdmiPlugged to run.
3090        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
3091        mHdmiPlugged = !plugged;
3092        setHdmiPlugged(!mHdmiPlugged);
3093    }
3094
3095    /**
3096     * @return Whether music is being played right now.
3097     */
3098    boolean isMusicActive() {
3099        final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
3100        if (am == null) {
3101            Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
3102            return false;
3103        }
3104        return am.isMusicActive();
3105    }
3106
3107    /**
3108     * Tell the audio service to adjust the volume appropriate to the event.
3109     * @param keycode
3110     */
3111    void handleVolumeKey(int stream, int keycode) {
3112        IAudioService audioService = getAudioService();
3113        if (audioService == null) {
3114            return;
3115        }
3116        try {
3117            // since audio is playing, we shouldn't have to hold a wake lock
3118            // during the call, but we do it as a precaution for the rare possibility
3119            // that the music stops right before we call this
3120            // TODO: Actually handle MUTE.
3121            mBroadcastWakeLock.acquire();
3122            audioService.adjustStreamVolume(stream,
3123                keycode == KeyEvent.KEYCODE_VOLUME_UP
3124                            ? AudioManager.ADJUST_RAISE
3125                            : AudioManager.ADJUST_LOWER,
3126                    0);
3127        } catch (RemoteException e) {
3128            Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
3129        } finally {
3130            mBroadcastWakeLock.release();
3131        }
3132    }
3133
3134    final Object mScreenshotLock = new Object();
3135    ServiceConnection mScreenshotConnection = null;
3136
3137    final Runnable mScreenshotTimeout = new Runnable() {
3138        @Override public void run() {
3139            synchronized (mScreenshotLock) {
3140                if (mScreenshotConnection != null) {
3141                    mContext.unbindService(mScreenshotConnection);
3142                    mScreenshotConnection = null;
3143                }
3144            }
3145        }
3146    };
3147
3148    // Assume this is called from the Handler thread.
3149    private void takeScreenshot() {
3150        synchronized (mScreenshotLock) {
3151            if (mScreenshotConnection != null) {
3152                return;
3153            }
3154            ComponentName cn = new ComponentName("com.android.systemui",
3155                    "com.android.systemui.screenshot.TakeScreenshotService");
3156            Intent intent = new Intent();
3157            intent.setComponent(cn);
3158            ServiceConnection conn = new ServiceConnection() {
3159                @Override
3160                public void onServiceConnected(ComponentName name, IBinder service) {
3161                    synchronized (mScreenshotLock) {
3162                        if (mScreenshotConnection != this) {
3163                            return;
3164                        }
3165                        Messenger messenger = new Messenger(service);
3166                        Message msg = Message.obtain(null, 1);
3167                        final ServiceConnection myConn = this;
3168                        Handler h = new Handler(mHandler.getLooper()) {
3169                            @Override
3170                            public void handleMessage(Message msg) {
3171                                synchronized (mScreenshotLock) {
3172                                    if (mScreenshotConnection == myConn) {
3173                                        mContext.unbindService(mScreenshotConnection);
3174                                        mScreenshotConnection = null;
3175                                        mHandler.removeCallbacks(mScreenshotTimeout);
3176                                    }
3177                                }
3178                            }
3179                        };
3180                        msg.replyTo = new Messenger(h);
3181                        msg.arg1 = msg.arg2 = 0;
3182                        if (mStatusBar != null && mStatusBar.isVisibleLw())
3183                            msg.arg1 = 1;
3184                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
3185                            msg.arg2 = 1;
3186                        try {
3187                            messenger.send(msg);
3188                        } catch (RemoteException e) {
3189                        }
3190                    }
3191                }
3192                @Override
3193                public void onServiceDisconnected(ComponentName name) {}
3194            };
3195            if (mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE)) {
3196                mScreenshotConnection = conn;
3197                mHandler.postDelayed(mScreenshotTimeout, 10000);
3198            }
3199        }
3200    }
3201
3202    /** {@inheritDoc} */
3203    @Override
3204    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
3205        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
3206        final boolean canceled = event.isCanceled();
3207        final int keyCode = event.getKeyCode();
3208
3209        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
3210
3211        // If screen is off then we treat the case where the keyguard is open but hidden
3212        // the same as if it were open and in front.
3213        // This will prevent any keys other than the power button from waking the screen
3214        // when the keyguard is hidden by another activity.
3215        final boolean keyguardActive = (mKeyguardMediator == null ? false :
3216                                            (isScreenOn ?
3217                                                mKeyguardMediator.isShowingAndNotHidden() :
3218                                                mKeyguardMediator.isShowing()));
3219
3220        if (!mSystemBooted) {
3221            // If we have not yet booted, don't let key events do anything.
3222            return 0;
3223        }
3224
3225        if (DEBUG_INPUT) {
3226            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
3227                  + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive);
3228        }
3229
3230        if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
3231                && event.getRepeatCount() == 0) {
3232            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
3233        }
3234
3235        if (keyCode == KeyEvent.KEYCODE_POWER) {
3236            policyFlags |= WindowManagerPolicy.FLAG_WAKE;
3237        }
3238        final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE
3239                | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3240
3241        // Basic policy based on screen state and keyguard.
3242        // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
3243        //        is on or off, really.  We should care about whether the device is in an
3244        //        interactive state or is in suspend pretending to be "off".
3245        //        The primary screen might be turned off due to proximity sensor or
3246        //        because we are presenting media on an auxiliary screen or remotely controlling
3247        //        the device some other way (which is why we have an exemption here for injected
3248        //        events).
3249        int result;
3250        if ((isScreenOn && !mHeadless) || (isInjected && !isWakeKey)) {
3251            // When the screen is on or if the key is injected pass the key to the application.
3252            result = ACTION_PASS_TO_USER;
3253        } else {
3254            // When the screen is off and the key is not injected, determine whether
3255            // to wake the device but don't pass the key to the application.
3256            result = 0;
3257            if (down && isWakeKey) {
3258                if (keyguardActive) {
3259                    // If the keyguard is showing, let it decide what to do with the wake key.
3260                    mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode,
3261                            mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED);
3262                } else {
3263                    // Otherwise, wake the device ourselves.
3264                    result |= ACTION_POKE_USER_ACTIVITY;
3265                }
3266            }
3267        }
3268
3269        // Handle special keys.
3270        switch (keyCode) {
3271            case KeyEvent.KEYCODE_VOLUME_DOWN:
3272            case KeyEvent.KEYCODE_VOLUME_UP:
3273            case KeyEvent.KEYCODE_VOLUME_MUTE: {
3274                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
3275                    if (down) {
3276                        if (isScreenOn && !mVolumeDownKeyTriggered
3277                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3278                            mVolumeDownKeyTriggered = true;
3279                            mVolumeDownKeyTime = event.getDownTime();
3280                            mVolumeDownKeyConsumedByScreenshotChord = false;
3281                            cancelPendingPowerKeyAction();
3282                            interceptScreenshotChord();
3283                        }
3284                    } else {
3285                        mVolumeDownKeyTriggered = false;
3286                        cancelPendingScreenshotChordAction();
3287                    }
3288                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
3289                    if (down) {
3290                        if (isScreenOn && !mVolumeUpKeyTriggered
3291                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3292                            mVolumeUpKeyTriggered = true;
3293                            cancelPendingPowerKeyAction();
3294                            cancelPendingScreenshotChordAction();
3295                        }
3296                    } else {
3297                        mVolumeUpKeyTriggered = false;
3298                        cancelPendingScreenshotChordAction();
3299                    }
3300                }
3301                if (down) {
3302                    ITelephony telephonyService = getTelephonyService();
3303                    if (telephonyService != null) {
3304                        try {
3305                            if (telephonyService.isRinging()) {
3306                                // If an incoming call is ringing, either VOLUME key means
3307                                // "silence ringer".  We handle these keys here, rather than
3308                                // in the InCallScreen, to make sure we'll respond to them
3309                                // even if the InCallScreen hasn't come to the foreground yet.
3310                                // Look for the DOWN event here, to agree with the "fallback"
3311                                // behavior in the InCallScreen.
3312                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3313                                      + " VOLUME key-down while ringing: Silence ringer!");
3314
3315                                // Silence the ringer.  (It's safe to call this
3316                                // even if the ringer has already been silenced.)
3317                                telephonyService.silenceRinger();
3318
3319                                // And *don't* pass this key thru to the current activity
3320                                // (which is probably the InCallScreen.)
3321                                result &= ~ACTION_PASS_TO_USER;
3322                                break;
3323                            }
3324                            if (telephonyService.isOffhook()
3325                                    && (result & ACTION_PASS_TO_USER) == 0) {
3326                                // If we are in call but we decided not to pass the key to
3327                                // the application, handle the volume change here.
3328                                handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
3329                                break;
3330                            }
3331                        } catch (RemoteException ex) {
3332                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3333                        }
3334                    }
3335
3336                    if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
3337                        // If music is playing but we decided not to pass the key to the
3338                        // application, handle the volume change here.
3339                        handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
3340                        break;
3341                    }
3342                }
3343                break;
3344            }
3345
3346            case KeyEvent.KEYCODE_ENDCALL: {
3347                result &= ~ACTION_PASS_TO_USER;
3348                if (down) {
3349                    ITelephony telephonyService = getTelephonyService();
3350                    boolean hungUp = false;
3351                    if (telephonyService != null) {
3352                        try {
3353                            hungUp = telephonyService.endCall();
3354                        } catch (RemoteException ex) {
3355                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3356                        }
3357                    }
3358                    interceptPowerKeyDown(!isScreenOn || hungUp);
3359                } else {
3360                    if (interceptPowerKeyUp(canceled)) {
3361                        if ((mEndcallBehavior
3362                                & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
3363                            if (goHome()) {
3364                                break;
3365                            }
3366                        }
3367                        if ((mEndcallBehavior
3368                                & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
3369                            result = (result & ~ACTION_POKE_USER_ACTIVITY) | ACTION_GO_TO_SLEEP;
3370                        }
3371                    }
3372                }
3373                break;
3374            }
3375
3376            case KeyEvent.KEYCODE_POWER: {
3377                result &= ~ACTION_PASS_TO_USER;
3378                if (down) {
3379                    if (isScreenOn && !mPowerKeyTriggered
3380                            && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3381                        mPowerKeyTriggered = true;
3382                        mPowerKeyTime = event.getDownTime();
3383                        interceptScreenshotChord();
3384                    }
3385
3386                    ITelephony telephonyService = getTelephonyService();
3387                    boolean hungUp = false;
3388                    if (telephonyService != null) {
3389                        try {
3390                            if (telephonyService.isRinging()) {
3391                                // Pressing Power while there's a ringing incoming
3392                                // call should silence the ringer.
3393                                telephonyService.silenceRinger();
3394                            } else if ((mIncallPowerBehavior
3395                                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
3396                                    && telephonyService.isOffhook()) {
3397                                // Otherwise, if "Power button ends call" is enabled,
3398                                // the Power button will hang up any current active call.
3399                                hungUp = telephonyService.endCall();
3400                            }
3401                        } catch (RemoteException ex) {
3402                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3403                        }
3404                    }
3405                    interceptPowerKeyDown(!isScreenOn || hungUp
3406                            || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered);
3407                } else {
3408                    mPowerKeyTriggered = false;
3409                    cancelPendingScreenshotChordAction();
3410                    if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) {
3411                        result = (result & ~ACTION_POKE_USER_ACTIVITY) | ACTION_GO_TO_SLEEP;
3412                    }
3413                    mPendingPowerKeyUpCanceled = false;
3414                }
3415                break;
3416            }
3417
3418            case KeyEvent.KEYCODE_MEDIA_PLAY:
3419            case KeyEvent.KEYCODE_MEDIA_PAUSE:
3420            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3421                if (down) {
3422                    ITelephony telephonyService = getTelephonyService();
3423                    if (telephonyService != null) {
3424                        try {
3425                            if (!telephonyService.isIdle()) {
3426                                // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
3427                                // to avoid music playback.
3428                                break;
3429                            }
3430                        } catch (RemoteException ex) {
3431                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3432                        }
3433                    }
3434                }
3435            case KeyEvent.KEYCODE_HEADSETHOOK:
3436            case KeyEvent.KEYCODE_MUTE:
3437            case KeyEvent.KEYCODE_MEDIA_STOP:
3438            case KeyEvent.KEYCODE_MEDIA_NEXT:
3439            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
3440            case KeyEvent.KEYCODE_MEDIA_REWIND:
3441            case KeyEvent.KEYCODE_MEDIA_RECORD:
3442            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
3443                if ((result & ACTION_PASS_TO_USER) == 0) {
3444                    // Only do this if we would otherwise not pass it to the user. In that
3445                    // case, the PhoneWindow class will do the same thing, except it will
3446                    // only do it if the showing app doesn't process the key on its own.
3447                    // Note that we need to make a copy of the key event here because the
3448                    // original key event will be recycled when we return.
3449                    mBroadcastWakeLock.acquire();
3450                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
3451                            new KeyEvent(event));
3452                    msg.setAsynchronous(true);
3453                    msg.sendToTarget();
3454                }
3455                break;
3456            }
3457
3458            case KeyEvent.KEYCODE_CALL: {
3459                if (down) {
3460                    ITelephony telephonyService = getTelephonyService();
3461                    if (telephonyService != null) {
3462                        try {
3463                            if (telephonyService.isRinging()) {
3464                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3465                                      + " CALL key-down while ringing: Answer the call!");
3466                                telephonyService.answerRingingCall();
3467
3468                                // And *don't* pass this key thru to the current activity
3469                                // (which is presumably the InCallScreen.)
3470                                result &= ~ACTION_PASS_TO_USER;
3471                            }
3472                        } catch (RemoteException ex) {
3473                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3474                        }
3475                    }
3476                }
3477                break;
3478            }
3479        }
3480        return result;
3481    }
3482
3483    /** {@inheritDoc} */
3484    @Override
3485    public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
3486        int result = 0;
3487
3488        final boolean isWakeMotion = (policyFlags
3489                & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3490        if (isWakeMotion) {
3491            if (mKeyguardMediator != null && mKeyguardMediator.isShowing()) {
3492                // If the keyguard is showing, let it decide what to do with the wake motion.
3493                mKeyguardMediator.onWakeMotionWhenKeyguardShowingTq();
3494            } else {
3495                // Otherwise, wake the device ourselves.
3496                result |= ACTION_POKE_USER_ACTIVITY;
3497            }
3498        }
3499        return result;
3500    }
3501
3502    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
3503        if (DEBUG_INPUT) {
3504            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
3505        }
3506
3507        if (mHavePendingMediaKeyRepeatWithWakeLock) {
3508            if (DEBUG_INPUT) {
3509                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
3510            }
3511
3512            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
3513            mHavePendingMediaKeyRepeatWithWakeLock = false;
3514            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
3515        }
3516
3517        dispatchMediaKeyWithWakeLockToAudioService(event);
3518
3519        if (event.getAction() == KeyEvent.ACTION_DOWN
3520                && event.getRepeatCount() == 0) {
3521            mHavePendingMediaKeyRepeatWithWakeLock = true;
3522
3523            Message msg = mHandler.obtainMessage(
3524                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
3525            msg.setAsynchronous(true);
3526            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
3527        } else {
3528            mBroadcastWakeLock.release();
3529        }
3530    }
3531
3532    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
3533        mHavePendingMediaKeyRepeatWithWakeLock = false;
3534
3535        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
3536                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
3537        if (DEBUG_INPUT) {
3538            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
3539        }
3540
3541        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
3542        mBroadcastWakeLock.release();
3543    }
3544
3545    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
3546        if (ActivityManagerNative.isSystemReady()) {
3547            IAudioService audioService = getAudioService();
3548            if (audioService != null) {
3549                try {
3550                    audioService.dispatchMediaKeyEventUnderWakelock(event);
3551                } catch (RemoteException e) {
3552                    Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e);
3553                }
3554            }
3555        }
3556    }
3557
3558    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
3559        public void onReceive(Context context, Intent intent) {
3560            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
3561                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3562                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
3563            } else {
3564                try {
3565                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
3566                            ServiceManager.getService(Context.UI_MODE_SERVICE));
3567                    mUiMode = uiModeService.getCurrentModeType();
3568                } catch (RemoteException e) {
3569                }
3570            }
3571            updateRotation(true);
3572            updateOrientationListenerLp();
3573        }
3574    };
3575
3576    BroadcastReceiver mPowerReceiver = new BroadcastReceiver() {
3577        public void onReceive(Context context, Intent intent) {
3578            if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
3579                mPluggedIn = (0 != intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0));
3580                if (localLOGV) Log.v(TAG, "BATTERY_CHANGED: " + intent + " plugged=" + mPluggedIn);
3581            }
3582        }
3583    };
3584
3585    /** {@inheritDoc} */
3586    public void screenTurnedOff(int why) {
3587        EventLog.writeEvent(70000, 0);
3588        synchronized (mLock) {
3589            mScreenOnEarly = false;
3590            mScreenOnFully = false;
3591        }
3592        if (mKeyguardMediator != null) {
3593            mKeyguardMediator.onScreenTurnedOff(why);
3594        }
3595        synchronized (mLock) {
3596            updateOrientationListenerLp();
3597            updateLockScreenTimeout();
3598        }
3599    }
3600
3601    /** {@inheritDoc} */
3602    public void screenTurningOn(final ScreenOnListener screenOnListener) {
3603        EventLog.writeEvent(70000, 1);
3604        if (false) {
3605            RuntimeException here = new RuntimeException("here");
3606            here.fillInStackTrace();
3607            Slog.i(TAG, "Screen turning on...", here);
3608        }
3609        if (screenOnListener != null) {
3610            if (mKeyguardMediator != null) {
3611                try {
3612                    mWindowManager.setEventDispatching(true);
3613                } catch (RemoteException unhandled) {
3614                }
3615                mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() {
3616                    @Override public void onShown(IBinder windowToken) {
3617                        if (windowToken != null) {
3618                            try {
3619                                mWindowManager.waitForWindowDrawn(windowToken,
3620                                        new IRemoteCallback.Stub() {
3621                                    @Override public void sendResult(Bundle data) {
3622                                        Slog.i(TAG, "Lock screen displayed!");
3623                                        screenOnListener.onScreenOn();
3624                                        synchronized (mLock) {
3625                                            mScreenOnFully = true;
3626                                        }
3627                                    }
3628                                });
3629                            } catch (RemoteException e) {
3630                            }
3631                        } else {
3632                            Slog.i(TAG, "No lock screen!");
3633                            screenOnListener.onScreenOn();
3634                            synchronized (mLock) {
3635                                mScreenOnFully = true;
3636                            }
3637                        }
3638                    }
3639                });
3640            }
3641        } else {
3642            if (mKeyguardMediator != null) {
3643                // Must set mScreenOn = true.
3644                mKeyguardMediator.onScreenTurnedOn(null);
3645            }
3646            synchronized (mLock) {
3647                mScreenOnFully = true;
3648            }
3649        }
3650        synchronized (mLock) {
3651            mScreenOnEarly = true;
3652            updateOrientationListenerLp();
3653            updateLockScreenTimeout();
3654        }
3655    }
3656
3657    /** {@inheritDoc} */
3658    public boolean isScreenOnEarly() {
3659        return mScreenOnEarly;
3660    }
3661
3662    /** {@inheritDoc} */
3663    public boolean isScreenOnFully() {
3664        return mScreenOnFully;
3665    }
3666
3667    /** {@inheritDoc} */
3668    public void enableKeyguard(boolean enabled) {
3669        if (mKeyguardMediator != null) {
3670            mKeyguardMediator.setKeyguardEnabled(enabled);
3671        }
3672    }
3673
3674    /** {@inheritDoc} */
3675    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
3676        if (mKeyguardMediator != null) {
3677            mKeyguardMediator.verifyUnlock(callback);
3678        }
3679    }
3680
3681    private boolean keyguardIsShowingTq() {
3682        if (mKeyguardMediator == null) return false;
3683        return mKeyguardMediator.isShowingAndNotHidden();
3684    }
3685
3686
3687    /** {@inheritDoc} */
3688    public boolean isKeyguardLocked() {
3689        return keyguardOn();
3690    }
3691
3692    /** {@inheritDoc} */
3693    public boolean isKeyguardSecure() {
3694        if (mKeyguardMediator == null) return false;
3695        return mKeyguardMediator.isSecure();
3696    }
3697
3698    /** {@inheritDoc} */
3699    public boolean inKeyguardRestrictedKeyInputMode() {
3700        if (mKeyguardMediator == null) return false;
3701        return mKeyguardMediator.isInputRestricted();
3702    }
3703
3704    public void dismissKeyguardLw() {
3705        if (!mKeyguardMediator.isSecure()) {
3706            if (mKeyguardMediator.isShowing()) {
3707                mHandler.post(new Runnable() {
3708                    public void run() {
3709                        mKeyguardMediator.keyguardDone(false, true);
3710                    }
3711                });
3712            }
3713        }
3714    }
3715
3716    void sendCloseSystemWindows() {
3717        sendCloseSystemWindows(mContext, null);
3718    }
3719
3720    void sendCloseSystemWindows(String reason) {
3721        sendCloseSystemWindows(mContext, reason);
3722    }
3723
3724    static void sendCloseSystemWindows(Context context, String reason) {
3725        if (ActivityManagerNative.isSystemReady()) {
3726            try {
3727                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
3728            } catch (RemoteException e) {
3729            }
3730        }
3731    }
3732
3733    @Override
3734    public int rotationForOrientationLw(int orientation, int lastRotation) {
3735        if (false) {
3736            Slog.v(TAG, "rotationForOrientationLw(orient="
3737                        + orientation + ", last=" + lastRotation
3738                        + "); user=" + mUserRotation + " "
3739                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
3740                            ? "USER_ROTATION_LOCKED" : "")
3741                        );
3742        }
3743
3744        synchronized (mLock) {
3745            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
3746            if (sensorRotation < 0) {
3747                sensorRotation = lastRotation;
3748            }
3749
3750            final int preferredRotation;
3751            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
3752                // Ignore sensor when lid switch is open and rotation is forced.
3753                preferredRotation = mLidOpenRotation;
3754            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
3755                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
3756                // Ignore sensor when in car dock unless explicitly enabled.
3757                // This case can override the behavior of NOSENSOR, and can also
3758                // enable 180 degree rotation while docked.
3759                preferredRotation = mCarDockEnablesAccelerometer
3760                        ? sensorRotation : mCarDockRotation;
3761            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
3762                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
3763                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
3764                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
3765                // Ignore sensor when in desk dock unless explicitly enabled.
3766                // This case can override the behavior of NOSENSOR, and can also
3767                // enable 180 degree rotation while docked.
3768                preferredRotation = mDeskDockEnablesAccelerometer
3769                        ? sensorRotation : mDeskDockRotation;
3770            } else if (mHdmiPlugged) {
3771                // Ignore sensor when plugged into HDMI.
3772                // Note that the dock orientation overrides the HDMI orientation.
3773                preferredRotation = mHdmiRotation;
3774            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
3775                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
3776                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED))
3777                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
3778                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
3779                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
3780                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
3781                // Otherwise, use sensor only if requested by the application or enabled
3782                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
3783                if (mAllowAllRotations < 0) {
3784                    // Can't read this during init() because the context doesn't
3785                    // have display metrics at that time so we cannot determine
3786                    // tablet vs. phone then.
3787                    mAllowAllRotations = mContext.getResources().getBoolean(
3788                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
3789                }
3790                if (sensorRotation != Surface.ROTATION_180
3791                        || mAllowAllRotations == 1
3792                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
3793                    preferredRotation = sensorRotation;
3794                } else {
3795                    preferredRotation = lastRotation;
3796                }
3797            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
3798                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
3799                // Apply rotation lock.  Does not apply to NOSENSOR.
3800                // The idea is that the user rotation expresses a weak preference for the direction
3801                // of gravity and as NOSENSOR is never affected by gravity, then neither should
3802                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
3803                preferredRotation = mUserRotation;
3804            } else {
3805                // No overriding preference.
3806                // We will do exactly what the application asked us to do.
3807                preferredRotation = -1;
3808            }
3809
3810            switch (orientation) {
3811                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
3812                    // Return portrait unless overridden.
3813                    if (isAnyPortrait(preferredRotation)) {
3814                        return preferredRotation;
3815                    }
3816                    return mPortraitRotation;
3817
3818                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
3819                    // Return landscape unless overridden.
3820                    if (isLandscapeOrSeascape(preferredRotation)) {
3821                        return preferredRotation;
3822                    }
3823                    return mLandscapeRotation;
3824
3825                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
3826                    // Return reverse portrait unless overridden.
3827                    if (isAnyPortrait(preferredRotation)) {
3828                        return preferredRotation;
3829                    }
3830                    return mUpsideDownRotation;
3831
3832                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
3833                    // Return seascape unless overridden.
3834                    if (isLandscapeOrSeascape(preferredRotation)) {
3835                        return preferredRotation;
3836                    }
3837                    return mSeascapeRotation;
3838
3839                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
3840                    // Return either landscape rotation.
3841                    if (isLandscapeOrSeascape(preferredRotation)) {
3842                        return preferredRotation;
3843                    }
3844                    if (isLandscapeOrSeascape(lastRotation)) {
3845                        return lastRotation;
3846                    }
3847                    return mLandscapeRotation;
3848
3849                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
3850                    // Return either portrait rotation.
3851                    if (isAnyPortrait(preferredRotation)) {
3852                        return preferredRotation;
3853                    }
3854                    if (isAnyPortrait(lastRotation)) {
3855                        return lastRotation;
3856                    }
3857                    return mPortraitRotation;
3858
3859                default:
3860                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
3861                    // just return the preferred orientation we already calculated.
3862                    if (preferredRotation >= 0) {
3863                        return preferredRotation;
3864                    }
3865                    return Surface.ROTATION_0;
3866            }
3867        }
3868    }
3869
3870    @Override
3871    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
3872        switch (orientation) {
3873            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
3874            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
3875            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
3876                return isAnyPortrait(rotation);
3877
3878            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
3879            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
3880            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
3881                return isLandscapeOrSeascape(rotation);
3882
3883            default:
3884                return true;
3885        }
3886    }
3887
3888    @Override
3889    public void setRotationLw(int rotation) {
3890        mOrientationListener.setCurrentRotation(rotation);
3891    }
3892
3893    private boolean isLandscapeOrSeascape(int rotation) {
3894        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
3895    }
3896
3897    private boolean isAnyPortrait(int rotation) {
3898        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
3899    }
3900
3901
3902    // User rotation: to be used when all else fails in assigning an orientation to the device
3903    public void setUserRotationMode(int mode, int rot) {
3904        ContentResolver res = mContext.getContentResolver();
3905
3906        // mUserRotationMode and mUserRotation will be assigned by the content observer
3907        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
3908            Settings.System.putInt(res,
3909                    Settings.System.USER_ROTATION,
3910                    rot);
3911            Settings.System.putInt(res,
3912                    Settings.System.ACCELEROMETER_ROTATION,
3913                    0);
3914        } else {
3915            Settings.System.putInt(res,
3916                    Settings.System.ACCELEROMETER_ROTATION,
3917                    1);
3918        }
3919    }
3920
3921    public void setSafeMode(boolean safeMode) {
3922        mSafeMode = safeMode;
3923        performHapticFeedbackLw(null, safeMode
3924                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
3925                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
3926    }
3927
3928    static long[] getLongIntArray(Resources r, int resid) {
3929        int[] ar = r.getIntArray(resid);
3930        if (ar == null) {
3931            return null;
3932        }
3933        long[] out = new long[ar.length];
3934        for (int i=0; i<ar.length; i++) {
3935            out[i] = ar[i];
3936        }
3937        return out;
3938    }
3939
3940    /** {@inheritDoc} */
3941    public void systemReady() {
3942        if (mKeyguardMediator != null) {
3943            // tell the keyguard
3944            mKeyguardMediator.onSystemReady();
3945        }
3946        synchronized (mLock) {
3947            updateOrientationListenerLp();
3948            mSystemReady = true;
3949            mHandler.post(new Runnable() {
3950                public void run() {
3951                    updateSettings();
3952                }
3953            });
3954        }
3955    }
3956
3957    /** {@inheritDoc} */
3958    public void systemBooted() {
3959        synchronized (mLock) {
3960            mSystemBooted = true;
3961        }
3962    }
3963
3964    ProgressDialog mBootMsgDialog = null;
3965
3966    /** {@inheritDoc} */
3967    public void showBootMessage(final CharSequence msg, final boolean always) {
3968        if (mHeadless) return;
3969        mHandler.post(new Runnable() {
3970            @Override public void run() {
3971                if (mBootMsgDialog == null) {
3972                    mBootMsgDialog = new ProgressDialog(mContext) {
3973                        // This dialog will consume all events coming in to
3974                        // it, to avoid it trying to do things too early in boot.
3975                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
3976                            return true;
3977                        }
3978                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3979                            return true;
3980                        }
3981                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
3982                            return true;
3983                        }
3984                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
3985                            return true;
3986                        }
3987                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
3988                            return true;
3989                        }
3990                        @Override public boolean dispatchPopulateAccessibilityEvent(
3991                                AccessibilityEvent event) {
3992                            return true;
3993                        }
3994                    };
3995                    mBootMsgDialog.setTitle(R.string.android_upgrading_title);
3996                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
3997                    mBootMsgDialog.setIndeterminate(true);
3998                    mBootMsgDialog.getWindow().setType(
3999                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
4000                    mBootMsgDialog.getWindow().addFlags(
4001                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
4002                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
4003                    mBootMsgDialog.getWindow().setDimAmount(1);
4004                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
4005                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
4006                    mBootMsgDialog.getWindow().setAttributes(lp);
4007                    mBootMsgDialog.setCancelable(false);
4008                    mBootMsgDialog.show();
4009                }
4010                mBootMsgDialog.setMessage(msg);
4011            }
4012        });
4013    }
4014
4015    /** {@inheritDoc} */
4016    public void hideBootMessages() {
4017        mHandler.post(new Runnable() {
4018            @Override public void run() {
4019                if (mBootMsgDialog != null) {
4020                    mBootMsgDialog.dismiss();
4021                    mBootMsgDialog = null;
4022                }
4023            }
4024        });
4025    }
4026
4027    /** {@inheritDoc} */
4028    public void userActivity() {
4029        // ***************************************
4030        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
4031        // ***************************************
4032        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
4033        // WITH ITS LOCKS HELD.
4034        //
4035        // This code must be VERY careful about the locks
4036        // it acquires.
4037        // In fact, the current code acquires way too many,
4038        // and probably has lurking deadlocks.
4039
4040        synchronized (mScreenLockTimeout) {
4041            if (mLockScreenTimerActive) {
4042                // reset the timer
4043                mHandler.removeCallbacks(mScreenLockTimeout);
4044                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4045            }
4046        }
4047    }
4048
4049    private IDreamManager getDreamManager() {
4050        if (!mScreenSaverFeatureAvailable) {
4051            return null;
4052        }
4053
4054        IDreamManager sandman = IDreamManager.Stub.asInterface(
4055                ServiceManager.checkService("dreams"));
4056        if (sandman == null) {
4057            Log.w(TAG, "Unable to find IDreamManager");
4058        }
4059        return sandman;
4060    }
4061
4062    @Override
4063    public boolean isScreenSaverEnabled() {
4064        return (mScreenSaverFeatureAvailable && mScreenSaverEnabledByUser
4065                && mScreenSaverMayRun && mScreenOnEarly && mPluggedIn);
4066    }
4067
4068    @Override
4069    public boolean startScreenSaver() {
4070        synchronized (mLock) {
4071            if (isScreenSaverEnabled()) {
4072                IDreamManager dm = getDreamManager();
4073                if (dm == null) return false;
4074
4075                try {
4076                    if (localLOGV) Log.v(TAG, "startScreenSaver: entering dreamland...");
4077
4078                    dm.dream();
4079                    return true;
4080                } catch (RemoteException ex) {
4081                    // too bad, so sad, oh mom, oh dad
4082                }
4083            }
4084        }
4085        return false;
4086    }
4087
4088    @Override
4089    public void stopScreenSaver() {
4090        synchronized (mLock) {
4091            IDreamManager dm = getDreamManager();
4092            if (dm == null) return;
4093
4094            try {
4095                if (localLOGV) Log.v(TAG, "startScreenSaver: awakening...");
4096
4097                dm.awaken();
4098            } catch (RemoteException ex) {
4099            }
4100        }
4101    }
4102
4103    Runnable mScreenLockTimeout = new Runnable() {
4104        public void run() {
4105            synchronized (this) {
4106                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
4107                if (mKeyguardMediator != null) {
4108                    mKeyguardMediator.doKeyguardTimeout();
4109                }
4110                mLockScreenTimerActive = false;
4111            }
4112        }
4113    };
4114
4115    public void lockNow() {
4116        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
4117        mHandler.removeCallbacks(mScreenLockTimeout);
4118        mHandler.post(mScreenLockTimeout);
4119    }
4120
4121    private void updateLockScreenTimeout() {
4122        synchronized (mScreenLockTimeout) {
4123            boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly &&
4124                    mKeyguardMediator != null && mKeyguardMediator.isSecure());
4125            if (mLockScreenTimerActive != enable) {
4126                if (enable) {
4127                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
4128                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4129                } else {
4130                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
4131                    mHandler.removeCallbacks(mScreenLockTimeout);
4132                }
4133                mLockScreenTimerActive = enable;
4134            }
4135        }
4136    }
4137
4138    /** {@inheritDoc} */
4139    public void enableScreenAfterBoot() {
4140        readLidState();
4141        applyLidSwitchState();
4142        updateRotation(true);
4143    }
4144
4145    private void applyLidSwitchState() {
4146        mPowerManager.setKeyboardVisibility(isBuiltInKeyboardVisible());
4147
4148        if (mLidState == LID_CLOSED && mLidControlsSleep) {
4149            mPowerManager.goToSleep(SystemClock.uptimeMillis());
4150        }
4151    }
4152
4153    void updateRotation(boolean alwaysSendConfiguration) {
4154        try {
4155            //set orientation on WindowManager
4156            mWindowManager.updateRotation(alwaysSendConfiguration, false);
4157        } catch (RemoteException e) {
4158            // Ignore
4159        }
4160    }
4161
4162    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
4163        try {
4164            //set orientation on WindowManager
4165            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
4166        } catch (RemoteException e) {
4167            // Ignore
4168        }
4169    }
4170
4171    /**
4172     * Return an Intent to launch the currently active dock app as home.  Returns
4173     * null if the standard home should be launched, which is the case if any of the following is
4174     * true:
4175     * <ul>
4176     *  <li>The device is not in either car mode or desk mode
4177     *  <li>The device is in car mode but ENABLE_CAR_DOCK_HOME_CAPTURE is false
4178     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
4179     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
4180     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
4181     * </ul>
4182     * @return
4183     */
4184    Intent createHomeDockIntent() {
4185        Intent intent = null;
4186
4187        // What home does is based on the mode, not the dock state.  That
4188        // is, when in car mode you should be taken to car home regardless
4189        // of whether we are actually in a car dock.
4190        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
4191            if (ENABLE_CAR_DOCK_HOME_CAPTURE) {
4192                intent = mCarDockIntent;
4193            }
4194        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
4195            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
4196                intent = mDeskDockIntent;
4197            }
4198        }
4199
4200        if (intent == null) {
4201            return null;
4202        }
4203
4204        ActivityInfo ai = intent.resolveActivityInfo(
4205                mContext.getPackageManager(), PackageManager.GET_META_DATA);
4206        if (ai == null) {
4207            return null;
4208        }
4209
4210        if (ai.metaData != null && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
4211            intent = new Intent(intent);
4212            intent.setClassName(ai.packageName, ai.name);
4213            return intent;
4214        }
4215
4216        return null;
4217    }
4218
4219    void startDockOrHome() {
4220        Intent dock = createHomeDockIntent();
4221        if (dock != null) {
4222            try {
4223                mContext.startActivity(dock);
4224                return;
4225            } catch (ActivityNotFoundException e) {
4226            }
4227        }
4228        mContext.startActivity(mHomeIntent);
4229    }
4230
4231    /**
4232     * goes to the home screen
4233     * @return whether it did anything
4234     */
4235    boolean goHome() {
4236        if (false) {
4237            // This code always brings home to the front.
4238            try {
4239                ActivityManagerNative.getDefault().stopAppSwitches();
4240            } catch (RemoteException e) {
4241            }
4242            sendCloseSystemWindows();
4243            startDockOrHome();
4244        } else {
4245            // This code brings home to the front or, if it is already
4246            // at the front, puts the device to sleep.
4247            try {
4248                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
4249                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
4250                    Log.d(TAG, "UTS-TEST-MODE");
4251                } else {
4252                    ActivityManagerNative.getDefault().stopAppSwitches();
4253                    sendCloseSystemWindows();
4254                    Intent dock = createHomeDockIntent();
4255                    if (dock != null) {
4256                        int result = ActivityManagerNative.getDefault()
4257                                .startActivity(null, dock,
4258                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
4259                                        null, null, 0,
4260                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4261                                        null, null, null);
4262                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4263                            return false;
4264                        }
4265                    }
4266                }
4267                int result = ActivityManagerNative.getDefault()
4268                        .startActivity(null, mHomeIntent,
4269                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
4270                                null, null, 0,
4271                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4272                                null, null, null);
4273                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4274                    return false;
4275                }
4276            } catch (RemoteException ex) {
4277                // bummer, the activity manager, which is in this process, is dead
4278            }
4279        }
4280        return true;
4281    }
4282
4283    public void setCurrentOrientationLw(int newOrientation) {
4284        synchronized (mLock) {
4285            if (newOrientation != mCurrentAppOrientation) {
4286                mCurrentAppOrientation = newOrientation;
4287                updateOrientationListenerLp();
4288            }
4289        }
4290    }
4291
4292    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
4293        final boolean hapticsDisabled = Settings.System.getInt(mContext.getContentResolver(),
4294                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 0;
4295        if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
4296            return false;
4297        }
4298        long[] pattern = null;
4299        switch (effectId) {
4300            case HapticFeedbackConstants.LONG_PRESS:
4301                pattern = mLongPressVibePattern;
4302                break;
4303            case HapticFeedbackConstants.VIRTUAL_KEY:
4304                pattern = mVirtualKeyVibePattern;
4305                break;
4306            case HapticFeedbackConstants.KEYBOARD_TAP:
4307                pattern = mKeyboardTapVibePattern;
4308                break;
4309            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
4310                pattern = mSafeModeDisabledVibePattern;
4311                break;
4312            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
4313                pattern = mSafeModeEnabledVibePattern;
4314                break;
4315            default:
4316                return false;
4317        }
4318        if (pattern.length == 1) {
4319            // One-shot vibration
4320            mVibrator.vibrate(pattern[0]);
4321        } else {
4322            // Pattern vibration
4323            mVibrator.vibrate(pattern, -1);
4324        }
4325        return true;
4326    }
4327
4328    public void screenOnStartedLw() {
4329        // The window manager has just grabbed a wake lock. This is our cue to disable the screen
4330        // saver.
4331        synchronized (mLock) {
4332            mScreenSaverMayRun = false;
4333        }
4334    }
4335
4336    public void screenOnStoppedLw() {
4337        if (mPowerManager.isScreenOn()) {
4338            if (mKeyguardMediator != null && !mKeyguardMediator.isShowingAndNotHidden()) {
4339                long curTime = SystemClock.uptimeMillis();
4340                mPowerManager.userActivity(curTime, false, LocalPowerManager.OTHER_EVENT);
4341            }
4342
4343            synchronized (mLock) {
4344                // even if the keyguard is up, now that all the wakelocks have been released, we
4345                // should re-enable the screen saver
4346                mScreenSaverMayRun = true;
4347            }
4348        }
4349    }
4350
4351    public boolean allowKeyRepeat() {
4352        // disable key repeat when screen is off
4353        return mScreenOnEarly;
4354    }
4355
4356    private int updateSystemUiVisibilityLw() {
4357        // If there is no window focused, there will be nobody to handle the events
4358        // anyway, so just hang on in whatever state we're in until things settle down.
4359        if (mFocusedWindow == null) {
4360            return 0;
4361        }
4362        final int visibility = mFocusedWindow.getSystemUiVisibility()
4363                & ~mResettingSystemUiFlags
4364                & ~mForceClearedSystemUiFlags;
4365        int diff = visibility ^ mLastSystemUiFlags;
4366        final boolean needsMenu = mFocusedWindow.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
4367        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
4368                && mFocusedApp == mFocusedWindow.getAppToken()) {
4369            return 0;
4370        }
4371        mLastSystemUiFlags = visibility;
4372        mLastFocusNeedsMenu = needsMenu;
4373        mFocusedApp = mFocusedWindow.getAppToken();
4374        mHandler.post(new Runnable() {
4375                public void run() {
4376                    try {
4377                        IStatusBarService statusbar = getStatusBarService();
4378                        if (statusbar != null) {
4379                            statusbar.setSystemUiVisibility(visibility, 0xffffffff);
4380                            statusbar.topAppWindowChanged(needsMenu);
4381                        }
4382                    } catch (RemoteException e) {
4383                        // re-acquire status bar service next time it is needed.
4384                        mStatusBarService = null;
4385                    }
4386                }
4387            });
4388        return diff;
4389    }
4390
4391    // Use this instead of checking config_showNavigationBar so that it can be consistently
4392    // overridden by qemu.hw.mainkeys in the emulator.
4393    public boolean hasNavigationBar() {
4394        return mHasNavigationBar;
4395    }
4396
4397    @Override
4398    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
4399        mLastInputMethodWindow = ime;
4400        mLastInputMethodTargetWindow = target;
4401    }
4402
4403    public void dump(String prefix, PrintWriter pw, String[] args) {
4404        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
4405                pw.print(" mSystemReady="); pw.print(mSystemReady);
4406                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
4407        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
4408                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
4409                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
4410        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
4411                || mForceClearedSystemUiFlags != 0) {
4412            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
4413                    pw.print(Integer.toHexString(mLastSystemUiFlags));
4414                    pw.print(" mResettingSystemUiFlags=0x");
4415                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
4416                    pw.print(" mForceClearedSystemUiFlags=0x");
4417                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
4418        }
4419        if (mLastFocusNeedsMenu) {
4420            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
4421                    pw.println(mLastFocusNeedsMenu);
4422        }
4423        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
4424                pw.print(" mDockMode="); pw.print(mDockMode);
4425                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
4426                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
4427        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
4428                pw.print(" mUserRotation="); pw.print(mUserRotation);
4429                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
4430        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
4431        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
4432                pw.print(mCarDockEnablesAccelerometer);
4433                pw.print(" mDeskDockEnablesAccelerometer=");
4434                pw.println(mDeskDockEnablesAccelerometer);
4435        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
4436                pw.print(mLidKeyboardAccessibility);
4437                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
4438                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
4439        pw.print(prefix); pw.print("mLongPressOnPowerBehavior=");
4440                pw.print(mLongPressOnPowerBehavior);
4441                pw.print(" mHasSoftInput="); pw.println(mHasSoftInput);
4442        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
4443                pw.print(" mScreenOnFully="); pw.print(mScreenOnFully);
4444                pw.print(" mOrientationSensorEnabled="); pw.println(mOrientationSensorEnabled);
4445        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
4446                pw.print(","); pw.print(mUnrestrictedScreenTop);
4447                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
4448                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
4449        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
4450                pw.print(","); pw.print(mRestrictedScreenTop);
4451                pw.print(") "); pw.print(mRestrictedScreenWidth);
4452                pw.print("x"); pw.println(mRestrictedScreenHeight);
4453        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
4454                pw.print(","); pw.print(mStableFullscreenTop);
4455                pw.print(")-("); pw.print(mStableFullscreenRight);
4456                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
4457        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
4458                pw.print(","); pw.print(mStableTop);
4459                pw.print(")-("); pw.print(mStableRight);
4460                pw.print(","); pw.print(mStableBottom); pw.println(")");
4461        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
4462                pw.print(","); pw.print(mSystemTop);
4463                pw.print(")-("); pw.print(mSystemRight);
4464                pw.print(","); pw.print(mSystemBottom); pw.println(")");
4465        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
4466                pw.print(","); pw.print(mCurTop);
4467                pw.print(")-("); pw.print(mCurRight);
4468                pw.print(","); pw.print(mCurBottom); pw.println(")");
4469        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
4470                pw.print(","); pw.print(mContentTop);
4471                pw.print(")-("); pw.print(mContentRight);
4472                pw.print(","); pw.print(mContentBottom); pw.println(")");
4473        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
4474                pw.print(","); pw.print(mDockTop);
4475                pw.print(")-("); pw.print(mDockRight);
4476                pw.print(","); pw.print(mDockBottom); pw.println(")");
4477        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
4478                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
4479        pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
4480                pw.println(mTopFullscreenOpaqueWindowState);
4481        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
4482                pw.print(" mForceStatusBar="); pw.print(mForceStatusBar);
4483                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
4484        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
4485                pw.print(" mHomePressed="); pw.println(mHomePressed);
4486        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
4487                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
4488                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
4489        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
4490                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
4491                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
4492        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
4493                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
4494        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
4495                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
4496    }
4497}
4498