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