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