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