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