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