PhoneWindowManager.java revision 73bad0ec973d4616fa77536f59747c503d55109a
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) Log.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) Log.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) Log.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) Log.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) Log.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                hideKeyguardScrim();
1726                break;
1727            case TYPE_KEYGUARD_SCRIM:
1728                if (mKeyguardScrim != null) {
1729                    return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
1730                }
1731                mKeyguardScrim = win;
1732                break;
1733
1734        }
1735        return WindowManagerGlobal.ADD_OKAY;
1736    }
1737
1738    /** {@inheritDoc} */
1739    public void removeWindowLw(WindowState win) {
1740        if (mStatusBar == win) {
1741            mStatusBar = null;
1742        } else if (mKeyguard == win) {
1743            Log.v(TAG, "Removing keyguard window (Did it crash?)");
1744            mKeyguard = null;
1745            showKeyguardScrimLw();
1746        } else if (mKeyguardScrim == win) {
1747            Log.v(TAG, "Removing keyguard scrim");
1748            mKeyguardScrim = null;
1749        } if (mNavigationBar == win) {
1750            mNavigationBar = null;
1751        }
1752    }
1753
1754    private void showKeyguardScrimLw() {
1755        Log.v(TAG, "*** SHOWING KEYGUARD SCRIM ***");
1756    }
1757
1758    private void hideKeyguardScrim() {
1759        Log.v(TAG, "*** HIDING KEYGUARD SCRIM ***");
1760    }
1761
1762    static final boolean PRINT_ANIM = false;
1763
1764    /** {@inheritDoc} */
1765    @Override
1766    public int selectAnimationLw(WindowState win, int transit) {
1767        if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
1768              + ": transit=" + transit);
1769        if (win == mStatusBar) {
1770            if (transit == TRANSIT_EXIT
1771                    || transit == TRANSIT_HIDE) {
1772                return R.anim.dock_top_exit;
1773            } else if (transit == TRANSIT_ENTER
1774                    || transit == TRANSIT_SHOW) {
1775                return R.anim.dock_top_enter;
1776            }
1777        } else if (win == mNavigationBar) {
1778            // This can be on either the bottom or the right.
1779            if (mNavigationBarOnBottom) {
1780                if (transit == TRANSIT_EXIT
1781                        || transit == TRANSIT_HIDE) {
1782                    return R.anim.dock_bottom_exit;
1783                } else if (transit == TRANSIT_ENTER
1784                        || transit == TRANSIT_SHOW) {
1785                    return R.anim.dock_bottom_enter;
1786                }
1787            } else {
1788                if (transit == TRANSIT_EXIT
1789                        || transit == TRANSIT_HIDE) {
1790                    return R.anim.dock_right_exit;
1791                } else if (transit == TRANSIT_ENTER
1792                        || transit == TRANSIT_SHOW) {
1793                    return R.anim.dock_right_enter;
1794                }
1795            }
1796        }
1797
1798        if (transit == TRANSIT_PREVIEW_DONE) {
1799            if (win.hasAppShownWindows()) {
1800                if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
1801                return com.android.internal.R.anim.app_starting_exit;
1802            }
1803        } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
1804                && transit == TRANSIT_ENTER) {
1805            // Special case: we are animating in a dream, while the keyguard
1806            // is shown.  We don't want an animation on the dream, because
1807            // we need it shown immediately with the keyguard animating away
1808            // to reveal it.
1809            return -1;
1810        }
1811
1812        return 0;
1813    }
1814
1815    @Override
1816    public void selectRotationAnimationLw(int anim[]) {
1817        if (PRINT_ANIM) Slog.i(TAG, "selectRotationAnimation mTopFullscreen="
1818                + mTopFullscreenOpaqueWindowState + " rotationAnimation="
1819                + (mTopFullscreenOpaqueWindowState == null ?
1820                        "0" : mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation));
1821        if (mTopFullscreenOpaqueWindowState != null && mTopIsFullscreen) {
1822            switch (mTopFullscreenOpaqueWindowState.getAttrs().rotationAnimation) {
1823                case ROTATION_ANIMATION_CROSSFADE:
1824                    anim[0] = R.anim.rotation_animation_xfade_exit;
1825                    anim[1] = R.anim.rotation_animation_enter;
1826                    break;
1827                case ROTATION_ANIMATION_JUMPCUT:
1828                    anim[0] = R.anim.rotation_animation_jump_exit;
1829                    anim[1] = R.anim.rotation_animation_enter;
1830                    break;
1831                case ROTATION_ANIMATION_ROTATE:
1832                default:
1833                    anim[0] = anim[1] = 0;
1834                    break;
1835            }
1836        } else {
1837            anim[0] = anim[1] = 0;
1838        }
1839    }
1840
1841    @Override
1842    public boolean validateRotationAnimationLw(int exitAnimId, int enterAnimId,
1843            boolean forceDefault) {
1844        switch (exitAnimId) {
1845            case R.anim.rotation_animation_xfade_exit:
1846            case R.anim.rotation_animation_jump_exit:
1847                // These are the only cases that matter.
1848                if (forceDefault) {
1849                    return false;
1850                }
1851                int anim[] = new int[2];
1852                selectRotationAnimationLw(anim);
1853                return (exitAnimId == anim[0] && enterAnimId == anim[1]);
1854            default:
1855                return true;
1856        }
1857    }
1858
1859    @Override
1860    public Animation createForceHideEnterAnimation(boolean onWallpaper) {
1861        return AnimationUtils.loadAnimation(mContext, onWallpaper
1862                ? com.android.internal.R.anim.lock_screen_wallpaper_behind_enter
1863                : com.android.internal.R.anim.lock_screen_behind_enter);
1864    }
1865
1866    private static void awakenDreams() {
1867        IDreamManager dreamManager = getDreamManager();
1868        if (dreamManager != null) {
1869            try {
1870                dreamManager.awaken();
1871            } catch (RemoteException e) {
1872                // fine, stay asleep then
1873            }
1874        }
1875    }
1876
1877    static IDreamManager getDreamManager() {
1878        return IDreamManager.Stub.asInterface(
1879                ServiceManager.checkService(DreamService.DREAM_SERVICE));
1880    }
1881
1882    static ITelephony getTelephonyService() {
1883        return ITelephony.Stub.asInterface(
1884                ServiceManager.checkService(Context.TELEPHONY_SERVICE));
1885    }
1886
1887    static IAudioService getAudioService() {
1888        IAudioService audioService = IAudioService.Stub.asInterface(
1889                ServiceManager.checkService(Context.AUDIO_SERVICE));
1890        if (audioService == null) {
1891            Log.w(TAG, "Unable to find IAudioService interface.");
1892        }
1893        return audioService;
1894    }
1895
1896    boolean keyguardOn() {
1897        return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode();
1898    }
1899
1900    private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
1901            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
1902            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
1903        };
1904
1905    /** {@inheritDoc} */
1906    @Override
1907    public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
1908        final boolean keyguardOn = keyguardOn();
1909        final int keyCode = event.getKeyCode();
1910        final int repeatCount = event.getRepeatCount();
1911        final int metaState = event.getMetaState();
1912        final int flags = event.getFlags();
1913        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
1914        final boolean canceled = event.isCanceled();
1915
1916        if (DEBUG_INPUT) {
1917            Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
1918                    + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
1919                    + " canceled=" + canceled);
1920        }
1921
1922        // If we think we might have a volume down & power key chord on the way
1923        // but we're not sure, then tell the dispatcher to wait a little while and
1924        // try again later before dispatching.
1925        if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
1926            if (mVolumeDownKeyTriggered && !mPowerKeyTriggered) {
1927                final long now = SystemClock.uptimeMillis();
1928                final long timeoutTime = mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
1929                if (now < timeoutTime) {
1930                    return timeoutTime - now;
1931                }
1932            }
1933            if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
1934                    && mVolumeDownKeyConsumedByScreenshotChord) {
1935                if (!down) {
1936                    mVolumeDownKeyConsumedByScreenshotChord = false;
1937                }
1938                return -1;
1939            }
1940        }
1941
1942        // First we always handle the home key here, so applications
1943        // can never break it, although if keyguard is on, we do let
1944        // it handle it, because that gives us the correct 5 second
1945        // timeout.
1946        if (keyCode == KeyEvent.KEYCODE_HOME) {
1947
1948            // If we have released the home key, and didn't do anything else
1949            // while it was pressed, then it is time to go home!
1950            if (!down) {
1951                final boolean homeWasLongPressed = mHomeLongPressed;
1952                mHomePressed = false;
1953                mHomeLongPressed = false;
1954                if (!homeWasLongPressed) {
1955                    if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) {
1956                        try {
1957                            IStatusBarService statusbar = getStatusBarService();
1958                            if (statusbar != null) {
1959                                statusbar.cancelPreloadRecentApps();
1960                            }
1961                        } catch (RemoteException e) {
1962                            Slog.e(TAG, "RemoteException when showing recent apps", e);
1963                            // re-acquire status bar service next time it is needed.
1964                            mStatusBarService = null;
1965                        }
1966                    }
1967
1968                    mHomePressed = false;
1969                    if (!canceled) {
1970                        // If an incoming call is ringing, HOME is totally disabled.
1971                        // (The user is already on the InCallScreen at this point,
1972                        // and his ONLY options are to answer or reject the call.)
1973                        boolean incomingRinging = false;
1974                        try {
1975                            ITelephony telephonyService = getTelephonyService();
1976                            if (telephonyService != null) {
1977                                incomingRinging = telephonyService.isRinging();
1978                            }
1979                        } catch (RemoteException ex) {
1980                            Log.w(TAG, "RemoteException from getPhoneInterface()", ex);
1981                        }
1982
1983                        if (incomingRinging) {
1984                            Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
1985                        } else {
1986                            launchHomeFromHotKey();
1987                        }
1988                    } else {
1989                        Log.i(TAG, "Ignoring HOME; event canceled.");
1990                    }
1991                    return -1;
1992                }
1993            }
1994
1995            // If a system window has focus, then it doesn't make sense
1996            // right now to interact with applications.
1997            WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
1998            if (attrs != null) {
1999                final int type = attrs.type;
2000                if (type == WindowManager.LayoutParams.TYPE_KEYGUARD
2001                        || type == WindowManager.LayoutParams.TYPE_KEYGUARD_SCRIM
2002                        || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {
2003                    // the "app" is keyguard, so give it the key
2004                    return 0;
2005                }
2006                final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
2007                for (int i=0; i<typeCount; i++) {
2008                    if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
2009                        // don't do anything, but also don't pass it to the app
2010                        return -1;
2011                    }
2012                }
2013            }
2014            if (down) {
2015                if (!mHomePressed && mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
2016                    try {
2017                        IStatusBarService statusbar = getStatusBarService();
2018                        if (statusbar != null) {
2019                            statusbar.preloadRecentApps();
2020                        }
2021                    } catch (RemoteException e) {
2022                        Slog.e(TAG, "RemoteException when preloading recent apps", e);
2023                        // re-acquire status bar service next time it is needed.
2024                        mStatusBarService = null;
2025                    }
2026                }
2027                if (repeatCount == 0) {
2028                    mHomePressed = true;
2029                } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
2030                    if (!keyguardOn) {
2031                        handleLongPressOnHome();
2032                    }
2033                }
2034            }
2035            return -1;
2036        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
2037            // Hijack modified menu keys for debugging features
2038            final int chordBug = KeyEvent.META_SHIFT_ON;
2039
2040            if (down && repeatCount == 0) {
2041                if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
2042                    Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
2043                    mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
2044                            null, null, null, 0, null, null);
2045                    return -1;
2046                } else if (SHOW_PROCESSES_ON_ALT_MENU &&
2047                        (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
2048                    Intent service = new Intent();
2049                    service.setClassName(mContext, "com.android.server.LoadAverageService");
2050                    ContentResolver res = mContext.getContentResolver();
2051                    boolean shown = Settings.Global.getInt(
2052                            res, Settings.Global.SHOW_PROCESSES, 0) != 0;
2053                    if (!shown) {
2054                        mContext.startService(service);
2055                    } else {
2056                        mContext.stopService(service);
2057                    }
2058                    Settings.Global.putInt(
2059                            res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
2060                    return -1;
2061                }
2062            }
2063        } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
2064            if (down) {
2065                if (repeatCount == 0) {
2066                    mSearchKeyShortcutPending = true;
2067                    mConsumeSearchKeyUp = false;
2068                }
2069            } else {
2070                mSearchKeyShortcutPending = false;
2071                if (mConsumeSearchKeyUp) {
2072                    mConsumeSearchKeyUp = false;
2073                    return -1;
2074                }
2075            }
2076            return 0;
2077        } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
2078            if (!keyguardOn) {
2079                try {
2080                    IStatusBarService statusbar = getStatusBarService();
2081                    if (statusbar != null) {
2082                        if (down && repeatCount == 0) {
2083                            statusbar.preloadRecentApps();
2084                        } else if (!down) {
2085                            statusbar.toggleRecentApps();
2086                        }
2087                    }
2088                } catch (RemoteException e) {
2089                    Slog.e(TAG, "RemoteException when preloading recent apps", e);
2090                    // re-acquire status bar service next time it is needed.
2091                    mStatusBarService = null;
2092                }
2093            }
2094            return -1;
2095        } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
2096            if (down) {
2097                if (repeatCount == 0) {
2098                    mAssistKeyLongPressed = false;
2099                } else if (repeatCount == 1) {
2100                    mAssistKeyLongPressed = true;
2101                    if (!keyguardOn) {
2102                         launchAssistLongPressAction();
2103                    }
2104                }
2105            } else {
2106                if (mAssistKeyLongPressed) {
2107                    mAssistKeyLongPressed = false;
2108                } else {
2109                    if (!keyguardOn) {
2110                        launchAssistAction();
2111                    }
2112                }
2113            }
2114            return -1;
2115        } else if (keyCode == KeyEvent.KEYCODE_SYSRQ) {
2116            if (down && repeatCount == 0) {
2117                mHandler.post(mScreenshotRunnable);
2118            }
2119            return -1;
2120        } else if (keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP
2121                || keyCode == KeyEvent.KEYCODE_BRIGHTNESS_DOWN) {
2122            if (down) {
2123                int direction = keyCode == KeyEvent.KEYCODE_BRIGHTNESS_UP ? 1 : -1;
2124
2125                // Disable autobrightness if it's on
2126                int auto = Settings.System.getIntForUser(
2127                        mContext.getContentResolver(),
2128                        Settings.System.SCREEN_BRIGHTNESS_MODE,
2129                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
2130                        UserHandle.USER_CURRENT_OR_SELF);
2131                if (auto != 0) {
2132                    Settings.System.putIntForUser(mContext.getContentResolver(),
2133                            Settings.System.SCREEN_BRIGHTNESS_MODE,
2134                            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,
2135                            UserHandle.USER_CURRENT_OR_SELF);
2136                }
2137
2138                int min = mPowerManager.getMinimumScreenBrightnessSetting();
2139                int max = mPowerManager.getMaximumScreenBrightnessSetting();
2140                int step = (max - min + BRIGHTNESS_STEPS - 1) / BRIGHTNESS_STEPS * direction;
2141                int brightness = Settings.System.getIntForUser(mContext.getContentResolver(),
2142                        Settings.System.SCREEN_BRIGHTNESS,
2143                        mPowerManager.getDefaultScreenBrightnessSetting(),
2144                        UserHandle.USER_CURRENT_OR_SELF);
2145                brightness += step;
2146                // Make sure we don't go beyond the limits.
2147                brightness = Math.min(max, brightness);
2148                brightness = Math.max(min, brightness);
2149
2150                Settings.System.putIntForUser(mContext.getContentResolver(),
2151                        Settings.System.SCREEN_BRIGHTNESS, brightness,
2152                        UserHandle.USER_CURRENT_OR_SELF);
2153                Intent intent = new Intent(Intent.ACTION_SHOW_BRIGHTNESS_DIALOG);
2154                mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT_OR_SELF);
2155            }
2156            return -1;
2157        }
2158
2159        // Shortcuts are invoked through Search+key, so intercept those here
2160        // Any printing key that is chorded with Search should be consumed
2161        // even if no shortcut was invoked.  This prevents text from being
2162        // inadvertently inserted when using a keyboard that has built-in macro
2163        // shortcut keys (that emit Search+x) and some of them are not registered.
2164        if (mSearchKeyShortcutPending) {
2165            final KeyCharacterMap kcm = event.getKeyCharacterMap();
2166            if (kcm.isPrintingKey(keyCode)) {
2167                mConsumeSearchKeyUp = true;
2168                mSearchKeyShortcutPending = false;
2169                if (down && repeatCount == 0 && !keyguardOn) {
2170                    Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
2171                    if (shortcutIntent != null) {
2172                        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2173                        try {
2174                            mContext.startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
2175                        } catch (ActivityNotFoundException ex) {
2176                            Slog.w(TAG, "Dropping shortcut key combination because "
2177                                    + "the activity to which it is registered was not found: "
2178                                    + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
2179                        }
2180                    } else {
2181                        Slog.i(TAG, "Dropping unregistered shortcut key combination: "
2182                                + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
2183                    }
2184                }
2185                return -1;
2186            }
2187        }
2188
2189        // Invoke shortcuts using Meta.
2190        if (down && repeatCount == 0 && !keyguardOn
2191                && (metaState & KeyEvent.META_META_ON) != 0) {
2192            final KeyCharacterMap kcm = event.getKeyCharacterMap();
2193            if (kcm.isPrintingKey(keyCode)) {
2194                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
2195                        metaState & ~(KeyEvent.META_META_ON
2196                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
2197                if (shortcutIntent != null) {
2198                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2199                    try {
2200                        mContext.startActivityAsUser(shortcutIntent, UserHandle.CURRENT);
2201                    } catch (ActivityNotFoundException ex) {
2202                        Slog.w(TAG, "Dropping shortcut key combination because "
2203                                + "the activity to which it is registered was not found: "
2204                                + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
2205                    }
2206                    return -1;
2207                }
2208            }
2209        }
2210
2211        // Handle application launch keys.
2212        if (down && repeatCount == 0 && !keyguardOn) {
2213            String category = sApplicationLaunchKeyCategories.get(keyCode);
2214            if (category != null) {
2215                Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
2216                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2217                try {
2218                    mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2219                } catch (ActivityNotFoundException ex) {
2220                    Slog.w(TAG, "Dropping application launch key because "
2221                            + "the activity to which it is registered was not found: "
2222                            + "keyCode=" + keyCode + ", category=" + category, ex);
2223                }
2224                return -1;
2225            }
2226        }
2227
2228        // Display task switcher for ALT-TAB or Meta-TAB.
2229        if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
2230            if (mRecentAppsDialogHeldModifiers == 0 && !keyguardOn) {
2231                final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
2232                if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)
2233                        || KeyEvent.metaStateHasModifiers(
2234                                shiftlessModifiers, KeyEvent.META_META_ON)) {
2235                    mRecentAppsDialogHeldModifiers = shiftlessModifiers;
2236                    showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW);
2237                    return -1;
2238                }
2239            }
2240        } else if (!down && mRecentAppsDialogHeldModifiers != 0
2241                && (metaState & mRecentAppsDialogHeldModifiers) == 0) {
2242            mRecentAppsDialogHeldModifiers = 0;
2243            showOrHideRecentAppsDialog(keyguardOn ? RECENT_APPS_BEHAVIOR_DISMISS :
2244                    RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH);
2245        }
2246
2247        // Handle keyboard language switching.
2248        if (down && repeatCount == 0
2249                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
2250                        || (keyCode == KeyEvent.KEYCODE_SPACE
2251                                && (metaState & KeyEvent.META_CTRL_MASK) != 0))) {
2252            int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1;
2253            mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction);
2254            return -1;
2255        }
2256        if (mLanguageSwitchKeyPressed && !down
2257                && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
2258                        || keyCode == KeyEvent.KEYCODE_SPACE)) {
2259            mLanguageSwitchKeyPressed = false;
2260            return -1;
2261        }
2262
2263        if (mGlobalKeyManager.handleGlobalKey(mContext, keyCode, event)) {
2264            return -1;
2265        }
2266
2267        // Let the application handle the key.
2268        return 0;
2269    }
2270
2271    /** {@inheritDoc} */
2272    @Override
2273    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
2274        // Note: This method is only called if the initial down was unhandled.
2275        if (DEBUG_INPUT) {
2276            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
2277                    + ", flags=" + event.getFlags()
2278                    + ", keyCode=" + event.getKeyCode()
2279                    + ", scanCode=" + event.getScanCode()
2280                    + ", metaState=" + event.getMetaState()
2281                    + ", repeatCount=" + event.getRepeatCount()
2282                    + ", policyFlags=" + policyFlags);
2283        }
2284
2285        KeyEvent fallbackEvent = null;
2286        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
2287            final KeyCharacterMap kcm = event.getKeyCharacterMap();
2288            final int keyCode = event.getKeyCode();
2289            final int metaState = event.getMetaState();
2290            final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
2291                    && event.getRepeatCount() == 0;
2292
2293            // Check for fallback actions specified by the key character map.
2294            final FallbackAction fallbackAction;
2295            if (initialDown) {
2296                fallbackAction = kcm.getFallbackAction(keyCode, metaState);
2297            } else {
2298                fallbackAction = mFallbackActions.get(keyCode);
2299            }
2300
2301            if (fallbackAction != null) {
2302                if (DEBUG_INPUT) {
2303                    Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
2304                            + " metaState=" + Integer.toHexString(fallbackAction.metaState));
2305                }
2306
2307                final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
2308                fallbackEvent = KeyEvent.obtain(
2309                        event.getDownTime(), event.getEventTime(),
2310                        event.getAction(), fallbackAction.keyCode,
2311                        event.getRepeatCount(), fallbackAction.metaState,
2312                        event.getDeviceId(), event.getScanCode(),
2313                        flags, event.getSource(), null);
2314
2315                if (!interceptFallback(win, fallbackEvent, policyFlags)) {
2316                    fallbackEvent.recycle();
2317                    fallbackEvent = null;
2318                }
2319
2320                if (initialDown) {
2321                    mFallbackActions.put(keyCode, fallbackAction);
2322                } else if (event.getAction() == KeyEvent.ACTION_UP) {
2323                    mFallbackActions.remove(keyCode);
2324                    fallbackAction.recycle();
2325                }
2326            }
2327        }
2328
2329        if (DEBUG_INPUT) {
2330            if (fallbackEvent == null) {
2331                Slog.d(TAG, "No fallback.");
2332            } else {
2333                Slog.d(TAG, "Performing fallback: " + fallbackEvent);
2334            }
2335        }
2336        return fallbackEvent;
2337    }
2338
2339    private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
2340        int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags, true);
2341        if ((actions & ACTION_PASS_TO_USER) != 0) {
2342            long delayMillis = interceptKeyBeforeDispatching(
2343                    win, fallbackEvent, policyFlags);
2344            if (delayMillis == 0) {
2345                return true;
2346            }
2347        }
2348        return false;
2349    }
2350
2351    private void launchAssistLongPressAction() {
2352        performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
2353        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
2354
2355        // launch the search activity
2356        Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
2357        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2358        try {
2359            // TODO: This only stops the factory-installed search manager.
2360            // Need to formalize an API to handle others
2361            SearchManager searchManager = getSearchManager();
2362            if (searchManager != null) {
2363                searchManager.stopSearch();
2364            }
2365            mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2366        } catch (ActivityNotFoundException e) {
2367            Slog.w(TAG, "No activity to handle assist long press action.", e);
2368        }
2369    }
2370
2371    private void launchAssistAction() {
2372        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
2373        Intent intent = ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
2374                .getAssistIntent(mContext, true, UserHandle.USER_CURRENT);
2375        if (intent != null) {
2376            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
2377                    | Intent.FLAG_ACTIVITY_SINGLE_TOP
2378                    | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2379            try {
2380                mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2381            } catch (ActivityNotFoundException e) {
2382                Slog.w(TAG, "No activity to handle assist action.", e);
2383            }
2384        }
2385    }
2386
2387    private SearchManager getSearchManager() {
2388        if (mSearchManager == null) {
2389            mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
2390        }
2391        return mSearchManager;
2392    }
2393
2394    /**
2395     * A home key -> launch home action was detected.  Take the appropriate action
2396     * given the situation with the keyguard.
2397     */
2398    void launchHomeFromHotKey() {
2399        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowingAndNotHidden()) {
2400            // don't launch home if keyguard showing
2401        } else if (!mHideLockScreen && mKeyguardDelegate.isInputRestricted()) {
2402            // when in keyguard restricted mode, must first verify unlock
2403            // before launching home
2404            mKeyguardDelegate.verifyUnlock(new OnKeyguardExitResult() {
2405                public void onKeyguardExitResult(boolean success) {
2406                    if (success) {
2407                        try {
2408                            ActivityManagerNative.getDefault().stopAppSwitches();
2409                        } catch (RemoteException e) {
2410                        }
2411                        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
2412                        startDockOrHome();
2413                    }
2414                }
2415            });
2416        } else {
2417            // no keyguard stuff to worry about, just launch home!
2418            try {
2419                ActivityManagerNative.getDefault().stopAppSwitches();
2420            } catch (RemoteException e) {
2421            }
2422            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
2423            startDockOrHome();
2424        }
2425    }
2426
2427    /**
2428     * A delayed callback use to determine when it is okay to re-allow applications
2429     * to use certain system UI flags.  This is used to prevent applications from
2430     * spamming system UI changes that prevent the navigation bar from being shown.
2431     */
2432    final Runnable mAllowSystemUiDelay = new Runnable() {
2433        @Override public void run() {
2434        }
2435    };
2436
2437    /**
2438     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
2439     * to determine when the nav bar should be shown and prevent applications from
2440     * receiving those touches.
2441     */
2442    final class HideNavInputEventReceiver extends InputEventReceiver {
2443        public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
2444            super(inputChannel, looper);
2445        }
2446
2447        @Override
2448        public void onInputEvent(InputEvent event) {
2449            boolean handled = false;
2450            try {
2451                if (event instanceof MotionEvent
2452                        && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2453                    final MotionEvent motionEvent = (MotionEvent)event;
2454                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
2455                        // When the user taps down, we re-show the nav bar.
2456                        boolean changed = false;
2457                        synchronized (mLock) {
2458                            // Any user activity always causes us to show the
2459                            // navigation controls, if they had been hidden.
2460                            // We also clear the low profile and only content
2461                            // flags so that tapping on the screen will atomically
2462                            // restore all currently hidden screen decorations.
2463                            int newVal = mResettingSystemUiFlags |
2464                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2465                                    View.SYSTEM_UI_FLAG_LOW_PROFILE |
2466                                    View.SYSTEM_UI_FLAG_FULLSCREEN;
2467                            if (mResettingSystemUiFlags != newVal) {
2468                                mResettingSystemUiFlags = newVal;
2469                                changed = true;
2470                            }
2471                            // We don't allow the system's nav bar to be hidden
2472                            // again for 1 second, to prevent applications from
2473                            // spamming us and keeping it from being shown.
2474                            newVal = mForceClearedSystemUiFlags |
2475                                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
2476                            if (mForceClearedSystemUiFlags != newVal) {
2477                                mForceClearedSystemUiFlags = newVal;
2478                                changed = true;
2479                                mHandler.postDelayed(new Runnable() {
2480                                    @Override public void run() {
2481                                        synchronized (mLock) {
2482                                            // Clear flags.
2483                                            mForceClearedSystemUiFlags &=
2484                                                    ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
2485                                        }
2486                                        mWindowManagerFuncs.reevaluateStatusBarVisibility();
2487                                    }
2488                                }, 1000);
2489                            }
2490                        }
2491                        if (changed) {
2492                            mWindowManagerFuncs.reevaluateStatusBarVisibility();
2493                        }
2494                    }
2495                }
2496            } finally {
2497                finishInputEvent(event, handled);
2498            }
2499        }
2500    }
2501    final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
2502            new InputEventReceiver.Factory() {
2503        @Override
2504        public InputEventReceiver createInputEventReceiver(
2505                InputChannel inputChannel, Looper looper) {
2506            return new HideNavInputEventReceiver(inputChannel, looper);
2507        }
2508    };
2509
2510    @Override
2511    public int adjustSystemUiVisibilityLw(int visibility) {
2512        if (mHideybars == HIDEYBARS_SHOWING && 0 == (visibility & View.STATUS_BAR_OVERLAY)) {
2513            mHideybars = HIDEYBARS_HIDING;
2514            mStatusBar.hideLw(true);
2515        }
2516        // Reset any bits in mForceClearingStatusBarVisibility that
2517        // are now clear.
2518        mResettingSystemUiFlags &= visibility;
2519        // Clear any bits in the new visibility that are currently being
2520        // force cleared, before reporting it.
2521        return visibility & ~mResettingSystemUiFlags
2522                & ~mForceClearedSystemUiFlags;
2523    }
2524
2525    @Override
2526    public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
2527        final int fl = attrs.flags;
2528        final int systemUiVisibility = (attrs.systemUiVisibility|attrs.subtreeSystemUiVisibility);
2529
2530        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
2531                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
2532            int availRight, availBottom;
2533            if (mCanHideNavigationBar &&
2534                    (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
2535                availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
2536                availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
2537            } else {
2538                availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
2539                availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
2540            }
2541            if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
2542                if ((fl & FLAG_FULLSCREEN) != 0) {
2543                    contentInset.set(mStableFullscreenLeft, mStableFullscreenTop,
2544                            availRight - mStableFullscreenRight,
2545                            availBottom - mStableFullscreenBottom);
2546                } else {
2547                    contentInset.set(mStableLeft, mStableTop,
2548                            availRight - mStableRight, availBottom - mStableBottom);
2549                }
2550            } else if ((fl & FLAG_FULLSCREEN) != 0 || (fl & FLAG_LAYOUT_IN_OVERSCAN) != 0) {
2551                contentInset.setEmpty();
2552            } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
2553                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
2554                contentInset.set(mCurLeft, mCurTop,
2555                        availRight - mCurRight, availBottom - mCurBottom);
2556            } else {
2557                contentInset.set(mCurLeft, mCurTop,
2558                        availRight - mCurRight, availBottom - mCurBottom);
2559            }
2560            return;
2561        }
2562        contentInset.setEmpty();
2563    }
2564
2565    /** {@inheritDoc} */
2566    @Override
2567    public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
2568                              int displayRotation) {
2569        final int overscanLeft, overscanTop, overscanRight, overscanBottom;
2570        if (isDefaultDisplay) {
2571            switch (displayRotation) {
2572                case Surface.ROTATION_90:
2573                    overscanLeft = mOverscanTop;
2574                    overscanTop = mOverscanRight;
2575                    overscanRight = mOverscanBottom;
2576                    overscanBottom = mOverscanLeft;
2577                    break;
2578                case Surface.ROTATION_180:
2579                    overscanLeft = mOverscanRight;
2580                    overscanTop = mOverscanBottom;
2581                    overscanRight = mOverscanLeft;
2582                    overscanBottom = mOverscanTop;
2583                    break;
2584                case Surface.ROTATION_270:
2585                    overscanLeft = mOverscanBottom;
2586                    overscanTop = mOverscanLeft;
2587                    overscanRight = mOverscanTop;
2588                    overscanBottom = mOverscanRight;
2589                    break;
2590                default:
2591                    overscanLeft = mOverscanLeft;
2592                    overscanTop = mOverscanTop;
2593                    overscanRight = mOverscanRight;
2594                    overscanBottom = mOverscanBottom;
2595                    break;
2596            }
2597        } else {
2598            overscanLeft = 0;
2599            overscanTop = 0;
2600            overscanRight = 0;
2601            overscanBottom = 0;
2602        }
2603        mOverscanScreenLeft = mRestrictedOverscanScreenLeft = 0;
2604        mOverscanScreenTop = mRestrictedOverscanScreenTop = 0;
2605        mOverscanScreenWidth = mRestrictedOverscanScreenWidth = displayWidth;
2606        mOverscanScreenHeight = mRestrictedOverscanScreenHeight = displayHeight;
2607        mSystemLeft = 0;
2608        mSystemTop = 0;
2609        mSystemRight = displayWidth;
2610        mSystemBottom = displayHeight;
2611        mUnrestrictedScreenLeft = overscanLeft;
2612        mUnrestrictedScreenTop = overscanTop;
2613        mUnrestrictedScreenWidth = displayWidth - overscanLeft - overscanRight;
2614        mUnrestrictedScreenHeight = displayHeight - overscanTop - overscanBottom;
2615        mRestrictedScreenLeft = mUnrestrictedScreenLeft;
2616        mRestrictedScreenTop = mUnrestrictedScreenTop;
2617        mRestrictedScreenWidth = mUnrestrictedScreenWidth;
2618        mRestrictedScreenHeight = mUnrestrictedScreenHeight;
2619        mDockLeft = mContentLeft = mStableLeft = mStableFullscreenLeft
2620                = mCurLeft = mUnrestrictedScreenLeft;
2621        mDockTop = mContentTop = mStableTop = mStableFullscreenTop
2622                = mCurTop = mUnrestrictedScreenTop;
2623        mDockRight = mContentRight = mStableRight = mStableFullscreenRight
2624                = mCurRight = displayWidth - overscanRight;
2625        mDockBottom = mContentBottom = mStableBottom = mStableFullscreenBottom
2626                = mCurBottom = displayHeight - overscanBottom;
2627        mDockLayer = 0x10000000;
2628        mStatusBarLayer = -1;
2629
2630        // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
2631        final Rect pf = mTmpParentFrame;
2632        final Rect df = mTmpDisplayFrame;
2633        final Rect of = mTmpOverscanFrame;
2634        final Rect vf = mTmpVisibleFrame;
2635        pf.left = df.left = of.left = vf.left = mDockLeft;
2636        pf.top = df.top = of.top = vf.top = mDockTop;
2637        pf.right = df.right = of.right = vf.right = mDockRight;
2638        pf.bottom = df.bottom = of.bottom = vf.bottom = mDockBottom;
2639
2640        if (isDefaultDisplay) {
2641            // For purposes of putting out fake window up to steal focus, we will
2642            // drive nav being hidden only by whether it is requested.
2643            boolean navVisible = (mLastSystemUiFlags&View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
2644
2645            // When the navigation bar isn't visible, we put up a fake
2646            // input window to catch all touch events.  This way we can
2647            // detect when the user presses anywhere to bring back the nav
2648            // bar and ensure the application doesn't see the event.
2649            if (navVisible) {
2650                if (mHideNavFakeWindow != null) {
2651                    mHideNavFakeWindow.dismiss();
2652                    mHideNavFakeWindow = null;
2653                }
2654            } else if (mHideNavFakeWindow == null) {
2655                mHideNavFakeWindow = mWindowManagerFuncs.addFakeWindow(
2656                        mHandler.getLooper(), mHideNavInputEventReceiverFactory,
2657                        "hidden nav", WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER,
2658                        0, false, false, true);
2659            }
2660
2661            // For purposes of positioning and showing the nav bar, if we have
2662            // decided that it can't be hidden (because of the screen aspect ratio),
2663            // then take that into account.
2664            navVisible |= !mCanHideNavigationBar;
2665
2666            if (mNavigationBar != null) {
2667                // Force the navigation bar to its appropriate place and
2668                // size.  We need to do this directly, instead of relying on
2669                // it to bubble up from the nav bar, because this needs to
2670                // change atomically with screen rotations.
2671                mNavigationBarOnBottom = (!mNavigationBarCanMove || displayWidth < displayHeight);
2672                if (mNavigationBarOnBottom) {
2673                    // It's a system nav bar or a portrait screen; nav bar goes on bottom.
2674                    int top = displayHeight - overscanBottom
2675                            - mNavigationBarHeightForRotation[displayRotation];
2676                    mTmpNavigationFrame.set(0, top, displayWidth, displayHeight - overscanBottom);
2677                    mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
2678                    if (navVisible) {
2679                        mNavigationBar.showLw(true);
2680                        mDockBottom = mTmpNavigationFrame.top;
2681                        mRestrictedScreenHeight = mDockBottom - mRestrictedScreenTop;
2682                        mRestrictedOverscanScreenHeight = mDockBottom - mRestrictedOverscanScreenTop;
2683                    } else {
2684                        // We currently want to hide the navigation UI.
2685                        mNavigationBar.hideLw(true);
2686                    }
2687                    if (navVisible && !mNavigationBar.isAnimatingLw()) {
2688                        // If the nav bar is currently requested to be visible,
2689                        // and not in the process of animating on or off, then
2690                        // we can tell the app that it is covered by it.
2691                        mSystemBottom = mTmpNavigationFrame.top;
2692                    }
2693                } else {
2694                    // Landscape screen; nav bar goes to the right.
2695                    int left = displayWidth - overscanRight
2696                            - mNavigationBarWidthForRotation[displayRotation];
2697                    mTmpNavigationFrame.set(left, 0, displayWidth - overscanRight, displayHeight);
2698                    mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
2699                    if (navVisible) {
2700                        mNavigationBar.showLw(true);
2701                        mDockRight = mTmpNavigationFrame.left;
2702                        mRestrictedScreenWidth = mDockRight - mRestrictedScreenLeft;
2703                        mRestrictedOverscanScreenWidth = mDockRight - mRestrictedOverscanScreenLeft;
2704                    } else {
2705                        // We currently want to hide the navigation UI.
2706                        mNavigationBar.hideLw(true);
2707                    }
2708                    if (navVisible && !mNavigationBar.isAnimatingLw()) {
2709                        // If the nav bar is currently requested to be visible,
2710                        // and not in the process of animating on or off, then
2711                        // we can tell the app that it is covered by it.
2712                        mSystemRight = mTmpNavigationFrame.left;
2713                    }
2714                }
2715                // Make sure the content and current rectangles are updated to
2716                // account for the restrictions from the navigation bar.
2717                mContentTop = mCurTop = mDockTop;
2718                mContentBottom = mCurBottom = mDockBottom;
2719                mContentLeft = mCurLeft = mDockLeft;
2720                mContentRight = mCurRight = mDockRight;
2721                mStatusBarLayer = mNavigationBar.getSurfaceLayer();
2722                // And compute the final frame.
2723                mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
2724                        mTmpNavigationFrame, mTmpNavigationFrame, mTmpNavigationFrame);
2725                if (DEBUG_LAYOUT) Log.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
2726            }
2727            if (DEBUG_LAYOUT) Log.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
2728                    mDockLeft, mDockTop, mDockRight, mDockBottom));
2729
2730            // decide where the status bar goes ahead of time
2731            if (mStatusBar != null) {
2732                // apply any navigation bar insets
2733                pf.left = df.left = of.left = mUnrestrictedScreenLeft;
2734                pf.top = df.top = of.top = mUnrestrictedScreenTop;
2735                pf.right = df.right = of.right = mUnrestrictedScreenWidth + mUnrestrictedScreenLeft;
2736                pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenHeight
2737                        + mUnrestrictedScreenTop;
2738                vf.left = mStableLeft;
2739                vf.top = mStableTop;
2740                vf.right = mStableRight;
2741                vf.bottom = mStableBottom;
2742
2743                mStatusBarLayer = mStatusBar.getSurfaceLayer();
2744
2745                // Let the status bar determine its size.
2746                mStatusBar.computeFrameLw(pf, df, vf, vf, vf);
2747
2748                // For layout, the status bar is always at the top with our fixed height.
2749                mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
2750
2751                boolean statusBarOverlay = (mLastSystemUiFlags & View.STATUS_BAR_OVERLAY) != 0;
2752
2753                // If the status bar is hidden, we don't want to cause
2754                // windows behind it to scroll.
2755                if (mStatusBar.isVisibleLw() && !statusBarOverlay) {
2756                    // Status bar may go away, so the screen area it occupies
2757                    // is available to apps but just covering them when the
2758                    // status bar is visible.
2759                    mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
2760
2761                    mContentTop = mCurTop = mDockTop;
2762                    mContentBottom = mCurBottom = mDockBottom;
2763                    mContentLeft = mCurLeft = mDockLeft;
2764                    mContentRight = mCurRight = mDockRight;
2765
2766                    if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: " +
2767                        String.format(
2768                            "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
2769                            mDockLeft, mDockTop, mDockRight, mDockBottom,
2770                            mContentLeft, mContentTop, mContentRight, mContentBottom,
2771                            mCurLeft, mCurTop, mCurRight, mCurBottom));
2772                }
2773                if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw() && !statusBarOverlay) {
2774                    // If the status bar is currently requested to be visible,
2775                    // and not in the process of animating on or off, then
2776                    // we can tell the app that it is covered by it.
2777                    mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
2778                }
2779                if (mHideybars == HIDEYBARS_HIDING && !mStatusBar.isVisibleLw()) {
2780                    // Hideybars have finished animating out, cleanup and reset alpha
2781                    mHideybars = HIDEYBARS_NONE;
2782                    updateSystemUiVisibilityLw();
2783                }
2784            }
2785        }
2786    }
2787
2788    /** {@inheritDoc} */
2789    @Override
2790    public int getSystemDecorRectLw(Rect systemRect) {
2791        systemRect.left = mSystemLeft;
2792        systemRect.top = mSystemTop;
2793        systemRect.right = mSystemRight;
2794        systemRect.bottom = mSystemBottom;
2795        if (mStatusBar != null) return mStatusBar.getSurfaceLayer();
2796        if (mNavigationBar != null) return mNavigationBar.getSurfaceLayer();
2797        return 0;
2798    }
2799
2800    @Override
2801    public void getContentRectLw(Rect r) {
2802        r.set(mContentLeft, mContentTop, mContentRight, mContentBottom);
2803    }
2804
2805    void setAttachedWindowFrames(WindowState win, int fl, int adjust, WindowState attached,
2806            boolean insetDecors, Rect pf, Rect df, Rect of, Rect cf, Rect vf) {
2807        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
2808            // Here's a special case: if this attached window is a panel that is
2809            // above the dock window, and the window it is attached to is below
2810            // the dock window, then the frames we computed for the window it is
2811            // attached to can not be used because the dock is effectively part
2812            // of the underlying window and the attached window is floating on top
2813            // of the whole thing.  So, we ignore the attached window and explicitly
2814            // compute the frames that would be appropriate without the dock.
2815            df.left = of.left = cf.left = vf.left = mDockLeft;
2816            df.top = of.top = cf.top = vf.top = mDockTop;
2817            df.right = of.right = cf.right = vf.right = mDockRight;
2818            df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
2819        } else {
2820            // The effective display frame of the attached window depends on
2821            // whether it is taking care of insetting its content.  If not,
2822            // we need to use the parent's content frame so that the entire
2823            // window is positioned within that content.  Otherwise we can use
2824            // the display frame and let the attached window take care of
2825            // positioning its content appropriately.
2826            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2827                cf.set(attached.getOverscanFrameLw());
2828            } else {
2829                // If the window is resizing, then we want to base the content
2830                // frame on our attached content frame to resize...  however,
2831                // things can be tricky if the attached window is NOT in resize
2832                // mode, in which case its content frame will be larger.
2833                // Ungh.  So to deal with that, make sure the content frame
2834                // we end up using is not covering the IM dock.
2835                cf.set(attached.getContentFrameLw());
2836                if (attached.getSurfaceLayer() < mDockLayer) {
2837                    if (cf.left < mContentLeft) cf.left = mContentLeft;
2838                    if (cf.top < mContentTop) cf.top = mContentTop;
2839                    if (cf.right > mContentRight) cf.right = mContentRight;
2840                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
2841                }
2842            }
2843            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
2844            of.set(insetDecors ? attached.getOverscanFrameLw() : cf);
2845            vf.set(attached.getVisibleFrameLw());
2846        }
2847        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
2848        // window should be positioned relative to its parent or the entire
2849        // screen.
2850        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
2851                ? attached.getFrameLw() : df);
2852    }
2853
2854    private void applyStableConstraints(int sysui, int fl, Rect r) {
2855        if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
2856            // If app is requesting a stable layout, don't let the
2857            // content insets go below the stable values.
2858            if ((fl & FLAG_FULLSCREEN) != 0) {
2859                if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
2860                if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
2861                if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
2862                if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
2863            } else {
2864                if (r.left < mStableLeft) r.left = mStableLeft;
2865                if (r.top < mStableTop) r.top = mStableTop;
2866                if (r.right > mStableRight) r.right = mStableRight;
2867                if (r.bottom > mStableBottom) r.bottom = mStableBottom;
2868            }
2869        }
2870    }
2871
2872    /** {@inheritDoc} */
2873    @Override
2874    public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
2875            WindowState attached) {
2876        // we've already done the status bar
2877        if (win == mStatusBar || win == mNavigationBar) {
2878            return;
2879        }
2880        final boolean isDefaultDisplay = win.isDefaultDisplay();
2881        final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
2882                (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
2883        if (needsToOffsetInputMethodTarget) {
2884            if (DEBUG_LAYOUT) {
2885                Slog.i(TAG, "Offset ime target window by the last ime window state");
2886            }
2887            offsetInputMethodWindowLw(mLastInputMethodWindow);
2888        }
2889
2890        final int fl = attrs.flags;
2891        final int sim = attrs.softInputMode;
2892        final int sysUiFl = win.getSystemUiVisibility();
2893
2894        final Rect pf = mTmpParentFrame;
2895        final Rect df = mTmpDisplayFrame;
2896        final Rect of = mTmpOverscanFrame;
2897        final Rect cf = mTmpContentFrame;
2898        final Rect vf = mTmpVisibleFrame;
2899
2900        final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
2901                && mNavigationBar != null && mNavigationBar.isVisibleLw());
2902
2903        final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
2904
2905        if (!isDefaultDisplay) {
2906            if (attached != null) {
2907                // If this window is attached to another, our display
2908                // frame is the same as the one we are attached to.
2909                setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
2910            } else {
2911                // Give the window full screen.
2912                pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
2913                pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
2914                pf.right = df.right = of.right = cf.right
2915                        = mOverscanScreenLeft + mOverscanScreenWidth;
2916                pf.bottom = df.bottom = of.bottom = cf.bottom
2917                        = mOverscanScreenTop + mOverscanScreenHeight;
2918            }
2919        } else  if (attrs.type == TYPE_INPUT_METHOD) {
2920            pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
2921            pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
2922            pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
2923            pf.bottom = df.bottom = of.bottom = cf.bottom = vf.bottom = mDockBottom;
2924            // IM dock windows always go to the bottom of the screen.
2925            attrs.gravity = Gravity.BOTTOM;
2926            mDockLayer = win.getSurfaceLayer();
2927        } else {
2928            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
2929                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
2930                if (DEBUG_LAYOUT)
2931                    Log.v(TAG, "layoutWindowLw(" + attrs.getTitle()
2932                            + "): IN_SCREEN, INSET_DECOR");
2933                // This is the case for a normal activity window: we want it
2934                // to cover all of the screen space, and it can take care of
2935                // moving its contents to account for screen decorations that
2936                // intrude into that space.
2937                if (attached != null) {
2938                    // If this window is attached to another, our display
2939                    // frame is the same as the one we are attached to.
2940                    setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, of, cf, vf);
2941                } else {
2942                    if (attrs.type == TYPE_STATUS_BAR_PANEL
2943                            || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
2944                        // Status bar panels are the only windows who can go on top of
2945                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
2946                        // permission, so they have the same privileges as the status
2947                        // bar itself.
2948                        //
2949                        // However, they should still dodge the navigation bar if it exists.
2950
2951                        pf.left = df.left = of.left = hasNavBar
2952                                ? mDockLeft : mUnrestrictedScreenLeft;
2953                        pf.top = df.top = of.top = mUnrestrictedScreenTop;
2954                        pf.right = df.right = of.right = hasNavBar
2955                                ? mRestrictedScreenLeft+mRestrictedScreenWidth
2956                                : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
2957                        pf.bottom = df.bottom = of.bottom = hasNavBar
2958                                ? mRestrictedScreenTop+mRestrictedScreenHeight
2959                                : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
2960
2961                        if (DEBUG_LAYOUT) {
2962                            Log.v(TAG, String.format(
2963                                        "Laying out status bar window: (%d,%d - %d,%d)",
2964                                        pf.left, pf.top, pf.right, pf.bottom));
2965                        }
2966                    } else if ((attrs.flags&FLAG_LAYOUT_IN_OVERSCAN) != 0
2967                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
2968                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
2969                        // Asking to layout into the overscan region, so give it that pure
2970                        // unrestricted area.
2971                        pf.left = df.left = of.left = mOverscanScreenLeft;
2972                        pf.top = df.top = of.top = mOverscanScreenTop;
2973                        pf.right = df.right = of.right = mOverscanScreenLeft + mOverscanScreenWidth;
2974                        pf.bottom = df.bottom = of.bottom = mOverscanScreenTop
2975                                + mOverscanScreenHeight;
2976                    } else if (mCanHideNavigationBar
2977                            && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
2978                            && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
2979                            && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
2980                        // Asking for layout as if the nav bar is hidden, lets the
2981                        // application extend into the unrestricted overscan screen area.  We
2982                        // only do this for application windows to ensure no window that
2983                        // can be above the nav bar can do this.
2984                        pf.left = df.left = mOverscanScreenLeft;
2985                        pf.top = df.top = mOverscanScreenTop;
2986                        pf.right = df.right = mOverscanScreenLeft + mOverscanScreenWidth;
2987                        pf.bottom = df.bottom = mOverscanScreenTop + mOverscanScreenHeight;
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                    } else {
2996                        pf.left = df.left = mRestrictedOverscanScreenLeft;
2997                        pf.top = df.top = mRestrictedOverscanScreenTop;
2998                        pf.right = df.right = mRestrictedOverscanScreenLeft
2999                                + mRestrictedOverscanScreenWidth;
3000                        pf.bottom = df.bottom = mRestrictedOverscanScreenTop
3001                                + mRestrictedOverscanScreenHeight;
3002                        // We need to tell the app about where the frame inside the overscan
3003                        // is, so it can inset its content by that amount -- it didn't ask
3004                        // to actually extend itself into the overscan region.
3005                        of.left = mUnrestrictedScreenLeft;
3006                        of.top = mUnrestrictedScreenTop;
3007                        of.right = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3008                        of.bottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3009                    }
3010
3011                    if ((attrs.flags&FLAG_FULLSCREEN) == 0) {
3012                        if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3013                            cf.left = mDockLeft;
3014                            cf.top = mDockTop;
3015                            cf.right = mDockRight;
3016                            cf.bottom = mDockBottom;
3017                        } else {
3018                            cf.left = mContentLeft;
3019                            cf.top = mContentTop;
3020                            cf.right = mContentRight;
3021                            cf.bottom = mContentBottom;
3022                        }
3023                    } else {
3024                        // Full screen windows are always given a layout that is as if the
3025                        // status bar and other transient decors are gone.  This is to avoid
3026                        // bad states when moving from a window that is not hding the
3027                        // status bar to one that is.
3028                        cf.left = mRestrictedScreenLeft;
3029                        cf.top = mRestrictedScreenTop;
3030                        cf.right = mRestrictedScreenLeft + mRestrictedScreenWidth;
3031                        cf.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
3032                    }
3033
3034                    applyStableConstraints(sysUiFl, fl, cf);
3035                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3036                        vf.left = mCurLeft;
3037                        vf.top = mCurTop;
3038                        vf.right = mCurRight;
3039                        vf.bottom = mCurBottom;
3040                    } else {
3041                        vf.set(cf);
3042                    }
3043                }
3044            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
3045                    & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
3046                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
3047                if (DEBUG_LAYOUT)
3048                    Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): IN_SCREEN");
3049                // A window that has requested to fill the entire screen just
3050                // gets everything, period.
3051                if (attrs.type == TYPE_STATUS_BAR_PANEL
3052                        || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
3053                    pf.left = df.left = of.left = cf.left = hasNavBar
3054                            ? mDockLeft : mUnrestrictedScreenLeft;
3055                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
3056                    pf.right = df.right = of.right = cf.right = hasNavBar
3057                                        ? mRestrictedScreenLeft+mRestrictedScreenWidth
3058                                        : mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
3059                    pf.bottom = df.bottom = of.bottom = cf.bottom = hasNavBar
3060                                          ? mRestrictedScreenTop+mRestrictedScreenHeight
3061                                          : mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
3062                    if (DEBUG_LAYOUT) {
3063                        Log.v(TAG, String.format(
3064                                    "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
3065                                    pf.left, pf.top, pf.right, pf.bottom));
3066                    }
3067                } else if (attrs.type == TYPE_NAVIGATION_BAR
3068                        || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
3069                    // The navigation bar has Real Ultimate Power.
3070                    pf.left = df.left = of.left = mUnrestrictedScreenLeft;
3071                    pf.top = df.top = of.top = mUnrestrictedScreenTop;
3072                    pf.right = df.right = of.right = mUnrestrictedScreenLeft
3073                            + mUnrestrictedScreenWidth;
3074                    pf.bottom = df.bottom = of.bottom = mUnrestrictedScreenTop
3075                            + mUnrestrictedScreenHeight;
3076                    if (DEBUG_LAYOUT) {
3077                        Log.v(TAG, String.format(
3078                                    "Laying out navigation bar window: (%d,%d - %d,%d)",
3079                                    pf.left, pf.top, pf.right, pf.bottom));
3080                    }
3081                } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
3082                                || attrs.type == TYPE_BOOT_PROGRESS)
3083                        && ((fl & FLAG_FULLSCREEN) != 0)) {
3084                    // Fullscreen secure system overlays get what they ask for.
3085                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3086                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3087                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
3088                            + mOverscanScreenWidth;
3089                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
3090                            + mOverscanScreenHeight;
3091                } else if (attrs.type == TYPE_BOOT_PROGRESS
3092                        || attrs.type == TYPE_UNIVERSE_BACKGROUND) {
3093                    // Boot progress screen always covers entire display.
3094                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3095                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3096                    pf.right = df.right = of.right = cf.right = mOverscanScreenLeft
3097                            + mOverscanScreenWidth;
3098                    pf.bottom = df.bottom = of.bottom = cf.bottom = mOverscanScreenTop
3099                            + mOverscanScreenHeight;
3100                } else if (attrs.type == WindowManager.LayoutParams.TYPE_WALLPAPER) {
3101                    // The wallpaper mostly goes into the overscan region.
3102                    pf.left = df.left = of.left = cf.left = mRestrictedOverscanScreenLeft;
3103                    pf.top = df.top = of.top = cf.top = mRestrictedOverscanScreenTop;
3104                    pf.right = df.right = of.right = cf.right
3105                            = mRestrictedOverscanScreenLeft + mRestrictedOverscanScreenWidth;
3106                    pf.bottom = df.bottom = of.bottom = cf.bottom
3107                            = mRestrictedOverscanScreenTop + mRestrictedOverscanScreenHeight;
3108                } else if ((attrs.flags & FLAG_LAYOUT_IN_OVERSCAN) != 0
3109                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3110                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3111                    // Asking to layout into the overscan region, so give it that pure
3112                    // unrestricted area.
3113                    pf.left = df.left = of.left = cf.left = mOverscanScreenLeft;
3114                    pf.top = df.top = of.top = cf.top = mOverscanScreenTop;
3115                    pf.right = df.right = of.right = cf.right
3116                            = mOverscanScreenLeft + mOverscanScreenWidth;
3117                    pf.bottom = df.bottom = of.bottom = cf.bottom
3118                            = mOverscanScreenTop + mOverscanScreenHeight;
3119                } else if (mCanHideNavigationBar
3120                        && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
3121                        && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
3122                        && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
3123                    // Asking for layout as if the nav bar is hidden, lets the
3124                    // application extend into the unrestricted screen area.  We
3125                    // only do this for application windows to ensure no window that
3126                    // can be above the nav bar can do this.
3127                    // XXX This assumes that an app asking for this will also
3128                    // ask for layout in only content.  We can't currently figure out
3129                    // what the screen would be if only laying out to hide the nav bar.
3130                    pf.left = df.left = of.left = cf.left = mUnrestrictedScreenLeft;
3131                    pf.top = df.top = of.top = cf.top = mUnrestrictedScreenTop;
3132                    pf.right = df.right = of.right = cf.right = mUnrestrictedScreenLeft
3133                            + mUnrestrictedScreenWidth;
3134                    pf.bottom = df.bottom = of.bottom = cf.bottom = mUnrestrictedScreenTop
3135                            + mUnrestrictedScreenHeight;
3136                } else {
3137                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
3138                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
3139                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
3140                            + mRestrictedScreenWidth;
3141                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
3142                            + mRestrictedScreenHeight;
3143                }
3144
3145                applyStableConstraints(sysUiFl, fl, cf);
3146
3147                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3148                    vf.left = mCurLeft;
3149                    vf.top = mCurTop;
3150                    vf.right = mCurRight;
3151                    vf.bottom = mCurBottom;
3152                } else {
3153                    vf.set(cf);
3154                }
3155            } else if (attached != null) {
3156                if (DEBUG_LAYOUT)
3157                    Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): attached to " + attached);
3158                // A child window should be placed inside of the same visible
3159                // frame that its parent had.
3160                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, of, cf, vf);
3161            } else {
3162                if (DEBUG_LAYOUT)
3163                    Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): normal window");
3164                // Otherwise, a normal window must be placed inside the content
3165                // of all screen decorations.
3166                if (attrs.type == TYPE_STATUS_BAR_PANEL) {
3167                    // Status bar panels are the only windows who can go on top of
3168                    // the status bar.  They are protected by the STATUS_BAR_SERVICE
3169                    // permission, so they have the same privileges as the status
3170                    // bar itself.
3171                    pf.left = df.left = of.left = cf.left = mRestrictedScreenLeft;
3172                    pf.top = df.top = of.top = cf.top = mRestrictedScreenTop;
3173                    pf.right = df.right = of.right = cf.right = mRestrictedScreenLeft
3174                            + mRestrictedScreenWidth;
3175                    pf.bottom = df.bottom = of.bottom = cf.bottom = mRestrictedScreenTop
3176                            + mRestrictedScreenHeight;
3177                } else {
3178                    pf.left = mContentLeft;
3179                    pf.top = mContentTop;
3180                    pf.right = mContentRight;
3181                    pf.bottom = mContentBottom;
3182                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
3183                        df.left = of.left = cf.left = mDockLeft;
3184                        df.top = of.top = cf.top = mDockTop;
3185                        df.right = of.right = cf.right = mDockRight;
3186                        df.bottom = of.bottom = cf.bottom = mDockBottom;
3187                    } else {
3188                        df.left = of.left = cf.left = mContentLeft;
3189                        df.top = of.top = cf.top = mContentTop;
3190                        df.right = of.right = cf.right = mContentRight;
3191                        df.bottom = of.bottom = cf.bottom = mContentBottom;
3192                    }
3193                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
3194                        vf.left = mCurLeft;
3195                        vf.top = mCurTop;
3196                        vf.right = mCurRight;
3197                        vf.bottom = mCurBottom;
3198                    } else {
3199                        vf.set(cf);
3200                    }
3201                }
3202            }
3203        }
3204
3205        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
3206            df.left = df.top = of.left = of.top = cf.left = cf.top = vf.left = vf.top = -10000;
3207            df.right = df.bottom = of.right = of.bottom = cf.right = cf.bottom
3208                    = vf.right = vf.bottom = 10000;
3209        }
3210
3211        if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
3212                + ": sim=#" + Integer.toHexString(sim)
3213                + " attach=" + attached + " type=" + attrs.type
3214                + String.format(" flags=0x%08x", fl)
3215                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
3216                + " of=" + of.toShortString()
3217                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
3218
3219        win.computeFrameLw(pf, df, of, cf, vf);
3220
3221        // Dock windows carve out the bottom of the screen, so normal windows
3222        // can't appear underneath them.
3223        if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
3224                && !win.getGivenInsetsPendingLw()) {
3225            setLastInputMethodWindowLw(null, null);
3226            offsetInputMethodWindowLw(win);
3227        }
3228    }
3229
3230    private void offsetInputMethodWindowLw(WindowState win) {
3231        int top = win.getContentFrameLw().top;
3232        top += win.getGivenContentInsetsLw().top;
3233        if (mContentBottom > top) {
3234            mContentBottom = top;
3235        }
3236        top = win.getVisibleFrameLw().top;
3237        top += win.getGivenVisibleInsetsLw().top;
3238        if (mCurBottom > top) {
3239            mCurBottom = top;
3240        }
3241        if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
3242                + mDockBottom + " mContentBottom="
3243                + mContentBottom + " mCurBottom=" + mCurBottom);
3244    }
3245
3246    /** {@inheritDoc} */
3247    @Override
3248    public void finishLayoutLw() {
3249        return;
3250    }
3251
3252    /** {@inheritDoc} */
3253    @Override
3254    public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
3255        mTopFullscreenOpaqueWindowState = null;
3256        mForceStatusBar = false;
3257        mForceStatusBarFromKeyguard = false;
3258        mForcingShowNavBar = false;
3259        mForcingShowNavBarLayer = -1;
3260
3261        mHideLockScreen = false;
3262        mAllowLockscreenWhenOn = false;
3263        mDismissKeyguard = DISMISS_KEYGUARD_NONE;
3264        mShowingLockscreen = false;
3265        mShowingDream = false;
3266    }
3267
3268    /** {@inheritDoc} */
3269    @Override
3270    public void applyPostLayoutPolicyLw(WindowState win,
3271                                WindowManager.LayoutParams attrs) {
3272        if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
3273                + win.isVisibleOrBehindKeyguardLw());
3274        if (mTopFullscreenOpaqueWindowState == null && (win.getAttrs().privateFlags
3275                &WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_SHOW_NAV_BAR) != 0) {
3276            if (mForcingShowNavBarLayer < 0) {
3277                mForcingShowNavBar = true;
3278                mForcingShowNavBarLayer = win.getSurfaceLayer();
3279            }
3280        }
3281        if (mTopFullscreenOpaqueWindowState == null &&
3282                win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
3283            if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
3284                if (attrs.type == TYPE_KEYGUARD) {
3285                    mForceStatusBarFromKeyguard = true;
3286                } else {
3287                    mForceStatusBar = true;
3288                }
3289            }
3290            if (attrs.type == TYPE_KEYGUARD) {
3291                mShowingLockscreen = true;
3292            }
3293            boolean applyWindow = attrs.type >= FIRST_APPLICATION_WINDOW
3294                    && attrs.type <= LAST_APPLICATION_WINDOW;
3295            if (attrs.type == TYPE_DREAM) {
3296                // If the lockscreen was showing when the dream started then wait
3297                // for the dream to draw before hiding the lockscreen.
3298                if (!mDreamingLockscreen
3299                        || (win.isVisibleLw() && win.hasDrawnLw())) {
3300                    mShowingDream = true;
3301                    applyWindow = true;
3302                }
3303            }
3304            if (applyWindow
3305                    && attrs.x == 0 && attrs.y == 0
3306                    && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
3307                    && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
3308                if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
3309                mTopFullscreenOpaqueWindowState = win;
3310                if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
3311                    if (DEBUG_LAYOUT) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
3312                    mHideLockScreen = true;
3313                    mForceStatusBarFromKeyguard = false;
3314                }
3315                if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0
3316                        && mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
3317                    if (DEBUG_LAYOUT) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
3318                    mDismissKeyguard = mWinDismissingKeyguard == win ?
3319                            DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
3320                    mWinDismissingKeyguard = win;
3321                    mForceStatusBarFromKeyguard =
3322                            mShowingLockscreen && isKeyguardSecure();
3323                }
3324                if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
3325                    mAllowLockscreenWhenOn = true;
3326                }
3327            }
3328        }
3329    }
3330
3331    /** {@inheritDoc} */
3332    @Override
3333    public int finishPostLayoutPolicyLw() {
3334        int changes = 0;
3335        boolean topIsFullscreen = false;
3336
3337        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
3338                ? mTopFullscreenOpaqueWindowState.getAttrs()
3339                : null;
3340
3341        // If we are not currently showing a dream then remember the current
3342        // lockscreen state.  We will use this to determine whether the dream
3343        // started while the lockscreen was showing and remember this state
3344        // while the dream is showing.
3345        if (!mShowingDream) {
3346            mDreamingLockscreen = mShowingLockscreen;
3347        }
3348
3349        if (mStatusBar != null) {
3350            if (DEBUG_LAYOUT) Log.i(TAG, "force=" + mForceStatusBar
3351                    + " forcefkg=" + mForceStatusBarFromKeyguard
3352                    + " top=" + mTopFullscreenOpaqueWindowState);
3353            if (mForceStatusBar || mForceStatusBarFromKeyguard) {
3354                if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar: forced");
3355                if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
3356            } else if (mTopFullscreenOpaqueWindowState != null) {
3357                if (localLOGV) {
3358                    Log.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
3359                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
3360                    Log.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
3361                            + " lp.flags=0x" + Integer.toHexString(lp.flags));
3362                }
3363                topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
3364                        || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
3365                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
3366                // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window
3367                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
3368                // case though.
3369                if (mHideybars == HIDEYBARS_SHOWING) {
3370                    if (mStatusBar.showLw(true)) {
3371                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
3372                    }
3373                } else if (topIsFullscreen) {
3374                    if (DEBUG_LAYOUT) Log.v(TAG, "** HIDING status bar");
3375                    if (mStatusBar.hideLw(true)) {
3376                        changes |= FINISH_LAYOUT_REDO_LAYOUT;
3377
3378                        mHandler.post(new Runnable() {
3379                            @Override
3380                            public void run() {
3381                            try {
3382                                IStatusBarService statusbar = getStatusBarService();
3383                                if (statusbar != null) {
3384                                    statusbar.collapsePanels();
3385                                }
3386                            } catch (RemoteException ex) {
3387                                // re-acquire status bar service next time it is needed.
3388                                mStatusBarService = null;
3389                            }
3390                        }});
3391                    } else if (DEBUG_LAYOUT) {
3392                        Log.v(TAG, "Preventing status bar from hiding by policy");
3393                    }
3394                } else {
3395                    if (DEBUG_LAYOUT) Log.v(TAG, "** SHOWING status bar: top is not fullscreen");
3396                    if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
3397                }
3398            }
3399        }
3400
3401        mTopIsFullscreen = topIsFullscreen;
3402
3403        // Hide the key guard if a visible window explicitly specifies that it wants to be
3404        // displayed when the screen is locked.
3405        if (mKeyguard != null) {
3406            if (localLOGV) Log.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
3407                    + mHideLockScreen);
3408            if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !mKeyguardDelegate.isSecure()) {
3409                if (mKeyguard.hideLw(true)) {
3410                    changes |= FINISH_LAYOUT_REDO_LAYOUT
3411                            | FINISH_LAYOUT_REDO_CONFIG
3412                            | FINISH_LAYOUT_REDO_WALLPAPER;
3413                }
3414                if (mKeyguardDelegate.isShowing()) {
3415                    mHandler.post(new Runnable() {
3416                        @Override
3417                        public void run() {
3418                            mKeyguardDelegate.keyguardDone(false, false);
3419                        }
3420                    });
3421                }
3422            } else if (mHideLockScreen) {
3423                if (mKeyguard.hideLw(true)) {
3424                    changes |= FINISH_LAYOUT_REDO_LAYOUT
3425                            | FINISH_LAYOUT_REDO_CONFIG
3426                            | FINISH_LAYOUT_REDO_WALLPAPER;
3427                }
3428                mKeyguardDelegate.setHidden(true);
3429            } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
3430                // This is the case of keyguard isSecure() and not mHideLockScreen.
3431                if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
3432                    // Only launch the next keyguard unlock window once per window.
3433                    if (mKeyguard.showLw(true)) {
3434                        changes |= FINISH_LAYOUT_REDO_LAYOUT
3435                                | FINISH_LAYOUT_REDO_CONFIG
3436                                | FINISH_LAYOUT_REDO_WALLPAPER;
3437                    }
3438                    mKeyguardDelegate.setHidden(false);
3439                    mHandler.post(new Runnable() {
3440                        @Override
3441                        public void run() {
3442                            mKeyguardDelegate.dismiss();
3443                        }
3444                    });
3445                }
3446            } else {
3447                mWinDismissingKeyguard = null;
3448                if (mKeyguard.showLw(true)) {
3449                    changes |= FINISH_LAYOUT_REDO_LAYOUT
3450                            | FINISH_LAYOUT_REDO_CONFIG
3451                            | FINISH_LAYOUT_REDO_WALLPAPER;
3452                }
3453                mKeyguardDelegate.setHidden(false);
3454            }
3455        }
3456
3457        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
3458            // If the navigation bar has been hidden or shown, we need to do another
3459            // layout pass to update that window.
3460            changes |= FINISH_LAYOUT_REDO_LAYOUT;
3461        }
3462
3463        // update since mAllowLockscreenWhenOn might have changed
3464        updateLockScreenTimeout();
3465        return changes;
3466    }
3467
3468    public boolean allowAppAnimationsLw() {
3469        if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) {
3470            // If keyguard is currently visible, no reason to animate
3471            // behind it.
3472            return false;
3473        }
3474        return true;
3475    }
3476
3477    public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
3478        mFocusedWindow = newFocus;
3479        if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
3480            // If the navigation bar has been hidden or shown, we need to do another
3481            // layout pass to update that window.
3482            return FINISH_LAYOUT_REDO_LAYOUT;
3483        }
3484        return 0;
3485    }
3486
3487    /** {@inheritDoc} */
3488    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
3489        // do nothing if headless
3490        if (mHeadless) return;
3491
3492        // lid changed state
3493        final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
3494        if (newLidState == mLidState) {
3495            return;
3496        }
3497
3498        mLidState = newLidState;
3499        applyLidSwitchState();
3500        updateRotation(true);
3501
3502        if (lidOpen) {
3503            if (keyguardIsShowingTq()) {
3504                mKeyguardDelegate.onWakeKeyWhenKeyguardShowingTq(KeyEvent.KEYCODE_POWER);
3505            } else {
3506                mPowerManager.wakeUp(SystemClock.uptimeMillis());
3507            }
3508        } else if (!mLidControlsSleep) {
3509            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3510        }
3511    }
3512
3513    void setHdmiPlugged(boolean plugged) {
3514        if (mHdmiPlugged != plugged) {
3515            mHdmiPlugged = plugged;
3516            updateRotation(true, true);
3517            Intent intent = new Intent(ACTION_HDMI_PLUGGED);
3518            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3519            intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
3520            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3521        }
3522    }
3523
3524    void initializeHdmiState() {
3525        boolean plugged = false;
3526        // watch for HDMI plug messages if the hdmi switch exists
3527        if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
3528            mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
3529
3530            final String filename = "/sys/class/switch/hdmi/state";
3531            FileReader reader = null;
3532            try {
3533                reader = new FileReader(filename);
3534                char[] buf = new char[15];
3535                int n = reader.read(buf);
3536                if (n > 1) {
3537                    plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
3538                }
3539            } catch (IOException ex) {
3540                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3541            } catch (NumberFormatException ex) {
3542                Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3543            } finally {
3544                if (reader != null) {
3545                    try {
3546                        reader.close();
3547                    } catch (IOException ex) {
3548                    }
3549                }
3550            }
3551        }
3552        // This dance forces the code in setHdmiPlugged to run.
3553        // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
3554        mHdmiPlugged = !plugged;
3555        setHdmiPlugged(!mHdmiPlugged);
3556    }
3557
3558    /**
3559     * @return Whether music is being played right now.
3560     */
3561    boolean isMusicActive() {
3562        final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
3563        if (am == null) {
3564            Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
3565            return false;
3566        }
3567        return am.isMusicActive();
3568    }
3569
3570    /**
3571     * Tell the audio service to adjust the volume appropriate to the event.
3572     * @param keycode
3573     */
3574    void handleVolumeKey(int stream, int keycode) {
3575        IAudioService audioService = getAudioService();
3576        if (audioService == null) {
3577            return;
3578        }
3579        try {
3580            // since audio is playing, we shouldn't have to hold a wake lock
3581            // during the call, but we do it as a precaution for the rare possibility
3582            // that the music stops right before we call this
3583            // TODO: Actually handle MUTE.
3584            mBroadcastWakeLock.acquire();
3585            audioService.adjustStreamVolume(stream,
3586                keycode == KeyEvent.KEYCODE_VOLUME_UP
3587                            ? AudioManager.ADJUST_RAISE
3588                            : AudioManager.ADJUST_LOWER,
3589                    0);
3590        } catch (RemoteException e) {
3591            Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
3592        } finally {
3593            mBroadcastWakeLock.release();
3594        }
3595    }
3596
3597    final Object mScreenshotLock = new Object();
3598    ServiceConnection mScreenshotConnection = null;
3599
3600    final Runnable mScreenshotTimeout = new Runnable() {
3601        @Override public void run() {
3602            synchronized (mScreenshotLock) {
3603                if (mScreenshotConnection != null) {
3604                    mContext.unbindService(mScreenshotConnection);
3605                    mScreenshotConnection = null;
3606                }
3607            }
3608        }
3609    };
3610
3611    // Assume this is called from the Handler thread.
3612    private void takeScreenshot() {
3613        synchronized (mScreenshotLock) {
3614            if (mScreenshotConnection != null) {
3615                return;
3616            }
3617            ComponentName cn = new ComponentName("com.android.systemui",
3618                    "com.android.systemui.screenshot.TakeScreenshotService");
3619            Intent intent = new Intent();
3620            intent.setComponent(cn);
3621            ServiceConnection conn = new ServiceConnection() {
3622                @Override
3623                public void onServiceConnected(ComponentName name, IBinder service) {
3624                    synchronized (mScreenshotLock) {
3625                        if (mScreenshotConnection != this) {
3626                            return;
3627                        }
3628                        Messenger messenger = new Messenger(service);
3629                        Message msg = Message.obtain(null, 1);
3630                        final ServiceConnection myConn = this;
3631                        Handler h = new Handler(mHandler.getLooper()) {
3632                            @Override
3633                            public void handleMessage(Message msg) {
3634                                synchronized (mScreenshotLock) {
3635                                    if (mScreenshotConnection == myConn) {
3636                                        mContext.unbindService(mScreenshotConnection);
3637                                        mScreenshotConnection = null;
3638                                        mHandler.removeCallbacks(mScreenshotTimeout);
3639                                    }
3640                                }
3641                            }
3642                        };
3643                        msg.replyTo = new Messenger(h);
3644                        msg.arg1 = msg.arg2 = 0;
3645                        if (mStatusBar != null && mStatusBar.isVisibleLw())
3646                            msg.arg1 = 1;
3647                        if (mNavigationBar != null && mNavigationBar.isVisibleLw())
3648                            msg.arg2 = 1;
3649                        try {
3650                            messenger.send(msg);
3651                        } catch (RemoteException e) {
3652                        }
3653                    }
3654                }
3655                @Override
3656                public void onServiceDisconnected(ComponentName name) {}
3657            };
3658            if (mContext.bindServiceAsUser(
3659                    intent, conn, Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
3660                mScreenshotConnection = conn;
3661                mHandler.postDelayed(mScreenshotTimeout, 10000);
3662            }
3663        }
3664    }
3665
3666    /** {@inheritDoc} */
3667    @Override
3668    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
3669        if (!mSystemBooted) {
3670            // If we have not yet booted, don't let key events do anything.
3671            return 0;
3672        }
3673
3674        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
3675        final boolean canceled = event.isCanceled();
3676        final int keyCode = event.getKeyCode();
3677
3678        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
3679
3680        // If screen is off then we treat the case where the keyguard is open but hidden
3681        // the same as if it were open and in front.
3682        // This will prevent any keys other than the power button from waking the screen
3683        // when the keyguard is hidden by another activity.
3684        final boolean keyguardActive = (mKeyguardDelegate == null ? false :
3685                                            (isScreenOn ?
3686                                                mKeyguardDelegate.isShowingAndNotHidden() :
3687                                                mKeyguardDelegate.isShowing()));
3688
3689        if (keyCode == KeyEvent.KEYCODE_POWER) {
3690            policyFlags |= WindowManagerPolicy.FLAG_WAKE;
3691        }
3692        final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE
3693                | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3694
3695        if (DEBUG_INPUT) {
3696            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
3697                    + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive
3698                    + " policyFlags=" + Integer.toHexString(policyFlags)
3699                    + " isWakeKey=" + isWakeKey);
3700        }
3701
3702        if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
3703                && event.getRepeatCount() == 0) {
3704            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
3705        }
3706
3707        // Basic policy based on screen state and keyguard.
3708        // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
3709        //        is on or off, really.  We should care about whether the device is in an
3710        //        interactive state or is in suspend pretending to be "off".
3711        //        The primary screen might be turned off due to proximity sensor or
3712        //        because we are presenting media on an auxiliary screen or remotely controlling
3713        //        the device some other way (which is why we have an exemption here for injected
3714        //        events).
3715        int result;
3716        if ((isScreenOn && !mHeadless) || (isInjected && !isWakeKey)) {
3717            // When the screen is on or if the key is injected pass the key to the application.
3718            result = ACTION_PASS_TO_USER;
3719        } else {
3720            // When the screen is off and the key is not injected, determine whether
3721            // to wake the device but don't pass the key to the application.
3722            result = 0;
3723            if (down && isWakeKey && isWakeKeyWhenScreenOff(keyCode)) {
3724                if (keyguardActive) {
3725                    // If the keyguard is showing, let it wake the device when ready.
3726                    mKeyguardDelegate.onWakeKeyWhenKeyguardShowingTq(keyCode);
3727                } else {
3728                    // Otherwise, wake the device ourselves.
3729                    result |= ACTION_WAKE_UP;
3730                }
3731            }
3732        }
3733
3734        // If the key would be handled globally, just return the result, don't worry about special
3735        // key processing.
3736        if (mGlobalKeyManager.shouldHandleGlobalKey(keyCode, event)) {
3737            return result;
3738        }
3739
3740        // Handle special keys.
3741        switch (keyCode) {
3742            case KeyEvent.KEYCODE_VOLUME_DOWN:
3743            case KeyEvent.KEYCODE_VOLUME_UP:
3744            case KeyEvent.KEYCODE_VOLUME_MUTE: {
3745                if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
3746                    if (down) {
3747                        if (isScreenOn && !mVolumeDownKeyTriggered
3748                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3749                            mVolumeDownKeyTriggered = true;
3750                            mVolumeDownKeyTime = event.getDownTime();
3751                            mVolumeDownKeyConsumedByScreenshotChord = false;
3752                            cancelPendingPowerKeyAction();
3753                            interceptScreenshotChord();
3754                        }
3755                    } else {
3756                        mVolumeDownKeyTriggered = false;
3757                        cancelPendingScreenshotChordAction();
3758                    }
3759                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
3760                    if (down) {
3761                        if (isScreenOn && !mVolumeUpKeyTriggered
3762                                && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3763                            mVolumeUpKeyTriggered = true;
3764                            cancelPendingPowerKeyAction();
3765                            cancelPendingScreenshotChordAction();
3766                        }
3767                    } else {
3768                        mVolumeUpKeyTriggered = false;
3769                        cancelPendingScreenshotChordAction();
3770                    }
3771                }
3772                if (down) {
3773                    ITelephony telephonyService = getTelephonyService();
3774                    if (telephonyService != null) {
3775                        try {
3776                            if (telephonyService.isRinging()) {
3777                                // If an incoming call is ringing, either VOLUME key means
3778                                // "silence ringer".  We handle these keys here, rather than
3779                                // in the InCallScreen, to make sure we'll respond to them
3780                                // even if the InCallScreen hasn't come to the foreground yet.
3781                                // Look for the DOWN event here, to agree with the "fallback"
3782                                // behavior in the InCallScreen.
3783                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3784                                      + " VOLUME key-down while ringing: Silence ringer!");
3785
3786                                // Silence the ringer.  (It's safe to call this
3787                                // even if the ringer has already been silenced.)
3788                                telephonyService.silenceRinger();
3789
3790                                // And *don't* pass this key thru to the current activity
3791                                // (which is probably the InCallScreen.)
3792                                result &= ~ACTION_PASS_TO_USER;
3793                                break;
3794                            }
3795                            if (telephonyService.isOffhook()
3796                                    && (result & ACTION_PASS_TO_USER) == 0) {
3797                                // If we are in call but we decided not to pass the key to
3798                                // the application, handle the volume change here.
3799                                handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
3800                                break;
3801                            }
3802                        } catch (RemoteException ex) {
3803                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3804                        }
3805                    }
3806
3807                    if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
3808                        // If music is playing but we decided not to pass the key to the
3809                        // application, handle the volume change here.
3810                        handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
3811                        break;
3812                    }
3813                }
3814                break;
3815            }
3816
3817            case KeyEvent.KEYCODE_ENDCALL: {
3818                result &= ~ACTION_PASS_TO_USER;
3819                if (down) {
3820                    ITelephony telephonyService = getTelephonyService();
3821                    boolean hungUp = false;
3822                    if (telephonyService != null) {
3823                        try {
3824                            hungUp = telephonyService.endCall();
3825                        } catch (RemoteException ex) {
3826                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3827                        }
3828                    }
3829                    interceptPowerKeyDown(!isScreenOn || hungUp);
3830                } else {
3831                    if (interceptPowerKeyUp(canceled)) {
3832                        if ((mEndcallBehavior
3833                                & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
3834                            if (goHome()) {
3835                                break;
3836                            }
3837                        }
3838                        if ((mEndcallBehavior
3839                                & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
3840                            result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3841                        }
3842                    }
3843                }
3844                break;
3845            }
3846
3847            case KeyEvent.KEYCODE_POWER: {
3848                result &= ~ACTION_PASS_TO_USER;
3849                if (down) {
3850                    if (isScreenOn && !mPowerKeyTriggered
3851                            && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3852                        mPowerKeyTriggered = true;
3853                        mPowerKeyTime = event.getDownTime();
3854                        interceptScreenshotChord();
3855                    }
3856
3857                    ITelephony telephonyService = getTelephonyService();
3858                    boolean hungUp = false;
3859                    if (telephonyService != null) {
3860                        try {
3861                            if (telephonyService.isRinging()) {
3862                                // Pressing Power while there's a ringing incoming
3863                                // call should silence the ringer.
3864                                telephonyService.silenceRinger();
3865                            } else if ((mIncallPowerBehavior
3866                                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
3867                                    && telephonyService.isOffhook()) {
3868                                // Otherwise, if "Power button ends call" is enabled,
3869                                // the Power button will hang up any current active call.
3870                                hungUp = telephonyService.endCall();
3871                            }
3872                        } catch (RemoteException ex) {
3873                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3874                        }
3875                    }
3876                    interceptPowerKeyDown(!isScreenOn || hungUp
3877                            || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered);
3878                } else {
3879                    mPowerKeyTriggered = false;
3880                    cancelPendingScreenshotChordAction();
3881                    if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) {
3882                        result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3883                    }
3884                    mPendingPowerKeyUpCanceled = false;
3885                }
3886                break;
3887            }
3888
3889            case KeyEvent.KEYCODE_MEDIA_PLAY:
3890            case KeyEvent.KEYCODE_MEDIA_PAUSE:
3891            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3892                if (down) {
3893                    ITelephony telephonyService = getTelephonyService();
3894                    if (telephonyService != null) {
3895                        try {
3896                            if (!telephonyService.isIdle()) {
3897                                // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
3898                                // to avoid music playback.
3899                                break;
3900                            }
3901                        } catch (RemoteException ex) {
3902                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3903                        }
3904                    }
3905                }
3906            case KeyEvent.KEYCODE_HEADSETHOOK:
3907            case KeyEvent.KEYCODE_MUTE:
3908            case KeyEvent.KEYCODE_MEDIA_STOP:
3909            case KeyEvent.KEYCODE_MEDIA_NEXT:
3910            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
3911            case KeyEvent.KEYCODE_MEDIA_REWIND:
3912            case KeyEvent.KEYCODE_MEDIA_RECORD:
3913            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
3914                if ((result & ACTION_PASS_TO_USER) == 0) {
3915                    // Only do this if we would otherwise not pass it to the user. In that
3916                    // case, the PhoneWindow class will do the same thing, except it will
3917                    // only do it if the showing app doesn't process the key on its own.
3918                    // Note that we need to make a copy of the key event here because the
3919                    // original key event will be recycled when we return.
3920                    mBroadcastWakeLock.acquire();
3921                    Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
3922                            new KeyEvent(event));
3923                    msg.setAsynchronous(true);
3924                    msg.sendToTarget();
3925                }
3926                break;
3927            }
3928
3929            case KeyEvent.KEYCODE_CALL: {
3930                if (down) {
3931                    ITelephony telephonyService = getTelephonyService();
3932                    if (telephonyService != null) {
3933                        try {
3934                            if (telephonyService.isRinging()) {
3935                                Log.i(TAG, "interceptKeyBeforeQueueing:"
3936                                      + " CALL key-down while ringing: Answer the call!");
3937                                telephonyService.answerRingingCall();
3938
3939                                // And *don't* pass this key thru to the current activity
3940                                // (which is presumably the InCallScreen.)
3941                                result &= ~ACTION_PASS_TO_USER;
3942                            }
3943                        } catch (RemoteException ex) {
3944                            Log.w(TAG, "ITelephony threw RemoteException", ex);
3945                        }
3946                    }
3947                }
3948                break;
3949            }
3950        }
3951        return result;
3952    }
3953
3954    /**
3955     * When the screen is off we ignore some keys that might otherwise typically
3956     * be considered wake keys.  We filter them out here.
3957     *
3958     * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
3959     * is always considered a wake key.
3960     */
3961    private boolean isWakeKeyWhenScreenOff(int keyCode) {
3962        switch (keyCode) {
3963            // ignore volume keys unless docked
3964            case KeyEvent.KEYCODE_VOLUME_UP:
3965            case KeyEvent.KEYCODE_VOLUME_DOWN:
3966            case KeyEvent.KEYCODE_VOLUME_MUTE:
3967                return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
3968
3969            // ignore media and camera keys
3970            case KeyEvent.KEYCODE_MUTE:
3971            case KeyEvent.KEYCODE_HEADSETHOOK:
3972            case KeyEvent.KEYCODE_MEDIA_PLAY:
3973            case KeyEvent.KEYCODE_MEDIA_PAUSE:
3974            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3975            case KeyEvent.KEYCODE_MEDIA_STOP:
3976            case KeyEvent.KEYCODE_MEDIA_NEXT:
3977            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
3978            case KeyEvent.KEYCODE_MEDIA_REWIND:
3979            case KeyEvent.KEYCODE_MEDIA_RECORD:
3980            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
3981            case KeyEvent.KEYCODE_CAMERA:
3982                return false;
3983        }
3984        return true;
3985    }
3986
3987
3988    /** {@inheritDoc} */
3989    @Override
3990    public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
3991        int result = 0;
3992
3993        final boolean isWakeMotion = (policyFlags
3994                & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3995        if (isWakeMotion) {
3996            if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
3997                // If the keyguard is showing, let it decide what to do with the wake motion.
3998                mKeyguardDelegate.onWakeMotionWhenKeyguardShowing();
3999            } else {
4000                // Otherwise, wake the device ourselves.
4001                result |= ACTION_WAKE_UP;
4002            }
4003        }
4004        return result;
4005    }
4006
4007    void dispatchMediaKeyWithWakeLock(KeyEvent event) {
4008        if (DEBUG_INPUT) {
4009            Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
4010        }
4011
4012        if (mHavePendingMediaKeyRepeatWithWakeLock) {
4013            if (DEBUG_INPUT) {
4014                Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
4015            }
4016
4017            mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
4018            mHavePendingMediaKeyRepeatWithWakeLock = false;
4019            mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
4020        }
4021
4022        dispatchMediaKeyWithWakeLockToAudioService(event);
4023
4024        if (event.getAction() == KeyEvent.ACTION_DOWN
4025                && event.getRepeatCount() == 0) {
4026            mHavePendingMediaKeyRepeatWithWakeLock = true;
4027
4028            Message msg = mHandler.obtainMessage(
4029                    MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
4030            msg.setAsynchronous(true);
4031            mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
4032        } else {
4033            mBroadcastWakeLock.release();
4034        }
4035    }
4036
4037    void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
4038        mHavePendingMediaKeyRepeatWithWakeLock = false;
4039
4040        KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
4041                SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
4042        if (DEBUG_INPUT) {
4043            Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
4044        }
4045
4046        dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
4047        mBroadcastWakeLock.release();
4048    }
4049
4050    void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
4051        if (ActivityManagerNative.isSystemReady()) {
4052            IAudioService audioService = getAudioService();
4053            if (audioService != null) {
4054                try {
4055                    audioService.dispatchMediaKeyEventUnderWakelock(event);
4056                } catch (RemoteException e) {
4057                    Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e);
4058                }
4059            }
4060        }
4061    }
4062
4063    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
4064        @Override
4065        public void onReceive(Context context, Intent intent) {
4066            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
4067                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
4068                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
4069            } else {
4070                try {
4071                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
4072                            ServiceManager.getService(Context.UI_MODE_SERVICE));
4073                    mUiMode = uiModeService.getCurrentModeType();
4074                } catch (RemoteException e) {
4075                }
4076            }
4077            updateRotation(true);
4078            synchronized (mLock) {
4079                updateOrientationListenerLp();
4080            }
4081        }
4082    };
4083
4084    BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
4085        @Override
4086        public void onReceive(Context context, Intent intent) {
4087            if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
4088                if (mKeyguardDelegate != null) {
4089                    mKeyguardDelegate.onDreamingStarted();
4090                }
4091            } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
4092                if (mKeyguardDelegate != null) {
4093                    mKeyguardDelegate.onDreamingStopped();
4094                }
4095            }
4096        }
4097    };
4098
4099    BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
4100        @Override
4101        public void onReceive(Context context, Intent intent) {
4102            if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
4103                // tickle the settings observer: this first ensures that we're
4104                // observing the relevant settings for the newly-active user,
4105                // and then updates our own bookkeeping based on the now-
4106                // current user.
4107                mSettingsObserver.onChange(false);
4108
4109                // force a re-application of focused window sysui visibility.
4110                // the window may never have been shown for this user
4111                // e.g. the keyguard when going through the new-user setup flow
4112                synchronized(mLock) {
4113                    mLastSystemUiFlags = 0;
4114                    updateSystemUiVisibilityLw();
4115                }
4116            }
4117        }
4118    };
4119
4120    private void showHideybars() {
4121        synchronized(mLock) {
4122            if (mHideybars == HIDEYBARS_SHOWING) {
4123                if (DEBUG) Slog.d(TAG, "Not showing hideybars, already shown");
4124                return;
4125            }
4126            if (mStatusBar.isDisplayedLw()) {
4127                if (DEBUG) Slog.d(TAG, "Not showing hideybars, status bar already visible");
4128                return;
4129            }
4130            mHideybars = HIDEYBARS_SHOWING;
4131            updateSystemUiVisibilityLw();
4132        }
4133    }
4134
4135    @Override
4136    public void screenTurnedOff(int why) {
4137        EventLog.writeEvent(70000, 0);
4138        synchronized (mLock) {
4139            mScreenOnEarly = false;
4140            mScreenOnFully = false;
4141        }
4142        if (mKeyguardDelegate != null) {
4143            mKeyguardDelegate.onScreenTurnedOff(why);
4144        }
4145        synchronized (mLock) {
4146            updateOrientationListenerLp();
4147            updateLockScreenTimeout();
4148        }
4149    }
4150
4151    @Override
4152    public void screenTurningOn(final ScreenOnListener screenOnListener) {
4153        EventLog.writeEvent(70000, 1);
4154        if (false) {
4155            RuntimeException here = new RuntimeException("here");
4156            here.fillInStackTrace();
4157            Slog.i(TAG, "Screen turning on...", here);
4158        }
4159
4160        synchronized (mLock) {
4161            mScreenOnEarly = true;
4162            updateOrientationListenerLp();
4163            updateLockScreenTimeout();
4164        }
4165
4166        waitForKeyguard(screenOnListener);
4167    }
4168
4169    private void waitForKeyguard(final ScreenOnListener screenOnListener) {
4170        if (mKeyguardDelegate != null) {
4171            if (screenOnListener != null) {
4172                mKeyguardDelegate.onScreenTurnedOn(new KeyguardServiceDelegate.ShowListener() {
4173                    @Override
4174                    public void onShown(IBinder windowToken) {
4175                        waitForKeyguardWindowDrawn(windowToken, screenOnListener);
4176                    }
4177                });
4178                return;
4179            } else {
4180                mKeyguardDelegate.onScreenTurnedOn(null);
4181            }
4182        } else {
4183            Slog.i(TAG, "No keyguard interface!");
4184        }
4185        finishScreenTurningOn(screenOnListener);
4186    }
4187
4188    private void waitForKeyguardWindowDrawn(IBinder windowToken,
4189            final ScreenOnListener screenOnListener) {
4190        if (windowToken != null) {
4191            try {
4192                if (mWindowManager.waitForWindowDrawn(
4193                        windowToken, new IRemoteCallback.Stub() {
4194                    @Override
4195                    public void sendResult(Bundle data) {
4196                        Slog.i(TAG, "Lock screen displayed!");
4197                        finishScreenTurningOn(screenOnListener);
4198                    }
4199                })) {
4200                    return;
4201                }
4202            } catch (RemoteException ex) {
4203                // Can't happen in system process.
4204            }
4205        }
4206
4207        Slog.i(TAG, "No lock screen!");
4208        finishScreenTurningOn(screenOnListener);
4209    }
4210
4211    private void finishScreenTurningOn(ScreenOnListener screenOnListener) {
4212        synchronized (mLock) {
4213            mScreenOnFully = true;
4214        }
4215
4216        try {
4217            mWindowManager.setEventDispatching(true);
4218        } catch (RemoteException unhandled) {
4219        }
4220
4221        if (screenOnListener != null) {
4222            screenOnListener.onScreenOn();
4223        }
4224    }
4225
4226    @Override
4227    public boolean isScreenOnEarly() {
4228        return mScreenOnEarly;
4229    }
4230
4231    @Override
4232    public boolean isScreenOnFully() {
4233        return mScreenOnFully;
4234    }
4235
4236    /** {@inheritDoc} */
4237    public void enableKeyguard(boolean enabled) {
4238        if (mKeyguardDelegate != null) {
4239            mKeyguardDelegate.setKeyguardEnabled(enabled);
4240        }
4241    }
4242
4243    /** {@inheritDoc} */
4244    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
4245        if (mKeyguardDelegate != null) {
4246            mKeyguardDelegate.verifyUnlock(callback);
4247        }
4248    }
4249
4250    private boolean keyguardIsShowingTq() {
4251        if (mKeyguardDelegate == null) return false;
4252        return mKeyguardDelegate.isShowingAndNotHidden();
4253    }
4254
4255
4256    /** {@inheritDoc} */
4257    public boolean isKeyguardLocked() {
4258        return keyguardOn();
4259    }
4260
4261    /** {@inheritDoc} */
4262    public boolean isKeyguardSecure() {
4263        if (mKeyguardDelegate == null) return false;
4264        return mKeyguardDelegate.isSecure();
4265    }
4266
4267    /** {@inheritDoc} */
4268    public boolean inKeyguardRestrictedKeyInputMode() {
4269        if (mKeyguardDelegate == null) return false;
4270        return mKeyguardDelegate.isInputRestricted();
4271    }
4272
4273    public void dismissKeyguardLw() {
4274        if (mKeyguardDelegate != null && mKeyguardDelegate.isShowing()) {
4275            mHandler.post(new Runnable() {
4276                public void run() {
4277                    if (mKeyguardDelegate.isDismissable()) {
4278                        // Can we just finish the keyguard straight away?
4279                        mKeyguardDelegate.keyguardDone(false, true);
4280                    } else {
4281                        // ask the keyguard to prompt the user to authenticate if necessary
4282                        mKeyguardDelegate.dismiss();
4283                    }
4284                }
4285            });
4286        }
4287    }
4288
4289    void sendCloseSystemWindows() {
4290        sendCloseSystemWindows(mContext, null);
4291    }
4292
4293    void sendCloseSystemWindows(String reason) {
4294        sendCloseSystemWindows(mContext, reason);
4295    }
4296
4297    static void sendCloseSystemWindows(Context context, String reason) {
4298        if (ActivityManagerNative.isSystemReady()) {
4299            try {
4300                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
4301            } catch (RemoteException e) {
4302            }
4303        }
4304    }
4305
4306    @Override
4307    public int rotationForOrientationLw(int orientation, int lastRotation) {
4308        if (false) {
4309            Slog.v(TAG, "rotationForOrientationLw(orient="
4310                        + orientation + ", last=" + lastRotation
4311                        + "); user=" + mUserRotation + " "
4312                        + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
4313                            ? "USER_ROTATION_LOCKED" : "")
4314                        );
4315        }
4316
4317        synchronized (mLock) {
4318            int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
4319            if (sensorRotation < 0) {
4320                sensorRotation = lastRotation;
4321            }
4322
4323            final int preferredRotation;
4324            if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
4325                // Ignore sensor when lid switch is open and rotation is forced.
4326                preferredRotation = mLidOpenRotation;
4327            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
4328                    && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
4329                // Ignore sensor when in car dock unless explicitly enabled.
4330                // This case can override the behavior of NOSENSOR, and can also
4331                // enable 180 degree rotation while docked.
4332                preferredRotation = mCarDockEnablesAccelerometer
4333                        ? sensorRotation : mCarDockRotation;
4334            } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
4335                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
4336                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
4337                    && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
4338                // Ignore sensor when in desk dock unless explicitly enabled.
4339                // This case can override the behavior of NOSENSOR, and can also
4340                // enable 180 degree rotation while docked.
4341                preferredRotation = mDeskDockEnablesAccelerometer
4342                        ? sensorRotation : mDeskDockRotation;
4343            } else if (mHdmiPlugged && mDemoHdmiRotationLock) {
4344                // Ignore sensor when plugged into HDMI when demo HDMI rotation lock enabled.
4345                // Note that the dock orientation overrides the HDMI orientation.
4346                preferredRotation = mDemoHdmiRotation;
4347            } else if (mHdmiPlugged && mDockMode == Intent.EXTRA_DOCK_STATE_UNDOCKED
4348                    && mUndockedHdmiRotation >= 0) {
4349                // Ignore sensor when plugged into HDMI and an undocked orientation has
4350                // been specified in the configuration (only for legacy devices without
4351                // full multi-display support).
4352                // Note that the dock orientation overrides the HDMI orientation.
4353                preferredRotation = mUndockedHdmiRotation;
4354            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LOCKED) {
4355                // Application just wants to remain locked in the last rotation.
4356                preferredRotation = lastRotation;
4357            } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
4358                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
4359                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
4360                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE
4361                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
4362                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER))
4363                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
4364                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
4365                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
4366                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
4367                // Otherwise, use sensor only if requested by the application or enabled
4368                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
4369                if (mAllowAllRotations < 0) {
4370                    // Can't read this during init() because the context doesn't
4371                    // have display metrics at that time so we cannot determine
4372                    // tablet vs. phone then.
4373                    mAllowAllRotations = mContext.getResources().getBoolean(
4374                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
4375                }
4376                if (sensorRotation != Surface.ROTATION_180
4377                        || mAllowAllRotations == 1
4378                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
4379                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_USER) {
4380                    preferredRotation = sensorRotation;
4381                } else {
4382                    preferredRotation = lastRotation;
4383                }
4384            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
4385                    && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
4386                // Apply rotation lock.  Does not apply to NOSENSOR.
4387                // The idea is that the user rotation expresses a weak preference for the direction
4388                // of gravity and as NOSENSOR is never affected by gravity, then neither should
4389                // NOSENSOR be affected by rotation lock (although it will be affected by docks).
4390                preferredRotation = mUserRotation;
4391            } else {
4392                // No overriding preference.
4393                // We will do exactly what the application asked us to do.
4394                preferredRotation = -1;
4395            }
4396
4397            switch (orientation) {
4398                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
4399                    // Return portrait unless overridden.
4400                    if (isAnyPortrait(preferredRotation)) {
4401                        return preferredRotation;
4402                    }
4403                    return mPortraitRotation;
4404
4405                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
4406                    // Return landscape unless overridden.
4407                    if (isLandscapeOrSeascape(preferredRotation)) {
4408                        return preferredRotation;
4409                    }
4410                    return mLandscapeRotation;
4411
4412                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
4413                    // Return reverse portrait unless overridden.
4414                    if (isAnyPortrait(preferredRotation)) {
4415                        return preferredRotation;
4416                    }
4417                    return mUpsideDownRotation;
4418
4419                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
4420                    // Return seascape unless overridden.
4421                    if (isLandscapeOrSeascape(preferredRotation)) {
4422                        return preferredRotation;
4423                    }
4424                    return mSeascapeRotation;
4425
4426                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
4427                case ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE:
4428                    // Return either landscape rotation.
4429                    if (isLandscapeOrSeascape(preferredRotation)) {
4430                        return preferredRotation;
4431                    }
4432                    if (isLandscapeOrSeascape(lastRotation)) {
4433                        return lastRotation;
4434                    }
4435                    return mLandscapeRotation;
4436
4437                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
4438                case ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT:
4439                    // Return either portrait rotation.
4440                    if (isAnyPortrait(preferredRotation)) {
4441                        return preferredRotation;
4442                    }
4443                    if (isAnyPortrait(lastRotation)) {
4444                        return lastRotation;
4445                    }
4446                    return mPortraitRotation;
4447
4448                default:
4449                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
4450                    // just return the preferred orientation we already calculated.
4451                    if (preferredRotation >= 0) {
4452                        return preferredRotation;
4453                    }
4454                    return Surface.ROTATION_0;
4455            }
4456        }
4457    }
4458
4459    @Override
4460    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
4461        switch (orientation) {
4462            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
4463            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
4464            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
4465                return isAnyPortrait(rotation);
4466
4467            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
4468            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
4469            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
4470                return isLandscapeOrSeascape(rotation);
4471
4472            default:
4473                return true;
4474        }
4475    }
4476
4477    @Override
4478    public void setRotationLw(int rotation) {
4479        mOrientationListener.setCurrentRotation(rotation);
4480    }
4481
4482    private boolean isLandscapeOrSeascape(int rotation) {
4483        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
4484    }
4485
4486    private boolean isAnyPortrait(int rotation) {
4487        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
4488    }
4489
4490    public int getUserRotationMode() {
4491        return Settings.System.getIntForUser(mContext.getContentResolver(),
4492                Settings.System.USER_ROTATION, WindowManagerPolicy.USER_ROTATION_FREE,
4493                UserHandle.USER_CURRENT);
4494    }
4495
4496    // User rotation: to be used when all else fails in assigning an orientation to the device
4497    public void setUserRotationMode(int mode, int rot) {
4498        ContentResolver res = mContext.getContentResolver();
4499
4500        // mUserRotationMode and mUserRotation will be assigned by the content observer
4501        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
4502            Settings.System.putIntForUser(res,
4503                    Settings.System.USER_ROTATION,
4504                    rot,
4505                    UserHandle.USER_CURRENT);
4506            Settings.System.putIntForUser(res,
4507                    Settings.System.ACCELEROMETER_ROTATION,
4508                    0,
4509                    UserHandle.USER_CURRENT);
4510        } else {
4511            Settings.System.putIntForUser(res,
4512                    Settings.System.ACCELEROMETER_ROTATION,
4513                    1,
4514                    UserHandle.USER_CURRENT);
4515        }
4516    }
4517
4518    public void setSafeMode(boolean safeMode) {
4519        mSafeMode = safeMode;
4520        performHapticFeedbackLw(null, safeMode
4521                ? HapticFeedbackConstants.SAFE_MODE_ENABLED
4522                : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
4523    }
4524
4525    static long[] getLongIntArray(Resources r, int resid) {
4526        int[] ar = r.getIntArray(resid);
4527        if (ar == null) {
4528            return null;
4529        }
4530        long[] out = new long[ar.length];
4531        for (int i=0; i<ar.length; i++) {
4532            out[i] = ar[i];
4533        }
4534        return out;
4535    }
4536
4537    /** {@inheritDoc} */
4538    public void systemReady() {
4539        if (!mHeadless) {
4540            mKeyguardDelegate = new KeyguardServiceDelegate(mContext, null);
4541            mKeyguardDelegate.onSystemReady();
4542        }
4543        synchronized (mLock) {
4544            updateOrientationListenerLp();
4545            mSystemReady = true;
4546            mHandler.post(new Runnable() {
4547                public void run() {
4548                    updateSettings();
4549                }
4550            });
4551        }
4552    }
4553
4554    /** {@inheritDoc} */
4555    public void systemBooted() {
4556        synchronized (mLock) {
4557            mSystemBooted = true;
4558        }
4559    }
4560
4561    ProgressDialog mBootMsgDialog = null;
4562
4563    /** {@inheritDoc} */
4564    public void showBootMessage(final CharSequence msg, final boolean always) {
4565        if (mHeadless) return;
4566        mHandler.post(new Runnable() {
4567            @Override public void run() {
4568                if (mBootMsgDialog == null) {
4569                    mBootMsgDialog = new ProgressDialog(mContext) {
4570                        // This dialog will consume all events coming in to
4571                        // it, to avoid it trying to do things too early in boot.
4572                        @Override public boolean dispatchKeyEvent(KeyEvent event) {
4573                            return true;
4574                        }
4575                        @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4576                            return true;
4577                        }
4578                        @Override public boolean dispatchTouchEvent(MotionEvent ev) {
4579                            return true;
4580                        }
4581                        @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
4582                            return true;
4583                        }
4584                        @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
4585                            return true;
4586                        }
4587                        @Override public boolean dispatchPopulateAccessibilityEvent(
4588                                AccessibilityEvent event) {
4589                            return true;
4590                        }
4591                    };
4592                    mBootMsgDialog.setTitle(R.string.android_upgrading_title);
4593                    mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
4594                    mBootMsgDialog.setIndeterminate(true);
4595                    mBootMsgDialog.getWindow().setType(
4596                            WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
4597                    mBootMsgDialog.getWindow().addFlags(
4598                            WindowManager.LayoutParams.FLAG_DIM_BEHIND
4599                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
4600                    mBootMsgDialog.getWindow().setDimAmount(1);
4601                    WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
4602                    lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
4603                    mBootMsgDialog.getWindow().setAttributes(lp);
4604                    mBootMsgDialog.setCancelable(false);
4605                    mBootMsgDialog.show();
4606                }
4607                mBootMsgDialog.setMessage(msg);
4608            }
4609        });
4610    }
4611
4612    /** {@inheritDoc} */
4613    public void hideBootMessages() {
4614        mHandler.post(new Runnable() {
4615            @Override public void run() {
4616                if (mBootMsgDialog != null) {
4617                    mBootMsgDialog.dismiss();
4618                    mBootMsgDialog = null;
4619                }
4620            }
4621        });
4622    }
4623
4624    /** {@inheritDoc} */
4625    public void userActivity() {
4626        // ***************************************
4627        // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
4628        // ***************************************
4629        // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
4630        // WITH ITS LOCKS HELD.
4631        //
4632        // This code must be VERY careful about the locks
4633        // it acquires.
4634        // In fact, the current code acquires way too many,
4635        // and probably has lurking deadlocks.
4636
4637        synchronized (mScreenLockTimeout) {
4638            if (mLockScreenTimerActive) {
4639                // reset the timer
4640                mHandler.removeCallbacks(mScreenLockTimeout);
4641                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4642            }
4643        }
4644    }
4645
4646    class ScreenLockTimeout implements Runnable {
4647        Bundle options;
4648
4649        @Override
4650        public void run() {
4651            synchronized (this) {
4652                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
4653                if (mKeyguardDelegate != null) {
4654                    mKeyguardDelegate.doKeyguardTimeout(options);
4655                }
4656                mLockScreenTimerActive = false;
4657                options = null;
4658            }
4659        }
4660
4661        public void setLockOptions(Bundle options) {
4662            this.options = options;
4663        }
4664    }
4665
4666    ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
4667
4668    public void lockNow(Bundle options) {
4669        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
4670        mHandler.removeCallbacks(mScreenLockTimeout);
4671        if (options != null) {
4672            // In case multiple calls are made to lockNow, we don't wipe out the options
4673            // until the runnable actually executes.
4674            mScreenLockTimeout.setLockOptions(options);
4675        }
4676        mHandler.post(mScreenLockTimeout);
4677    }
4678
4679    private void updateLockScreenTimeout() {
4680        synchronized (mScreenLockTimeout) {
4681            boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly &&
4682                    mKeyguardDelegate != null && mKeyguardDelegate.isSecure());
4683            if (mLockScreenTimerActive != enable) {
4684                if (enable) {
4685                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
4686                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4687                } else {
4688                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
4689                    mHandler.removeCallbacks(mScreenLockTimeout);
4690                }
4691                mLockScreenTimerActive = enable;
4692            }
4693        }
4694    }
4695
4696    /** {@inheritDoc} */
4697    public void enableScreenAfterBoot() {
4698        readLidState();
4699        applyLidSwitchState();
4700        updateRotation(true);
4701    }
4702
4703    private void applyLidSwitchState() {
4704        if (mLidState == LID_CLOSED && mLidControlsSleep) {
4705            mPowerManager.goToSleep(SystemClock.uptimeMillis());
4706        }
4707    }
4708
4709    void updateRotation(boolean alwaysSendConfiguration) {
4710        try {
4711            //set orientation on WindowManager
4712            mWindowManager.updateRotation(alwaysSendConfiguration, false);
4713        } catch (RemoteException e) {
4714            // Ignore
4715        }
4716    }
4717
4718    void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
4719        try {
4720            //set orientation on WindowManager
4721            mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
4722        } catch (RemoteException e) {
4723            // Ignore
4724        }
4725    }
4726
4727    /**
4728     * Return an Intent to launch the currently active dock app as home.  Returns
4729     * null if the standard home should be launched, which is the case if any of the following is
4730     * true:
4731     * <ul>
4732     *  <li>The device is not in either car mode or desk mode
4733     *  <li>The device is in car mode but ENABLE_CAR_DOCK_HOME_CAPTURE is false
4734     *  <li>The device is in desk mode but ENABLE_DESK_DOCK_HOME_CAPTURE is false
4735     *  <li>The device is in car mode but there's no CAR_DOCK app with METADATA_DOCK_HOME
4736     *  <li>The device is in desk mode but there's no DESK_DOCK app with METADATA_DOCK_HOME
4737     * </ul>
4738     * @return
4739     */
4740    Intent createHomeDockIntent() {
4741        Intent intent = null;
4742
4743        // What home does is based on the mode, not the dock state.  That
4744        // is, when in car mode you should be taken to car home regardless
4745        // of whether we are actually in a car dock.
4746        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
4747            if (ENABLE_CAR_DOCK_HOME_CAPTURE) {
4748                intent = mCarDockIntent;
4749            }
4750        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
4751            if (ENABLE_DESK_DOCK_HOME_CAPTURE) {
4752                intent = mDeskDockIntent;
4753            }
4754        }
4755
4756        if (intent == null) {
4757            return null;
4758        }
4759
4760        ActivityInfo ai = null;
4761        ResolveInfo info = mContext.getPackageManager().resolveActivityAsUser(
4762                intent,
4763                PackageManager.MATCH_DEFAULT_ONLY,
4764                UserHandle.USER_CURRENT);
4765        if (info != null) {
4766            ai = info.activityInfo;
4767        }
4768        if (ai != null
4769                && ai.metaData != null
4770                && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
4771            intent = new Intent(intent);
4772            intent.setClassName(ai.packageName, ai.name);
4773            return intent;
4774        }
4775
4776        return null;
4777    }
4778
4779    void startDockOrHome() {
4780        awakenDreams();
4781
4782        Intent dock = createHomeDockIntent();
4783        if (dock != null) {
4784            try {
4785                mContext.startActivityAsUser(dock, UserHandle.CURRENT);
4786                return;
4787            } catch (ActivityNotFoundException e) {
4788            }
4789        }
4790
4791        mContext.startActivityAsUser(mHomeIntent, UserHandle.CURRENT);
4792    }
4793
4794    /**
4795     * goes to the home screen
4796     * @return whether it did anything
4797     */
4798    boolean goHome() {
4799        if (false) {
4800            // This code always brings home to the front.
4801            try {
4802                ActivityManagerNative.getDefault().stopAppSwitches();
4803            } catch (RemoteException e) {
4804            }
4805            sendCloseSystemWindows();
4806            startDockOrHome();
4807        } else {
4808            // This code brings home to the front or, if it is already
4809            // at the front, puts the device to sleep.
4810            try {
4811                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
4812                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
4813                    Log.d(TAG, "UTS-TEST-MODE");
4814                } else {
4815                    ActivityManagerNative.getDefault().stopAppSwitches();
4816                    sendCloseSystemWindows();
4817                    Intent dock = createHomeDockIntent();
4818                    if (dock != null) {
4819                        int result = ActivityManagerNative.getDefault()
4820                                .startActivityAsUser(null, null, dock,
4821                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
4822                                        null, null, 0,
4823                                        ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4824                                        null, null, null, UserHandle.USER_CURRENT);
4825                        if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4826                            return false;
4827                        }
4828                    }
4829                }
4830                int result = ActivityManagerNative.getDefault()
4831                        .startActivityAsUser(null, null, mHomeIntent,
4832                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
4833                                null, null, 0,
4834                                ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4835                                null, null, null, UserHandle.USER_CURRENT);
4836                if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4837                    return false;
4838                }
4839            } catch (RemoteException ex) {
4840                // bummer, the activity manager, which is in this process, is dead
4841            }
4842        }
4843        return true;
4844    }
4845
4846    public void setCurrentOrientationLw(int newOrientation) {
4847        synchronized (mLock) {
4848            if (newOrientation != mCurrentAppOrientation) {
4849                mCurrentAppOrientation = newOrientation;
4850                updateOrientationListenerLp();
4851            }
4852        }
4853    }
4854
4855    private void performAuditoryFeedbackForAccessibilityIfNeed() {
4856        if (!isGlobalAccessibilityGestureEnabled()) {
4857            return;
4858        }
4859        AudioManager audioManager = (AudioManager) mContext.getSystemService(
4860                Context.AUDIO_SERVICE);
4861        if (audioManager.isSilentMode()) {
4862            return;
4863        }
4864        Ringtone ringTone = RingtoneManager.getRingtone(mContext,
4865                Settings.System.DEFAULT_NOTIFICATION_URI);
4866        ringTone.setStreamType(AudioManager.STREAM_MUSIC);
4867        ringTone.play();
4868    }
4869    private boolean isGlobalAccessibilityGestureEnabled() {
4870        return Settings.Global.getInt(mContext.getContentResolver(),
4871                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
4872    }
4873
4874    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
4875        if (!mVibrator.hasVibrator()) {
4876            return false;
4877        }
4878        final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
4879                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
4880        if (!always && (hapticsDisabled || mKeyguardDelegate.isShowingAndNotHidden())) {
4881            return false;
4882        }
4883        long[] pattern = null;
4884        switch (effectId) {
4885            case HapticFeedbackConstants.LONG_PRESS:
4886                pattern = mLongPressVibePattern;
4887                break;
4888            case HapticFeedbackConstants.VIRTUAL_KEY:
4889                pattern = mVirtualKeyVibePattern;
4890                break;
4891            case HapticFeedbackConstants.KEYBOARD_TAP:
4892                pattern = mKeyboardTapVibePattern;
4893                break;
4894            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
4895                pattern = mSafeModeDisabledVibePattern;
4896                break;
4897            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
4898                pattern = mSafeModeEnabledVibePattern;
4899                break;
4900            default:
4901                return false;
4902        }
4903        int owningUid;
4904        String owningPackage;
4905        if (win != null) {
4906            owningUid = win.getOwningUid();
4907            owningPackage = win.getOwningPackage();
4908        } else {
4909            owningUid = android.os.Process.myUid();
4910            owningPackage = mContext.getBasePackageName();
4911        }
4912        if (pattern.length == 1) {
4913            // One-shot vibration
4914            mVibrator.vibrate(owningUid, owningPackage, pattern[0]);
4915        } else {
4916            // Pattern vibration
4917            mVibrator.vibrate(owningUid, owningPackage, pattern, -1);
4918        }
4919        return true;
4920    }
4921
4922    @Override
4923    public void keepScreenOnStartedLw() {
4924    }
4925
4926    @Override
4927    public void keepScreenOnStoppedLw() {
4928        if (mKeyguardDelegate != null && !mKeyguardDelegate.isShowingAndNotHidden()) {
4929            long curTime = SystemClock.uptimeMillis();
4930            mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
4931        }
4932    }
4933
4934    private int updateSystemUiVisibilityLw() {
4935        // If there is no window focused, there will be nobody to handle the events
4936        // anyway, so just hang on in whatever state we're in until things settle down.
4937        if (mFocusedWindow == null) {
4938            return 0;
4939        }
4940        if (mFocusedWindow.getAttrs().type == TYPE_KEYGUARD && mHideLockScreen == true) {
4941            // We are updating at a point where the keyguard has gotten
4942            // focus, but we were last in a state where the top window is
4943            // hiding it.  This is probably because the keyguard as been
4944            // shown while the top window was displayed, so we want to ignore
4945            // it here because this is just a very transient change and it
4946            // will quickly lose focus once it correctly gets hidden.
4947            return 0;
4948        }
4949
4950        int tmpVisibility = mFocusedWindow.getSystemUiVisibility()
4951                & ~mResettingSystemUiFlags
4952                & ~mForceClearedSystemUiFlags;
4953        if (mForcingShowNavBar && mFocusedWindow.getSurfaceLayer() < mForcingShowNavBarLayer) {
4954            tmpVisibility &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
4955        }
4956
4957        boolean hideybarsAllowed =
4958                (mFocusedWindow.getAttrs().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
4959                || mFocusedWindow.getAttrs().type == TYPE_STATUS_BAR;
4960        if (mHideybars == HIDEYBARS_SHOWING) {
4961            if (!hideybarsAllowed) {
4962                mHideybars = HIDEYBARS_NONE;
4963                if ((tmpVisibility & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0) {
4964                    // hideybars for View.SYSTEM_UI_FLAG_FULLSCREEN: clear the clearable flags
4965                    int newVal = mResettingSystemUiFlags | View.SYSTEM_UI_CLEARABLE_FLAGS;
4966                    if (newVal != mResettingSystemUiFlags) {
4967                        mResettingSystemUiFlags = newVal;
4968                        mWindowManagerFuncs.reevaluateStatusBarVisibility();
4969                    }
4970                }
4971            } else {
4972                // hideybars for WM.LP.FLAG_FULLSCREEN: show transparent status bar
4973                tmpVisibility |= View.STATUS_BAR_OVERLAY;
4974                if ((mLastSystemUiFlags & View.STATUS_BAR_OVERLAY) == 0) {
4975                    mStatusBar.showLw(true);
4976                }
4977            }
4978        }
4979        final int visibility = tmpVisibility;
4980        int diff = visibility ^ mLastSystemUiFlags;
4981        final boolean needsMenu = mFocusedWindow.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
4982        if (diff == 0 && mLastFocusNeedsMenu == needsMenu
4983                && mFocusedApp == mFocusedWindow.getAppToken()) {
4984            return 0;
4985        }
4986        mLastSystemUiFlags = visibility;
4987        mLastFocusNeedsMenu = needsMenu;
4988        mFocusedApp = mFocusedWindow.getAppToken();
4989        mHandler.post(new Runnable() {
4990                public void run() {
4991                    try {
4992                        IStatusBarService statusbar = getStatusBarService();
4993                        if (statusbar != null) {
4994                            statusbar.setSystemUiVisibility(visibility, 0xffffffff);
4995                            statusbar.topAppWindowChanged(needsMenu);
4996                        }
4997                    } catch (RemoteException e) {
4998                        // re-acquire status bar service next time it is needed.
4999                        mStatusBarService = null;
5000                    }
5001                }
5002            });
5003        return diff;
5004    }
5005
5006    // Use this instead of checking config_showNavigationBar so that it can be consistently
5007    // overridden by qemu.hw.mainkeys in the emulator.
5008    public boolean hasNavigationBar() {
5009        return mHasNavigationBar;
5010    }
5011
5012    @Override
5013    public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
5014        mLastInputMethodWindow = ime;
5015        mLastInputMethodTargetWindow = target;
5016    }
5017
5018    @Override
5019    public void setCurrentUserLw(int newUserId) {
5020        if (mKeyguardDelegate != null) {
5021            mKeyguardDelegate.setCurrentUser(newUserId);
5022        }
5023        if (mStatusBarService != null) {
5024            try {
5025                mStatusBarService.setCurrentUser(newUserId);
5026            } catch (RemoteException e) {
5027                // oh well
5028            }
5029        }
5030        setLastInputMethodWindowLw(null, null);
5031    }
5032
5033    @Override
5034    public void showAssistant() {
5035        mKeyguardDelegate.showAssistant();
5036    }
5037
5038    @Override
5039    public boolean canMagnifyWindow(int windowType) {
5040        switch (windowType) {
5041            case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
5042            case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
5043            case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
5044            case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
5045                return false;
5046            }
5047        }
5048        return true;
5049    }
5050
5051    @Override
5052    public boolean isTopLevelWindow(int windowType) {
5053        if (windowType >= WindowManager.LayoutParams.FIRST_SUB_WINDOW
5054                && windowType <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
5055            return (windowType == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG);
5056        }
5057        return true;
5058    }
5059
5060    @Override
5061    public void dump(String prefix, PrintWriter pw, String[] args) {
5062        pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
5063                pw.print(" mSystemReady="); pw.print(mSystemReady);
5064                pw.print(" mSystemBooted="); pw.println(mSystemBooted);
5065        pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
5066                pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
5067                pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
5068        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
5069                || mForceClearedSystemUiFlags != 0) {
5070            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
5071                    pw.print(Integer.toHexString(mLastSystemUiFlags));
5072                    pw.print(" mResettingSystemUiFlags=0x");
5073                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
5074                    pw.print(" mForceClearedSystemUiFlags=0x");
5075                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
5076        }
5077        if (mLastFocusNeedsMenu) {
5078            pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
5079                    pw.println(mLastFocusNeedsMenu);
5080        }
5081        pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
5082                pw.print(" mDockMode="); pw.print(mDockMode);
5083                pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
5084                pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
5085        pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
5086                pw.print(" mUserRotation="); pw.print(mUserRotation);
5087                pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
5088        pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
5089        pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
5090                pw.print(mCarDockEnablesAccelerometer);
5091                pw.print(" mDeskDockEnablesAccelerometer=");
5092                pw.println(mDeskDockEnablesAccelerometer);
5093        pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
5094                pw.print(mLidKeyboardAccessibility);
5095                pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
5096                pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
5097        pw.print(prefix); pw.print("mLongPressOnPowerBehavior=");
5098                pw.print(mLongPressOnPowerBehavior);
5099                pw.print(" mHasSoftInput="); pw.println(mHasSoftInput);
5100        pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
5101                pw.print(" mScreenOnFully="); pw.print(mScreenOnFully);
5102                pw.print(" mOrientationSensorEnabled="); pw.println(mOrientationSensorEnabled);
5103        pw.print(prefix); pw.print("mOverscanScreen=("); pw.print(mOverscanScreenLeft);
5104                pw.print(","); pw.print(mOverscanScreenTop);
5105                pw.print(") "); pw.print(mOverscanScreenWidth);
5106                pw.print("x"); pw.println(mOverscanScreenHeight);
5107        if (mOverscanLeft != 0 || mOverscanTop != 0
5108                || mOverscanRight != 0 || mOverscanBottom != 0) {
5109            pw.print(prefix); pw.print("mOverscan left="); pw.print(mOverscanLeft);
5110                    pw.print(" top="); pw.print(mOverscanTop);
5111                    pw.print(" right="); pw.print(mOverscanRight);
5112                    pw.print(" bottom="); pw.println(mOverscanBottom);
5113        }
5114        pw.print(prefix); pw.print("mRestrictedOverscanScreen=(");
5115                pw.print(mRestrictedOverscanScreenLeft);
5116                pw.print(","); pw.print(mRestrictedOverscanScreenTop);
5117                pw.print(") "); pw.print(mRestrictedOverscanScreenWidth);
5118                pw.print("x"); pw.println(mRestrictedOverscanScreenHeight);
5119        pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
5120                pw.print(","); pw.print(mUnrestrictedScreenTop);
5121                pw.print(") "); pw.print(mUnrestrictedScreenWidth);
5122                pw.print("x"); pw.println(mUnrestrictedScreenHeight);
5123        pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
5124                pw.print(","); pw.print(mRestrictedScreenTop);
5125                pw.print(") "); pw.print(mRestrictedScreenWidth);
5126                pw.print("x"); pw.println(mRestrictedScreenHeight);
5127        pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
5128                pw.print(","); pw.print(mStableFullscreenTop);
5129                pw.print(")-("); pw.print(mStableFullscreenRight);
5130                pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
5131        pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
5132                pw.print(","); pw.print(mStableTop);
5133                pw.print(")-("); pw.print(mStableRight);
5134                pw.print(","); pw.print(mStableBottom); pw.println(")");
5135        pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
5136                pw.print(","); pw.print(mSystemTop);
5137                pw.print(")-("); pw.print(mSystemRight);
5138                pw.print(","); pw.print(mSystemBottom); pw.println(")");
5139        pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
5140                pw.print(","); pw.print(mCurTop);
5141                pw.print(")-("); pw.print(mCurRight);
5142                pw.print(","); pw.print(mCurBottom); pw.println(")");
5143        pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
5144                pw.print(","); pw.print(mContentTop);
5145                pw.print(")-("); pw.print(mContentRight);
5146                pw.print(","); pw.print(mContentBottom); pw.println(")");
5147        pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
5148                pw.print(","); pw.print(mDockTop);
5149                pw.print(")-("); pw.print(mDockRight);
5150                pw.print(","); pw.print(mDockBottom); pw.println(")");
5151        pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
5152                pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
5153        pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
5154                pw.print(" mShowingDream="); pw.print(mShowingDream);
5155                pw.print(" mDreamingLockscreen="); pw.println(mDreamingLockscreen);
5156        if (mLastInputMethodWindow != null) {
5157            pw.print(prefix); pw.print("mLastInputMethodWindow=");
5158                    pw.println(mLastInputMethodWindow);
5159        }
5160        if (mLastInputMethodTargetWindow != null) {
5161            pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
5162                    pw.println(mLastInputMethodTargetWindow);
5163        }
5164        if (mStatusBar != null) {
5165            pw.print(prefix); pw.print("mStatusBar=");
5166                    pw.println(mStatusBar);
5167        }
5168        if (mNavigationBar != null) {
5169            pw.print(prefix); pw.print("mNavigationBar=");
5170                    pw.println(mNavigationBar);
5171        }
5172        if (mKeyguard != null) {
5173            pw.print(prefix); pw.print("mKeyguard=");
5174                    pw.println(mKeyguard);
5175        }
5176        if (mFocusedWindow != null) {
5177            pw.print(prefix); pw.print("mFocusedWindow=");
5178                    pw.println(mFocusedWindow);
5179        }
5180        if (mFocusedApp != null) {
5181            pw.print(prefix); pw.print("mFocusedApp=");
5182                    pw.println(mFocusedApp);
5183        }
5184        if (mWinDismissingKeyguard != null) {
5185            pw.print(prefix); pw.print("mWinDismissingKeyguard=");
5186                    pw.println(mWinDismissingKeyguard);
5187        }
5188        if (mTopFullscreenOpaqueWindowState != null) {
5189            pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
5190                    pw.println(mTopFullscreenOpaqueWindowState);
5191        }
5192        if (mForcingShowNavBar) {
5193            pw.print(prefix); pw.print("mForcingShowNavBar=");
5194                    pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
5195                    pw.println(mForcingShowNavBarLayer);
5196        }
5197        pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
5198                pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
5199        pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
5200                pw.print(" mForceStatusBarFromKeyguard=");
5201                pw.println(mForceStatusBarFromKeyguard);
5202        pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
5203                pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
5204                pw.print(" mHomePressed="); pw.println(mHomePressed);
5205        pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
5206                pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
5207                pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
5208        pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
5209                pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
5210                pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
5211        pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
5212                pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
5213        pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
5214                pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
5215        pw.print(prefix); pw.print("mDemoHdmiRotation="); pw.print(mDemoHdmiRotation);
5216                pw.print(" mDemoHdmiRotationLock="); pw.println(mDemoHdmiRotationLock);
5217        pw.print(prefix); pw.print("mUndockedHdmiRotation="); pw.println(mUndockedHdmiRotation);
5218    }
5219}
5220