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