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