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