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