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