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