PhoneWindowManager.java revision 1cf70bbf96930662cab0e699d70b62865766ff52
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.util.SparseIntArray;
75import android.view.Display;
76import android.view.Gravity;
77import android.view.HapticFeedbackConstants;
78import android.view.IApplicationToken;
79import android.view.IWindowManager;
80import android.view.InputChannel;
81import android.view.InputDevice;
82import android.view.InputEvent;
83import android.view.InputEventReceiver;
84import android.view.KeyCharacterMap;
85import android.view.KeyEvent;
86import android.view.MotionEvent;
87import android.view.WindowManagerGlobal;
88import android.view.WindowOrientationListener;
89import android.view.Surface;
90import android.view.View;
91import android.view.ViewConfiguration;
92import android.view.Window;
93import android.view.WindowManager;
94import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
95import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
96import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
97import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
98import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
99import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
100import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
101import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
102import static android.view.WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON;
103import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
104import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
105import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
106import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
107import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
108import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY;
109import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
110import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
111import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
112import static android.view.WindowManager.LayoutParams.TYPE_DISPLAY_OVERLAY;
113import static android.view.WindowManager.LayoutParams.TYPE_DRAG;
114import static android.view.WindowManager.LayoutParams.TYPE_DREAM;
115import static android.view.WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER;
116import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD;
117import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
118import static android.view.WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY;
119import static android.view.WindowManager.LayoutParams.TYPE_PHONE;
120import static android.view.WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
121import static android.view.WindowManager.LayoutParams.TYPE_SEARCH_BAR;
122import static android.view.WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
123import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
124import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
125import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
126import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG;
127import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
128import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
129import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
130import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
131import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
132import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
133import static android.view.WindowManager.LayoutParams.TYPE_UNIVERSE_BACKGROUND;
134import static android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY;
135import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
136import static android.view.WindowManager.LayoutParams.TYPE_POINTER;
137import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR;
138import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL;
139import static android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS;
140import android.view.WindowManagerPolicy;
141import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_ABSENT;
142import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN;
143import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_CLOSED;
144import android.view.KeyCharacterMap.FallbackAction;
145import android.view.accessibility.AccessibilityEvent;
146import android.view.animation.Animation;
147import android.view.animation.AnimationUtils;
148
149import java.io.File;
150import java.io.FileReader;
151import java.io.IOException;
152import java.io.PrintWriter;
153
154/**
155 * WindowManagerPolicy implementation for the Android phone UI.  This
156 * introduces a new method suffix, Lp, for an internal lock of the
157 * PhoneWindowManager.  This is used to protect some internal state, and
158 * can be acquired with either thw Lw and Li lock held, so has the restrictions
159 * of both of those when held.
160 */
161public class PhoneWindowManager implements WindowManagerPolicy {
162    static final String TAG = "WindowManager";
163    static final boolean DEBUG = false;
164    static final boolean localLOGV = false;
165    static final boolean DEBUG_LAYOUT = false;
166    static final boolean DEBUG_INPUT = false;
167    static final boolean DEBUG_STARTING_WINDOW = false;
168    static final boolean SHOW_STARTING_ANIMATIONS = true;
169    static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
170
171    // Whether to allow dock apps with METADATA_DOCK_HOME to temporarily take over the Home key.
172    // No longer recommended for desk docks; still useful in car docks.
173    static final boolean ENABLE_CAR_DOCK_HOME_CAPTURE = true;
174    static final boolean ENABLE_DESK_DOCK_HOME_CAPTURE = false;
175
176    static final int LONG_PRESS_POWER_NOTHING = 0;
177    static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
178    static final int LONG_PRESS_POWER_SHUT_OFF = 2;
179    static final int LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM = 3;
180
181    // These need to match the documentation/constant in
182    // core/res/res/values/config.xml
183    static final int LONG_PRESS_HOME_NOTHING = 0;
184    static final int LONG_PRESS_HOME_RECENT_DIALOG = 1;
185    static final int LONG_PRESS_HOME_RECENT_SYSTEM_UI = 2;
186
187    // wallpaper is at the bottom, though the window manager may move it.
188    static final int UNIVERSE_BACKGROUND_LAYER = 1;
189    static final int WALLPAPER_LAYER = 2;
190    static final int APPLICATION_LAYER = 2;
191    static final int PHONE_LAYER = 3;
192    static final int SEARCH_BAR_LAYER = 4;
193    static final int SYSTEM_DIALOG_LAYER = 5;
194    // toasts and the plugged-in battery thing
195    static final int TOAST_LAYER = 6;
196    // SIM errors and unlock.  Not sure if this really should be in a high layer.
197    static final int PRIORITY_PHONE_LAYER = 7;
198    // like the ANR / app crashed dialogs
199    static final int SYSTEM_ALERT_LAYER = 8;
200    // on-screen keyboards and other such input method user interfaces go here.
201    static final int INPUT_METHOD_LAYER = 9;
202    // on-screen keyboards and other such input method user interfaces go here.
203    static final int INPUT_METHOD_DIALOG_LAYER = 10;
204    // the keyguard; nothing on top of these can take focus, since they are
205    // responsible for power management when displayed.
206    static final int KEYGUARD_LAYER = 11;
207    static final int KEYGUARD_DIALOG_LAYER = 12;
208    // used for Dreams (screensavers with TYPE_DREAM windows)
209    static final int SCREENSAVER_LAYER = 13;
210    static final int STATUS_BAR_SUB_PANEL_LAYER = 14;
211    static final int STATUS_BAR_LAYER = 15;
212    static final int STATUS_BAR_PANEL_LAYER = 16;
213    // the on-screen volume indicator and controller shown when the user
214    // changes the device volume
215    static final int VOLUME_OVERLAY_LAYER = 17;
216    // things in here CAN NOT take focus, but are shown on top of everything else.
217    static final int SYSTEM_OVERLAY_LAYER = 18;
218    // the navigation bar, if available, shows atop most things
219    static final int NAVIGATION_BAR_LAYER = 19;
220    // some panels (e.g. search) need to show on top of the navigation bar
221    static final int NAVIGATION_BAR_PANEL_LAYER = 20;
222    // system-level error dialogs
223    static final int SYSTEM_ERROR_LAYER = 21;
224    // used to highlight the magnified portion of a display
225    static final int MAGNIFICATION_OVERLAY_LAYER = 22;
226    // used to simulate secondary display devices
227    static final int DISPLAY_OVERLAY_LAYER = 23;
228    // the drag layer: input for drag-and-drop is associated with this window,
229    // which sits above all other focusable windows
230    static final int DRAG_LAYER = 24;
231    static final int SECURE_SYSTEM_OVERLAY_LAYER = 25;
232    static final int BOOT_PROGRESS_LAYER = 26;
233    // the (mouse) pointer layer
234    static final int POINTER_LAYER = 27;
235    static final int HIDDEN_NAV_CONSUMER_LAYER = 28;
236
237    static final int APPLICATION_MEDIA_SUBLAYER = -2;
238    static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
239    static final int APPLICATION_PANEL_SUBLAYER = 1;
240    static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
241
242    static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
243    static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
244    static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
245    static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
246    static public final String SYSTEM_DIALOG_REASON_ASSIST = "assist";
247
248    /**
249     * These are the system UI flags that, when changing, can cause the layout
250     * of the screen to change.
251     */
252    static final int SYSTEM_UI_CHANGING_LAYOUT =
253            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
254
255    /* Table of Application Launch keys.  Maps from key codes to intent categories.
256     *
257     * These are special keys that are used to launch particular kinds of applications,
258     * such as a web browser.  HID defines nearly a hundred of them in the Consumer (0x0C)
259     * usage page.  We don't support quite that many yet...
260     */
261    static SparseArray<String> sApplicationLaunchKeyCategories;
262    static {
263        sApplicationLaunchKeyCategories = new SparseArray<String>();
264        sApplicationLaunchKeyCategories.append(
265                KeyEvent.KEYCODE_EXPLORER, Intent.CATEGORY_APP_BROWSER);
266        sApplicationLaunchKeyCategories.append(
267                KeyEvent.KEYCODE_ENVELOPE, Intent.CATEGORY_APP_EMAIL);
268        sApplicationLaunchKeyCategories.append(
269                KeyEvent.KEYCODE_CONTACTS, Intent.CATEGORY_APP_CONTACTS);
270        sApplicationLaunchKeyCategories.append(
271                KeyEvent.KEYCODE_CALENDAR, Intent.CATEGORY_APP_CALENDAR);
272        sApplicationLaunchKeyCategories.append(
273                KeyEvent.KEYCODE_MUSIC, Intent.CATEGORY_APP_MUSIC);
274        sApplicationLaunchKeyCategories.append(
275                KeyEvent.KEYCODE_CALCULATOR, Intent.CATEGORY_APP_CALCULATOR);
276    }
277
278    /**
279     * Lock protecting internal state.  Must not call out into window
280     * manager with lock held.  (This lock will be acquired in places
281     * where the window manager is calling in with its own lock held.)
282     */
283    final Object mLock = new Object();
284
285    Context mContext;
286    IWindowManager mWindowManager;
287    WindowManagerFuncs mWindowManagerFuncs;
288    PowerManager mPowerManager;
289    IStatusBarService mStatusBarService;
290    final Object mServiceAquireLock = new Object();
291    Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
292    SearchManager mSearchManager;
293
294    // Vibrator pattern for haptic feedback of a long press.
295    long[] mLongPressVibePattern;
296
297    // Vibrator pattern for haptic feedback of virtual key press.
298    long[] mVirtualKeyVibePattern;
299
300    // Vibrator pattern for a short vibration.
301    long[] mKeyboardTapVibePattern;
302
303    // Vibrator pattern for haptic feedback during boot when safe mode is disabled.
304    long[] mSafeModeDisabledVibePattern;
305
306    // Vibrator pattern for haptic feedback during boot when safe mode is enabled.
307    long[] mSafeModeEnabledVibePattern;
308
309    /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
310    boolean mEnableShiftMenuBugReports = false;
311
312    boolean mHeadless;
313    boolean mSafeMode;
314    WindowState mStatusBar = null;
315    boolean mHasSystemNavBar;
316    int mStatusBarHeight;
317    WindowState mNavigationBar = null;
318    boolean mHasNavigationBar = false;
319    boolean mCanHideNavigationBar = false;
320    boolean mNavigationBarCanMove = false; // can the navigation bar ever move to the side?
321    boolean mNavigationBarOnBottom = true; // is the navigation bar on the bottom *right now*?
322    int[] mNavigationBarHeightForRotation = new int[4];
323    int[] mNavigationBarWidthForRotation = new int[4];
324
325    WindowState mKeyguard = null;
326    KeyguardViewMediator mKeyguardMediator;
327    GlobalActions mGlobalActions;
328    volatile boolean mPowerKeyHandled; // accessed from input reader and handler thread
329    boolean mPendingPowerKeyUpCanceled;
330    Handler mHandler;
331    WindowState mLastInputMethodWindow = null;
332    WindowState mLastInputMethodTargetWindow = null;
333
334    static final int RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS = 0;
335    static final int RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW = 1;
336    static final int RECENT_APPS_BEHAVIOR_DISMISS = 2;
337    static final int RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH = 3;
338
339    RecentApplicationsDialog mRecentAppsDialog;
340    int mRecentAppsDialogHeldModifiers;
341    boolean mLanguageSwitchKeyPressed;
342
343    int mLidState = LID_ABSENT;
344    boolean mHaveBuiltInKeyboard;
345
346    boolean mSystemReady;
347    boolean mSystemBooted;
348    boolean mHdmiPlugged;
349    int mUiMode;
350    int mDockMode = Intent.EXTRA_DOCK_STATE_UNDOCKED;
351    int mLidOpenRotation;
352    int mCarDockRotation;
353    int mDeskDockRotation;
354    int mHdmiRotation;
355
356    int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE;
357    int mUserRotation = Surface.ROTATION_0;
358    boolean mAccelerometerDefault;
359
360    int mAllowAllRotations = -1;
361    boolean mCarDockEnablesAccelerometer;
362    boolean mDeskDockEnablesAccelerometer;
363    int mLidKeyboardAccessibility;
364    int mLidNavigationAccessibility;
365    boolean mLidControlsSleep;
366    int mLongPressOnPowerBehavior = -1;
367    boolean mScreenOnEarly = false;
368    boolean mScreenOnFully = false;
369    boolean mOrientationSensorEnabled = false;
370    int mLastSensorRotation = -1;
371    int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
372    boolean mHasSoftInput = false;
373
374    int mPointerLocationMode = 0; // guarded by mLock
375
376    // The last window we were told about in focusChanged.
377    WindowState mFocusedWindow;
378    IApplicationToken mFocusedApp;
379
380    private static final class PointerLocationInputEventReceiver extends InputEventReceiver {
381        private final PointerLocationView mView;
382
383        public PointerLocationInputEventReceiver(InputChannel inputChannel, Looper looper,
384                PointerLocationView view) {
385            super(inputChannel, looper);
386            mView = view;
387        }
388
389        @Override
390        public void onInputEvent(InputEvent event) {
391            boolean handled = false;
392            try {
393                if (event instanceof MotionEvent
394                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
395                    final MotionEvent motionEvent = (MotionEvent)event;
396                    mView.addPointerEvent(motionEvent);
397                    handled = true;
398                }
399            } finally {
400                finishInputEvent(event, handled);
401            }
402        }
403    }
404
405    // Pointer location view state, only modified on the mHandler Looper.
406    PointerLocationInputEventReceiver mPointerLocationInputEventReceiver;
407    PointerLocationView mPointerLocationView;
408    InputChannel mPointerLocationInputChannel;
409
410    // The current size of the screen; really; (ir)regardless of whether the status
411    // bar can be hidden or not
412    int mUnrestrictedScreenLeft, mUnrestrictedScreenTop;
413    int mUnrestrictedScreenWidth, mUnrestrictedScreenHeight;
414    // The current size of the screen; these may be different than (0,0)-(dw,dh)
415    // if the status bar can't be hidden; in that case it effectively carves out
416    // that area of the display from all other windows.
417    int mRestrictedScreenLeft, mRestrictedScreenTop;
418    int mRestrictedScreenWidth, mRestrictedScreenHeight;
419    // During layout, the current screen borders accounting for any currently
420    // visible system UI elements.
421    int mSystemLeft, mSystemTop, mSystemRight, mSystemBottom;
422    // For applications requesting stable content insets, these are them.
423    int mStableLeft, mStableTop, mStableRight, mStableBottom;
424    // For applications requesting stable content insets but have also set the
425    // fullscreen window flag, these are the stable dimensions without the status bar.
426    int mStableFullscreenLeft, mStableFullscreenTop;
427    int mStableFullscreenRight, mStableFullscreenBottom;
428    // During layout, the current screen borders with all outer decoration
429    // (status bar, input method dock) accounted for.
430    int mCurLeft, mCurTop, mCurRight, mCurBottom;
431    // During layout, the frame in which content should be displayed
432    // to the user, accounting for all screen decoration except for any
433    // space they deem as available for other content.  This is usually
434    // the same as mCur*, but may be larger if the screen decor has supplied
435    // content insets.
436    int mContentLeft, mContentTop, mContentRight, mContentBottom;
437    // During layout, the current screen borders along which input method
438    // windows are placed.
439    int mDockLeft, mDockTop, mDockRight, mDockBottom;
440    // During layout, the layer at which the doc window is placed.
441    int mDockLayer;
442    // During layout, this is the layer of the status bar.
443    int mStatusBarLayer;
444    int mLastSystemUiFlags;
445    // Bits that we are in the process of clearing, so we want to prevent
446    // them from being set by applications until everything has been updated
447    // to have them clear.
448    int mResettingSystemUiFlags = 0;
449    // Bits that we are currently always keeping cleared.
450    int mForceClearedSystemUiFlags = 0;
451    // What we last reported to system UI about whether the compatibility
452    // menu needs to be displayed.
453    boolean mLastFocusNeedsMenu = false;
454
455    FakeWindow mHideNavFakeWindow = null;
456
457    static final Rect mTmpParentFrame = new Rect();
458    static final Rect mTmpDisplayFrame = new Rect();
459    static final Rect mTmpContentFrame = new Rect();
460    static final Rect mTmpVisibleFrame = new Rect();
461    static final Rect mTmpNavigationFrame = new Rect();
462
463    WindowState mTopFullscreenOpaqueWindowState;
464    boolean mTopIsFullscreen;
465    boolean mForceStatusBar;
466    boolean mHideLockScreen;
467    boolean mDismissKeyguard;
468    boolean mHomePressed;
469    boolean mHomeLongPressed;
470    Intent mHomeIntent;
471    Intent mCarDockIntent;
472    Intent mDeskDockIntent;
473    boolean mSearchKeyShortcutPending;
474    boolean mConsumeSearchKeyUp;
475    boolean mAssistKeyLongPressed;
476
477    // support for activating the lock screen while the screen is on
478    boolean mAllowLockscreenWhenOn;
479    int mLockScreenTimeout;
480    boolean mLockScreenTimerActive;
481
482    // Behavior of ENDCALL Button.  (See Settings.System.END_BUTTON_BEHAVIOR.)
483    int mEndcallBehavior;
484
485    // Behavior of POWER button while in-call and screen on.
486    // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.)
487    int mIncallPowerBehavior;
488
489    Display mDisplay;
490
491    int mLandscapeRotation = 0;  // default landscape rotation
492    int mSeascapeRotation = 0;   // "other" landscape rotation, 180 degrees from mLandscapeRotation
493    int mPortraitRotation = 0;   // default portrait rotation
494    int mUpsideDownRotation = 0; // "other" portrait rotation
495
496    // What we do when the user long presses on home
497    private int mLongPressOnHomeBehavior = -1;
498
499    // Screenshot trigger states
500    // Time to volume and power must be pressed within this interval of each other.
501    private static final long SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS = 150;
502    private boolean mScreenshotChordEnabled;
503    private boolean mVolumeDownKeyTriggered;
504    private long mVolumeDownKeyTime;
505    private boolean mVolumeDownKeyConsumedByScreenshotChord;
506    private boolean mVolumeUpKeyTriggered;
507    private boolean mPowerKeyTriggered;
508    private long mPowerKeyTime;
509
510    ShortcutManager mShortcutManager;
511    PowerManager.WakeLock mBroadcastWakeLock;
512    boolean mHavePendingMediaKeyRepeatWithWakeLock;
513
514    // Fallback actions by key code.
515    private final SparseArray<KeyCharacterMap.FallbackAction> mFallbackActions =
516            new SparseArray<KeyCharacterMap.FallbackAction>();
517
518    private static final int MSG_ENABLE_POINTER_LOCATION = 1;
519    private static final int MSG_DISABLE_POINTER_LOCATION = 2;
520    private static final int MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK = 3;
521    private static final int MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK = 4;
522
523    private class PolicyHandler extends Handler {
524        @Override
525        public void handleMessage(Message msg) {
526            switch (msg.what) {
527                case MSG_ENABLE_POINTER_LOCATION:
528                    enablePointerLocation();
529                    break;
530                case MSG_DISABLE_POINTER_LOCATION:
531                    disablePointerLocation();
532                    break;
533                case MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK:
534                    dispatchMediaKeyWithWakeLock((KeyEvent)msg.obj);
535                    break;
536                case MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK:
537                    dispatchMediaKeyRepeatWithWakeLock((KeyEvent)msg.obj);
538                    break;
539            }
540        }
541    }
542
543    private UEventObserver mHDMIObserver = new UEventObserver() {
544        @Override
545        public void onUEvent(UEventObserver.UEvent event) {
546            setHdmiPlugged("1".equals(event.get("SWITCH_STATE")));
547        }
548    };
549
550    class SettingsObserver extends ContentObserver {
551        SettingsObserver(Handler handler) {
552            super(handler);
553        }
554
555        void observe() {
556            ContentResolver resolver = mContext.getContentResolver();
557            resolver.registerContentObserver(Settings.System.getUriFor(
558                    Settings.System.END_BUTTON_BEHAVIOR), false, this);
559            resolver.registerContentObserver(Settings.Secure.getUriFor(
560                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this);
561            resolver.registerContentObserver(Settings.System.getUriFor(
562                    Settings.System.ACCELEROMETER_ROTATION), false, this);
563            resolver.registerContentObserver(Settings.System.getUriFor(
564                    Settings.System.USER_ROTATION), false, this);
565            resolver.registerContentObserver(Settings.System.getUriFor(
566                    Settings.System.SCREEN_OFF_TIMEOUT), false, this);
567            resolver.registerContentObserver(Settings.System.getUriFor(
568                    Settings.System.POINTER_LOCATION), false, this);
569            resolver.registerContentObserver(Settings.Secure.getUriFor(
570                    Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
571            resolver.registerContentObserver(Settings.System.getUriFor(
572                    "fancy_rotation_anim"), false, this);
573            updateSettings();
574        }
575
576        @Override public void onChange(boolean selfChange) {
577            updateSettings();
578            updateRotation(false);
579        }
580    }
581
582    class MyOrientationListener extends WindowOrientationListener {
583        MyOrientationListener(Context context) {
584            super(context);
585        }
586
587        @Override
588        public void onProposedRotationChanged(int rotation) {
589            if (localLOGV) Log.v(TAG, "onProposedRotationChanged, rotation=" + rotation);
590            updateRotation(false);
591        }
592    }
593    MyOrientationListener mOrientationListener;
594
595    IStatusBarService getStatusBarService() {
596        synchronized (mServiceAquireLock) {
597            if (mStatusBarService == null) {
598                mStatusBarService = IStatusBarService.Stub.asInterface(
599                        ServiceManager.getService("statusbar"));
600            }
601            return mStatusBarService;
602        }
603    }
604
605    /*
606     * We always let the sensor be switched on by default except when
607     * the user has explicitly disabled sensor based rotation or when the
608     * screen is switched off.
609     */
610    boolean needSensorRunningLp() {
611        if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
612                || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
613                || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
614                || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
615            // If the application has explicitly requested to follow the
616            // orientation, then we need to turn the sensor or.
617            return true;
618        }
619        if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) ||
620                (mDeskDockEnablesAccelerometer && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
621                        || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
622                        || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK))) {
623            // enable accelerometer if we are docked in a dock that enables accelerometer
624            // orientation management,
625            return true;
626        }
627        if (mUserRotationMode == USER_ROTATION_LOCKED) {
628            // If the setting for using the sensor by default is enabled, then
629            // we will always leave it on.  Note that the user could go to
630            // a window that forces an orientation that does not use the
631            // sensor and in theory we could turn it off... however, when next
632            // turning it on we won't have a good value for the current
633            // orientation for a little bit, which can cause orientation
634            // changes to lag, so we'd like to keep it always on.  (It will
635            // still be turned off when the screen is off.)
636            return false;
637        }
638        return true;
639    }
640
641    /*
642     * Various use cases for invoking this function
643     * screen turning off, should always disable listeners if already enabled
644     * screen turned on and current app has sensor based orientation, enable listeners
645     * if not already enabled
646     * screen turned on and current app does not have sensor orientation, disable listeners if
647     * already enabled
648     * screen turning on and current app has sensor based orientation, enable listeners if needed
649     * screen turning on and current app has nosensor based orientation, do nothing
650     */
651    void updateOrientationListenerLp() {
652        if (!mOrientationListener.canDetectOrientation()) {
653            // If sensor is turned off or nonexistent for some reason
654            return;
655        }
656        //Could have been invoked due to screen turning on or off or
657        //change of the currently visible window's orientation
658        if (localLOGV) Log.v(TAG, "Screen status="+mScreenOnEarly+
659                ", current orientation="+mCurrentAppOrientation+
660                ", SensorEnabled="+mOrientationSensorEnabled);
661        boolean disable = true;
662        if (mScreenOnEarly) {
663            if (needSensorRunningLp()) {
664                disable = false;
665                //enable listener if not already enabled
666                if (!mOrientationSensorEnabled) {
667                    mOrientationListener.enable();
668                    if(localLOGV) Log.v(TAG, "Enabling listeners");
669                    mOrientationSensorEnabled = true;
670                }
671            }
672        }
673        //check if sensors need to be disabled
674        if (disable && mOrientationSensorEnabled) {
675            mOrientationListener.disable();
676            if(localLOGV) Log.v(TAG, "Disabling listeners");
677            mOrientationSensorEnabled = false;
678        }
679    }
680
681    private void interceptPowerKeyDown(boolean handled) {
682        mPowerKeyHandled = handled;
683        if (!handled) {
684            mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
685        }
686    }
687
688    private boolean interceptPowerKeyUp(boolean canceled) {
689        if (!mPowerKeyHandled) {
690            mHandler.removeCallbacks(mPowerLongPress);
691            return !canceled;
692        }
693        return false;
694    }
695
696    private void cancelPendingPowerKeyAction() {
697        if (!mPowerKeyHandled) {
698            mHandler.removeCallbacks(mPowerLongPress);
699        }
700        if (mPowerKeyTriggered) {
701            mPendingPowerKeyUpCanceled = true;
702        }
703    }
704
705    private void interceptScreenshotChord() {
706        if (mScreenshotChordEnabled
707                && mVolumeDownKeyTriggered && mPowerKeyTriggered && !mVolumeUpKeyTriggered) {
708            final long now = SystemClock.uptimeMillis();
709            if (now <= mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS
710                    && now <= mPowerKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) {
711                mVolumeDownKeyConsumedByScreenshotChord = true;
712                cancelPendingPowerKeyAction();
713
714                mHandler.postDelayed(mScreenshotChordLongPress,
715                        ViewConfiguration.getGlobalActionKeyTimeout());
716            }
717        }
718    }
719
720    private void cancelPendingScreenshotChordAction() {
721        mHandler.removeCallbacks(mScreenshotChordLongPress);
722    }
723
724    private final Runnable mPowerLongPress = new Runnable() {
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.collapse();
2920                                }
2921                            } catch (RemoteException ex) {
2922                                // re-acquire status bar service next time it is needed.
2923                                mStatusBarService = null;
2924                            }
2925                        }});
2926                    } else if (DEBUG_LAYOUT) {
2927                        Log.v(TAG, "Preventing status bar from hiding by policy");
2928                    }
2929                } else {
2930                    if (DEBUG_LAYOUT) Log.v(TAG, "** SHOWING status bar: top is not fullscreen");
2931                    if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
2932                }
2933            }
2934        }
2935
2936        mTopIsFullscreen = topIsFullscreen;
2937
2938        // Hide the key guard if a visible window explicitly specifies that it wants to be
2939        // displayed when the screen is locked.
2940        if (mKeyguard != null) {
2941            if (localLOGV) Log.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
2942                    + mHideLockScreen);
2943            if (mDismissKeyguard && !mKeyguardMediator.isSecure()) {
2944                if (mKeyguard.hideLw(true)) {
2945                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2946                            | FINISH_LAYOUT_REDO_CONFIG
2947                            | FINISH_LAYOUT_REDO_WALLPAPER;
2948                }
2949                if (mKeyguardMediator.isShowing()) {
2950                    mHandler.post(new Runnable() {
2951                        public void run() {
2952                            mKeyguardMediator.keyguardDone(false, false);
2953                        }
2954                    });
2955                }
2956            } else if (mHideLockScreen) {
2957                if (mKeyguard.hideLw(true)) {
2958                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2959                            | FINISH_LAYOUT_REDO_CONFIG
2960                            | FINISH_LAYOUT_REDO_WALLPAPER;
2961                }
2962                mKeyguardMediator.setHidden(true);
2963            } else {
2964                if (mKeyguard.showLw(true)) {
2965                    changes |= FINISH_LAYOUT_REDO_LAYOUT
2966                            | FINISH_LAYOUT_REDO_CONFIG
2967                            | FINISH_LAYOUT_REDO_WALLPAPER;
2968                }
2969                mKeyguardMediator.setHidden(false);
2970            }
2971        }
2972
2973        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
2974            // If the navigation bar has been hidden or shown, we need to do another
2975            // layout pass to update that window.
2976            changes |= FINISH_LAYOUT_REDO_LAYOUT;
2977        }
2978
2979        // update since mAllowLockscreenWhenOn might have changed
2980        updateLockScreenTimeout();
2981        return changes;
2982    }
2983
2984    public boolean allowAppAnimationsLw() {
2985        if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) {
2986            // If keyguard is currently visible, no reason to animate
2987            // behind it.
2988            return false;
2989        }
2990        return true;
2991    }
2992
2993    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
2994        mFocusedWindow = newFocus;
2995        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
2996            // If the navigation bar has been hidden or shown, we need to do another
2997            // layout pass to update that window.
2998            return FINISH_LAYOUT_REDO_LAYOUT;
2999        }
3000        return 0;
3001    }
3002
3003    /** {@inheritDoc} */
3004    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
3005        // do nothing if headless
3006        if (mHeadless) return;
3007
3008        // lid changed state
3009        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
3010        if (newLidState == mLidState) {
3011            return;
3012        }
3013
3014        mLidState = newLidState;
3015        applyLidSwitchState();
3016        updateRotation(true);
3017
3018        if (lidOpen) {
3019            if (keyguardIsShowingTq()) {
3020                mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(
3021                        KeyEvent.KEYCODE_POWER, mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED);
3022            } else {
3023                mPowerManager.wakeUp(SystemClock.uptimeMillis());
3024            }
3025        } else if (!mLidControlsSleep) {
3026            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3027        }
3028    }
3029
3030    void setHdmiPlugged(boolean plugged) {
3031        if (mHdmiPlugged != plugged) {
3032            mHdmiPlugged = plugged;
3033            updateRotation(true, true);
3034            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
3035            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3036            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
3037            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3038        }
3039    }
3040
3041    void initializeHdmiState() {
3042        boolean plugged = false;
3043        // watch for HDMI plug messages if the hdmi switch exists
3044        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
3045            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
3046
3047            final String filename = "/sys/class/switch/hdmi/state";
3048            FileReader reader = null;
3049            try {
3050                reader = new FileReader(filename);
3051                char[] buf = new char[15];
3052                int n = reader.read(buf);
3053                if (n > 1) {
3054                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
3055                }
3056            } catch (IOException ex) {
3057                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3058            } catch (NumberFormatException ex) {
3059                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3060            } finally {
3061                if (reader != null) {
3062                    try {
3063                        reader.close();
3064                    } catch (IOException ex) {
3065                    }
3066                }
3067            }
3068        }
3069        // This dance forces the code in setHdmiPlugged to run.
3070        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
3071        mHdmiPlugged = !plugged;
3072        setHdmiPlugged(!mHdmiPlugged);
3073    }
3074
3075    /**
3076     * @return Whether music is being played right now.
3077     */
3078    boolean isMusicActive() {
3079        final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
3080        if (am == null) {
3081            Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
3082            return false;
3083        }
3084        return am.isMusicActive();
3085    }
3086
3087    /**
3088     * Tell the audio service to adjust the volume appropriate to the event.
3089     * @param keycode
3090     */
3091    void handleVolumeKey(int stream, int keycode) {
3092        IAudioService audioService = getAudioService();
3093        if (audioService == null) {
3094            return;
3095        }
3096        try {
3097            // since audio is playing, we shouldn't have to hold a wake lock
3098            // during the call, but we do it as a precaution for the rare possibility
3099            // that the music stops right before we call this
3100            // TODO: Actually handle MUTE.
3101            mBroadcastWakeLock.acquire();
3102            audioService.adjustStreamVolume(stream,
3103                keycode == KeyEvent.KEYCODE_VOLUME_UP
3104                            ? AudioManager.ADJUST_RAISE
3105                            : AudioManager.ADJUST_LOWER,
3106                    0);
3107        } catch (RemoteException e) {
3108            Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
3109        } finally {
3110            mBroadcastWakeLock.release();
3111        }
3112    }
3113
3114    final Object mScreenshotLock = new Object();
3115    ServiceConnection mScreenshotConnection = null;
3116
3117    final Runnable mScreenshotTimeout = new Runnable() {
3118        @Override public void run() {
3119            synchronized (mScreenshotLock) {
3120                if (mScreenshotConnection != null) {
3121                    mContext.unbindService(mScreenshotConnection);
3122                    mScreenshotConnection = null;
3123                }
3124            }
3125        }
3126    };
3127
3128    // Assume this is called from the Handler thread.
3129    private void takeScreenshot() {
3130        synchronized (mScreenshotLock) {
3131            if (mScreenshotConnection != null) {
3132                return;
3133            }
3134            ComponentName cn = new ComponentName("com.android.systemui",
3135                    "com.android.systemui.screenshot.TakeScreenshotService");
3136            Intent intent = new Intent();
3137            intent.setComponent(cn);
3138            ServiceConnection conn = new ServiceConnection() {
3139                @Override
3140                public void onServiceConnected(ComponentName name, IBinder service) {
3141                    synchronized (mScreenshotLock) {
3142                        if (mScreenshotConnection != this) {
3143                            return;
3144                        }
3145                        Messenger messenger = new Messenger(service);
3146                        Message msg = Message.obtain(null, 1);
3147                        final ServiceConnection myConn = this;
3148                        Handler h = new Handler(mHandler.getLooper()) {
3149                            @Override
3150                            public void handleMessage(Message msg) {
3151                                synchronized (mScreenshotLock) {
3152                                    if (mScreenshotConnection == myConn) {
3153                                        mContext.unbindService(mScreenshotConnection);
3154                                        mScreenshotConnection = null;
3155                                        mHandler.removeCallbacks(mScreenshotTimeout);
3156                                    }
3157                                }
3158                            }
3159                        };
3160                        msg.replyTo = new Messenger(h);
3161                        msg.arg1 = msg.arg2 = 0;
3162                        if (mStatusBar != null && mStatusBar.isVisibleLw())
3163                            msg.arg1 = 1;
3164                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
3165                            msg.arg2 = 1;
3166                        try {
3167                            messenger.send(msg);
3168                        } catch (RemoteException e) {
3169                        }
3170                    }
3171                }
3172                @Override
3173                public void onServiceDisconnected(ComponentName name) {}
3174            };
3175            if (mContext.bindService(
3176                    intent, conn, Context.BIND_AUTO_CREATE, UserHandle.USER_CURRENT)) {
3177                mScreenshotConnection = conn;
3178                mHandler.postDelayed(mScreenshotTimeout, 10000);
3179            }
3180        }
3181    }
3182
3183    /** {@inheritDoc} */
3184    @Override
3185    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
3186        if (!mSystemBooted) {
3187            // If we have not yet booted, don't let key events do anything.
3188            return 0;
3189        }
3190
3191        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
3192        final boolean canceled = event.isCanceled();
3193        final int keyCode = event.getKeyCode();
3194
3195        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
3196
3197        // If screen is off then we treat the case where the keyguard is open but hidden
3198        // the same as if it were open and in front.
3199        // This will prevent any keys other than the power button from waking the screen
3200        // when the keyguard is hidden by another activity.
3201        final boolean keyguardActive = (mKeyguardMediator == null ? false :
3202                                            (isScreenOn ?
3203                                                mKeyguardMediator.isShowingAndNotHidden() :
3204                                                mKeyguardMediator.isShowing()));
3205
3206        if (keyCode == KeyEvent.KEYCODE_POWER) {
3207            policyFlags |= WindowManagerPolicy.FLAG_WAKE;
3208        }
3209        final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE
3210                | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3211
3212        if (DEBUG_INPUT) {
3213            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
3214                    + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive
3215                    + " policyFlags=" + Integer.toHexString(policyFlags)
3216                    + " isWakeKey=" + isWakeKey);
3217        }
3218
3219        if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
3220                && event.getRepeatCount() == 0) {
3221            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
3222        }
3223
3224        // Basic policy based on screen state and keyguard.
3225        // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
3226        //        is on or off, really.  We should care about whether the device is in an
3227        //        interactive state or is in suspend pretending to be "off".
3228        //        The primary screen might be turned off due to proximity sensor or
3229        //        because we are presenting media on an auxiliary screen or remotely controlling
3230        //        the device some other way (which is why we have an exemption here for injected
3231        //        events).
3232        int result;
3233        if ((isScreenOn && !mHeadless) || (isInjected && !isWakeKey)) {
3234            // When the screen is on or if the key is injected pass the key to the application.
3235            result = ACTION_PASS_TO_USER;
3236        } else {
3237            // When the screen is off and the key is not injected, determine whether
3238            // to wake the device but don't pass the key to the application.
3239            result = 0;
3240            if (down && isWakeKey) {
3241                if (keyguardActive) {
3242                    // If the keyguard is showing, let it decide what to do with the wake key.
3243                    mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode,
3244                            mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED);
3245                } else {
3246                    // Otherwise, wake the device ourselves.
3247                    result |= ACTION_WAKE_UP;
3248                }
3249            }
3250        }
3251
3252        // Handle special keys.
3253        switch (keyCode) {
3254            case KeyEvent.KEYCODE_VOLUME_DOWN:
3255            case KeyEvent.KEYCODE_VOLUME_UP:
3256            case KeyEvent.KEYCODE_VOLUME_MUTE: {
3257                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
3258                    if (down) {
3259                        if (isScreenOn && !mVolumeDownKeyTriggered
3260                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3261                            mVolumeDownKeyTriggered = true;
3262                            mVolumeDownKeyTime = event.getDownTime();
3263                            mVolumeDownKeyConsumedByScreenshotChord = false;
3264                            cancelPendingPowerKeyAction();
3265                            interceptScreenshotChord();
3266                        }
3267                    } else {
3268                        mVolumeDownKeyTriggered = false;
3269                        cancelPendingScreenshotChordAction();
3270                    }
3271                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
3272                    if (down) {
3273                        if (isScreenOn && !mVolumeUpKeyTriggered
3274                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3275                            mVolumeUpKeyTriggered = true;
3276                            cancelPendingPowerKeyAction();
3277                            cancelPendingScreenshotChordAction();
3278                        }
3279                    } else {
3280                        mVolumeUpKeyTriggered = false;
3281                        cancelPendingScreenshotChordAction();
3282                    }
3283                }
3284                if (down) {
3285                    ITelephony telephonyService = getTelephonyService();
3286                    if (telephonyService != null) {
3287                        try {
3288                            if (telephonyService.isRinging()) {
3289                                // If an incoming call is ringing, either VOLUME key means
3290                                // "silence ringer".  We handle these keys here, rather than
3291                                // in the InCallScreen, to make sure we'll respond to them
3292                                // even if the InCallScreen hasn't come to the foreground yet.
3293                                // Look for the DOWN event here, to agree with the "fallback"
3294                                // behavior in the InCallScreen.
3295                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3296                                      + " VOLUME key-down while ringing: Silence ringer!");
3297
3298                                // Silence the ringer.  (It's safe to call this
3299                                // even if the ringer has already been silenced.)
3300                                telephonyService.silenceRinger();
3301
3302                                // And *don't* pass this key thru to the current activity
3303                                // (which is probably the InCallScreen.)
3304                                result &= ~ACTION_PASS_TO_USER;
3305                                break;
3306                            }
3307                            if (telephonyService.isOffhook()
3308                                    && (result & ACTION_PASS_TO_USER) == 0) {
3309                                // If we are in call but we decided not to pass the key to
3310                                // the application, handle the volume change here.
3311                                handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
3312                                break;
3313                            }
3314                        } catch (RemoteException ex) {
3315                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3316                        }
3317                    }
3318
3319                    if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
3320                        // If music is playing but we decided not to pass the key to the
3321                        // application, handle the volume change here.
3322                        handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
3323                        break;
3324                    }
3325                }
3326                break;
3327            }
3328
3329            case KeyEvent.KEYCODE_ENDCALL: {
3330                result &= ~ACTION_PASS_TO_USER;
3331                if (down) {
3332                    ITelephony telephonyService = getTelephonyService();
3333                    boolean hungUp = false;
3334                    if (telephonyService != null) {
3335                        try {
3336                            hungUp = telephonyService.endCall();
3337                        } catch (RemoteException ex) {
3338                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3339                        }
3340                    }
3341                    interceptPowerKeyDown(!isScreenOn || hungUp);
3342                } else {
3343                    if (interceptPowerKeyUp(canceled)) {
3344                        if ((mEndcallBehavior
3345                                & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
3346                            if (goHome()) {
3347                                break;
3348                            }
3349                        }
3350                        if ((mEndcallBehavior
3351                                & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
3352                            result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3353                        }
3354                    }
3355                }
3356                break;
3357            }
3358
3359            case KeyEvent.KEYCODE_POWER: {
3360                result &= ~ACTION_PASS_TO_USER;
3361                if (down) {
3362                    if (isScreenOn && !mPowerKeyTriggered
3363                            && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3364                        mPowerKeyTriggered = true;
3365                        mPowerKeyTime = event.getDownTime();
3366                        interceptScreenshotChord();
3367                    }
3368
3369                    ITelephony telephonyService = getTelephonyService();
3370                    boolean hungUp = false;
3371                    if (telephonyService != null) {
3372                        try {
3373                            if (telephonyService.isRinging()) {
3374                                // Pressing Power while there's a ringing incoming
3375                                // call should silence the ringer.
3376                                telephonyService.silenceRinger();
3377                            } else if ((mIncallPowerBehavior
3378                                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
3379                                    && telephonyService.isOffhook()) {
3380                                // Otherwise, if "Power button ends call" is enabled,
3381                                // the Power button will hang up any current active call.
3382                                hungUp = telephonyService.endCall();
3383                            }
3384                        } catch (RemoteException ex) {
3385                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3386                        }
3387                    }
3388                    interceptPowerKeyDown(!isScreenOn || hungUp
3389                            || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered);
3390                } else {
3391                    mPowerKeyTriggered = false;
3392                    cancelPendingScreenshotChordAction();
3393                    if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) {
3394                        result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3395                    }
3396                    mPendingPowerKeyUpCanceled = false;
3397                }
3398                break;
3399            }
3400
3401            case KeyEvent.KEYCODE_MEDIA_PLAY:
3402            case KeyEvent.KEYCODE_MEDIA_PAUSE:
3403            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3404                if (down) {
3405                    ITelephony telephonyService = getTelephonyService();
3406                    if (telephonyService != null) {
3407                        try {
3408                            if (!telephonyService.isIdle()) {
3409                                // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
3410                                // to avoid music playback.
3411                                break;
3412                            }
3413                        } catch (RemoteException ex) {
3414                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3415                        }
3416                    }
3417                }
3418            case KeyEvent.KEYCODE_HEADSETHOOK:
3419            case KeyEvent.KEYCODE_MUTE:
3420            case KeyEvent.KEYCODE_MEDIA_STOP:
3421            case KeyEvent.KEYCODE_MEDIA_NEXT:
3422            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
3423            case KeyEvent.KEYCODE_MEDIA_REWIND:
3424            case KeyEvent.KEYCODE_MEDIA_RECORD:
3425            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
3426                if ((result & ACTION_PASS_TO_USER) == 0) {
3427                    // Only do this if we would otherwise not pass it to the user. In that
3428                    // case, the PhoneWindow class will do the same thing, except it will
3429                    // only do it if the showing app doesn't process the key on its own.
3430                    // Note that we need to make a copy of the key event here because the
3431                    // original key event will be recycled when we return.
3432                    mBroadcastWakeLock.acquire();
3433                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
3434                            new KeyEvent(event));
3435                    msg.setAsynchronous(true);
3436                    msg.sendToTarget();
3437                }
3438                break;
3439            }
3440
3441            case KeyEvent.KEYCODE_CALL: {
3442                if (down) {
3443                    ITelephony telephonyService = getTelephonyService();
3444                    if (telephonyService != null) {
3445                        try {
3446                            if (telephonyService.isRinging()) {
3447                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3448                                      + " CALL key-down while ringing: Answer the call!");
3449                                telephonyService.answerRingingCall();
3450
3451                                // And *don't* pass this key thru to the current activity
3452                                // (which is presumably the InCallScreen.)
3453                                result &= ~ACTION_PASS_TO_USER;
3454                            }
3455                        } catch (RemoteException ex) {
3456                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3457                        }
3458                    }
3459                }
3460                break;
3461            }
3462        }
3463        return result;
3464    }
3465
3466    /** {@inheritDoc} */
3467    @Override
3468    public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
3469        int result = 0;
3470
3471        final boolean isWakeMotion = (policyFlags
3472                & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3473        if (isWakeMotion) {
3474            if (mKeyguardMediator != null && mKeyguardMediator.isShowing()) {
3475                // If the keyguard is showing, let it decide what to do with the wake motion.
3476                mKeyguardMediator.onWakeMotionWhenKeyguardShowingTq();
3477            } else {
3478                // Otherwise, wake the device ourselves.
3479                result |= ACTION_WAKE_UP;
3480            }
3481        }
3482        return result;
3483    }
3484
3485    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
3486        if (DEBUG_INPUT) {
3487            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
3488        }
3489
3490        if (mHavePendingMediaKeyRepeatWithWakeLock) {
3491            if (DEBUG_INPUT) {
3492                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
3493            }
3494
3495            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
3496            mHavePendingMediaKeyRepeatWithWakeLock = false;
3497            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
3498        }
3499
3500        dispatchMediaKeyWithWakeLockToAudioService(event);
3501
3502        if (event.getAction() == KeyEvent.ACTION_DOWN
3503                && event.getRepeatCount() == 0) {
3504            mHavePendingMediaKeyRepeatWithWakeLock = true;
3505
3506            Message msg = mHandler.obtainMessage(
3507                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
3508            msg.setAsynchronous(true);
3509            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
3510        } else {
3511            mBroadcastWakeLock.release();
3512        }
3513    }
3514
3515    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
3516        mHavePendingMediaKeyRepeatWithWakeLock = false;
3517
3518        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
3519                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
3520        if (DEBUG_INPUT) {
3521            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
3522        }
3523
3524        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
3525        mBroadcastWakeLock.release();
3526    }
3527
3528    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
3529        if (ActivityManagerNative.isSystemReady()) {
3530            IAudioService audioService = getAudioService();
3531            if (audioService != null) {
3532                try {
3533                    audioService.dispatchMediaKeyEventUnderWakelock(event);
3534                } catch (RemoteException e) {
3535                    Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e);
3536                }
3537            }
3538        }
3539    }
3540
3541    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
3542        public void onReceive(Context context, Intent intent) {
3543            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
3544                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3545                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
3546            } else {
3547                try {
3548                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
3549                            ServiceManager.getService(Context.UI_MODE_SERVICE));
3550                    mUiMode = uiModeService.getCurrentModeType();
3551                } catch (RemoteException e) {
3552                }
3553            }
3554            updateRotation(true);
3555            updateOrientationListenerLp();
3556        }
3557    };
3558
3559    /** {@inheritDoc} */
3560    public void screenTurnedOff(int why) {
3561        EventLog.writeEvent(70000, 0);
3562        synchronized (mLock) {
3563            mScreenOnEarly = false;
3564            mScreenOnFully = false;
3565        }
3566        if (mKeyguardMediator != null) {
3567            mKeyguardMediator.onScreenTurnedOff(why);
3568        }
3569        synchronized (mLock) {
3570            updateOrientationListenerLp();
3571            updateLockScreenTimeout();
3572        }
3573    }
3574
3575    /** {@inheritDoc} */
3576    public void screenTurningOn(final ScreenOnListener screenOnListener) {
3577        EventLog.writeEvent(70000, 1);
3578        if (false) {
3579            RuntimeException here = new RuntimeException("here");
3580            here.fillInStackTrace();
3581            Slog.i(TAG, "Screen turning on...", here);
3582        }
3583        if (screenOnListener != null) {
3584            if (mKeyguardMediator != null) {
3585                try {
3586                    mWindowManager.setEventDispatching(true);
3587                } catch (RemoteException unhandled) {
3588                }
3589                mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() {
3590                    @Override public void onShown(IBinder windowToken) {
3591                        if (windowToken != null) {
3592                            try {
3593                                mWindowManager.waitForWindowDrawn(windowToken,
3594                                        new IRemoteCallback.Stub() {
3595                                    @Override public void sendResult(Bundle data) {
3596                                        Slog.i(TAG, "Lock screen displayed!");
3597                                        screenOnListener.onScreenOn();
3598                                        synchronized (mLock) {
3599                                            mScreenOnFully = true;
3600                                        }
3601                                    }
3602                                });
3603                            } catch (RemoteException e) {
3604                            }
3605                        } else {
3606                            Slog.i(TAG, "No lock screen!");
3607                            screenOnListener.onScreenOn();
3608                            synchronized (mLock) {
3609                                mScreenOnFully = true;
3610                            }
3611                        }
3612                    }
3613                });
3614            }
3615        } else {
3616            if (mKeyguardMediator != null) {
3617                // Must set mScreenOn = true.
3618                mKeyguardMediator.onScreenTurnedOn(null);
3619            }
3620            synchronized (mLock) {
3621                mScreenOnFully = true;
3622            }
3623        }
3624        synchronized (mLock) {
3625            mScreenOnEarly = true;
3626            updateOrientationListenerLp();
3627            updateLockScreenTimeout();
3628        }
3629    }
3630
3631    /** {@inheritDoc} */
3632    public boolean isScreenOnEarly() {
3633        return mScreenOnEarly;
3634    }
3635
3636    /** {@inheritDoc} */
3637    public boolean isScreenOnFully() {
3638        return mScreenOnFully;
3639    }
3640
3641    /** {@inheritDoc} */
3642    public void enableKeyguard(boolean enabled) {
3643        if (mKeyguardMediator != null) {
3644            mKeyguardMediator.setKeyguardEnabled(enabled);
3645        }
3646    }
3647
3648    /** {@inheritDoc} */
3649    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
3650        if (mKeyguardMediator != null) {
3651            mKeyguardMediator.verifyUnlock(callback);
3652        }
3653    }
3654
3655    private boolean keyguardIsShowingTq() {
3656        if (mKeyguardMediator == null) return false;
3657        return mKeyguardMediator.isShowingAndNotHidden();
3658    }
3659
3660
3661    /** {@inheritDoc} */
3662    public boolean isKeyguardLocked() {
3663        return keyguardOn();
3664    }
3665
3666    /** {@inheritDoc} */
3667    public boolean isKeyguardSecure() {
3668        if (mKeyguardMediator == null) return false;
3669        return mKeyguardMediator.isSecure();
3670    }
3671
3672    /** {@inheritDoc} */
3673    public boolean inKeyguardRestrictedKeyInputMode() {
3674        if (mKeyguardMediator == null) return false;
3675        return mKeyguardMediator.isInputRestricted();
3676    }
3677
3678    public void dismissKeyguardLw() {
3679        if (!mKeyguardMediator.isSecure()) {
3680            if (mKeyguardMediator.isShowing()) {
3681                mHandler.post(new Runnable() {
3682                    public void run() {
3683                        mKeyguardMediator.keyguardDone(false, true);
3684                    }
3685                });
3686            }
3687        }
3688    }
3689
3690    void sendCloseSystemWindows() {
3691        sendCloseSystemWindows(mContext, null);
3692    }
3693
3694    void sendCloseSystemWindows(String reason) {
3695        sendCloseSystemWindows(mContext, reason);
3696    }
3697
3698    static void sendCloseSystemWindows(Context context, String reason) {
3699        if (ActivityManagerNative.isSystemReady()) {
3700            try {
3701                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
3702            } catch (RemoteException e) {
3703            }
3704        }
3705    }
3706
3707    @Override
3708    public int rotationForOrientationLw(int orientation, int lastRotation) {
3709        if (false) {
3710            Slog.v(TAG, "rotationForOrientationLw(orient="
3711                        + orientation + ", last=" + lastRotation
3712                        + "); user=" + mUserRotation + " "
3713                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
3714                            ? "USER_ROTATION_LOCKED" : "")
3715                        );
3716        }
3717
3718        synchronized (mLock) {
3719            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
3720            if (sensorRotation < 0) {
3721                // Sensor is disabled, device probably just turned off.
3722                if (mLastSensorRotation >= 0) {
3723                    sensorRotation = mLastSensorRotation;
3724                } else {
3725                    // Sensor has never been enabled. Last resort is to use lastRotation.
3726                    sensorRotation = lastRotation;
3727                }
3728            } else {
3729                // Valid sensor data, save it away.
3730                mLastSensorRotation = sensorRotation;
3731            }
3732
3733            final int preferredRotation;
3734            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
3735                // Ignore sensor when lid switch is open and rotation is forced.
3736                preferredRotation = mLidOpenRotation;
3737            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
3738                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
3739                // Ignore sensor when in car dock unless explicitly enabled.
3740                // This case can override the behavior of NOSENSOR, and can also
3741                // enable 180 degree rotation while docked.
3742                preferredRotation = mCarDockEnablesAccelerometer
3743                        ? sensorRotation : mCarDockRotation;
3744            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
3745                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
3746                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
3747                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
3748                // Ignore sensor when in desk dock unless explicitly enabled.
3749                // This case can override the behavior of NOSENSOR, and can also
3750                // enable 180 degree rotation while docked.
3751                preferredRotation = mDeskDockEnablesAccelerometer
3752                        ? sensorRotation : mDeskDockRotation;
3753            } else if (mHdmiPlugged) {
3754                // Ignore sensor when plugged into HDMI.
3755                // Note that the dock orientation overrides the HDMI orientation.
3756                preferredRotation = mHdmiRotation;
3757            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
3758                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
3759                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED))
3760                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
3761                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
3762                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
3763                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
3764                // Otherwise, use sensor only if requested by the application or enabled
3765                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
3766                if (mAllowAllRotations < 0) {
3767                    // Can't read this during init() because the context doesn't
3768                    // have display metrics at that time so we cannot determine
3769                    // tablet vs. phone then.
3770                    mAllowAllRotations = mContext.getResources().getBoolean(
3771                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
3772                }
3773                if (sensorRotation != Surface.ROTATION_180
3774                        || mAllowAllRotations == 1
3775                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
3776                    preferredRotation = sensorRotation;
3777                } else {
3778                    preferredRotation = lastRotation;
3779                }
3780            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
3781                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
3782                // Apply rotation lock.  Does not apply to NOSENSOR.
3783                // The idea is that the user rotation expresses a weak preference for the direction
3784                // of gravity and as NOSENSOR is never affected by gravity, then neither should
3785                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
3786                preferredRotation = mUserRotation;
3787            } else {
3788                // No overriding preference.
3789                // We will do exactly what the application asked us to do.
3790                preferredRotation = -1;
3791            }
3792
3793            switch (orientation) {
3794                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
3795                    // Return portrait unless overridden.
3796                    if (isAnyPortrait(preferredRotation)) {
3797                        return preferredRotation;
3798                    }
3799                    return mPortraitRotation;
3800
3801                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
3802                    // Return landscape unless overridden.
3803                    if (isLandscapeOrSeascape(preferredRotation)) {
3804                        return preferredRotation;
3805                    }
3806                    return mLandscapeRotation;
3807
3808                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
3809                    // Return reverse portrait unless overridden.
3810                    if (isAnyPortrait(preferredRotation)) {
3811                        return preferredRotation;
3812                    }
3813                    return mUpsideDownRotation;
3814
3815                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
3816                    // Return seascape unless overridden.
3817                    if (isLandscapeOrSeascape(preferredRotation)) {
3818                        return preferredRotation;
3819                    }
3820                    return mSeascapeRotation;
3821
3822                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
3823                    // Return either landscape rotation.
3824                    if (isLandscapeOrSeascape(preferredRotation)) {
3825                        return preferredRotation;
3826                    }
3827                    if (isLandscapeOrSeascape(lastRotation)) {
3828                        return lastRotation;
3829                    }
3830                    return mLandscapeRotation;
3831
3832                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
3833                    // Return either portrait rotation.
3834                    if (isAnyPortrait(preferredRotation)) {
3835                        return preferredRotation;
3836                    }
3837                    if (isAnyPortrait(lastRotation)) {
3838                        return lastRotation;
3839                    }
3840                    return mPortraitRotation;
3841
3842                default:
3843                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
3844                    // just return the preferred orientation we already calculated.
3845                    if (preferredRotation >= 0) {
3846                        return preferredRotation;
3847                    }
3848                    return Surface.ROTATION_0;
3849            }
3850        }
3851    }
3852
3853    @Override
3854    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
3855        switch (orientation) {
3856            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
3857            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
3858            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
3859                return isAnyPortrait(rotation);
3860
3861            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
3862            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
3863            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
3864                return isLandscapeOrSeascape(rotation);
3865
3866            default:
3867                return true;
3868        }
3869    }
3870
3871    @Override
3872    public void setRotationLw(int rotation) {
3873        mOrientationListener.setCurrentRotation(rotation);
3874    }
3875
3876    private boolean isLandscapeOrSeascape(int rotation) {
3877        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
3878    }
3879
3880    private boolean isAnyPortrait(int rotation) {
3881        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
3882    }
3883
3884
3885    // User rotation: to be used when all else fails in assigning an orientation to the device
3886    public void setUserRotationMode(int mode, int rot) {
3887        ContentResolver res = mContext.getContentResolver();
3888
3889        // mUserRotationMode and mUserRotation will be assigned by the content observer
3890        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
3891            Settings.System.putInt(res,
3892                    Settings.System.USER_ROTATION,
3893                    rot);
3894            Settings.System.putInt(res,
3895                    Settings.System.ACCELEROMETER_ROTATION,
3896                    0);
3897        } else {
3898            Settings.System.putInt(res,
3899                    Settings.System.ACCELEROMETER_ROTATION,
3900                    1);
3901        }
3902    }
3903
3904    public void setSafeMode(boolean safeMode) {
3905        mSafeMode = safeMode;
3906        performHapticFeedbackLw(null, safeMode
3907                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
3908                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
3909    }
3910
3911    static long[] getLongIntArray(Resources r, int resid) {
3912        int[] ar = r.getIntArray(resid);
3913        if (ar == null) {
3914            return null;
3915        }
3916        long[] out = new long[ar.length];
3917        for (int i=0; i<ar.length; i++) {
3918            out[i] = ar[i];
3919        }
3920        return out;
3921    }
3922
3923    /** {@inheritDoc} */
3924    public void systemReady() {
3925        if (mKeyguardMediator != null) {
3926            // tell the keyguard
3927            mKeyguardMediator.onSystemReady();
3928        }
3929        synchronized (mLock) {
3930            updateOrientationListenerLp();
3931            mSystemReady = true;
3932            mHandler.post(new Runnable() {
3933                public void run() {
3934                    updateSettings();
3935                }
3936            });
3937        }
3938    }
3939
3940    /** {@inheritDoc} */
3941    public void systemBooted() {
3942        synchronized (mLock) {
3943            mSystemBooted = true;
3944        }
3945    }
3946
3947    ProgressDialog mBootMsgDialog = null;
3948
3949    /** {@inheritDoc} */
3950    public void showBootMessage(final CharSequence msg, final boolean always) {
3951        if (mHeadless) return;
3952        mHandler.post(new Runnable() {
3953            @Override public void run() {
3954                if (mBootMsgDialog == null) {
3955                    mBootMsgDialog = new ProgressDialog(mContext) {
3956                        // This dialog will consume all events coming in to
3957                        // it, to avoid it trying to do things too early in boot.
3958                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
3959                            return true;
3960                        }
3961                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
3962                            return true;
3963                        }
3964                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
3965                            return true;
3966                        }
3967                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
3968                            return true;
3969                        }
3970                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
3971                            return true;
3972                        }
3973                        @Override public boolean dispatchPopulateAccessibilityEvent(
3974                                AccessibilityEvent event) {
3975                            return true;
3976                        }
3977                    };
3978                    mBootMsgDialog.setTitle(R.string.android_upgrading_title);
3979                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
3980                    mBootMsgDialog.setIndeterminate(true);
3981                    mBootMsgDialog.getWindow().setType(
3982                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
3983                    mBootMsgDialog.getWindow().addFlags(
3984                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
3985                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
3986                    mBootMsgDialog.getWindow().setDimAmount(1);
3987                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
3988                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
3989                    mBootMsgDialog.getWindow().setAttributes(lp);
3990                    mBootMsgDialog.setCancelable(false);
3991                    mBootMsgDialog.show();
3992                }
3993                mBootMsgDialog.setMessage(msg);
3994            }
3995        });
3996    }
3997
3998    /** {@inheritDoc} */
3999    public void hideBootMessages() {
4000        mHandler.post(new Runnable() {
4001            @Override public void run() {
4002                if (mBootMsgDialog != null) {
4003                    mBootMsgDialog.dismiss();
4004                    mBootMsgDialog = null;
4005                }
4006            }
4007        });
4008    }
4009
4010    /** {@inheritDoc} */
4011    public void userActivity() {
4012        // ***************************************
4013        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
4014        // ***************************************
4015        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
4016        // WITH ITS LOCKS HELD.
4017        //
4018        // This code must be VERY careful about the locks
4019        // it acquires.
4020        // In fact, the current code acquires way too many,
4021        // and probably has lurking deadlocks.
4022
4023        synchronized (mScreenLockTimeout) {
4024            if (mLockScreenTimerActive) {
4025                // reset the timer
4026                mHandler.removeCallbacks(mScreenLockTimeout);
4027                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4028            }
4029        }
4030    }
4031
4032    Runnable mScreenLockTimeout = new Runnable() {
4033        public void run() {
4034            synchronized (this) {
4035                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
4036                if (mKeyguardMediator != null) {
4037                    mKeyguardMediator.doKeyguardTimeout();
4038                }
4039                mLockScreenTimerActive = false;
4040            }
4041        }
4042    };
4043
4044    public void lockNow() {
4045        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
4046        mHandler.removeCallbacks(mScreenLockTimeout);
4047        mHandler.post(mScreenLockTimeout);
4048    }
4049
4050    private void updateLockScreenTimeout() {
4051        synchronized (mScreenLockTimeout) {
4052            boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly &&
4053                    mKeyguardMediator != null && mKeyguardMediator.isSecure());
4054            if (mLockScreenTimerActive != enable) {
4055                if (enable) {
4056                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
4057                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4058                } else {
4059                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
4060                    mHandler.removeCallbacks(mScreenLockTimeout);
4061                }
4062                mLockScreenTimerActive = enable;
4063            }
4064        }
4065    }
4066
4067    /** {@inheritDoc} */
4068    public void enableScreenAfterBoot() {
4069        readLidState();
4070        applyLidSwitchState();
4071        updateRotation(true);
4072    }
4073
4074    private void applyLidSwitchState() {
4075        if (mLidState == LID_CLOSED && mLidControlsSleep) {
4076            mPowerManager.goToSleep(SystemClock.uptimeMillis());
4077        }
4078    }
4079
4080    void updateRotation(boolean alwaysSendConfiguration) {
4081        try {
4082            //set orientation on WindowManager
4083            mWindowManager.updateRotation(alwaysSendConfiguration, false);
4084        } catch (RemoteException e) {
4085            // Ignore
4086        }
4087    }
4088
4089    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
4090        try {
4091            //set orientation on WindowManager
4092            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
4093        } catch (RemoteException e) {
4094            // Ignore
4095        }
4096    }
4097
4098    /**
4099     * Return an Intent to launch the currently active dock app as home.  Returns
4100     * null if the standard home should be launched, which is the case if any of the following is
4101     * true:
4102     * <ul>
4103     *  <li>The device is not in either car mode or desk mode
4104     *  <li>The device is in car mode but ENABLE_CAR_DOCK_HOME_CAPTURE is false
4105     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
4106     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
4107     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
4108     * </ul>
4109     * @return
4110     */
4111    Intent createHomeDockIntent() {
4112        Intent intent = null;
4113
4114        // What home does is based on the mode, not the dock state.  That
4115        // is, when in car mode you should be taken to car home regardless
4116        // of whether we are actually in a car dock.
4117        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
4118            if (ENABLE_CAR_DOCK_HOME_CAPTURE) {
4119                intent = mCarDockIntent;
4120            }
4121        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
4122            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
4123                intent = mDeskDockIntent;
4124            }
4125        }
4126
4127        if (intent == null) {
4128            return null;
4129        }
4130
4131        ActivityInfo ai = intent.resolveActivityInfo(
4132                mContext.getPackageManager(), PackageManager.GET_META_DATA);
4133        if (ai == null) {
4134            return null;
4135        }
4136
4137        if (ai.metaData != null && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
4138            intent = new Intent(intent);
4139            intent.setClassName(ai.packageName, ai.name);
4140            return intent;
4141        }
4142
4143        return null;
4144    }
4145
4146    void startDockOrHome() {
4147        Intent dock = createHomeDockIntent();
4148        if (dock != null) {
4149            try {
4150                mContext.startActivity(dock);
4151                return;
4152            } catch (ActivityNotFoundException e) {
4153            }
4154        }
4155        mContext.startActivity(mHomeIntent);
4156    }
4157
4158    /**
4159     * goes to the home screen
4160     * @return whether it did anything
4161     */
4162    boolean goHome() {
4163        if (false) {
4164            // This code always brings home to the front.
4165            try {
4166                ActivityManagerNative.getDefault().stopAppSwitches();
4167            } catch (RemoteException e) {
4168            }
4169            sendCloseSystemWindows();
4170            startDockOrHome();
4171        } else {
4172            // This code brings home to the front or, if it is already
4173            // at the front, puts the device to sleep.
4174            try {
4175                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
4176                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
4177                    Log.d(TAG, "UTS-TEST-MODE");
4178                } else {
4179                    ActivityManagerNative.getDefault().stopAppSwitches();
4180                    sendCloseSystemWindows();
4181                    Intent dock = createHomeDockIntent();
4182                    if (dock != null) {
4183                        int result = ActivityManagerNative.getDefault()
4184                                .startActivity(null, dock,
4185                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
4186                                        null, null, 0,
4187                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4188                                        null, null, null);
4189                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4190                            return false;
4191                        }
4192                    }
4193                }
4194                int result = ActivityManagerNative.getDefault()
4195                        .startActivity(null, mHomeIntent,
4196                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
4197                                null, null, 0,
4198                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4199                                null, null, null);
4200                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4201                    return false;
4202                }
4203            } catch (RemoteException ex) {
4204                // bummer, the activity manager, which is in this process, is dead
4205            }
4206        }
4207        return true;
4208    }
4209
4210    public void setCurrentOrientationLw(int newOrientation) {
4211        synchronized (mLock) {
4212            if (newOrientation != mCurrentAppOrientation) {
4213                mCurrentAppOrientation = newOrientation;
4214                updateOrientationListenerLp();
4215            }
4216        }
4217    }
4218
4219    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
4220        final boolean hapticsDisabled = Settings.System.getInt(mContext.getContentResolver(),
4221                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 0;
4222        if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
4223            return false;
4224        }
4225        long[] pattern = null;
4226        switch (effectId) {
4227            case HapticFeedbackConstants.LONG_PRESS:
4228                pattern = mLongPressVibePattern;
4229                break;
4230            case HapticFeedbackConstants.VIRTUAL_KEY:
4231                pattern = mVirtualKeyVibePattern;
4232                break;
4233            case HapticFeedbackConstants.KEYBOARD_TAP:
4234                pattern = mKeyboardTapVibePattern;
4235                break;
4236            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
4237                pattern = mSafeModeDisabledVibePattern;
4238                break;
4239            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
4240                pattern = mSafeModeEnabledVibePattern;
4241                break;
4242            default:
4243                return false;
4244        }
4245        if (pattern.length == 1) {
4246            // One-shot vibration
4247            mVibrator.vibrate(pattern[0]);
4248        } else {
4249            // Pattern vibration
4250            mVibrator.vibrate(pattern, -1);
4251        }
4252        return true;
4253    }
4254
4255    public void screenOnStartedLw() {
4256    }
4257
4258    public void screenOnStoppedLw() {
4259        if (mPowerManager.isScreenOn()) {
4260            if (mKeyguardMediator != null && !mKeyguardMediator.isShowingAndNotHidden()) {
4261                long curTime = SystemClock.uptimeMillis();
4262                mPowerManager.userActivity(curTime, false);
4263            }
4264        }
4265    }
4266
4267    public boolean allowKeyRepeat() {
4268        // disable key repeat when screen is off
4269        return mScreenOnEarly;
4270    }
4271
4272    private int updateSystemUiVisibilityLw() {
4273        // If there is no window focused, there will be nobody to handle the events
4274        // anyway, so just hang on in whatever state we're in until things settle down.
4275        if (mFocusedWindow == null) {
4276            return 0;
4277        }
4278        final int visibility = mFocusedWindow.getSystemUiVisibility()
4279                & ~mResettingSystemUiFlags
4280                & ~mForceClearedSystemUiFlags;
4281        int diff = visibility ^ mLastSystemUiFlags;
4282        final boolean needsMenu = mFocusedWindow.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
4283        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
4284                && mFocusedApp == mFocusedWindow.getAppToken()) {
4285            return 0;
4286        }
4287        mLastSystemUiFlags = visibility;
4288        mLastFocusNeedsMenu = needsMenu;
4289        mFocusedApp = mFocusedWindow.getAppToken();
4290        mHandler.post(new Runnable() {
4291                public void run() {
4292                    try {
4293                        IStatusBarService statusbar = getStatusBarService();
4294                        if (statusbar != null) {
4295                            statusbar.setSystemUiVisibility(visibility, 0xffffffff);
4296                            statusbar.topAppWindowChanged(needsMenu);
4297                        }
4298                    } catch (RemoteException e) {
4299                        // re-acquire status bar service next time it is needed.
4300                        mStatusBarService = null;
4301                    }
4302                }
4303            });
4304        return diff;
4305    }
4306
4307    // Use this instead of checking config_showNavigationBar so that it can be consistently
4308    // overridden by qemu.hw.mainkeys in the emulator.
4309    public boolean hasNavigationBar() {
4310        return mHasNavigationBar;
4311    }
4312
4313    @Override
4314    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
4315        mLastInputMethodWindow = ime;
4316        mLastInputMethodTargetWindow = target;
4317    }
4318
4319    public boolean canMagnifyWindow(WindowManager.LayoutParams attrs) {
4320        switch (attrs.type) {
4321            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
4322            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
4323            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
4324            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
4325                return false;
4326            }
4327        }
4328        return true;
4329    }
4330
4331    public void dump(String prefix, PrintWriter pw, String[] args) {
4332        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
4333                pw.print(" mSystemReady="); pw.print(mSystemReady);
4334                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
4335        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
4336                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
4337                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
4338        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
4339                || mForceClearedSystemUiFlags != 0) {
4340            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
4341                    pw.print(Integer.toHexString(mLastSystemUiFlags));
4342                    pw.print(" mResettingSystemUiFlags=0x");
4343                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
4344                    pw.print(" mForceClearedSystemUiFlags=0x");
4345                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
4346        }
4347        if (mLastFocusNeedsMenu) {
4348            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
4349                    pw.println(mLastFocusNeedsMenu);
4350        }
4351        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
4352                pw.print(" mDockMode="); pw.print(mDockMode);
4353                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
4354                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
4355        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
4356                pw.print(" mUserRotation="); pw.print(mUserRotation);
4357                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
4358        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
4359        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
4360                pw.print(mCarDockEnablesAccelerometer);
4361                pw.print(" mDeskDockEnablesAccelerometer=");
4362                pw.println(mDeskDockEnablesAccelerometer);
4363        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
4364                pw.print(mLidKeyboardAccessibility);
4365                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
4366                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
4367        pw.print(prefix); pw.print("mLongPressOnPowerBehavior=");
4368                pw.print(mLongPressOnPowerBehavior);
4369                pw.print(" mHasSoftInput="); pw.println(mHasSoftInput);
4370        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
4371                pw.print(" mScreenOnFully="); pw.print(mScreenOnFully);
4372                pw.print(" mOrientationSensorEnabled="); pw.println(mOrientationSensorEnabled);
4373        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
4374                pw.print(","); pw.print(mUnrestrictedScreenTop);
4375                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
4376                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
4377        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
4378                pw.print(","); pw.print(mRestrictedScreenTop);
4379                pw.print(") "); pw.print(mRestrictedScreenWidth);
4380                pw.print("x"); pw.println(mRestrictedScreenHeight);
4381        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
4382                pw.print(","); pw.print(mStableFullscreenTop);
4383                pw.print(")-("); pw.print(mStableFullscreenRight);
4384                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
4385        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
4386                pw.print(","); pw.print(mStableTop);
4387                pw.print(")-("); pw.print(mStableRight);
4388                pw.print(","); pw.print(mStableBottom); pw.println(")");
4389        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
4390                pw.print(","); pw.print(mSystemTop);
4391                pw.print(")-("); pw.print(mSystemRight);
4392                pw.print(","); pw.print(mSystemBottom); pw.println(")");
4393        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
4394                pw.print(","); pw.print(mCurTop);
4395                pw.print(")-("); pw.print(mCurRight);
4396                pw.print(","); pw.print(mCurBottom); pw.println(")");
4397        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
4398                pw.print(","); pw.print(mContentTop);
4399                pw.print(")-("); pw.print(mContentRight);
4400                pw.print(","); pw.print(mContentBottom); pw.println(")");
4401        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
4402                pw.print(","); pw.print(mDockTop);
4403                pw.print(")-("); pw.print(mDockRight);
4404                pw.print(","); pw.print(mDockBottom); pw.println(")");
4405        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
4406                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
4407        pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
4408                pw.println(mTopFullscreenOpaqueWindowState);
4409        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
4410                pw.print(" mForceStatusBar="); pw.print(mForceStatusBar);
4411                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
4412        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
4413                pw.print(" mHomePressed="); pw.println(mHomePressed);
4414        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
4415                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
4416                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
4417        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
4418                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
4419                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
4420        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
4421                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
4422        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
4423                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
4424    }
4425}
4426