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