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