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