PhoneWindowManager.java revision 83c09685f2e62bc3cf7e71bc61d903f4b9ccaeb4
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.UiModeManager;
24import android.content.ActivityNotFoundException;
25import android.content.BroadcastReceiver;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.ActivityInfo;
31import android.content.pm.PackageManager;
32import android.content.res.Configuration;
33import android.content.res.Resources;
34import android.database.ContentObserver;
35import android.graphics.PixelFormat;
36import android.graphics.Rect;
37import android.os.Handler;
38import android.os.IBinder;
39import android.os.LocalPowerManager;
40import android.os.Looper;
41import android.os.PowerManager;
42import android.os.RemoteException;
43import android.os.ServiceManager;
44import android.os.SystemClock;
45import android.os.SystemProperties;
46import android.os.Vibrator;
47import android.provider.Settings;
48
49import com.android.internal.R;
50import com.android.internal.app.ShutdownThread;
51import com.android.internal.policy.PolicyManager;
52import com.android.internal.statusbar.IStatusBarService;
53import com.android.internal.telephony.ITelephony;
54import com.android.internal.view.BaseInputHandler;
55import com.android.internal.widget.PointerLocationView;
56
57import android.telephony.TelephonyManager;
58import android.util.Config;
59import android.util.EventLog;
60import android.util.Log;
61import android.util.Slog;
62import android.view.Display;
63import android.view.Gravity;
64import android.view.HapticFeedbackConstants;
65import android.view.IWindowManager;
66import android.view.InputChannel;
67import android.view.InputDevice;
68import android.view.InputQueue;
69import android.view.InputHandler;
70import android.view.KeyCharacterMap;
71import android.view.KeyEvent;
72import android.view.MotionEvent;
73import android.view.WindowOrientationListener;
74import android.view.Surface;
75import android.view.View;
76import android.view.ViewConfiguration;
77import android.view.Window;
78import android.view.WindowManager;
79import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
80import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
81import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
82import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
83import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
84import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
85import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
86import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
87import static android.view.WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON;
88import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
89import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
90import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
91import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
92import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
93import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY;
94import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
95import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
96import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
97import static android.view.WindowManager.LayoutParams.TYPE_DRAG;
98import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD;
99import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
100import static android.view.WindowManager.LayoutParams.TYPE_PHONE;
101import static android.view.WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
102import static android.view.WindowManager.LayoutParams.TYPE_SEARCH_BAR;
103import static android.view.WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
104import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
105import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
106import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
107import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG;
108import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
109import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
110import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
111import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
112import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
113import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
114import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
115import static android.view.WindowManager.LayoutParams.TYPE_POINTER;
116import android.view.WindowManagerImpl;
117import android.view.WindowManagerPolicy;
118import android.view.animation.Animation;
119import android.view.animation.AnimationUtils;
120import android.media.IAudioService;
121import android.media.AudioManager;
122
123import java.util.ArrayList;
124
125/**
126 * WindowManagerPolicy implementation for the Android phone UI.  This
127 * introduces a new method suffix, Lp, for an internal lock of the
128 * PhoneWindowManager.  This is used to protect some internal state, and
129 * can be acquired with either thw Lw and Li lock held, so has the restrictions
130 * of both of those when held.
131 */
132public class PhoneWindowManager implements WindowManagerPolicy {
133    static final String TAG = "WindowManager";
134    static final boolean DEBUG = false;
135    static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
136    static final boolean DEBUG_LAYOUT = false;
137    static final boolean DEBUG_FALLBACK = false;
138    static final boolean SHOW_STARTING_ANIMATIONS = true;
139    static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
140
141    static final int LONG_PRESS_POWER_NOTHING = 0;
142    static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
143    static final int LONG_PRESS_POWER_SHUT_OFF = 2;
144
145    static final int LONG_PRESS_HOME_NOTHING = 0;
146    static final int LONG_PRESS_HOME_RECENT_DIALOG = 1;
147    static final int LONG_PRESS_HOME_RECENT_ACTIVITY = 2;
148
149    // wallpaper is at the bottom, though the window manager may move it.
150    static final int WALLPAPER_LAYER = 2;
151    static final int APPLICATION_LAYER = 2;
152    static final int PHONE_LAYER = 3;
153    static final int SEARCH_BAR_LAYER = 4;
154    static final int STATUS_BAR_SUB_PANEL_LAYER = 5;
155    static final int SYSTEM_DIALOG_LAYER = 6;
156    // toasts and the plugged-in battery thing
157    static final int TOAST_LAYER = 7;
158    static final int STATUS_BAR_LAYER = 8;
159    static final int STATUS_BAR_PANEL_LAYER = 9;
160    // SIM errors and unlock.  Not sure if this really should be in a high layer.
161    static final int PRIORITY_PHONE_LAYER = 10;
162    // like the ANR / app crashed dialogs
163    static final int SYSTEM_ALERT_LAYER = 11;
164    // system-level error dialogs
165    static final int SYSTEM_ERROR_LAYER = 12;
166    // on-screen keyboards and other such input method user interfaces go here.
167    static final int INPUT_METHOD_LAYER = 13;
168    // on-screen keyboards and other such input method user interfaces go here.
169    static final int INPUT_METHOD_DIALOG_LAYER = 14;
170    // the keyguard; nothing on top of these can take focus, since they are
171    // responsible for power management when displayed.
172    static final int KEYGUARD_LAYER = 15;
173    static final int KEYGUARD_DIALOG_LAYER = 16;
174    // the drag layer: input for drag-and-drop is associated with this window,
175    // which sits above all other focusable windows
176    static final int DRAG_LAYER = 17;
177    // things in here CAN NOT take focus, but are shown on top of everything else.
178    static final int SYSTEM_OVERLAY_LAYER = 18;
179    static final int SECURE_SYSTEM_OVERLAY_LAYER = 19;
180    // the (mouse) pointer layer
181    static final int POINTER_LAYER = 20;
182
183    static final int APPLICATION_MEDIA_SUBLAYER = -2;
184    static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
185    static final int APPLICATION_PANEL_SUBLAYER = 1;
186    static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
187
188    // Debugging: set this to have the system act like there is no hard keyboard.
189    static final boolean KEYBOARD_ALWAYS_HIDDEN = false;
190
191    static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
192    static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
193    static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
194    static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
195
196    // Useful scan codes.
197    private static final int SW_LID = 0x00;
198    private static final int BTN_MOUSE = 0x110;
199
200    final Object mLock = new Object();
201
202    Context mContext;
203    IWindowManager mWindowManager;
204    LocalPowerManager mPowerManager;
205    IStatusBarService mStatusBarService;
206    Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
207
208    // Vibrator pattern for haptic feedback of a long press.
209    long[] mLongPressVibePattern;
210
211    // Vibrator pattern for haptic feedback of virtual key press.
212    long[] mVirtualKeyVibePattern;
213
214    // Vibrator pattern for a short vibration.
215    long[] mKeyboardTapVibePattern;
216
217    // Vibrator pattern for haptic feedback during boot when safe mode is disabled.
218    long[] mSafeModeDisabledVibePattern;
219
220    // Vibrator pattern for haptic feedback during boot when safe mode is enabled.
221    long[] mSafeModeEnabledVibePattern;
222
223    /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
224    boolean mEnableShiftMenuBugReports = false;
225
226    boolean mSafeMode;
227    WindowState mStatusBar = null;
228    boolean mStatusBarCanHide;
229    final ArrayList<WindowState> mStatusBarPanels = new ArrayList<WindowState>();
230    WindowState mKeyguard = null;
231    KeyguardViewMediator mKeyguardMediator;
232    GlobalActions mGlobalActions;
233    volatile boolean mPowerKeyHandled;
234    RecentApplicationsDialog mRecentAppsDialog;
235    Handler mHandler;
236
237    boolean mSystemReady;
238    boolean mLidOpen;
239    int mUiMode = Configuration.UI_MODE_TYPE_NORMAL;
240    int mDockMode = Intent.EXTRA_DOCK_STATE_UNDOCKED;
241    int mLidOpenRotation;
242    int mCarDockRotation;
243    int mDeskDockRotation;
244
245    int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE;
246    int mUserRotation = Surface.ROTATION_0;
247
248    boolean mAllowAllRotations;
249    boolean mCarDockEnablesAccelerometer;
250    boolean mDeskDockEnablesAccelerometer;
251    int mLidKeyboardAccessibility;
252    int mLidNavigationAccessibility;
253    int mLongPressOnPowerBehavior = -1;
254    boolean mScreenOn = false;
255    boolean mOrientationSensorEnabled = false;
256    int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
257    static final int DEFAULT_ACCELEROMETER_ROTATION = 0;
258    int mAccelerometerDefault = DEFAULT_ACCELEROMETER_ROTATION;
259    boolean mHasSoftInput = false;
260
261    int mPointerLocationMode = 0;
262    PointerLocationView mPointerLocationView = null;
263    InputChannel mPointerLocationInputChannel;
264
265    private final InputHandler mPointerLocationInputHandler = new BaseInputHandler() {
266        @Override
267        public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
268            boolean handled = false;
269            try {
270                if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
271                    synchronized (mLock) {
272                        if (mPointerLocationView != null) {
273                            mPointerLocationView.addTouchEvent(event);
274                            handled = true;
275                        }
276                    }
277                }
278            } finally {
279                finishedCallback.finished(handled);
280            }
281        }
282    };
283
284    // The current size of the screen; really; (ir)regardless of whether the status
285    // bar can be hidden or not
286    int mUnrestrictedScreenLeft, mUnrestrictedScreenTop;
287    int mUnrestrictedScreenWidth, mUnrestrictedScreenHeight;
288    // The current size of the screen; these may be different than (0,0)-(dw,dh)
289    // if the status bar can't be hidden; in that case it effectively carves out
290    // that area of the display from all other windows.
291    int mRestrictedScreenLeft, mRestrictedScreenTop;
292    int mRestrictedScreenWidth, mRestrictedScreenHeight;
293    // During layout, the current screen borders with all outer decoration
294    // (status bar, input method dock) accounted for.
295    int mCurLeft, mCurTop, mCurRight, mCurBottom;
296    // During layout, the frame in which content should be displayed
297    // to the user, accounting for all screen decoration except for any
298    // space they deem as available for other content.  This is usually
299    // the same as mCur*, but may be larger if the screen decor has supplied
300    // content insets.
301    int mContentLeft, mContentTop, mContentRight, mContentBottom;
302    // During layout, the current screen borders along which input method
303    // windows are placed.
304    int mDockLeft, mDockTop, mDockRight, mDockBottom;
305    // During layout, the layer at which the doc window is placed.
306    int mDockLayer;
307
308    static final Rect mTmpParentFrame = new Rect();
309    static final Rect mTmpDisplayFrame = new Rect();
310    static final Rect mTmpContentFrame = new Rect();
311    static final Rect mTmpVisibleFrame = new Rect();
312
313    WindowState mTopFullscreenOpaqueWindowState;
314    boolean mTopIsFullscreen;
315    boolean mForceStatusBar;
316    boolean mHideLockScreen;
317    boolean mDismissKeyguard;
318    boolean mHomePressed;
319    Intent mHomeIntent;
320    Intent mCarDockIntent;
321    Intent mDeskDockIntent;
322    int mShortcutKeyPressed = -1;
323    boolean mConsumeShortcutKeyUp;
324    boolean mShowMenuKey = false; // track FLAG_NEEDS_MENU_KEY on frontmost window
325
326    // support for activating the lock screen while the screen is on
327    boolean mAllowLockscreenWhenOn;
328    int mLockScreenTimeout;
329    boolean mLockScreenTimerActive;
330
331    // Behavior of ENDCALL Button.  (See Settings.System.END_BUTTON_BEHAVIOR.)
332    int mEndcallBehavior;
333
334    // Behavior of POWER button while in-call and screen on.
335    // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.)
336    int mIncallPowerBehavior;
337
338    int mLandscapeRotation = -1; // default landscape rotation
339    int mSeascapeRotation = -1; // "other" landscape rotation, 180 degrees from mLandscapeRotation
340    int mPortraitRotation = -1; // default portrait rotation
341    int mUpsideDownRotation = -1; // "other" portrait rotation
342
343    // Nothing to see here, move along...
344    int mFancyRotationAnimation;
345
346    // What we do when the user long presses on home
347    private int mLongPressOnHomeBehavior = -1;
348
349    ShortcutManager mShortcutManager;
350    PowerManager.WakeLock mBroadcastWakeLock;
351
352    final KeyCharacterMap.FallbackAction mFallbackAction = new KeyCharacterMap.FallbackAction();
353
354    class SettingsObserver extends ContentObserver {
355        SettingsObserver(Handler handler) {
356            super(handler);
357        }
358
359        void observe() {
360            ContentResolver resolver = mContext.getContentResolver();
361            resolver.registerContentObserver(Settings.System.getUriFor(
362                    Settings.System.END_BUTTON_BEHAVIOR), false, this);
363            resolver.registerContentObserver(Settings.Secure.getUriFor(
364                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this);
365            resolver.registerContentObserver(Settings.System.getUriFor(
366                    Settings.System.ACCELEROMETER_ROTATION), false, this);
367            resolver.registerContentObserver(Settings.System.getUriFor(
368                    Settings.System.USER_ROTATION), false, this);
369            resolver.registerContentObserver(Settings.System.getUriFor(
370                    Settings.System.SCREEN_OFF_TIMEOUT), false, this);
371            resolver.registerContentObserver(Settings.System.getUriFor(
372                    Settings.System.POINTER_LOCATION), false, this);
373            resolver.registerContentObserver(Settings.Secure.getUriFor(
374                    Settings.Secure.DEFAULT_INPUT_METHOD), false, this);
375            resolver.registerContentObserver(Settings.System.getUriFor(
376                    "fancy_rotation_anim"), false, this);
377            updateSettings();
378        }
379
380        @Override public void onChange(boolean selfChange) {
381            updateSettings();
382            try {
383                mWindowManager.setRotation(USE_LAST_ROTATION, false,
384                        mFancyRotationAnimation);
385            } catch (RemoteException e) {
386                // Ignore
387            }
388        }
389    }
390
391    class MyOrientationListener extends WindowOrientationListener {
392        MyOrientationListener(Context context) {
393            super(context);
394        }
395
396        @Override
397        public void onOrientationChanged(int rotation) {
398            // Send updates based on orientation value
399            if (localLOGV) Log.v(TAG, "onOrientationChanged, rotation changed to " +rotation);
400            try {
401                mWindowManager.setRotation(rotation, false,
402                        mFancyRotationAnimation);
403            } catch (RemoteException e) {
404                // Ignore
405
406            }
407        }
408    }
409    MyOrientationListener mOrientationListener;
410
411    boolean useSensorForOrientationLp(int appOrientation) {
412        // The app says use the sensor.
413        if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
414                || appOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
415                || appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
416                || appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
417            return true;
418        }
419        // The user preference says we can rotate, and the app is willing to rotate.
420        if (mAccelerometerDefault != 0 &&
421                (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
422                 || appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)) {
423            return true;
424        }
425        // We're in a dock that has a rotation affinity, and the app is willing to rotate.
426        if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR)
427                || (mDeskDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_DESK)) {
428            // Note we override the nosensor flag here.
429            if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
430                    || appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
431                    || appOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
432                return true;
433            }
434        }
435        // Else, don't use the sensor.
436        return false;
437    }
438
439    /*
440     * We always let the sensor be switched on by default except when
441     * the user has explicitly disabled sensor based rotation or when the
442     * screen is switched off.
443     */
444    boolean needSensorRunningLp() {
445        if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
446                || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
447                || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
448                || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
449            // If the application has explicitly requested to follow the
450            // orientation, then we need to turn the sensor or.
451            return true;
452        }
453        if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) ||
454                (mDeskDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_DESK)) {
455            // enable accelerometer if we are docked in a dock that enables accelerometer
456            // orientation management,
457            return true;
458        }
459        if (mAccelerometerDefault == 0) {
460            // If the setting for using the sensor by default is enabled, then
461            // we will always leave it on.  Note that the user could go to
462            // a window that forces an orientation that does not use the
463            // sensor and in theory we could turn it off... however, when next
464            // turning it on we won't have a good value for the current
465            // orientation for a little bit, which can cause orientation
466            // changes to lag, so we'd like to keep it always on.  (It will
467            // still be turned off when the screen is off.)
468            return false;
469        }
470        return true;
471    }
472
473    /*
474     * Various use cases for invoking this function
475     * screen turning off, should always disable listeners if already enabled
476     * screen turned on and current app has sensor based orientation, enable listeners
477     * if not already enabled
478     * screen turned on and current app does not have sensor orientation, disable listeners if
479     * already enabled
480     * screen turning on and current app has sensor based orientation, enable listeners if needed
481     * screen turning on and current app has nosensor based orientation, do nothing
482     */
483    void updateOrientationListenerLp() {
484        if (!mOrientationListener.canDetectOrientation()) {
485            // If sensor is turned off or nonexistent for some reason
486            return;
487        }
488        //Could have been invoked due to screen turning on or off or
489        //change of the currently visible window's orientation
490        if (localLOGV) Log.v(TAG, "Screen status="+mScreenOn+
491                ", current orientation="+mCurrentAppOrientation+
492                ", SensorEnabled="+mOrientationSensorEnabled);
493        boolean disable = true;
494        if (mScreenOn) {
495            if (needSensorRunningLp()) {
496                disable = false;
497                //enable listener if not already enabled
498                if (!mOrientationSensorEnabled) {
499                    mOrientationListener.enable();
500                    if(localLOGV) Log.v(TAG, "Enabling listeners");
501                    mOrientationSensorEnabled = true;
502                }
503            }
504        }
505        //check if sensors need to be disabled
506        if (disable && mOrientationSensorEnabled) {
507            mOrientationListener.disable();
508            if(localLOGV) Log.v(TAG, "Disabling listeners");
509            mOrientationSensorEnabled = false;
510        }
511    }
512
513    private void interceptPowerKeyDown(boolean handled) {
514        mPowerKeyHandled = handled;
515        if (!handled) {
516            mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
517        }
518    }
519
520    private boolean interceptPowerKeyUp(boolean canceled) {
521        if (!mPowerKeyHandled) {
522            mHandler.removeCallbacks(mPowerLongPress);
523            return !canceled;
524        } else {
525            mPowerKeyHandled = true;
526            return false;
527        }
528    }
529
530    private final Runnable mPowerLongPress = new Runnable() {
531        public void run() {
532            if (!mPowerKeyHandled) {
533                // The context isn't read
534                if (mLongPressOnPowerBehavior < 0) {
535                    mLongPressOnPowerBehavior = mContext.getResources().getInteger(
536                            com.android.internal.R.integer.config_longPressOnPowerBehavior);
537                }
538                switch (mLongPressOnPowerBehavior) {
539                case LONG_PRESS_POWER_NOTHING:
540                    break;
541                case LONG_PRESS_POWER_GLOBAL_ACTIONS:
542                    mPowerKeyHandled = true;
543                    performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
544                    sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
545                    showGlobalActionsDialog();
546                    break;
547                case LONG_PRESS_POWER_SHUT_OFF:
548                    mPowerKeyHandled = true;
549                    performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
550                    sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
551                    ShutdownThread.shutdown(mContext, true);
552                    break;
553                }
554            }
555        }
556    };
557
558    void showGlobalActionsDialog() {
559        if (mGlobalActions == null) {
560            mGlobalActions = new GlobalActions(mContext);
561        }
562        final boolean keyguardShowing = mKeyguardMediator.isShowingAndNotHidden();
563        mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
564        if (keyguardShowing) {
565            // since it took two seconds of long press to bring this up,
566            // poke the wake lock so they have some time to see the dialog.
567            mKeyguardMediator.pokeWakelock();
568        }
569    }
570
571    boolean isDeviceProvisioned() {
572        return Settings.Secure.getInt(
573                mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
574    }
575
576    /**
577     * When a home-key longpress expires, close other system windows and launch the recent apps
578     */
579    Runnable mHomeLongPress = new Runnable() {
580        public void run() {
581            /*
582             * Eat the longpress so it won't dismiss the recent apps dialog when
583             * the user lets go of the home key
584             */
585            mHomePressed = false;
586            showRecentAppsDialog();
587        }
588    };
589
590    /**
591     * Create (if necessary) and launch the recent apps dialog
592     */
593    void showRecentAppsDialog() {
594        // We can't initialize this in init() since the configuration hasn't been loaded yet.
595        if (mLongPressOnHomeBehavior < 0) {
596            mLongPressOnHomeBehavior
597                    = mContext.getResources().getInteger(R.integer.config_longPressOnHomeBehavior);
598            if (mLongPressOnHomeBehavior < LONG_PRESS_HOME_NOTHING ||
599                    mLongPressOnHomeBehavior > LONG_PRESS_HOME_RECENT_ACTIVITY) {
600                mLongPressOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
601            }
602        }
603
604        if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) {
605            performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
606            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
607        }
608
609        if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_DIALOG) {
610            // Fallback to dialog if we fail to launch the above.
611            if (mRecentAppsDialog == null) {
612                mRecentAppsDialog = new RecentApplicationsDialog(mContext);
613            }
614            mRecentAppsDialog.show();
615        } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_ACTIVITY) {
616            try {
617                Intent intent = new Intent();
618                intent.setClassName("com.android.systemui",
619                        "com.android.systemui.recent.RecentApplicationsActivity");
620                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
621                        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
622                mContext.startActivity(intent);
623                return;
624            } catch (ActivityNotFoundException e) {
625                Log.e(TAG, "Failed to launch RecentAppsIntent", e);
626            }
627        }
628    }
629
630    /** {@inheritDoc} */
631    public void init(Context context, IWindowManager windowManager,
632            LocalPowerManager powerManager) {
633        mContext = context;
634        mWindowManager = windowManager;
635        mPowerManager = powerManager;
636        mKeyguardMediator = new KeyguardViewMediator(context, this, powerManager);
637        mHandler = new Handler();
638        mOrientationListener = new MyOrientationListener(mContext);
639        SettingsObserver settingsObserver = new SettingsObserver(mHandler);
640        settingsObserver.observe();
641        mShortcutManager = new ShortcutManager(context, mHandler);
642        mShortcutManager.observe();
643        mHomeIntent =  new Intent(Intent.ACTION_MAIN, null);
644        mHomeIntent.addCategory(Intent.CATEGORY_HOME);
645        mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
646                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
647        mCarDockIntent =  new Intent(Intent.ACTION_MAIN, null);
648        mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
649        mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
650                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
651        mDeskDockIntent =  new Intent(Intent.ACTION_MAIN, null);
652        mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
653        mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
654                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
655
656        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
657        mBroadcastWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
658                "PhoneWindowManager.mBroadcastWakeLock");
659        mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
660        mLidOpenRotation = readRotation(
661                com.android.internal.R.integer.config_lidOpenRotation);
662        mCarDockRotation = readRotation(
663                com.android.internal.R.integer.config_carDockRotation);
664        mDeskDockRotation = readRotation(
665                com.android.internal.R.integer.config_deskDockRotation);
666        mAllowAllRotations = mContext.getResources().getBoolean(
667                com.android.internal.R.bool.config_allowAllRotations);
668        mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
669                com.android.internal.R.bool.config_carDockEnablesAccelerometer);
670        mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
671                com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
672        mLidKeyboardAccessibility = mContext.getResources().getInteger(
673                com.android.internal.R.integer.config_lidKeyboardAccessibility);
674        mLidNavigationAccessibility = mContext.getResources().getInteger(
675                com.android.internal.R.integer.config_lidNavigationAccessibility);
676        // register for dock events
677        IntentFilter filter = new IntentFilter();
678        filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE);
679        filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE);
680        filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE);
681        filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE);
682        filter.addAction(Intent.ACTION_DOCK_EVENT);
683        Intent intent = context.registerReceiver(mDockReceiver, filter);
684        if (intent != null) {
685            // Retrieve current sticky dock event broadcast.
686            mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
687                    Intent.EXTRA_DOCK_STATE_UNDOCKED);
688        }
689        mVibrator = new Vibrator();
690        mLongPressVibePattern = getLongIntArray(mContext.getResources(),
691                com.android.internal.R.array.config_longPressVibePattern);
692        mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
693                com.android.internal.R.array.config_virtualKeyVibePattern);
694        mKeyboardTapVibePattern = getLongIntArray(mContext.getResources(),
695                com.android.internal.R.array.config_keyboardTapVibePattern);
696        mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
697                com.android.internal.R.array.config_safeModeDisabledVibePattern);
698        mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
699                com.android.internal.R.array.config_safeModeEnabledVibePattern);
700
701        // Note: the Configuration is not stable here, so we cannot load mStatusBarCanHide from
702        // config_statusBarCanHide because the latter depends on the screen size
703    }
704
705    public void updateSettings() {
706        ContentResolver resolver = mContext.getContentResolver();
707        boolean updateRotation = false;
708        View addView = null;
709        View removeView = null;
710        synchronized (mLock) {
711            mEndcallBehavior = Settings.System.getInt(resolver,
712                    Settings.System.END_BUTTON_BEHAVIOR,
713                    Settings.System.END_BUTTON_BEHAVIOR_DEFAULT);
714            mIncallPowerBehavior = Settings.Secure.getInt(resolver,
715                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
716                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT);
717            mFancyRotationAnimation = Settings.System.getInt(resolver,
718                    "fancy_rotation_anim", 0) != 0 ? 0x80 : 0;
719            int accelerometerDefault = Settings.System.getInt(resolver,
720                    Settings.System.ACCELEROMETER_ROTATION, DEFAULT_ACCELEROMETER_ROTATION);
721
722            // set up rotation lock state
723            mUserRotationMode = (accelerometerDefault == 0)
724                ? WindowManagerPolicy.USER_ROTATION_LOCKED
725                : WindowManagerPolicy.USER_ROTATION_FREE;
726            mUserRotation = Settings.System.getInt(resolver,
727                    Settings.System.USER_ROTATION,
728                    Surface.ROTATION_0);
729
730            if (mAccelerometerDefault != accelerometerDefault) {
731                mAccelerometerDefault = accelerometerDefault;
732                updateOrientationListenerLp();
733            }
734
735            if (mSystemReady) {
736                int pointerLocation = Settings.System.getInt(resolver,
737                        Settings.System.POINTER_LOCATION, 0);
738                if (mPointerLocationMode != pointerLocation) {
739                    mPointerLocationMode = pointerLocation;
740                    if (pointerLocation != 0) {
741                        if (mPointerLocationView == null) {
742                            mPointerLocationView = new PointerLocationView(mContext);
743                            mPointerLocationView.setPrintCoords(false);
744                            addView = mPointerLocationView;
745                        }
746                    } else {
747                        removeView = mPointerLocationView;
748                        mPointerLocationView = null;
749                    }
750                }
751            }
752            // use screen off timeout setting as the timeout for the lockscreen
753            mLockScreenTimeout = Settings.System.getInt(resolver,
754                    Settings.System.SCREEN_OFF_TIMEOUT, 0);
755            String imId = Settings.Secure.getString(resolver,
756                    Settings.Secure.DEFAULT_INPUT_METHOD);
757            boolean hasSoftInput = imId != null && imId.length() > 0;
758            if (mHasSoftInput != hasSoftInput) {
759                mHasSoftInput = hasSoftInput;
760                updateRotation = true;
761            }
762        }
763        if (updateRotation) {
764            updateRotation(0);
765        }
766        if (addView != null) {
767            WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
768                    WindowManager.LayoutParams.MATCH_PARENT,
769                    WindowManager.LayoutParams.MATCH_PARENT);
770            lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
771            lp.flags =
772                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
773                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
774                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
775            lp.format = PixelFormat.TRANSLUCENT;
776            lp.setTitle("PointerLocation");
777            WindowManagerImpl wm = (WindowManagerImpl)
778                    mContext.getSystemService(Context.WINDOW_SERVICE);
779            wm.addView(addView, lp);
780
781            if (mPointerLocationInputChannel == null) {
782                try {
783                    mPointerLocationInputChannel =
784                        mWindowManager.monitorInput("PointerLocationView");
785                    InputQueue.registerInputChannel(mPointerLocationInputChannel,
786                            mPointerLocationInputHandler, mHandler.getLooper().getQueue());
787                } catch (RemoteException ex) {
788                    Slog.e(TAG, "Could not set up input monitoring channel for PointerLocation.",
789                            ex);
790                }
791            }
792        }
793        if (removeView != null) {
794            if (mPointerLocationInputChannel != null) {
795                InputQueue.unregisterInputChannel(mPointerLocationInputChannel);
796                mPointerLocationInputChannel.dispose();
797                mPointerLocationInputChannel = null;
798            }
799
800            WindowManagerImpl wm = (WindowManagerImpl)
801                    mContext.getSystemService(Context.WINDOW_SERVICE);
802            wm.removeView(removeView);
803        }
804    }
805
806    private int readRotation(int resID) {
807        try {
808            int rotation = mContext.getResources().getInteger(resID);
809            switch (rotation) {
810                case 0:
811                    return Surface.ROTATION_0;
812                case 90:
813                    return Surface.ROTATION_90;
814                case 180:
815                    return Surface.ROTATION_180;
816                case 270:
817                    return Surface.ROTATION_270;
818            }
819        } catch (Resources.NotFoundException e) {
820            // fall through
821        }
822        return -1;
823    }
824
825    /** {@inheritDoc} */
826    public int checkAddPermission(WindowManager.LayoutParams attrs) {
827        int type = attrs.type;
828
829        if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
830                || type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) {
831            return WindowManagerImpl.ADD_OKAY;
832        }
833        String permission = null;
834        switch (type) {
835            case TYPE_TOAST:
836                // XXX right now the app process has complete control over
837                // this...  should introduce a token to let the system
838                // monitor/control what they are doing.
839                break;
840            case TYPE_INPUT_METHOD:
841            case TYPE_WALLPAPER:
842                // The window manager will check these.
843                break;
844            case TYPE_PHONE:
845            case TYPE_PRIORITY_PHONE:
846            case TYPE_SYSTEM_ALERT:
847            case TYPE_SYSTEM_ERROR:
848            case TYPE_SYSTEM_OVERLAY:
849                permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
850                break;
851            default:
852                permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
853        }
854        if (permission != null) {
855            if (mContext.checkCallingOrSelfPermission(permission)
856                    != PackageManager.PERMISSION_GRANTED) {
857                return WindowManagerImpl.ADD_PERMISSION_DENIED;
858            }
859        }
860        return WindowManagerImpl.ADD_OKAY;
861    }
862
863    public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
864        switch (attrs.type) {
865            case TYPE_SYSTEM_OVERLAY:
866            case TYPE_SECURE_SYSTEM_OVERLAY:
867            case TYPE_TOAST:
868                // These types of windows can't receive input events.
869                attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
870                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
871                break;
872        }
873    }
874
875    void readLidState() {
876        try {
877            int sw = mWindowManager.getSwitchState(SW_LID);
878            if (sw >= 0) {
879                mLidOpen = sw == 0;
880            }
881        } catch (RemoteException e) {
882            // Ignore
883        }
884    }
885
886    private int determineHiddenState(boolean lidOpen,
887            int mode, int hiddenValue, int visibleValue) {
888        switch (mode) {
889            case 1:
890                return lidOpen ? visibleValue : hiddenValue;
891            case 2:
892                return lidOpen ? hiddenValue : visibleValue;
893        }
894        return visibleValue;
895    }
896
897    /** {@inheritDoc} */
898    public void adjustConfigurationLw(Configuration config) {
899        readLidState();
900        final boolean lidOpen = !KEYBOARD_ALWAYS_HIDDEN && mLidOpen;
901        mPowerManager.setKeyboardVisibility(lidOpen);
902        config.hardKeyboardHidden = determineHiddenState(lidOpen,
903                mLidKeyboardAccessibility, Configuration.HARDKEYBOARDHIDDEN_YES,
904                Configuration.HARDKEYBOARDHIDDEN_NO);
905        config.navigationHidden = determineHiddenState(lidOpen,
906                mLidNavigationAccessibility, Configuration.NAVIGATIONHIDDEN_YES,
907                Configuration.NAVIGATIONHIDDEN_NO);
908        config.keyboardHidden = (config.hardKeyboardHidden
909                        == Configuration.HARDKEYBOARDHIDDEN_NO || mHasSoftInput)
910                ? Configuration.KEYBOARDHIDDEN_NO
911                : Configuration.KEYBOARDHIDDEN_YES;
912    }
913
914    /** {@inheritDoc} */
915    public int windowTypeToLayerLw(int type) {
916        if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
917            return APPLICATION_LAYER;
918        }
919        switch (type) {
920        case TYPE_STATUS_BAR:
921            return STATUS_BAR_LAYER;
922        case TYPE_STATUS_BAR_PANEL:
923            return STATUS_BAR_PANEL_LAYER;
924        case TYPE_STATUS_BAR_SUB_PANEL:
925            return STATUS_BAR_SUB_PANEL_LAYER;
926        case TYPE_SYSTEM_DIALOG:
927            return SYSTEM_DIALOG_LAYER;
928        case TYPE_SEARCH_BAR:
929            return SEARCH_BAR_LAYER;
930        case TYPE_PHONE:
931            return PHONE_LAYER;
932        case TYPE_KEYGUARD:
933            return KEYGUARD_LAYER;
934        case TYPE_KEYGUARD_DIALOG:
935            return KEYGUARD_DIALOG_LAYER;
936        case TYPE_SYSTEM_ALERT:
937            return SYSTEM_ALERT_LAYER;
938        case TYPE_SYSTEM_ERROR:
939            return SYSTEM_ERROR_LAYER;
940        case TYPE_INPUT_METHOD:
941            return INPUT_METHOD_LAYER;
942        case TYPE_INPUT_METHOD_DIALOG:
943            return INPUT_METHOD_DIALOG_LAYER;
944        case TYPE_SYSTEM_OVERLAY:
945            return SYSTEM_OVERLAY_LAYER;
946        case TYPE_SECURE_SYSTEM_OVERLAY:
947            return SECURE_SYSTEM_OVERLAY_LAYER;
948        case TYPE_PRIORITY_PHONE:
949            return PRIORITY_PHONE_LAYER;
950        case TYPE_TOAST:
951            return TOAST_LAYER;
952        case TYPE_WALLPAPER:
953            return WALLPAPER_LAYER;
954        case TYPE_DRAG:
955            return DRAG_LAYER;
956        case TYPE_POINTER:
957            return POINTER_LAYER;
958        }
959        Log.e(TAG, "Unknown window type: " + type);
960        return APPLICATION_LAYER;
961    }
962
963    /** {@inheritDoc} */
964    public int subWindowTypeToLayerLw(int type) {
965        switch (type) {
966        case TYPE_APPLICATION_PANEL:
967        case TYPE_APPLICATION_ATTACHED_DIALOG:
968            return APPLICATION_PANEL_SUBLAYER;
969        case TYPE_APPLICATION_MEDIA:
970            return APPLICATION_MEDIA_SUBLAYER;
971        case TYPE_APPLICATION_MEDIA_OVERLAY:
972            return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
973        case TYPE_APPLICATION_SUB_PANEL:
974            return APPLICATION_SUB_PANEL_SUBLAYER;
975        }
976        Log.e(TAG, "Unknown sub-window type: " + type);
977        return 0;
978    }
979
980    public int getMaxWallpaperLayer() {
981        return STATUS_BAR_LAYER;
982    }
983
984    public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) {
985        return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD;
986    }
987
988    public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
989        return attrs.type != WindowManager.LayoutParams.TYPE_STATUS_BAR
990                && attrs.type != WindowManager.LayoutParams.TYPE_WALLPAPER;
991    }
992
993    /** {@inheritDoc} */
994    public View addStartingWindow(IBinder appToken, String packageName,
995                                  int theme, CharSequence nonLocalizedLabel,
996                                  int labelRes, int icon, int windowFlags) {
997        if (!SHOW_STARTING_ANIMATIONS) {
998            return null;
999        }
1000        if (packageName == null) {
1001            return null;
1002        }
1003
1004        try {
1005            Context context = mContext;
1006            boolean setTheme = false;
1007            //Log.i(TAG, "addStartingWindow " + packageName + ": nonLocalizedLabel="
1008            //        + nonLocalizedLabel + " theme=" + Integer.toHexString(theme));
1009            if (theme != 0 || labelRes != 0) {
1010                try {
1011                    context = context.createPackageContext(packageName, 0);
1012                    if (theme != 0) {
1013                        context.setTheme(theme);
1014                        setTheme = true;
1015                    }
1016                } catch (PackageManager.NameNotFoundException e) {
1017                    // Ignore
1018                }
1019            }
1020            if (!setTheme) {
1021                context.setTheme(com.android.internal.R.style.Theme);
1022            }
1023
1024            Window win = PolicyManager.makeNewWindow(context);
1025            if (win.getWindowStyle().getBoolean(
1026                    com.android.internal.R.styleable.Window_windowDisablePreview, false)) {
1027                return null;
1028            }
1029
1030            Resources r = context.getResources();
1031            win.setTitle(r.getText(labelRes, nonLocalizedLabel));
1032
1033            win.setType(
1034                WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
1035            // Force the window flags: this is a fake window, so it is not really
1036            // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
1037            // flag because we do know that the next window will take input
1038            // focus, so we want to get the IME window up on top of us right away.
1039            win.setFlags(
1040                windowFlags|
1041                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
1042                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
1043                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
1044                windowFlags|
1045                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
1046                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
1047                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
1048
1049            win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
1050                                WindowManager.LayoutParams.MATCH_PARENT);
1051
1052            final WindowManager.LayoutParams params = win.getAttributes();
1053            params.token = appToken;
1054            params.packageName = packageName;
1055            params.windowAnimations = win.getWindowStyle().getResourceId(
1056                    com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
1057            params.setTitle("Starting " + packageName);
1058
1059            WindowManagerImpl wm = (WindowManagerImpl)
1060                    context.getSystemService(Context.WINDOW_SERVICE);
1061            View view = win.getDecorView();
1062
1063            if (win.isFloating()) {
1064                // Whoops, there is no way to display an animation/preview
1065                // of such a thing!  After all that work...  let's skip it.
1066                // (Note that we must do this here because it is in
1067                // getDecorView() where the theme is evaluated...  maybe
1068                // we should peek the floating attribute from the theme
1069                // earlier.)
1070                return null;
1071            }
1072
1073            if (localLOGV) Log.v(
1074                TAG, "Adding starting window for " + packageName
1075                + " / " + appToken + ": "
1076                + (view.getParent() != null ? view : null));
1077
1078            wm.addView(view, params);
1079
1080            // Only return the view if it was successfully added to the
1081            // window manager... which we can tell by it having a parent.
1082            return view.getParent() != null ? view : null;
1083        } catch (WindowManagerImpl.BadTokenException e) {
1084            // ignore
1085            Log.w(TAG, appToken + " already running, starting window not displayed");
1086        } catch (RuntimeException e) {
1087            // don't crash if something else bad happens, for example a
1088            // failure loading resources because we are loading from an app
1089            // on external storage that has been unmounted.
1090            Log.w(TAG, appToken + " failed creating starting window", e);
1091        }
1092
1093        return null;
1094    }
1095
1096    /** {@inheritDoc} */
1097    public void removeStartingWindow(IBinder appToken, View window) {
1098        // RuntimeException e = new RuntimeException();
1099        // Log.i(TAG, "remove " + appToken + " " + window, e);
1100
1101        if (localLOGV) Log.v(
1102            TAG, "Removing starting window for " + appToken + ": " + window);
1103
1104        if (window != null) {
1105            WindowManagerImpl wm = (WindowManagerImpl) mContext.getSystemService(Context.WINDOW_SERVICE);
1106            wm.removeView(window);
1107        }
1108    }
1109
1110    /**
1111     * Preflight adding a window to the system.
1112     *
1113     * Currently enforces that three window types are singletons:
1114     * <ul>
1115     * <li>STATUS_BAR_TYPE</li>
1116     * <li>KEYGUARD_TYPE</li>
1117     * </ul>
1118     *
1119     * @param win The window to be added
1120     * @param attrs Information about the window to be added
1121     *
1122     * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons, WindowManagerImpl.ADD_MULTIPLE_SINGLETON
1123     */
1124    public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
1125        switch (attrs.type) {
1126            case TYPE_STATUS_BAR:
1127                mContext.enforceCallingOrSelfPermission(
1128                        android.Manifest.permission.STATUS_BAR_SERVICE,
1129                        "PhoneWindowManager");
1130                // TODO: Need to handle the race condition of the status bar proc
1131                // dying and coming back before the removeWindowLw cleanup has happened.
1132                if (mStatusBar != null) {
1133                    return WindowManagerImpl.ADD_MULTIPLE_SINGLETON;
1134                }
1135                mStatusBar = win;
1136
1137                // The Configuration will be stable by now, so we can load this
1138                mStatusBarCanHide = mContext.getResources().getBoolean(
1139                        com.android.internal.R.bool.config_statusBarCanHide);
1140
1141                break;
1142            case TYPE_STATUS_BAR_PANEL:
1143                mContext.enforceCallingOrSelfPermission(
1144                        android.Manifest.permission.STATUS_BAR_SERVICE,
1145                        "PhoneWindowManager");
1146                mStatusBarPanels.add(win);
1147                break;
1148            case TYPE_STATUS_BAR_SUB_PANEL:
1149                mContext.enforceCallingOrSelfPermission(
1150                        android.Manifest.permission.STATUS_BAR_SERVICE,
1151                        "PhoneWindowManager");
1152                mStatusBarPanels.add(win);
1153                break;
1154            case TYPE_KEYGUARD:
1155                if (mKeyguard != null) {
1156                    return WindowManagerImpl.ADD_MULTIPLE_SINGLETON;
1157                }
1158                mKeyguard = win;
1159                break;
1160        }
1161        return WindowManagerImpl.ADD_OKAY;
1162    }
1163
1164    /** {@inheritDoc} */
1165    public void removeWindowLw(WindowState win) {
1166        if (mStatusBar == win) {
1167            mStatusBar = null;
1168        }
1169        else if (mKeyguard == win) {
1170            mKeyguard = null;
1171        } else {
1172            mStatusBarPanels.remove(win);
1173        }
1174    }
1175
1176    static final boolean PRINT_ANIM = false;
1177
1178    /** {@inheritDoc} */
1179    public int selectAnimationLw(WindowState win, int transit) {
1180        if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
1181              + ": transit=" + transit);
1182        if (transit == TRANSIT_PREVIEW_DONE) {
1183            if (win.hasAppShownWindows()) {
1184                if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
1185                return com.android.internal.R.anim.app_starting_exit;
1186            }
1187        }
1188
1189        return 0;
1190    }
1191
1192    public Animation createForceHideEnterAnimation() {
1193        return AnimationUtils.loadAnimation(mContext,
1194                com.android.internal.R.anim.lock_screen_behind_enter);
1195    }
1196
1197    static ITelephony getTelephonyService() {
1198        ITelephony telephonyService = ITelephony.Stub.asInterface(
1199                ServiceManager.checkService(Context.TELEPHONY_SERVICE));
1200        if (telephonyService == null) {
1201            Log.w(TAG, "Unable to find ITelephony interface.");
1202        }
1203        return telephonyService;
1204    }
1205
1206    static IAudioService getAudioService() {
1207        IAudioService audioService = IAudioService.Stub.asInterface(
1208                ServiceManager.checkService(Context.AUDIO_SERVICE));
1209        if (audioService == null) {
1210            Log.w(TAG, "Unable to find IAudioService interface.");
1211        }
1212        return audioService;
1213    }
1214
1215    boolean keyguardOn() {
1216        return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode();
1217    }
1218
1219    private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
1220            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
1221            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
1222        };
1223
1224    /** {@inheritDoc} */
1225    @Override
1226    public boolean interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
1227        final boolean keyguardOn = keyguardOn();
1228        final int keyCode = event.getKeyCode();
1229        final int repeatCount = event.getRepeatCount();
1230        final int metaState = event.getMetaState();
1231        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
1232        final boolean canceled = event.isCanceled();
1233
1234        if (false) {
1235            Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
1236                    + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed);
1237        }
1238
1239        // First we always handle the home key here, so applications
1240        // can never break it, although if keyguard is on, we do let
1241        // it handle it, because that gives us the correct 5 second
1242        // timeout.
1243        if (keyCode == KeyEvent.KEYCODE_HOME) {
1244            // Clear a pending HOME longpress if the user releases Home
1245            if (!down) {
1246                mHandler.removeCallbacks(mHomeLongPress);
1247            }
1248
1249            // If we have released the home key, and didn't do anything else
1250            // while it was pressed, then it is time to go home!
1251            if (mHomePressed && !down) {
1252                mHomePressed = false;
1253                if (!canceled) {
1254                    // If an incoming call is ringing, HOME is totally disabled.
1255                    // (The user is already on the InCallScreen at this point,
1256                    // and his ONLY options are to answer or reject the call.)
1257                    boolean incomingRinging = false;
1258                    try {
1259                        ITelephony telephonyService = getTelephonyService();
1260                        if (telephonyService != null) {
1261                            incomingRinging = telephonyService.isRinging();
1262                        }
1263                    } catch (RemoteException ex) {
1264                        Log.w(TAG, "RemoteException from getPhoneInterface()", ex);
1265                    }
1266
1267                    if (incomingRinging) {
1268                        Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
1269                    } else {
1270                        launchHomeFromHotKey();
1271                    }
1272                } else {
1273                    Log.i(TAG, "Ignoring HOME; event canceled.");
1274                }
1275                return true;
1276            }
1277
1278            // If a system window has focus, then it doesn't make sense
1279            // right now to interact with applications.
1280            WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
1281            if (attrs != null) {
1282                final int type = attrs.type;
1283                if (type == WindowManager.LayoutParams.TYPE_KEYGUARD
1284                        || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {
1285                    // the "app" is keyguard, so give it the key
1286                    return false;
1287                }
1288                final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
1289                for (int i=0; i<typeCount; i++) {
1290                    if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
1291                        // don't do anything, but also don't pass it to the app
1292                        return true;
1293                    }
1294                }
1295            }
1296
1297            if (down && repeatCount == 0) {
1298                if (!keyguardOn) {
1299                    mHandler.postDelayed(mHomeLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
1300                }
1301                mHomePressed = true;
1302            }
1303            return true;
1304        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
1305            // Hijack modified menu keys for debugging features
1306            final int chordBug = KeyEvent.META_SHIFT_ON;
1307
1308            if (down && repeatCount == 0) {
1309                if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
1310                    Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
1311                    mContext.sendOrderedBroadcast(intent, null);
1312                    return true;
1313                } else if (SHOW_PROCESSES_ON_ALT_MENU &&
1314                        (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
1315                    Intent service = new Intent();
1316                    service.setClassName(mContext, "com.android.server.LoadAverageService");
1317                    ContentResolver res = mContext.getContentResolver();
1318                    boolean shown = Settings.System.getInt(
1319                            res, Settings.System.SHOW_PROCESSES, 0) != 0;
1320                    if (!shown) {
1321                        mContext.startService(service);
1322                    } else {
1323                        mContext.stopService(service);
1324                    }
1325                    Settings.System.putInt(
1326                            res, Settings.System.SHOW_PROCESSES, shown ? 0 : 1);
1327                    return true;
1328                }
1329            }
1330        } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
1331            if (down) {
1332                if (repeatCount == 0) {
1333                    mShortcutKeyPressed = keyCode;
1334                    mConsumeShortcutKeyUp = false;
1335                }
1336            } else if (keyCode == mShortcutKeyPressed) {
1337                mShortcutKeyPressed = -1;
1338                if (mConsumeShortcutKeyUp) {
1339                    mConsumeShortcutKeyUp = false;
1340                    return true;
1341                }
1342            }
1343            return false;
1344        } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
1345            if (!down) {
1346                showRecentAppsDialog();
1347            }
1348            return true;
1349        }
1350
1351        // Shortcuts are invoked through Search+key, so intercept those here
1352        // Any printing key that is chorded with Search should be consumed
1353        // even if no shortcut was invoked.  This prevents text from being
1354        // inadvertently inserted when using a keyboard that has built-in macro
1355        // shortcut keys (that emit Search+x) and some of them are not registered.
1356        if (mShortcutKeyPressed != -1) {
1357            final KeyCharacterMap kcm = event.getKeyCharacterMap();
1358            if (kcm.isPrintingKey(keyCode)) {
1359                mConsumeShortcutKeyUp = true;
1360                if (down && repeatCount == 0 && !keyguardOn) {
1361                    Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
1362                    if (shortcutIntent != null) {
1363                        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1364                        mContext.startActivity(shortcutIntent);
1365                    } else {
1366                        Slog.i(TAG, "Dropping unregistered shortcut key combination: "
1367                                + KeyEvent.keyCodeToString(mShortcutKeyPressed)
1368                                + "+" + KeyEvent.keyCodeToString(keyCode));
1369                    }
1370                }
1371                return true;
1372            }
1373        }
1374
1375        return false;
1376    }
1377
1378    /** {@inheritDoc} */
1379    @Override
1380    public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
1381        if (DEBUG_FALLBACK) {
1382            Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
1383                    + ", flags=" + event.getFlags()
1384                    + ", keyCode=" + event.getKeyCode()
1385                    + ", scanCode=" + event.getScanCode()
1386                    + ", metaState=" + event.getMetaState()
1387                    + ", repeatCount=" + event.getRepeatCount()
1388                    + ", policyFlags=" + policyFlags);
1389        }
1390
1391        if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
1392            // Invoke shortcuts using Meta as a fallback.
1393            final KeyCharacterMap kcm = event.getKeyCharacterMap();
1394            final int keyCode = event.getKeyCode();
1395            final int metaState = event.getMetaState();
1396            if ((metaState & KeyEvent.META_META_ON) != 0) {
1397                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
1398                        metaState & ~(KeyEvent.META_META_ON
1399                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
1400                if (shortcutIntent != null) {
1401                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1402                    mContext.startActivity(shortcutIntent);
1403                    return null;
1404                }
1405            }
1406
1407            // Check for fallback actions.
1408            if (kcm.getFallbackAction(keyCode, metaState, mFallbackAction)) {
1409                if (DEBUG_FALLBACK) {
1410                    Slog.d(TAG, "Fallback: keyCode=" + mFallbackAction.keyCode
1411                            + " metaState=" + Integer.toHexString(mFallbackAction.metaState));
1412                }
1413
1414                int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
1415                KeyEvent fallbackEvent = KeyEvent.obtain(
1416                        event.getDownTime(), event.getEventTime(),
1417                        event.getAction(), mFallbackAction.keyCode,
1418                        event.getRepeatCount(), mFallbackAction.metaState,
1419                        event.getDeviceId(), event.getScanCode(),
1420                        flags, event.getSource(), null);
1421                int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags, true);
1422                if ((actions & ACTION_PASS_TO_USER) != 0) {
1423                    if (!interceptKeyBeforeDispatching(win, fallbackEvent, policyFlags)) {
1424                        if (DEBUG_FALLBACK) {
1425                            Slog.d(TAG, "Performing fallback.");
1426                        }
1427                        return fallbackEvent;
1428                    }
1429                }
1430                fallbackEvent.recycle();
1431            }
1432        }
1433
1434        if (DEBUG_FALLBACK) {
1435            Slog.d(TAG, "No fallback.");
1436        }
1437        return null;
1438    }
1439
1440    /**
1441     * A home key -> launch home action was detected.  Take the appropriate action
1442     * given the situation with the keyguard.
1443     */
1444    void launchHomeFromHotKey() {
1445        if (mKeyguardMediator.isShowingAndNotHidden()) {
1446            // don't launch home if keyguard showing
1447        } else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) {
1448            // when in keyguard restricted mode, must first verify unlock
1449            // before launching home
1450            mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() {
1451                public void onKeyguardExitResult(boolean success) {
1452                    if (success) {
1453                        try {
1454                            ActivityManagerNative.getDefault().stopAppSwitches();
1455                        } catch (RemoteException e) {
1456                        }
1457                        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
1458                        startDockOrHome();
1459                    }
1460                }
1461            });
1462        } else {
1463            // no keyguard stuff to worry about, just launch home!
1464            try {
1465                ActivityManagerNative.getDefault().stopAppSwitches();
1466            } catch (RemoteException e) {
1467            }
1468            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
1469            startDockOrHome();
1470        }
1471    }
1472
1473    public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
1474        final int fl = attrs.flags;
1475
1476        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
1477                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
1478            contentInset.set(mCurLeft, mCurTop,
1479                    (mRestrictedScreenLeft+mRestrictedScreenWidth) - mCurRight,
1480                    (mRestrictedScreenTop+mRestrictedScreenHeight) - mCurBottom);
1481        } else {
1482            contentInset.setEmpty();
1483        }
1484    }
1485
1486    /** {@inheritDoc} */
1487    public void beginLayoutLw(int displayWidth, int displayHeight) {
1488        mUnrestrictedScreenLeft = mUnrestrictedScreenTop = 0;
1489        mUnrestrictedScreenWidth = displayWidth;
1490        mUnrestrictedScreenHeight = displayHeight;
1491        mRestrictedScreenLeft = mRestrictedScreenTop = 0;
1492        mRestrictedScreenWidth = displayWidth;
1493        mRestrictedScreenHeight = displayHeight;
1494        mDockLeft = mContentLeft = mCurLeft = 0;
1495        mDockTop = mContentTop = mCurTop = 0;
1496        mDockRight = mContentRight = mCurRight = displayWidth;
1497        mDockBottom = mContentBottom = mCurBottom = displayHeight;
1498        mDockLayer = 0x10000000;
1499
1500        // decide where the status bar goes ahead of time
1501        if (mStatusBar != null) {
1502            final Rect pf = mTmpParentFrame;
1503            final Rect df = mTmpDisplayFrame;
1504            final Rect vf = mTmpVisibleFrame;
1505            pf.left = df.left = vf.left = 0;
1506            pf.top = df.top = vf.top = 0;
1507            pf.right = df.right = vf.right = displayWidth;
1508            pf.bottom = df.bottom = vf.bottom = displayHeight;
1509
1510            mStatusBar.computeFrameLw(pf, df, vf, vf);
1511            if (mStatusBar.isVisibleLw()) {
1512                // If the status bar is hidden, we don't want to cause
1513                // windows behind it to scroll.
1514                final Rect r = mStatusBar.getFrameLw();
1515                if (mStatusBarCanHide) {
1516                    // Status bar may go away, so the screen area it occupies
1517                    // is available to apps but just covering them when the
1518                    // status bar is visible.
1519                    if (mDockTop == r.top) mDockTop = r.bottom;
1520                    else if (mDockBottom == r.bottom) mDockBottom = r.top;
1521                    mContentTop = mCurTop = mDockTop;
1522                    mContentBottom = mCurBottom = mDockBottom;
1523                    if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: mDockTop=" + mDockTop
1524                            + " mContentTop=" + mContentTop
1525                            + " mCurTop=" + mCurTop
1526                            + " mDockBottom=" + mDockBottom
1527                            + " mContentBottom=" + mContentBottom
1528                            + " mCurBottom=" + mCurBottom);
1529                } else {
1530                    // Status bar can't go away; the part of the screen it
1531                    // covers does not exist for anything behind it.
1532                    if (mRestrictedScreenTop == r.top) {
1533                        mRestrictedScreenTop = r.bottom;
1534                        mRestrictedScreenHeight -= (r.bottom-r.top);
1535                    } else if ((mRestrictedScreenHeight-mRestrictedScreenTop) == r.bottom) {
1536                        mRestrictedScreenHeight -= (r.bottom-r.top);
1537                    }
1538                    mContentTop = mCurTop = mDockTop = mRestrictedScreenTop;
1539                    mContentBottom = mCurBottom = mDockBottom
1540                            = mRestrictedScreenTop + mRestrictedScreenHeight;
1541                    if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: mRestrictedScreenTop="
1542                            + mRestrictedScreenTop
1543                            + " mRestrictedScreenHeight=" + mRestrictedScreenHeight);
1544                }
1545            }
1546        }
1547    }
1548
1549    void setAttachedWindowFrames(WindowState win, int fl, int adjust,
1550            WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) {
1551        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
1552            // Here's a special case: if this attached window is a panel that is
1553            // above the dock window, and the window it is attached to is below
1554            // the dock window, then the frames we computed for the window it is
1555            // attached to can not be used because the dock is effectively part
1556            // of the underlying window and the attached window is floating on top
1557            // of the whole thing.  So, we ignore the attached window and explicitly
1558            // compute the frames that would be appropriate without the dock.
1559            df.left = cf.left = vf.left = mDockLeft;
1560            df.top = cf.top = vf.top = mDockTop;
1561            df.right = cf.right = vf.right = mDockRight;
1562            df.bottom = cf.bottom = vf.bottom = mDockBottom;
1563        } else {
1564            // The effective display frame of the attached window depends on
1565            // whether it is taking care of insetting its content.  If not,
1566            // we need to use the parent's content frame so that the entire
1567            // window is positioned within that content.  Otherwise we can use
1568            // the display frame and let the attached window take care of
1569            // positioning its content appropriately.
1570            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
1571                cf.set(attached.getDisplayFrameLw());
1572            } else {
1573                // If the window is resizing, then we want to base the content
1574                // frame on our attached content frame to resize...  however,
1575                // things can be tricky if the attached window is NOT in resize
1576                // mode, in which case its content frame will be larger.
1577                // Ungh.  So to deal with that, make sure the content frame
1578                // we end up using is not covering the IM dock.
1579                cf.set(attached.getContentFrameLw());
1580                if (attached.getSurfaceLayer() < mDockLayer) {
1581                    if (cf.left < mContentLeft) cf.left = mContentLeft;
1582                    if (cf.top < mContentTop) cf.top = mContentTop;
1583                    if (cf.right > mContentRight) cf.right = mContentRight;
1584                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
1585                }
1586            }
1587            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
1588            vf.set(attached.getVisibleFrameLw());
1589        }
1590        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
1591        // window should be positioned relative to its parent or the entire
1592        // screen.
1593        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
1594                ? attached.getFrameLw() : df);
1595    }
1596
1597    /** {@inheritDoc} */
1598    public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
1599            WindowState attached) {
1600        // we've already done the status bar
1601        if (win == mStatusBar) {
1602            return;
1603        }
1604
1605        final int fl = attrs.flags;
1606        final int sim = attrs.softInputMode;
1607
1608        final Rect pf = mTmpParentFrame;
1609        final Rect df = mTmpDisplayFrame;
1610        final Rect cf = mTmpContentFrame;
1611        final Rect vf = mTmpVisibleFrame;
1612
1613        if (attrs.type == TYPE_INPUT_METHOD) {
1614            pf.left = df.left = cf.left = vf.left = mDockLeft;
1615            pf.top = df.top = cf.top = vf.top = mDockTop;
1616            pf.right = df.right = cf.right = vf.right = mDockRight;
1617            pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom;
1618            // IM dock windows always go to the bottom of the screen.
1619            attrs.gravity = Gravity.BOTTOM;
1620            mDockLayer = win.getSurfaceLayer();
1621        } else {
1622            final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
1623
1624            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
1625                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
1626                // This is the case for a normal activity window: we want it
1627                // to cover all of the screen space, and it can take care of
1628                // moving its contents to account for screen decorations that
1629                // intrude into that space.
1630                if (attached != null) {
1631                    // If this window is attached to another, our display
1632                    // frame is the same as the one we are attached to.
1633                    setAttachedWindowFrames(win, fl, sim, attached, true, pf, df, cf, vf);
1634                } else {
1635                    if (attrs.type == TYPE_STATUS_BAR_PANEL) {
1636                        // Status bar panels are the only windows who can go on top of
1637                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
1638                        // permission, so they have the same privileges as the status
1639                        // bar itself.
1640                        pf.left = df.left = mUnrestrictedScreenLeft;
1641                        pf.top = df.top = mUnrestrictedScreenTop;
1642                        pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
1643                        pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
1644                    } else {
1645                        pf.left = df.left = mRestrictedScreenLeft;
1646                        pf.top = df.top = mRestrictedScreenTop;
1647                        pf.right = df.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
1648                        pf.bottom = df.bottom = mRestrictedScreenTop+mRestrictedScreenHeight;
1649                    }
1650                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
1651                        cf.left = mDockLeft;
1652                        cf.top = mDockTop;
1653                        cf.right = mDockRight;
1654                        cf.bottom = mDockBottom;
1655                    } else {
1656                        cf.left = mContentLeft;
1657                        cf.top = mContentTop;
1658                        cf.right = mContentRight;
1659                        cf.bottom = mContentBottom;
1660                    }
1661                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
1662                        vf.left = mCurLeft;
1663                        vf.top = mCurTop;
1664                        vf.right = mCurRight;
1665                        vf.bottom = mCurBottom;
1666                    } else {
1667                        vf.set(cf);
1668                    }
1669                }
1670            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0) {
1671                // A window that has requested to fill the entire screen just
1672                // gets everything, period.
1673                if (attrs.type == TYPE_STATUS_BAR_PANEL) {
1674                    pf.left = df.left = cf.left = mUnrestrictedScreenLeft;
1675                    pf.top = df.top = cf.top = mUnrestrictedScreenTop;
1676                    pf.right = df.right = cf.right
1677                            = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
1678                    pf.bottom = df.bottom = cf.bottom
1679                            = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
1680                } else {
1681                    pf.left = df.left = cf.left = mRestrictedScreenLeft;
1682                    pf.top = df.top = cf.top = mRestrictedScreenTop;
1683                    pf.right = df.right = cf.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
1684                    pf.bottom = df.bottom = cf.bottom
1685                            = mRestrictedScreenTop+mRestrictedScreenHeight;
1686                }
1687                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
1688                    vf.left = mCurLeft;
1689                    vf.top = mCurTop;
1690                    vf.right = mCurRight;
1691                    vf.bottom = mCurBottom;
1692                } else {
1693                    vf.set(cf);
1694                }
1695            } else if (attached != null) {
1696                // A child window should be placed inside of the same visible
1697                // frame that its parent had.
1698                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, cf, vf);
1699            } else {
1700                // Otherwise, a normal window must be placed inside the content
1701                // of all screen decorations.
1702                pf.left = mContentLeft;
1703                pf.top = mContentTop;
1704                pf.right = mContentRight;
1705                pf.bottom = mContentBottom;
1706                if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
1707                    df.left = cf.left = mDockLeft;
1708                    df.top = cf.top = mDockTop;
1709                    df.right = cf.right = mDockRight;
1710                    df.bottom = cf.bottom = mDockBottom;
1711                } else {
1712                    df.left = cf.left = mContentLeft;
1713                    df.top = cf.top = mContentTop;
1714                    df.right = cf.right = mContentRight;
1715                    df.bottom = cf.bottom = mContentBottom;
1716                }
1717                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
1718                    vf.left = mCurLeft;
1719                    vf.top = mCurTop;
1720                    vf.right = mCurRight;
1721                    vf.bottom = mCurBottom;
1722                } else {
1723                    vf.set(cf);
1724                }
1725            }
1726        }
1727
1728        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
1729            df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000;
1730            df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
1731        }
1732
1733        if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
1734                + ": sim=#" + Integer.toHexString(sim)
1735                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
1736                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
1737
1738        win.computeFrameLw(pf, df, cf, vf);
1739
1740        // Dock windows carve out the bottom of the screen, so normal windows
1741        // can't appear underneath them.
1742        if (attrs.type == TYPE_INPUT_METHOD && !win.getGivenInsetsPendingLw()) {
1743            int top = win.getContentFrameLw().top;
1744            top += win.getGivenContentInsetsLw().top;
1745            if (mContentBottom > top) {
1746                mContentBottom = top;
1747            }
1748            top = win.getVisibleFrameLw().top;
1749            top += win.getGivenVisibleInsetsLw().top;
1750            if (mCurBottom > top) {
1751                mCurBottom = top;
1752            }
1753            if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
1754                    + mDockBottom + " mContentBottom="
1755                    + mContentBottom + " mCurBottom=" + mCurBottom);
1756        }
1757    }
1758
1759    /** {@inheritDoc} */
1760    public int finishLayoutLw() {
1761        return 0;
1762    }
1763
1764    /** {@inheritDoc} */
1765    public void beginAnimationLw(int displayWidth, int displayHeight) {
1766        mTopFullscreenOpaqueWindowState = null;
1767        mForceStatusBar = false;
1768
1769        mHideLockScreen = false;
1770        mAllowLockscreenWhenOn = false;
1771        mDismissKeyguard = false;
1772    }
1773
1774    /** {@inheritDoc} */
1775    public void animatingWindowLw(WindowState win,
1776                                WindowManager.LayoutParams attrs) {
1777        if (mTopFullscreenOpaqueWindowState == null &&
1778                win.isVisibleOrBehindKeyguardLw()) {
1779            if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
1780                mForceStatusBar = true;
1781            }
1782            if (attrs.type >= FIRST_APPLICATION_WINDOW
1783                    && attrs.type <= LAST_APPLICATION_WINDOW
1784                    && attrs.x == 0 && attrs.y == 0
1785                    && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
1786                    && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
1787                if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
1788                mTopFullscreenOpaqueWindowState = win;
1789                if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
1790                    if (localLOGV) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
1791                    mHideLockScreen = true;
1792                }
1793                if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0) {
1794                    if (localLOGV) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
1795                    mDismissKeyguard = true;
1796                }
1797                if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
1798                    mAllowLockscreenWhenOn = true;
1799                }
1800            }
1801        }
1802    }
1803
1804    /** {@inheritDoc} */
1805    public int finishAnimationLw() {
1806        int changes = 0;
1807        boolean topIsFullscreen = false;
1808
1809        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
1810                ? mTopFullscreenOpaqueWindowState.getAttrs()
1811                : null;
1812
1813        if (mStatusBar != null) {
1814            if (localLOGV) Log.i(TAG, "force=" + mForceStatusBar
1815                    + " top=" + mTopFullscreenOpaqueWindowState);
1816            if (mForceStatusBar) {
1817                if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
1818                if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
1819            } else if (mTopFullscreenOpaqueWindowState != null) {
1820                if (localLOGV) {
1821                    Log.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
1822                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
1823                    Log.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
1824                            + " lp.flags=0x" + Integer.toHexString(lp.flags));
1825                }
1826                topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
1827                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
1828                // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window
1829                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
1830                // case though.
1831                if (topIsFullscreen) {
1832                    if (mStatusBarCanHide) {
1833                        if (DEBUG_LAYOUT) Log.v(TAG, "Hiding status bar");
1834                        if (mStatusBar.hideLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
1835                    } else if (localLOGV) {
1836                        Log.v(TAG, "Preventing status bar from hiding by policy");
1837                    }
1838                } else {
1839                    if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
1840                    if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
1841                }
1842            }
1843        }
1844
1845        boolean topNeedsMenu = mShowMenuKey;
1846        if (lp != null) {
1847            topNeedsMenu = (lp.flags & WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY) != 0;
1848        }
1849
1850        if (DEBUG_LAYOUT) Log.v(TAG, "Top window "
1851                + (topNeedsMenu ? "needs" : "does not need")
1852                + " the MENU key");
1853
1854        final boolean changedFullscreen = (mTopIsFullscreen != topIsFullscreen);
1855        final boolean changedMenu = (topNeedsMenu != mShowMenuKey);
1856
1857        if (changedFullscreen || changedMenu) {
1858            final boolean topIsFullscreenF = topIsFullscreen;
1859            final boolean topNeedsMenuF = topNeedsMenu;
1860
1861            mTopIsFullscreen = topIsFullscreen;
1862            mShowMenuKey = topNeedsMenu;
1863
1864            mHandler.post(new Runnable() {
1865                    public void run() {
1866                        if (mStatusBarService == null) {
1867                            // This is the one that can not go away, but it doesn't come up
1868                            // before the window manager does, so don't fail if it doesn't
1869                            // exist. This works as long as no fullscreen windows come up
1870                            // before the status bar service does.
1871                            mStatusBarService = IStatusBarService.Stub.asInterface(
1872                                    ServiceManager.getService("statusbar"));
1873                        }
1874                        final IStatusBarService sbs = mStatusBarService;
1875                        if (mStatusBarService != null) {
1876                            try {
1877                                if (changedMenu) {
1878                                    sbs.setMenuKeyVisible(topNeedsMenuF);
1879                                }
1880                                if (changedFullscreen) {
1881                                    sbs.setActiveWindowIsFullscreen(topIsFullscreenF);
1882                                }
1883                            } catch (RemoteException e) {
1884                                // This should be impossible because we're in the same process.
1885                                mStatusBarService = null;
1886                            }
1887                        }
1888                    }
1889                });
1890        }
1891
1892        // Hide the key guard if a visible window explicitly specifies that it wants to be displayed
1893        // when the screen is locked
1894        if (mKeyguard != null) {
1895            if (localLOGV) Log.v(TAG, "finishAnimationLw::mHideKeyguard="+mHideLockScreen);
1896            if (mDismissKeyguard && !mKeyguardMediator.isSecure()) {
1897                if (mKeyguard.hideLw(true)) {
1898                    changes |= FINISH_LAYOUT_REDO_LAYOUT
1899                            | FINISH_LAYOUT_REDO_CONFIG
1900                            | FINISH_LAYOUT_REDO_WALLPAPER;
1901                }
1902                if (mKeyguardMediator.isShowing()) {
1903                    mHandler.post(new Runnable() {
1904                        public void run() {
1905                            mKeyguardMediator.keyguardDone(false, false);
1906                        }
1907                    });
1908                }
1909            } else if (mHideLockScreen) {
1910                if (mKeyguard.hideLw(true)) {
1911                    changes |= FINISH_LAYOUT_REDO_LAYOUT
1912                            | FINISH_LAYOUT_REDO_CONFIG
1913                            | FINISH_LAYOUT_REDO_WALLPAPER;
1914                }
1915                mKeyguardMediator.setHidden(true);
1916            } else {
1917                if (mKeyguard.showLw(true)) {
1918                    changes |= FINISH_LAYOUT_REDO_LAYOUT
1919                            | FINISH_LAYOUT_REDO_CONFIG
1920                            | FINISH_LAYOUT_REDO_WALLPAPER;
1921                }
1922                mKeyguardMediator.setHidden(false);
1923            }
1924        }
1925
1926        // update since mAllowLockscreenWhenOn might have changed
1927        updateLockScreenTimeout();
1928        return changes;
1929    }
1930
1931    public boolean allowAppAnimationsLw() {
1932        if (mKeyguard != null && mKeyguard.isVisibleLw()) {
1933            // If keyguard is currently visible, no reason to animate
1934            // behind it.
1935            return false;
1936        }
1937        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
1938            Rect rect = new Rect(mStatusBar.getShownFrameLw());
1939            for (int i=mStatusBarPanels.size()-1; i>=0; i--) {
1940                WindowState w = mStatusBarPanels.get(i);
1941                if (w.isVisibleLw()) {
1942                    rect.union(w.getShownFrameLw());
1943                }
1944            }
1945            final int insetw = mRestrictedScreenWidth/10;
1946            final int inseth = mRestrictedScreenHeight/10;
1947            if (rect.contains(insetw, inseth, mRestrictedScreenWidth-insetw,
1948                        mRestrictedScreenHeight-inseth)) {
1949                // All of the status bar windows put together cover the
1950                // screen, so the app can't be seen.  (Note this test doesn't
1951                // work if the rects of these windows are at off offsets or
1952                // sizes, causing gaps in the rect union we have computed.)
1953                return false;
1954            }
1955        }
1956        return true;
1957    }
1958
1959    /** {@inheritDoc} */
1960    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
1961        // lid changed state
1962        mLidOpen = lidOpen;
1963        boolean awakeNow = mKeyguardMediator.doLidChangeTq(mLidOpen);
1964        updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
1965        if (awakeNow) {
1966            // If the lid opening and we don't have to keep the
1967            // keyguard up, then we can turn on the screen
1968            // immediately.
1969            mKeyguardMediator.pokeWakelock();
1970        } else if (keyguardIsShowingTq()) {
1971            if (mLidOpen) {
1972                // If we are opening the lid and not hiding the
1973                // keyguard, then we need to have it turn on the
1974                // screen once it is shown.
1975                mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(
1976                        KeyEvent.KEYCODE_POWER);
1977            }
1978        } else {
1979            // Light up the keyboard if we are sliding up.
1980            if (mLidOpen) {
1981                mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
1982                        LocalPowerManager.BUTTON_EVENT);
1983            } else {
1984                mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
1985                        LocalPowerManager.OTHER_EVENT);
1986            }
1987        }
1988    }
1989
1990    /**
1991     * @return Whether music is being played right now.
1992     */
1993    boolean isMusicActive() {
1994        final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
1995        if (am == null) {
1996            Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
1997            return false;
1998        }
1999        return am.isMusicActive();
2000    }
2001
2002    /**
2003     * Tell the audio service to adjust the volume appropriate to the event.
2004     * @param keycode
2005     */
2006    void handleVolumeKey(int stream, int keycode) {
2007        IAudioService audioService = getAudioService();
2008        if (audioService == null) {
2009            return;
2010        }
2011        try {
2012            // since audio is playing, we shouldn't have to hold a wake lock
2013            // during the call, but we do it as a precaution for the rare possibility
2014            // that the music stops right before we call this
2015            // TODO: Actually handle MUTE.
2016            mBroadcastWakeLock.acquire();
2017            audioService.adjustStreamVolume(stream,
2018                keycode == KeyEvent.KEYCODE_VOLUME_UP
2019                            ? AudioManager.ADJUST_RAISE
2020                            : AudioManager.ADJUST_LOWER,
2021                    0);
2022        } catch (RemoteException e) {
2023            Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
2024        } finally {
2025            mBroadcastWakeLock.release();
2026        }
2027    }
2028
2029    /** {@inheritDoc} */
2030    @Override
2031    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
2032        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
2033        final boolean canceled = event.isCanceled();
2034        final int keyCode = event.getKeyCode();
2035
2036        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
2037
2038        // If screen is off then we treat the case where the keyguard is open but hidden
2039        // the same as if it were open and in front.
2040        // This will prevent any keys other than the power button from waking the screen
2041        // when the keyguard is hidden by another activity.
2042        final boolean keyguardActive = (isScreenOn ?
2043                                        mKeyguardMediator.isShowingAndNotHidden() :
2044                                        mKeyguardMediator.isShowing());
2045
2046        if (false) {
2047            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
2048                  + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive);
2049        }
2050
2051        if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0) {
2052            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
2053        }
2054
2055        // Basic policy based on screen state and keyguard.
2056        // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
2057        //        is on or off, really.  We should care about whether the device is in an
2058        //        interactive state or is in suspend pretending to be "off".
2059        //        The primary screen might be turned off due to proximity sensor or
2060        //        because we are presenting media on an auxiliary screen or remotely controlling
2061        //        the device some other way (which is why we have an exemption here for injected
2062        //        events).
2063        int result;
2064        if (isScreenOn || isInjected) {
2065            // When the screen is on or if the key is injected pass the key to the application.
2066            result = ACTION_PASS_TO_USER;
2067        } else {
2068            // When the screen is off and the key is not injected, determine whether
2069            // to wake the device but don't pass the key to the application.
2070            result = 0;
2071
2072            final boolean isWakeKey = (policyFlags
2073                    & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
2074            if (down && isWakeKey) {
2075                if (keyguardActive) {
2076                    // If the keyguard is showing, let it decide what to do with the wake key.
2077                    mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode);
2078                } else {
2079                    // Otherwise, wake the device ourselves.
2080                    result |= ACTION_POKE_USER_ACTIVITY;
2081                }
2082            }
2083        }
2084
2085        // Handle special keys.
2086        switch (keyCode) {
2087            case KeyEvent.KEYCODE_VOLUME_DOWN:
2088            case KeyEvent.KEYCODE_VOLUME_UP:
2089            case KeyEvent.KEYCODE_VOLUME_MUTE: {
2090                if (down) {
2091                    ITelephony telephonyService = getTelephonyService();
2092                    if (telephonyService != null) {
2093                        try {
2094                            if (telephonyService.isRinging()) {
2095                                // If an incoming call is ringing, either VOLUME key means
2096                                // "silence ringer".  We handle these keys here, rather than
2097                                // in the InCallScreen, to make sure we'll respond to them
2098                                // even if the InCallScreen hasn't come to the foreground yet.
2099                                // Look for the DOWN event here, to agree with the "fallback"
2100                                // behavior in the InCallScreen.
2101                                Log.i(TAG, "interceptKeyBeforeQueueing:"
2102                                      + " VOLUME key-down while ringing: Silence ringer!");
2103
2104                                // Silence the ringer.  (It's safe to call this
2105                                // even if the ringer has already been silenced.)
2106                                telephonyService.silenceRinger();
2107
2108                                // And *don't* pass this key thru to the current activity
2109                                // (which is probably the InCallScreen.)
2110                                result &= ~ACTION_PASS_TO_USER;
2111                                break;
2112                            }
2113                            if (telephonyService.isOffhook()
2114                                    && (result & ACTION_PASS_TO_USER) == 0) {
2115                                // If we are in call but we decided not to pass the key to
2116                                // the application, handle the volume change here.
2117                                handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
2118                                break;
2119                            }
2120                        } catch (RemoteException ex) {
2121                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2122                        }
2123                    }
2124
2125                    if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
2126                        // If music is playing but we decided not to pass the key to the
2127                        // application, handle the volume change here.
2128                        handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
2129                        break;
2130                    }
2131                }
2132                break;
2133            }
2134
2135            case KeyEvent.KEYCODE_ENDCALL: {
2136                result &= ~ACTION_PASS_TO_USER;
2137                if (down) {
2138                    ITelephony telephonyService = getTelephonyService();
2139                    boolean hungUp = false;
2140                    if (telephonyService != null) {
2141                        try {
2142                            hungUp = telephonyService.endCall();
2143                        } catch (RemoteException ex) {
2144                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2145                        }
2146                    }
2147                    interceptPowerKeyDown(!isScreenOn || hungUp);
2148                } else {
2149                    if (interceptPowerKeyUp(canceled)) {
2150                        if ((mEndcallBehavior
2151                                & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
2152                            if (goHome()) {
2153                                break;
2154                            }
2155                        }
2156                        if ((mEndcallBehavior
2157                                & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
2158                            result = (result & ~ACTION_POKE_USER_ACTIVITY) | ACTION_GO_TO_SLEEP;
2159                        }
2160                    }
2161                }
2162                break;
2163            }
2164
2165            case KeyEvent.KEYCODE_POWER: {
2166                result &= ~ACTION_PASS_TO_USER;
2167                if (down) {
2168                    ITelephony telephonyService = getTelephonyService();
2169                    boolean hungUp = false;
2170                    if (telephonyService != null) {
2171                        try {
2172                            if (telephonyService.isRinging()) {
2173                                // Pressing Power while there's a ringing incoming
2174                                // call should silence the ringer.
2175                                telephonyService.silenceRinger();
2176                            } else if ((mIncallPowerBehavior
2177                                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
2178                                    && telephonyService.isOffhook()) {
2179                                // Otherwise, if "Power button ends call" is enabled,
2180                                // the Power button will hang up any current active call.
2181                                hungUp = telephonyService.endCall();
2182                            }
2183                        } catch (RemoteException ex) {
2184                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2185                        }
2186                    }
2187                    interceptPowerKeyDown(!isScreenOn || hungUp);
2188                } else {
2189                    if (interceptPowerKeyUp(canceled)) {
2190                        result = (result & ~ACTION_POKE_USER_ACTIVITY) | ACTION_GO_TO_SLEEP;
2191                    }
2192                }
2193                break;
2194            }
2195
2196            case KeyEvent.KEYCODE_MEDIA_PLAY:
2197            case KeyEvent.KEYCODE_MEDIA_PAUSE:
2198            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
2199                if (down) {
2200                    ITelephony telephonyService = getTelephonyService();
2201                    if (telephonyService != null) {
2202                        try {
2203                            if (!telephonyService.isIdle()) {
2204                                // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
2205                                // to avoid music playback.
2206                                break;
2207                            }
2208                        } catch (RemoteException ex) {
2209                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2210                        }
2211                    }
2212                }
2213            case KeyEvent.KEYCODE_HEADSETHOOK:
2214            case KeyEvent.KEYCODE_MUTE:
2215            case KeyEvent.KEYCODE_MEDIA_STOP:
2216            case KeyEvent.KEYCODE_MEDIA_NEXT:
2217            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
2218            case KeyEvent.KEYCODE_MEDIA_REWIND:
2219            case KeyEvent.KEYCODE_MEDIA_RECORD:
2220            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
2221                if ((result & ACTION_PASS_TO_USER) == 0) {
2222                    // Only do this if we would otherwise not pass it to the user. In that
2223                    // case, the PhoneWindow class will do the same thing, except it will
2224                    // only do it if the showing app doesn't process the key on its own.
2225                    mBroadcastWakeLock.acquire();
2226                    mHandler.post(new PassHeadsetKey(new KeyEvent(event)));
2227                }
2228                break;
2229            }
2230
2231            case KeyEvent.KEYCODE_CALL: {
2232                if (down) {
2233                    ITelephony telephonyService = getTelephonyService();
2234                    if (telephonyService != null) {
2235                        try {
2236                            if (telephonyService.isRinging()) {
2237                                Log.i(TAG, "interceptKeyBeforeQueueing:"
2238                                      + " CALL key-down while ringing: Answer the call!");
2239                                telephonyService.answerRingingCall();
2240
2241                                // And *don't* pass this key thru to the current activity
2242                                // (which is presumably the InCallScreen.)
2243                                result &= ~ACTION_PASS_TO_USER;
2244                            }
2245                        } catch (RemoteException ex) {
2246                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2247                        }
2248                    }
2249                }
2250                break;
2251            }
2252        }
2253        return result;
2254    }
2255
2256    class PassHeadsetKey implements Runnable {
2257        KeyEvent mKeyEvent;
2258
2259        PassHeadsetKey(KeyEvent keyEvent) {
2260            mKeyEvent = keyEvent;
2261        }
2262
2263        public void run() {
2264            if (ActivityManagerNative.isSystemReady()) {
2265                Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
2266                intent.putExtra(Intent.EXTRA_KEY_EVENT, mKeyEvent);
2267                mContext.sendOrderedBroadcast(intent, null, mBroadcastDone,
2268                        mHandler, Activity.RESULT_OK, null, null);
2269            }
2270        }
2271    }
2272
2273    BroadcastReceiver mBroadcastDone = new BroadcastReceiver() {
2274        public void onReceive(Context context, Intent intent) {
2275            mBroadcastWakeLock.release();
2276        }
2277    };
2278
2279    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
2280        public void onReceive(Context context, Intent intent) {
2281            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
2282                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2283                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
2284            } else {
2285                try {
2286                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
2287                            ServiceManager.getService(Context.UI_MODE_SERVICE));
2288                    mUiMode = uiModeService.getCurrentModeType();
2289                } catch (RemoteException e) {
2290                }
2291            }
2292            updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
2293            updateOrientationListenerLp();
2294        }
2295    };
2296
2297    /** {@inheritDoc} */
2298    public void screenTurnedOff(int why) {
2299        EventLog.writeEvent(70000, 0);
2300        mKeyguardMediator.onScreenTurnedOff(why);
2301        synchronized (mLock) {
2302            mScreenOn = false;
2303            updateOrientationListenerLp();
2304            updateLockScreenTimeout();
2305        }
2306    }
2307
2308    /** {@inheritDoc} */
2309    public void screenTurnedOn() {
2310        EventLog.writeEvent(70000, 1);
2311        mKeyguardMediator.onScreenTurnedOn();
2312        synchronized (mLock) {
2313            mScreenOn = true;
2314            updateOrientationListenerLp();
2315            updateLockScreenTimeout();
2316        }
2317    }
2318
2319    /** {@inheritDoc} */
2320    public boolean isScreenOn() {
2321        return mScreenOn;
2322    }
2323
2324    /** {@inheritDoc} */
2325    public void enableKeyguard(boolean enabled) {
2326        mKeyguardMediator.setKeyguardEnabled(enabled);
2327    }
2328
2329    /** {@inheritDoc} */
2330    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
2331        mKeyguardMediator.verifyUnlock(callback);
2332    }
2333
2334    private boolean keyguardIsShowingTq() {
2335        return mKeyguardMediator.isShowingAndNotHidden();
2336    }
2337
2338    /** {@inheritDoc} */
2339    public boolean inKeyguardRestrictedKeyInputMode() {
2340        return mKeyguardMediator.isInputRestricted();
2341    }
2342
2343    void sendCloseSystemWindows() {
2344        sendCloseSystemWindows(mContext, null);
2345    }
2346
2347    void sendCloseSystemWindows(String reason) {
2348        sendCloseSystemWindows(mContext, reason);
2349    }
2350
2351    static void sendCloseSystemWindows(Context context, String reason) {
2352        if (ActivityManagerNative.isSystemReady()) {
2353            try {
2354                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
2355            } catch (RemoteException e) {
2356            }
2357        }
2358    }
2359
2360    public int rotationForOrientationLw(int orientation, int lastRotation,
2361            boolean displayEnabled) {
2362
2363        if (mPortraitRotation < 0) {
2364            // Initialize the rotation angles for each orientation once.
2365            Display d = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
2366                    .getDefaultDisplay();
2367            if (d.getWidth() > d.getHeight()) {
2368                mLandscapeRotation = Surface.ROTATION_0;
2369                mSeascapeRotation = Surface.ROTATION_180;
2370                if (mContext.getResources().getBoolean(
2371                        com.android.internal.R.bool.config_reverseDefaultRotation)) {
2372                    mPortraitRotation = Surface.ROTATION_90;
2373                    mUpsideDownRotation = Surface.ROTATION_270;
2374                } else {
2375                    mPortraitRotation = Surface.ROTATION_270;
2376                    mUpsideDownRotation = Surface.ROTATION_90;
2377                }
2378            } else {
2379                mPortraitRotation = Surface.ROTATION_0;
2380                mUpsideDownRotation = Surface.ROTATION_180;
2381                if (mContext.getResources().getBoolean(
2382                        com.android.internal.R.bool.config_reverseDefaultRotation)) {
2383                    mLandscapeRotation = Surface.ROTATION_270;
2384                    mSeascapeRotation = Surface.ROTATION_90;
2385                } else {
2386                    mLandscapeRotation = Surface.ROTATION_90;
2387                    mSeascapeRotation = Surface.ROTATION_270;
2388                }
2389            }
2390        }
2391
2392        synchronized (mLock) {
2393            switch (orientation) {
2394                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
2395                    //always return portrait if orientation set to portrait
2396                    return mPortraitRotation;
2397                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
2398                    //always return landscape if orientation set to landscape
2399                    return mLandscapeRotation;
2400                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
2401                    //always return portrait if orientation set to portrait
2402                    return mUpsideDownRotation;
2403                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
2404                    //always return seascape if orientation set to reverse landscape
2405                    return mSeascapeRotation;
2406                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
2407                    //return either landscape rotation based on the sensor
2408                    mOrientationListener.setAllow180Rotation(false);
2409                    return getCurrentLandscapeRotation(lastRotation);
2410                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
2411                    mOrientationListener.setAllow180Rotation(true);
2412                    return getCurrentPortraitRotation(lastRotation);
2413            }
2414
2415            mOrientationListener.setAllow180Rotation(mAllowAllRotations ||
2416                    orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
2417
2418            // case for nosensor meaning ignore sensor and consider only lid
2419            // or orientation sensor disabled
2420            //or case.unspecified
2421            if (mLidOpen) {
2422                return mLidOpenRotation;
2423            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
2424                return mCarDockRotation;
2425            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
2426                return mDeskDockRotation;
2427            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
2428                return mUserRotation;
2429            } else {
2430                if (useSensorForOrientationLp(orientation)) {
2431                    return mOrientationListener.getCurrentRotation(lastRotation);
2432                }
2433                return Surface.ROTATION_0;
2434            }
2435        }
2436    }
2437
2438    private int getCurrentLandscapeRotation(int lastRotation) {
2439        int sensorRotation = mOrientationListener.getCurrentRotation(lastRotation);
2440        if (isLandscapeOrSeascape(sensorRotation)) {
2441            return sensorRotation;
2442        }
2443        // try to preserve the old rotation if it was landscape
2444        if (isLandscapeOrSeascape(lastRotation)) {
2445            return lastRotation;
2446        }
2447        // default to one of the primary landscape rotation
2448        return mLandscapeRotation;
2449    }
2450
2451    private boolean isLandscapeOrSeascape(int sensorRotation) {
2452        return sensorRotation == mLandscapeRotation || sensorRotation == mSeascapeRotation;
2453    }
2454
2455    private int getCurrentPortraitRotation(int lastRotation) {
2456        int sensorRotation = mOrientationListener.getCurrentRotation(lastRotation);
2457        if (isAnyPortrait(sensorRotation)) {
2458            return sensorRotation;
2459        }
2460        // try to preserve the old rotation if it was portrait
2461        if (isAnyPortrait(lastRotation)) {
2462            return lastRotation;
2463        }
2464        // default to one of the primary portrait rotations
2465        return mPortraitRotation;
2466    }
2467
2468    private boolean isAnyPortrait(int sensorRotation) {
2469        return sensorRotation == mPortraitRotation || sensorRotation == mUpsideDownRotation;
2470    }
2471
2472
2473    // User rotation: to be used when all else fails in assigning an orientation to the device
2474    public void setUserRotationMode(int mode, int rot) {
2475        ContentResolver res = mContext.getContentResolver();
2476        mUserRotationMode = mode;
2477        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
2478            mUserRotation = rot;
2479            Settings.System.putInt(res,
2480                    Settings.System.ACCELEROMETER_ROTATION,
2481                    0);
2482            Settings.System.putInt(res,
2483                    Settings.System.USER_ROTATION,
2484                    rot);
2485        } else {
2486            Settings.System.putInt(res,
2487                    Settings.System.ACCELEROMETER_ROTATION,
2488                    1);
2489        }
2490    }
2491
2492    public boolean detectSafeMode() {
2493        try {
2494            int menuState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_MENU);
2495            int sState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_S);
2496            int dpadState = mWindowManager.getDPadKeycodeState(KeyEvent.KEYCODE_DPAD_CENTER);
2497            int trackballState = mWindowManager.getTrackballScancodeState(BTN_MOUSE);
2498            mSafeMode = menuState > 0 || sState > 0 || dpadState > 0 || trackballState > 0;
2499            performHapticFeedbackLw(null, mSafeMode
2500                    ? HapticFeedbackConstants.SAFE_MODE_ENABLED
2501                    : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
2502            if (mSafeMode) {
2503                Log.i(TAG, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
2504                        + " dpad=" + dpadState + " trackball=" + trackballState + ")");
2505            } else {
2506                Log.i(TAG, "SAFE MODE not enabled");
2507            }
2508            return mSafeMode;
2509        } catch (RemoteException e) {
2510            // Doom! (it's also local)
2511            throw new RuntimeException("window manager dead");
2512        }
2513    }
2514
2515    static long[] getLongIntArray(Resources r, int resid) {
2516        int[] ar = r.getIntArray(resid);
2517        if (ar == null) {
2518            return null;
2519        }
2520        long[] out = new long[ar.length];
2521        for (int i=0; i<ar.length; i++) {
2522            out[i] = ar[i];
2523        }
2524        return out;
2525    }
2526
2527    /** {@inheritDoc} */
2528    public void systemReady() {
2529        // tell the keyguard
2530        mKeyguardMediator.onSystemReady();
2531        android.os.SystemProperties.set("dev.bootcomplete", "1");
2532        synchronized (mLock) {
2533            updateOrientationListenerLp();
2534            mSystemReady = true;
2535            mHandler.post(new Runnable() {
2536                public void run() {
2537                    updateSettings();
2538                }
2539            });
2540        }
2541    }
2542
2543    /** {@inheritDoc} */
2544    public void userActivity() {
2545        synchronized (mScreenLockTimeout) {
2546            if (mLockScreenTimerActive) {
2547                // reset the timer
2548                mHandler.removeCallbacks(mScreenLockTimeout);
2549                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
2550            }
2551        }
2552    }
2553
2554    Runnable mScreenLockTimeout = new Runnable() {
2555        public void run() {
2556            synchronized (this) {
2557                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
2558                mKeyguardMediator.doKeyguardTimeout();
2559                mLockScreenTimerActive = false;
2560            }
2561        }
2562    };
2563
2564    private void updateLockScreenTimeout() {
2565        synchronized (mScreenLockTimeout) {
2566            boolean enable = (mAllowLockscreenWhenOn && mScreenOn && mKeyguardMediator.isSecure());
2567            if (mLockScreenTimerActive != enable) {
2568                if (enable) {
2569                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
2570                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
2571                } else {
2572                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
2573                    mHandler.removeCallbacks(mScreenLockTimeout);
2574                }
2575                mLockScreenTimerActive = enable;
2576            }
2577        }
2578    }
2579
2580    /** {@inheritDoc} */
2581    public void enableScreenAfterBoot() {
2582        readLidState();
2583        updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
2584    }
2585
2586    void updateRotation(int animFlags) {
2587        mPowerManager.setKeyboardVisibility(mLidOpen);
2588        int rotation = Surface.ROTATION_0;
2589        if (mLidOpen) {
2590            rotation = mLidOpenRotation;
2591        } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
2592            rotation = mCarDockRotation;
2593        } else if (mDockMode == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
2594            rotation = mDeskDockRotation;
2595        }
2596        //if lid is closed orientation will be portrait
2597        try {
2598            //set orientation on WindowManager
2599            mWindowManager.setRotation(rotation, true,
2600                    mFancyRotationAnimation | animFlags);
2601        } catch (RemoteException e) {
2602            // Ignore
2603        }
2604    }
2605
2606    /**
2607     * Return an Intent to launch the currently active dock as home.  Returns
2608     * null if the standard home should be launched.
2609     * @return
2610     */
2611    Intent createHomeDockIntent() {
2612        Intent intent;
2613
2614        // What home does is based on the mode, not the dock state.  That
2615        // is, when in car mode you should be taken to car home regardless
2616        // of whether we are actually in a car dock.
2617        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
2618            intent = mCarDockIntent;
2619        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
2620            intent = mDeskDockIntent;
2621        } else {
2622            return null;
2623        }
2624
2625        ActivityInfo ai = intent.resolveActivityInfo(
2626                mContext.getPackageManager(), PackageManager.GET_META_DATA);
2627        if (ai == null) {
2628            return null;
2629        }
2630
2631        if (ai.metaData != null && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
2632            intent = new Intent(intent);
2633            intent.setClassName(ai.packageName, ai.name);
2634            return intent;
2635        }
2636
2637        return null;
2638    }
2639
2640    void startDockOrHome() {
2641        Intent dock = createHomeDockIntent();
2642        if (dock != null) {
2643            try {
2644                mContext.startActivity(dock);
2645                return;
2646            } catch (ActivityNotFoundException e) {
2647            }
2648        }
2649        mContext.startActivity(mHomeIntent);
2650    }
2651
2652    /**
2653     * goes to the home screen
2654     * @return whether it did anything
2655     */
2656    boolean goHome() {
2657        if (false) {
2658            // This code always brings home to the front.
2659            try {
2660                ActivityManagerNative.getDefault().stopAppSwitches();
2661            } catch (RemoteException e) {
2662            }
2663            sendCloseSystemWindows();
2664            startDockOrHome();
2665        } else {
2666            // This code brings home to the front or, if it is already
2667            // at the front, puts the device to sleep.
2668            try {
2669                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
2670                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
2671                    Log.d(TAG, "UTS-TEST-MODE");
2672                } else {
2673                    ActivityManagerNative.getDefault().stopAppSwitches();
2674                    sendCloseSystemWindows();
2675                    Intent dock = createHomeDockIntent();
2676                    if (dock != null) {
2677                        int result = ActivityManagerNative.getDefault()
2678                                .startActivity(null, dock,
2679                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
2680                                        null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
2681                        if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
2682                            return false;
2683                        }
2684                    }
2685                }
2686                int result = ActivityManagerNative.getDefault()
2687                        .startActivity(null, mHomeIntent,
2688                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
2689                                null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
2690                if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
2691                    return false;
2692                }
2693            } catch (RemoteException ex) {
2694                // bummer, the activity manager, which is in this process, is dead
2695            }
2696        }
2697        return true;
2698    }
2699
2700    public void setCurrentOrientationLw(int newOrientation) {
2701        synchronized (mLock) {
2702            if (newOrientation != mCurrentAppOrientation) {
2703                mCurrentAppOrientation = newOrientation;
2704                updateOrientationListenerLp();
2705            }
2706        }
2707    }
2708
2709    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
2710        final boolean hapticsDisabled = Settings.System.getInt(mContext.getContentResolver(),
2711                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 0;
2712        if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
2713            return false;
2714        }
2715        long[] pattern = null;
2716        switch (effectId) {
2717            case HapticFeedbackConstants.LONG_PRESS:
2718                pattern = mLongPressVibePattern;
2719                break;
2720            case HapticFeedbackConstants.VIRTUAL_KEY:
2721                pattern = mVirtualKeyVibePattern;
2722                break;
2723            case HapticFeedbackConstants.KEYBOARD_TAP:
2724                pattern = mKeyboardTapVibePattern;
2725                break;
2726            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
2727                pattern = mSafeModeDisabledVibePattern;
2728                break;
2729            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
2730                pattern = mSafeModeEnabledVibePattern;
2731                break;
2732            default:
2733                return false;
2734        }
2735        if (pattern.length == 1) {
2736            // One-shot vibration
2737            mVibrator.vibrate(pattern[0]);
2738        } else {
2739            // Pattern vibration
2740            mVibrator.vibrate(pattern, -1);
2741        }
2742        return true;
2743    }
2744
2745    public void screenOnStoppedLw() {
2746        if (!mKeyguardMediator.isShowingAndNotHidden() && mPowerManager.isScreenOn()) {
2747            long curTime = SystemClock.uptimeMillis();
2748            mPowerManager.userActivity(curTime, false, LocalPowerManager.OTHER_EVENT);
2749        }
2750    }
2751
2752    public boolean allowKeyRepeat() {
2753        // disable key repeat when screen is off
2754        return mScreenOn;
2755    }
2756}
2757