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