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