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