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