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