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