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