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