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