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