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