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