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