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