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