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