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