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