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