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