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