PhoneWindowManager.java revision c1fb48d77ce2db2ca3af1dd2eeb91dc1b0f81b46
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, so intercept those here
1348        if (mShortcutKeyPressed != -1 && !mConsumeShortcutKeyUp) {
1349            if (down && repeatCount == 0 && !keyguardOn) {
1350                final KeyCharacterMap kcm = event.getKeyCharacterMap();
1351                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
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            // Invoke shortcuts using Meta as a fallback.
1386            final KeyCharacterMap kcm = event.getKeyCharacterMap();
1387            final int keyCode = event.getKeyCode();
1388            final int metaState = event.getMetaState();
1389            if ((metaState & KeyEvent.META_META_ON) != 0) {
1390                Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
1391                        metaState & ~(KeyEvent.META_META_ON
1392                                | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
1393                if (shortcutIntent != null) {
1394                    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1395                    mContext.startActivity(shortcutIntent);
1396                    return null;
1397                }
1398            }
1399
1400            // Check for fallback actions.
1401            if (kcm.getFallbackAction(keyCode, metaState, mFallbackAction)) {
1402                if (DEBUG_FALLBACK) {
1403                    Slog.d(TAG, "Fallback: keyCode=" + mFallbackAction.keyCode
1404                            + " metaState=" + Integer.toHexString(mFallbackAction.metaState));
1405                }
1406
1407                int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
1408                KeyEvent fallbackEvent = KeyEvent.obtain(
1409                        event.getDownTime(), event.getEventTime(),
1410                        event.getAction(), mFallbackAction.keyCode,
1411                        event.getRepeatCount(), mFallbackAction.metaState,
1412                        event.getDeviceId(), event.getScanCode(),
1413                        flags, event.getSource(), null);
1414                int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags, true);
1415                if ((actions & ACTION_PASS_TO_USER) != 0) {
1416                    if (!interceptKeyBeforeDispatching(win, fallbackEvent, policyFlags)) {
1417                        if (DEBUG_FALLBACK) {
1418                            Slog.d(TAG, "Performing fallback.");
1419                        }
1420                        return fallbackEvent;
1421                    }
1422                }
1423                fallbackEvent.recycle();
1424            }
1425        }
1426
1427        if (DEBUG_FALLBACK) {
1428            Slog.d(TAG, "No fallback.");
1429        }
1430        return null;
1431    }
1432
1433    /**
1434     * A home key -> launch home action was detected.  Take the appropriate action
1435     * given the situation with the keyguard.
1436     */
1437    void launchHomeFromHotKey() {
1438        if (mKeyguardMediator.isShowingAndNotHidden()) {
1439            // don't launch home if keyguard showing
1440        } else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) {
1441            // when in keyguard restricted mode, must first verify unlock
1442            // before launching home
1443            mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() {
1444                public void onKeyguardExitResult(boolean success) {
1445                    if (success) {
1446                        try {
1447                            ActivityManagerNative.getDefault().stopAppSwitches();
1448                        } catch (RemoteException e) {
1449                        }
1450                        sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
1451                        startDockOrHome();
1452                    }
1453                }
1454            });
1455        } else {
1456            // no keyguard stuff to worry about, just launch home!
1457            try {
1458                ActivityManagerNative.getDefault().stopAppSwitches();
1459            } catch (RemoteException e) {
1460            }
1461            sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
1462            startDockOrHome();
1463        }
1464    }
1465
1466    public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
1467        final int fl = attrs.flags;
1468
1469        if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
1470                == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
1471            contentInset.set(mCurLeft, mCurTop,
1472                    (mRestrictedScreenLeft+mRestrictedScreenWidth) - mCurRight,
1473                    (mRestrictedScreenTop+mRestrictedScreenHeight) - mCurBottom);
1474        } else {
1475            contentInset.setEmpty();
1476        }
1477    }
1478
1479    /** {@inheritDoc} */
1480    public void beginLayoutLw(int displayWidth, int displayHeight) {
1481        mUnrestrictedScreenLeft = mUnrestrictedScreenTop = 0;
1482        mUnrestrictedScreenWidth = displayWidth;
1483        mUnrestrictedScreenHeight = displayHeight;
1484        mRestrictedScreenLeft = mRestrictedScreenTop = 0;
1485        mRestrictedScreenWidth = displayWidth;
1486        mRestrictedScreenHeight = displayHeight;
1487        mDockLeft = mContentLeft = mCurLeft = 0;
1488        mDockTop = mContentTop = mCurTop = 0;
1489        mDockRight = mContentRight = mCurRight = displayWidth;
1490        mDockBottom = mContentBottom = mCurBottom = displayHeight;
1491        mDockLayer = 0x10000000;
1492
1493        // decide where the status bar goes ahead of time
1494        if (mStatusBar != null) {
1495            final Rect pf = mTmpParentFrame;
1496            final Rect df = mTmpDisplayFrame;
1497            final Rect vf = mTmpVisibleFrame;
1498            pf.left = df.left = vf.left = 0;
1499            pf.top = df.top = vf.top = 0;
1500            pf.right = df.right = vf.right = displayWidth;
1501            pf.bottom = df.bottom = vf.bottom = displayHeight;
1502
1503            mStatusBar.computeFrameLw(pf, df, vf, vf);
1504            if (mStatusBar.isVisibleLw()) {
1505                // If the status bar is hidden, we don't want to cause
1506                // windows behind it to scroll.
1507                final Rect r = mStatusBar.getFrameLw();
1508                if (mStatusBarCanHide) {
1509                    // Status bar may go away, so the screen area it occupies
1510                    // is available to apps but just covering them when the
1511                    // status bar is visible.
1512                    if (mDockTop == r.top) mDockTop = r.bottom;
1513                    else if (mDockBottom == r.bottom) mDockBottom = r.top;
1514                    mContentTop = mCurTop = mDockTop;
1515                    mContentBottom = mCurBottom = mDockBottom;
1516                    if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: mDockTop=" + mDockTop
1517                            + " mContentTop=" + mContentTop
1518                            + " mCurTop=" + mCurTop
1519                            + " mDockBottom=" + mDockBottom
1520                            + " mContentBottom=" + mContentBottom
1521                            + " mCurBottom=" + mCurBottom);
1522                } else {
1523                    // Status bar can't go away; the part of the screen it
1524                    // covers does not exist for anything behind it.
1525                    if (mRestrictedScreenTop == r.top) {
1526                        mRestrictedScreenTop = r.bottom;
1527                        mRestrictedScreenHeight -= (r.bottom-r.top);
1528                    } else if ((mRestrictedScreenHeight-mRestrictedScreenTop) == r.bottom) {
1529                        mRestrictedScreenHeight -= (r.bottom-r.top);
1530                    }
1531                    mContentTop = mCurTop = mDockTop = mRestrictedScreenTop;
1532                    mContentBottom = mCurBottom = mDockBottom
1533                            = mRestrictedScreenTop + mRestrictedScreenHeight;
1534                    if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: mRestrictedScreenTop="
1535                            + mRestrictedScreenTop
1536                            + " mRestrictedScreenHeight=" + mRestrictedScreenHeight);
1537                }
1538            }
1539        }
1540    }
1541
1542    void setAttachedWindowFrames(WindowState win, int fl, int adjust,
1543            WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) {
1544        if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
1545            // Here's a special case: if this attached window is a panel that is
1546            // above the dock window, and the window it is attached to is below
1547            // the dock window, then the frames we computed for the window it is
1548            // attached to can not be used because the dock is effectively part
1549            // of the underlying window and the attached window is floating on top
1550            // of the whole thing.  So, we ignore the attached window and explicitly
1551            // compute the frames that would be appropriate without the dock.
1552            df.left = cf.left = vf.left = mDockLeft;
1553            df.top = cf.top = vf.top = mDockTop;
1554            df.right = cf.right = vf.right = mDockRight;
1555            df.bottom = cf.bottom = vf.bottom = mDockBottom;
1556        } else {
1557            // The effective display frame of the attached window depends on
1558            // whether it is taking care of insetting its content.  If not,
1559            // we need to use the parent's content frame so that the entire
1560            // window is positioned within that content.  Otherwise we can use
1561            // the display frame and let the attached window take care of
1562            // positioning its content appropriately.
1563            if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
1564                cf.set(attached.getDisplayFrameLw());
1565            } else {
1566                // If the window is resizing, then we want to base the content
1567                // frame on our attached content frame to resize...  however,
1568                // things can be tricky if the attached window is NOT in resize
1569                // mode, in which case its content frame will be larger.
1570                // Ungh.  So to deal with that, make sure the content frame
1571                // we end up using is not covering the IM dock.
1572                cf.set(attached.getContentFrameLw());
1573                if (attached.getSurfaceLayer() < mDockLayer) {
1574                    if (cf.left < mContentLeft) cf.left = mContentLeft;
1575                    if (cf.top < mContentTop) cf.top = mContentTop;
1576                    if (cf.right > mContentRight) cf.right = mContentRight;
1577                    if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
1578                }
1579            }
1580            df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
1581            vf.set(attached.getVisibleFrameLw());
1582        }
1583        // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
1584        // window should be positioned relative to its parent or the entire
1585        // screen.
1586        pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
1587                ? attached.getFrameLw() : df);
1588    }
1589
1590    /** {@inheritDoc} */
1591    public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
1592            WindowState attached) {
1593        // we've already done the status bar
1594        if (win == mStatusBar) {
1595            return;
1596        }
1597
1598        final int fl = attrs.flags;
1599        final int sim = attrs.softInputMode;
1600
1601        final Rect pf = mTmpParentFrame;
1602        final Rect df = mTmpDisplayFrame;
1603        final Rect cf = mTmpContentFrame;
1604        final Rect vf = mTmpVisibleFrame;
1605
1606        if (attrs.type == TYPE_INPUT_METHOD) {
1607            pf.left = df.left = cf.left = vf.left = mDockLeft;
1608            pf.top = df.top = cf.top = vf.top = mDockTop;
1609            pf.right = df.right = cf.right = vf.right = mDockRight;
1610            pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom;
1611            // IM dock windows always go to the bottom of the screen.
1612            attrs.gravity = Gravity.BOTTOM;
1613            mDockLayer = win.getSurfaceLayer();
1614        } else {
1615            final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
1616
1617            if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
1618                    == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
1619                // This is the case for a normal activity window: we want it
1620                // to cover all of the screen space, and it can take care of
1621                // moving its contents to account for screen decorations that
1622                // intrude into that space.
1623                if (attached != null) {
1624                    // If this window is attached to another, our display
1625                    // frame is the same as the one we are attached to.
1626                    setAttachedWindowFrames(win, fl, sim, attached, true, pf, df, cf, vf);
1627                } else {
1628                    if (attrs.type == TYPE_STATUS_BAR_PANEL) {
1629                        // Status bar panels are the only windows who can go on top of
1630                        // the status bar.  They are protected by the STATUS_BAR_SERVICE
1631                        // permission, so they have the same privileges as the status
1632                        // bar itself.
1633                        pf.left = df.left = mUnrestrictedScreenLeft;
1634                        pf.top = df.top = mUnrestrictedScreenTop;
1635                        pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
1636                        pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
1637                    } else {
1638                        pf.left = df.left = mRestrictedScreenLeft;
1639                        pf.top = df.top = mRestrictedScreenTop;
1640                        pf.right = df.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
1641                        pf.bottom = df.bottom = mRestrictedScreenTop+mRestrictedScreenHeight;
1642                    }
1643                    if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
1644                        cf.left = mDockLeft;
1645                        cf.top = mDockTop;
1646                        cf.right = mDockRight;
1647                        cf.bottom = mDockBottom;
1648                    } else {
1649                        cf.left = mContentLeft;
1650                        cf.top = mContentTop;
1651                        cf.right = mContentRight;
1652                        cf.bottom = mContentBottom;
1653                    }
1654                    if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
1655                        vf.left = mCurLeft;
1656                        vf.top = mCurTop;
1657                        vf.right = mCurRight;
1658                        vf.bottom = mCurBottom;
1659                    } else {
1660                        vf.set(cf);
1661                    }
1662                }
1663            } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0) {
1664                // A window that has requested to fill the entire screen just
1665                // gets everything, period.
1666                if (attrs.type == TYPE_STATUS_BAR_PANEL) {
1667                    pf.left = df.left = cf.left = mUnrestrictedScreenLeft;
1668                    pf.top = df.top = cf.top = mUnrestrictedScreenTop;
1669                    pf.right = df.right = cf.right
1670                            = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
1671                    pf.bottom = df.bottom = cf.bottom
1672                            = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
1673                } else {
1674                    pf.left = df.left = cf.left = mRestrictedScreenLeft;
1675                    pf.top = df.top = cf.top = mRestrictedScreenTop;
1676                    pf.right = df.right = cf.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
1677                    pf.bottom = df.bottom = cf.bottom
1678                            = mRestrictedScreenTop+mRestrictedScreenHeight;
1679                }
1680                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
1681                    vf.left = mCurLeft;
1682                    vf.top = mCurTop;
1683                    vf.right = mCurRight;
1684                    vf.bottom = mCurBottom;
1685                } else {
1686                    vf.set(cf);
1687                }
1688            } else if (attached != null) {
1689                // A child window should be placed inside of the same visible
1690                // frame that its parent had.
1691                setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, cf, vf);
1692            } else {
1693                // Otherwise, a normal window must be placed inside the content
1694                // of all screen decorations.
1695                pf.left = mContentLeft;
1696                pf.top = mContentTop;
1697                pf.right = mContentRight;
1698                pf.bottom = mContentBottom;
1699                if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
1700                    df.left = cf.left = mDockLeft;
1701                    df.top = cf.top = mDockTop;
1702                    df.right = cf.right = mDockRight;
1703                    df.bottom = cf.bottom = mDockBottom;
1704                } else {
1705                    df.left = cf.left = mContentLeft;
1706                    df.top = cf.top = mContentTop;
1707                    df.right = cf.right = mContentRight;
1708                    df.bottom = cf.bottom = mContentBottom;
1709                }
1710                if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
1711                    vf.left = mCurLeft;
1712                    vf.top = mCurTop;
1713                    vf.right = mCurRight;
1714                    vf.bottom = mCurBottom;
1715                } else {
1716                    vf.set(cf);
1717                }
1718            }
1719        }
1720
1721        if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
1722            df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000;
1723            df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
1724        }
1725
1726        if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
1727                + ": sim=#" + Integer.toHexString(sim)
1728                + " pf=" + pf.toShortString() + " df=" + df.toShortString()
1729                + " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
1730
1731        win.computeFrameLw(pf, df, cf, vf);
1732
1733        // Dock windows carve out the bottom of the screen, so normal windows
1734        // can't appear underneath them.
1735        if (attrs.type == TYPE_INPUT_METHOD && !win.getGivenInsetsPendingLw()) {
1736            int top = win.getContentFrameLw().top;
1737            top += win.getGivenContentInsetsLw().top;
1738            if (mContentBottom > top) {
1739                mContentBottom = top;
1740            }
1741            top = win.getVisibleFrameLw().top;
1742            top += win.getGivenVisibleInsetsLw().top;
1743            if (mCurBottom > top) {
1744                mCurBottom = top;
1745            }
1746            if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
1747                    + mDockBottom + " mContentBottom="
1748                    + mContentBottom + " mCurBottom=" + mCurBottom);
1749        }
1750    }
1751
1752    /** {@inheritDoc} */
1753    public int finishLayoutLw() {
1754        return 0;
1755    }
1756
1757    /** {@inheritDoc} */
1758    public void beginAnimationLw(int displayWidth, int displayHeight) {
1759        mTopFullscreenOpaqueWindowState = null;
1760        mForceStatusBar = false;
1761
1762        mHideLockScreen = false;
1763        mAllowLockscreenWhenOn = false;
1764        mDismissKeyguard = false;
1765    }
1766
1767    /** {@inheritDoc} */
1768    public void animatingWindowLw(WindowState win,
1769                                WindowManager.LayoutParams attrs) {
1770        if (mTopFullscreenOpaqueWindowState == null &&
1771                win.isVisibleOrBehindKeyguardLw()) {
1772            if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
1773                mForceStatusBar = true;
1774            }
1775            if (attrs.type >= FIRST_APPLICATION_WINDOW
1776                    && attrs.type <= LAST_APPLICATION_WINDOW
1777                    && attrs.x == 0 && attrs.y == 0
1778                    && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
1779                    && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
1780                if (DEBUG_LAYOUT) Log.v(TAG, "Fullscreen window: " + win);
1781                mTopFullscreenOpaqueWindowState = win;
1782                if ((attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0) {
1783                    if (localLOGV) Log.v(TAG, "Setting mHideLockScreen to true by win " + win);
1784                    mHideLockScreen = true;
1785                }
1786                if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0) {
1787                    if (localLOGV) Log.v(TAG, "Setting mDismissKeyguard to true by win " + win);
1788                    mDismissKeyguard = true;
1789                }
1790                if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
1791                    mAllowLockscreenWhenOn = true;
1792                }
1793            }
1794        }
1795    }
1796
1797    /** {@inheritDoc} */
1798    public int finishAnimationLw() {
1799        int changes = 0;
1800        boolean topIsFullscreen = false;
1801
1802        final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
1803                ? mTopFullscreenOpaqueWindowState.getAttrs()
1804                : null;
1805
1806        if (mStatusBar != null) {
1807            if (localLOGV) Log.i(TAG, "force=" + mForceStatusBar
1808                    + " top=" + mTopFullscreenOpaqueWindowState);
1809            if (mForceStatusBar) {
1810                if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
1811                if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
1812            } else if (mTopFullscreenOpaqueWindowState != null) {
1813                if (localLOGV) {
1814                    Log.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
1815                            + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
1816                    Log.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
1817                            + " lp.flags=0x" + Integer.toHexString(lp.flags));
1818                }
1819                topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
1820                // The subtle difference between the window for mTopFullscreenOpaqueWindowState
1821                // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window
1822                // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
1823                // case though.
1824                if (topIsFullscreen) {
1825                    if (mStatusBarCanHide) {
1826                        if (DEBUG_LAYOUT) Log.v(TAG, "Hiding status bar");
1827                        if (mStatusBar.hideLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
1828                    } else if (localLOGV) {
1829                        Log.v(TAG, "Preventing status bar from hiding by policy");
1830                    }
1831                } else {
1832                    if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar");
1833                    if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
1834                }
1835            }
1836        }
1837
1838        boolean topNeedsMenu = mShowMenuKey;
1839        if (lp != null) {
1840            topNeedsMenu = (lp.flags & WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY) != 0;
1841        }
1842
1843        if (DEBUG_LAYOUT) Log.v(TAG, "Top window "
1844                + (topNeedsMenu ? "needs" : "does not need")
1845                + " the MENU key");
1846
1847        final boolean changedFullscreen = (mTopIsFullscreen != topIsFullscreen);
1848        final boolean changedMenu = (topNeedsMenu != mShowMenuKey);
1849
1850        if (changedFullscreen || changedMenu) {
1851            final boolean topIsFullscreenF = topIsFullscreen;
1852            final boolean topNeedsMenuF = topNeedsMenu;
1853
1854            mTopIsFullscreen = topIsFullscreen;
1855            mShowMenuKey = topNeedsMenu;
1856
1857            mHandler.post(new Runnable() {
1858                    public void run() {
1859                        if (mStatusBarService == null) {
1860                            // This is the one that can not go away, but it doesn't come up
1861                            // before the window manager does, so don't fail if it doesn't
1862                            // exist. This works as long as no fullscreen windows come up
1863                            // before the status bar service does.
1864                            mStatusBarService = IStatusBarService.Stub.asInterface(
1865                                    ServiceManager.getService("statusbar"));
1866                        }
1867                        final IStatusBarService sbs = mStatusBarService;
1868                        if (mStatusBarService != null) {
1869                            try {
1870                                if (changedMenu) {
1871                                    sbs.setMenuKeyVisible(topNeedsMenuF);
1872                                }
1873                                if (changedFullscreen) {
1874                                    sbs.setActiveWindowIsFullscreen(topIsFullscreenF);
1875                                }
1876                            } catch (RemoteException e) {
1877                                // This should be impossible because we're in the same process.
1878                                mStatusBarService = null;
1879                            }
1880                        }
1881                    }
1882                });
1883        }
1884
1885        // Hide the key guard if a visible window explicitly specifies that it wants to be displayed
1886        // when the screen is locked
1887        if (mKeyguard != null) {
1888            if (localLOGV) Log.v(TAG, "finishAnimationLw::mHideKeyguard="+mHideLockScreen);
1889            if (mDismissKeyguard && !mKeyguardMediator.isSecure()) {
1890                if (mKeyguard.hideLw(true)) {
1891                    changes |= FINISH_LAYOUT_REDO_LAYOUT
1892                            | FINISH_LAYOUT_REDO_CONFIG
1893                            | FINISH_LAYOUT_REDO_WALLPAPER;
1894                }
1895                if (mKeyguardMediator.isShowing()) {
1896                    mHandler.post(new Runnable() {
1897                        public void run() {
1898                            mKeyguardMediator.keyguardDone(false, false);
1899                        }
1900                    });
1901                }
1902            } else if (mHideLockScreen) {
1903                if (mKeyguard.hideLw(true)) {
1904                    changes |= FINISH_LAYOUT_REDO_LAYOUT
1905                            | FINISH_LAYOUT_REDO_CONFIG
1906                            | FINISH_LAYOUT_REDO_WALLPAPER;
1907                }
1908                mKeyguardMediator.setHidden(true);
1909            } else {
1910                if (mKeyguard.showLw(true)) {
1911                    changes |= FINISH_LAYOUT_REDO_LAYOUT
1912                            | FINISH_LAYOUT_REDO_CONFIG
1913                            | FINISH_LAYOUT_REDO_WALLPAPER;
1914                }
1915                mKeyguardMediator.setHidden(false);
1916            }
1917        }
1918
1919        // update since mAllowLockscreenWhenOn might have changed
1920        updateLockScreenTimeout();
1921        return changes;
1922    }
1923
1924    public boolean allowAppAnimationsLw() {
1925        if (mKeyguard != null && mKeyguard.isVisibleLw()) {
1926            // If keyguard is currently visible, no reason to animate
1927            // behind it.
1928            return false;
1929        }
1930        if (mStatusBar != null && mStatusBar.isVisibleLw()) {
1931            Rect rect = new Rect(mStatusBar.getShownFrameLw());
1932            for (int i=mStatusBarPanels.size()-1; i>=0; i--) {
1933                WindowState w = mStatusBarPanels.get(i);
1934                if (w.isVisibleLw()) {
1935                    rect.union(w.getShownFrameLw());
1936                }
1937            }
1938            final int insetw = mRestrictedScreenWidth/10;
1939            final int inseth = mRestrictedScreenHeight/10;
1940            if (rect.contains(insetw, inseth, mRestrictedScreenWidth-insetw,
1941                        mRestrictedScreenHeight-inseth)) {
1942                // All of the status bar windows put together cover the
1943                // screen, so the app can't be seen.  (Note this test doesn't
1944                // work if the rects of these windows are at off offsets or
1945                // sizes, causing gaps in the rect union we have computed.)
1946                return false;
1947            }
1948        }
1949        return true;
1950    }
1951
1952    /** {@inheritDoc} */
1953    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
1954        // lid changed state
1955        mLidOpen = lidOpen;
1956        boolean awakeNow = mKeyguardMediator.doLidChangeTq(mLidOpen);
1957        updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
1958        if (awakeNow) {
1959            // If the lid opening and we don't have to keep the
1960            // keyguard up, then we can turn on the screen
1961            // immediately.
1962            mKeyguardMediator.pokeWakelock();
1963        } else if (keyguardIsShowingTq()) {
1964            if (mLidOpen) {
1965                // If we are opening the lid and not hiding the
1966                // keyguard, then we need to have it turn on the
1967                // screen once it is shown.
1968                mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(
1969                        KeyEvent.KEYCODE_POWER);
1970            }
1971        } else {
1972            // Light up the keyboard if we are sliding up.
1973            if (mLidOpen) {
1974                mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
1975                        LocalPowerManager.BUTTON_EVENT);
1976            } else {
1977                mPowerManager.userActivity(SystemClock.uptimeMillis(), false,
1978                        LocalPowerManager.OTHER_EVENT);
1979            }
1980        }
1981    }
1982
1983    /**
1984     * @return Whether music is being played right now.
1985     */
1986    boolean isMusicActive() {
1987        final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
1988        if (am == null) {
1989            Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
1990            return false;
1991        }
1992        return am.isMusicActive();
1993    }
1994
1995    /**
1996     * Tell the audio service to adjust the volume appropriate to the event.
1997     * @param keycode
1998     */
1999    void handleVolumeKey(int stream, int keycode) {
2000        IAudioService audioService = getAudioService();
2001        if (audioService == null) {
2002            return;
2003        }
2004        try {
2005            // since audio is playing, we shouldn't have to hold a wake lock
2006            // during the call, but we do it as a precaution for the rare possibility
2007            // that the music stops right before we call this
2008            // TODO: Actually handle MUTE.
2009            mBroadcastWakeLock.acquire();
2010            audioService.adjustStreamVolume(stream,
2011                keycode == KeyEvent.KEYCODE_VOLUME_UP
2012                            ? AudioManager.ADJUST_RAISE
2013                            : AudioManager.ADJUST_LOWER,
2014                    0);
2015        } catch (RemoteException e) {
2016            Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
2017        } finally {
2018            mBroadcastWakeLock.release();
2019        }
2020    }
2021
2022    /** {@inheritDoc} */
2023    @Override
2024    public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
2025        final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
2026        final boolean canceled = event.isCanceled();
2027        final int keyCode = event.getKeyCode();
2028
2029        final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
2030
2031        // If screen is off then we treat the case where the keyguard is open but hidden
2032        // the same as if it were open and in front.
2033        // This will prevent any keys other than the power button from waking the screen
2034        // when the keyguard is hidden by another activity.
2035        final boolean keyguardActive = (isScreenOn ?
2036                                        mKeyguardMediator.isShowingAndNotHidden() :
2037                                        mKeyguardMediator.isShowing());
2038
2039        if (false) {
2040            Log.d(TAG, "interceptKeyTq keycode=" + keyCode
2041                  + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive);
2042        }
2043
2044        if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0) {
2045            performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
2046        }
2047
2048        // Basic policy based on screen state and keyguard.
2049        // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
2050        //        is on or off, really.  We should care about whether the device is in an
2051        //        interactive state or is in suspend pretending to be "off".
2052        //        The primary screen might be turned off due to proximity sensor or
2053        //        because we are presenting media on an auxiliary screen or remotely controlling
2054        //        the device some other way (which is why we have an exemption here for injected
2055        //        events).
2056        int result;
2057        if (isScreenOn || isInjected) {
2058            // When the screen is on or if the key is injected pass the key to the application.
2059            result = ACTION_PASS_TO_USER;
2060        } else {
2061            // When the screen is off and the key is not injected, determine whether
2062            // to wake the device but don't pass the key to the application.
2063            result = 0;
2064
2065            final boolean isWakeKey = (policyFlags
2066                    & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
2067            if (down && isWakeKey) {
2068                if (keyguardActive) {
2069                    // If the keyguard is showing, let it decide what to do with the wake key.
2070                    mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode);
2071                } else {
2072                    // Otherwise, wake the device ourselves.
2073                    result |= ACTION_POKE_USER_ACTIVITY;
2074                }
2075            }
2076        }
2077
2078        // Handle special keys.
2079        switch (keyCode) {
2080            case KeyEvent.KEYCODE_VOLUME_DOWN:
2081            case KeyEvent.KEYCODE_VOLUME_UP:
2082            case KeyEvent.KEYCODE_VOLUME_MUTE: {
2083                if (down) {
2084                    ITelephony telephonyService = getTelephonyService();
2085                    if (telephonyService != null) {
2086                        try {
2087                            if (telephonyService.isRinging()) {
2088                                // If an incoming call is ringing, either VOLUME key means
2089                                // "silence ringer".  We handle these keys here, rather than
2090                                // in the InCallScreen, to make sure we'll respond to them
2091                                // even if the InCallScreen hasn't come to the foreground yet.
2092                                // Look for the DOWN event here, to agree with the "fallback"
2093                                // behavior in the InCallScreen.
2094                                Log.i(TAG, "interceptKeyBeforeQueueing:"
2095                                      + " VOLUME key-down while ringing: Silence ringer!");
2096
2097                                // Silence the ringer.  (It's safe to call this
2098                                // even if the ringer has already been silenced.)
2099                                telephonyService.silenceRinger();
2100
2101                                // And *don't* pass this key thru to the current activity
2102                                // (which is probably the InCallScreen.)
2103                                result &= ~ACTION_PASS_TO_USER;
2104                                break;
2105                            }
2106                            if (telephonyService.isOffhook()
2107                                    && (result & ACTION_PASS_TO_USER) == 0) {
2108                                // If we are in call but we decided not to pass the key to
2109                                // the application, handle the volume change here.
2110                                handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
2111                                break;
2112                            }
2113                        } catch (RemoteException ex) {
2114                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2115                        }
2116                    }
2117
2118                    if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
2119                        // If music is playing but we decided not to pass the key to the
2120                        // application, handle the volume change here.
2121                        handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
2122                        break;
2123                    }
2124                }
2125                break;
2126            }
2127
2128            case KeyEvent.KEYCODE_ENDCALL: {
2129                result &= ~ACTION_PASS_TO_USER;
2130                if (down) {
2131                    ITelephony telephonyService = getTelephonyService();
2132                    boolean hungUp = false;
2133                    if (telephonyService != null) {
2134                        try {
2135                            hungUp = telephonyService.endCall();
2136                        } catch (RemoteException ex) {
2137                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2138                        }
2139                    }
2140                    interceptPowerKeyDown(!isScreenOn || hungUp);
2141                } else {
2142                    if (interceptPowerKeyUp(canceled)) {
2143                        if ((mEndcallBehavior
2144                                & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
2145                            if (goHome()) {
2146                                break;
2147                            }
2148                        }
2149                        if ((mEndcallBehavior
2150                                & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
2151                            result = (result & ~ACTION_POKE_USER_ACTIVITY) | ACTION_GO_TO_SLEEP;
2152                        }
2153                    }
2154                }
2155                break;
2156            }
2157
2158            case KeyEvent.KEYCODE_POWER: {
2159                result &= ~ACTION_PASS_TO_USER;
2160                if (down) {
2161                    ITelephony telephonyService = getTelephonyService();
2162                    boolean hungUp = false;
2163                    if (telephonyService != null) {
2164                        try {
2165                            if (telephonyService.isRinging()) {
2166                                // Pressing Power while there's a ringing incoming
2167                                // call should silence the ringer.
2168                                telephonyService.silenceRinger();
2169                            } else if ((mIncallPowerBehavior
2170                                    & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
2171                                    && telephonyService.isOffhook()) {
2172                                // Otherwise, if "Power button ends call" is enabled,
2173                                // the Power button will hang up any current active call.
2174                                hungUp = telephonyService.endCall();
2175                            }
2176                        } catch (RemoteException ex) {
2177                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2178                        }
2179                    }
2180                    interceptPowerKeyDown(!isScreenOn || hungUp);
2181                } else {
2182                    if (interceptPowerKeyUp(canceled)) {
2183                        result = (result & ~ACTION_POKE_USER_ACTIVITY) | ACTION_GO_TO_SLEEP;
2184                    }
2185                }
2186                break;
2187            }
2188
2189            case KeyEvent.KEYCODE_MEDIA_PLAY:
2190            case KeyEvent.KEYCODE_MEDIA_PAUSE:
2191            case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
2192                if (down) {
2193                    ITelephony telephonyService = getTelephonyService();
2194                    if (telephonyService != null) {
2195                        try {
2196                            if (!telephonyService.isIdle()) {
2197                                // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
2198                                // to avoid music playback.
2199                                break;
2200                            }
2201                        } catch (RemoteException ex) {
2202                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2203                        }
2204                    }
2205                }
2206            case KeyEvent.KEYCODE_HEADSETHOOK:
2207            case KeyEvent.KEYCODE_MUTE:
2208            case KeyEvent.KEYCODE_MEDIA_STOP:
2209            case KeyEvent.KEYCODE_MEDIA_NEXT:
2210            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
2211            case KeyEvent.KEYCODE_MEDIA_REWIND:
2212            case KeyEvent.KEYCODE_MEDIA_RECORD:
2213            case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
2214                if ((result & ACTION_PASS_TO_USER) == 0) {
2215                    // Only do this if we would otherwise not pass it to the user. In that
2216                    // case, the PhoneWindow class will do the same thing, except it will
2217                    // only do it if the showing app doesn't process the key on its own.
2218                    mBroadcastWakeLock.acquire();
2219                    mHandler.post(new PassHeadsetKey(new KeyEvent(event)));
2220                }
2221                break;
2222            }
2223
2224            case KeyEvent.KEYCODE_CALL: {
2225                if (down) {
2226                    ITelephony telephonyService = getTelephonyService();
2227                    if (telephonyService != null) {
2228                        try {
2229                            if (telephonyService.isRinging()) {
2230                                Log.i(TAG, "interceptKeyBeforeQueueing:"
2231                                      + " CALL key-down while ringing: Answer the call!");
2232                                telephonyService.answerRingingCall();
2233
2234                                // And *don't* pass this key thru to the current activity
2235                                // (which is presumably the InCallScreen.)
2236                                result &= ~ACTION_PASS_TO_USER;
2237                            }
2238                        } catch (RemoteException ex) {
2239                            Log.w(TAG, "ITelephony threw RemoteException", ex);
2240                        }
2241                    }
2242                }
2243                break;
2244            }
2245        }
2246        return result;
2247    }
2248
2249    class PassHeadsetKey implements Runnable {
2250        KeyEvent mKeyEvent;
2251
2252        PassHeadsetKey(KeyEvent keyEvent) {
2253            mKeyEvent = keyEvent;
2254        }
2255
2256        public void run() {
2257            if (ActivityManagerNative.isSystemReady()) {
2258                Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
2259                intent.putExtra(Intent.EXTRA_KEY_EVENT, mKeyEvent);
2260                mContext.sendOrderedBroadcast(intent, null, mBroadcastDone,
2261                        mHandler, Activity.RESULT_OK, null, null);
2262            }
2263        }
2264    }
2265
2266    BroadcastReceiver mBroadcastDone = new BroadcastReceiver() {
2267        public void onReceive(Context context, Intent intent) {
2268            mBroadcastWakeLock.release();
2269        }
2270    };
2271
2272    BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
2273        public void onReceive(Context context, Intent intent) {
2274            if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
2275                mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
2276                        Intent.EXTRA_DOCK_STATE_UNDOCKED);
2277            } else {
2278                try {
2279                    IUiModeManager uiModeService = IUiModeManager.Stub.asInterface(
2280                            ServiceManager.getService(Context.UI_MODE_SERVICE));
2281                    mUiMode = uiModeService.getCurrentModeType();
2282                } catch (RemoteException e) {
2283                }
2284            }
2285            updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
2286            updateOrientationListenerLp();
2287        }
2288    };
2289
2290    /** {@inheritDoc} */
2291    public void screenTurnedOff(int why) {
2292        EventLog.writeEvent(70000, 0);
2293        mKeyguardMediator.onScreenTurnedOff(why);
2294        synchronized (mLock) {
2295            mScreenOn = false;
2296            updateOrientationListenerLp();
2297            updateLockScreenTimeout();
2298        }
2299    }
2300
2301    /** {@inheritDoc} */
2302    public void screenTurnedOn() {
2303        EventLog.writeEvent(70000, 1);
2304        mKeyguardMediator.onScreenTurnedOn();
2305        synchronized (mLock) {
2306            mScreenOn = true;
2307            updateOrientationListenerLp();
2308            updateLockScreenTimeout();
2309        }
2310    }
2311
2312    /** {@inheritDoc} */
2313    public boolean isScreenOn() {
2314        return mScreenOn;
2315    }
2316
2317    /** {@inheritDoc} */
2318    public void enableKeyguard(boolean enabled) {
2319        mKeyguardMediator.setKeyguardEnabled(enabled);
2320    }
2321
2322    /** {@inheritDoc} */
2323    public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
2324        mKeyguardMediator.verifyUnlock(callback);
2325    }
2326
2327    private boolean keyguardIsShowingTq() {
2328        return mKeyguardMediator.isShowingAndNotHidden();
2329    }
2330
2331    /** {@inheritDoc} */
2332    public boolean inKeyguardRestrictedKeyInputMode() {
2333        return mKeyguardMediator.isInputRestricted();
2334    }
2335
2336    void sendCloseSystemWindows() {
2337        sendCloseSystemWindows(mContext, null);
2338    }
2339
2340    void sendCloseSystemWindows(String reason) {
2341        sendCloseSystemWindows(mContext, reason);
2342    }
2343
2344    static void sendCloseSystemWindows(Context context, String reason) {
2345        if (ActivityManagerNative.isSystemReady()) {
2346            try {
2347                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
2348            } catch (RemoteException e) {
2349            }
2350        }
2351    }
2352
2353    public int rotationForOrientationLw(int orientation, int lastRotation,
2354            boolean displayEnabled) {
2355
2356        if (mPortraitRotation < 0) {
2357            // Initialize the rotation angles for each orientation once.
2358            Display d = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
2359                    .getDefaultDisplay();
2360            if (d.getWidth() > d.getHeight()) {
2361                mPortraitRotation = Surface.ROTATION_90;
2362                mLandscapeRotation = Surface.ROTATION_0;
2363                mUpsideDownRotation = Surface.ROTATION_270;
2364                mSeascapeRotation = Surface.ROTATION_180;
2365            } else {
2366                mPortraitRotation = Surface.ROTATION_0;
2367                mLandscapeRotation = Surface.ROTATION_90;
2368                mUpsideDownRotation = Surface.ROTATION_180;
2369                mSeascapeRotation = Surface.ROTATION_270;
2370            }
2371        }
2372
2373        synchronized (mLock) {
2374            switch (orientation) {
2375                case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
2376                    //always return portrait if orientation set to portrait
2377                    return mPortraitRotation;
2378                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
2379                    //always return landscape if orientation set to landscape
2380                    return mLandscapeRotation;
2381                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
2382                    //always return portrait if orientation set to portrait
2383                    return mUpsideDownRotation;
2384                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
2385                    //always return seascape if orientation set to reverse landscape
2386                    return mSeascapeRotation;
2387                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
2388                    //return either landscape rotation based on the sensor
2389                    mOrientationListener.setAllow180Rotation(false);
2390                    return getCurrentLandscapeRotation(lastRotation);
2391                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
2392                    mOrientationListener.setAllow180Rotation(true);
2393                    return getCurrentPortraitRotation(lastRotation);
2394            }
2395
2396            mOrientationListener.setAllow180Rotation(mAllowAllRotations ||
2397                    orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
2398
2399            // case for nosensor meaning ignore sensor and consider only lid
2400            // or orientation sensor disabled
2401            //or case.unspecified
2402            if (mLidOpen) {
2403                return mLidOpenRotation;
2404            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
2405                return mCarDockRotation;
2406            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
2407                return mDeskDockRotation;
2408            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
2409                return mUserRotation;
2410            } else {
2411                if (useSensorForOrientationLp(orientation)) {
2412                    return mOrientationListener.getCurrentRotation(lastRotation);
2413                }
2414                return Surface.ROTATION_0;
2415            }
2416        }
2417    }
2418
2419    private int getCurrentLandscapeRotation(int lastRotation) {
2420        int sensorRotation = mOrientationListener.getCurrentRotation(lastRotation);
2421        if (isLandscapeOrSeascape(sensorRotation)) {
2422            return sensorRotation;
2423        }
2424        // try to preserve the old rotation if it was landscape
2425        if (isLandscapeOrSeascape(lastRotation)) {
2426            return lastRotation;
2427        }
2428        // default to one of the primary landscape rotation
2429        return mLandscapeRotation;
2430    }
2431
2432    private boolean isLandscapeOrSeascape(int sensorRotation) {
2433        return sensorRotation == mLandscapeRotation || sensorRotation == mSeascapeRotation;
2434    }
2435
2436    private int getCurrentPortraitRotation(int lastRotation) {
2437        int sensorRotation = mOrientationListener.getCurrentRotation(lastRotation);
2438        if (isAnyPortrait(sensorRotation)) {
2439            return sensorRotation;
2440        }
2441        // try to preserve the old rotation if it was portrait
2442        if (isAnyPortrait(lastRotation)) {
2443            return lastRotation;
2444        }
2445        // default to one of the primary portrait rotations
2446        return mPortraitRotation;
2447    }
2448
2449    private boolean isAnyPortrait(int sensorRotation) {
2450        return sensorRotation == mPortraitRotation || sensorRotation == mUpsideDownRotation;
2451    }
2452
2453
2454    // User rotation: to be used when all else fails in assigning an orientation to the device
2455    public void setUserRotationMode(int mode, int rot) {
2456        ContentResolver res = mContext.getContentResolver();
2457        mUserRotationMode = mode;
2458        if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
2459            mUserRotation = rot;
2460            Settings.System.putInt(res,
2461                    Settings.System.ACCELEROMETER_ROTATION,
2462                    0);
2463            Settings.System.putInt(res,
2464                    Settings.System.USER_ROTATION,
2465                    rot);
2466        } else {
2467            Settings.System.putInt(res,
2468                    Settings.System.ACCELEROMETER_ROTATION,
2469                    1);
2470        }
2471    }
2472
2473    public boolean detectSafeMode() {
2474        try {
2475            int menuState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_MENU);
2476            int sState = mWindowManager.getKeycodeState(KeyEvent.KEYCODE_S);
2477            int dpadState = mWindowManager.getDPadKeycodeState(KeyEvent.KEYCODE_DPAD_CENTER);
2478            int trackballState = mWindowManager.getTrackballScancodeState(BTN_MOUSE);
2479            mSafeMode = menuState > 0 || sState > 0 || dpadState > 0 || trackballState > 0;
2480            performHapticFeedbackLw(null, mSafeMode
2481                    ? HapticFeedbackConstants.SAFE_MODE_ENABLED
2482                    : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
2483            if (mSafeMode) {
2484                Log.i(TAG, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
2485                        + " dpad=" + dpadState + " trackball=" + trackballState + ")");
2486            } else {
2487                Log.i(TAG, "SAFE MODE not enabled");
2488            }
2489            return mSafeMode;
2490        } catch (RemoteException e) {
2491            // Doom! (it's also local)
2492            throw new RuntimeException("window manager dead");
2493        }
2494    }
2495
2496    static long[] getLongIntArray(Resources r, int resid) {
2497        int[] ar = r.getIntArray(resid);
2498        if (ar == null) {
2499            return null;
2500        }
2501        long[] out = new long[ar.length];
2502        for (int i=0; i<ar.length; i++) {
2503            out[i] = ar[i];
2504        }
2505        return out;
2506    }
2507
2508    /** {@inheritDoc} */
2509    public void systemReady() {
2510        // tell the keyguard
2511        mKeyguardMediator.onSystemReady();
2512        android.os.SystemProperties.set("dev.bootcomplete", "1");
2513        synchronized (mLock) {
2514            updateOrientationListenerLp();
2515            mSystemReady = true;
2516            mHandler.post(new Runnable() {
2517                public void run() {
2518                    updateSettings();
2519                }
2520            });
2521        }
2522    }
2523
2524    /** {@inheritDoc} */
2525    public void userActivity() {
2526        synchronized (mScreenLockTimeout) {
2527            if (mLockScreenTimerActive) {
2528                // reset the timer
2529                mHandler.removeCallbacks(mScreenLockTimeout);
2530                mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
2531            }
2532        }
2533    }
2534
2535    Runnable mScreenLockTimeout = new Runnable() {
2536        public void run() {
2537            synchronized (this) {
2538                if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
2539                mKeyguardMediator.doKeyguardTimeout();
2540                mLockScreenTimerActive = false;
2541            }
2542        }
2543    };
2544
2545    private void updateLockScreenTimeout() {
2546        synchronized (mScreenLockTimeout) {
2547            boolean enable = (mAllowLockscreenWhenOn && mScreenOn && mKeyguardMediator.isSecure());
2548            if (mLockScreenTimerActive != enable) {
2549                if (enable) {
2550                    if (localLOGV) Log.v(TAG, "setting lockscreen timer");
2551                    mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
2552                } else {
2553                    if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
2554                    mHandler.removeCallbacks(mScreenLockTimeout);
2555                }
2556                mLockScreenTimerActive = enable;
2557            }
2558        }
2559    }
2560
2561    /** {@inheritDoc} */
2562    public void enableScreenAfterBoot() {
2563        readLidState();
2564        updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
2565    }
2566
2567    void updateRotation(int animFlags) {
2568        mPowerManager.setKeyboardVisibility(mLidOpen);
2569        int rotation = Surface.ROTATION_0;
2570        if (mLidOpen) {
2571            rotation = mLidOpenRotation;
2572        } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
2573            rotation = mCarDockRotation;
2574        } else if (mDockMode == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
2575            rotation = mDeskDockRotation;
2576        }
2577        //if lid is closed orientation will be portrait
2578        try {
2579            //set orientation on WindowManager
2580            mWindowManager.setRotation(rotation, true,
2581                    mFancyRotationAnimation | animFlags);
2582        } catch (RemoteException e) {
2583            // Ignore
2584        }
2585    }
2586
2587    /**
2588     * Return an Intent to launch the currently active dock as home.  Returns
2589     * null if the standard home should be launched.
2590     * @return
2591     */
2592    Intent createHomeDockIntent() {
2593        Intent intent;
2594
2595        // What home does is based on the mode, not the dock state.  That
2596        // is, when in car mode you should be taken to car home regardless
2597        // of whether we are actually in a car dock.
2598        if (mUiMode == Configuration.UI_MODE_TYPE_CAR) {
2599            intent = mCarDockIntent;
2600        } else if (mUiMode == Configuration.UI_MODE_TYPE_DESK) {
2601            intent = mDeskDockIntent;
2602        } else {
2603            return null;
2604        }
2605
2606        ActivityInfo ai = intent.resolveActivityInfo(
2607                mContext.getPackageManager(), PackageManager.GET_META_DATA);
2608        if (ai == null) {
2609            return null;
2610        }
2611
2612        if (ai.metaData != null && ai.metaData.getBoolean(Intent.METADATA_DOCK_HOME)) {
2613            intent = new Intent(intent);
2614            intent.setClassName(ai.packageName, ai.name);
2615            return intent;
2616        }
2617
2618        return null;
2619    }
2620
2621    void startDockOrHome() {
2622        Intent dock = createHomeDockIntent();
2623        if (dock != null) {
2624            try {
2625                mContext.startActivity(dock);
2626                return;
2627            } catch (ActivityNotFoundException e) {
2628            }
2629        }
2630        mContext.startActivity(mHomeIntent);
2631    }
2632
2633    /**
2634     * goes to the home screen
2635     * @return whether it did anything
2636     */
2637    boolean goHome() {
2638        if (false) {
2639            // This code always brings home to the front.
2640            try {
2641                ActivityManagerNative.getDefault().stopAppSwitches();
2642            } catch (RemoteException e) {
2643            }
2644            sendCloseSystemWindows();
2645            startDockOrHome();
2646        } else {
2647            // This code brings home to the front or, if it is already
2648            // at the front, puts the device to sleep.
2649            try {
2650                if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
2651                    /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
2652                    Log.d(TAG, "UTS-TEST-MODE");
2653                } else {
2654                    ActivityManagerNative.getDefault().stopAppSwitches();
2655                    sendCloseSystemWindows();
2656                    Intent dock = createHomeDockIntent();
2657                    if (dock != null) {
2658                        int result = ActivityManagerNative.getDefault()
2659                                .startActivity(null, dock,
2660                                        dock.resolveTypeIfNeeded(mContext.getContentResolver()),
2661                                        null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
2662                        if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
2663                            return false;
2664                        }
2665                    }
2666                }
2667                int result = ActivityManagerNative.getDefault()
2668                        .startActivity(null, mHomeIntent,
2669                                mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
2670                                null, 0, null, null, 0, true /* onlyIfNeeded*/, false);
2671                if (result == IActivityManager.START_RETURN_INTENT_TO_CALLER) {
2672                    return false;
2673                }
2674            } catch (RemoteException ex) {
2675                // bummer, the activity manager, which is in this process, is dead
2676            }
2677        }
2678        return true;
2679    }
2680
2681    public void setCurrentOrientationLw(int newOrientation) {
2682        synchronized (mLock) {
2683            if (newOrientation != mCurrentAppOrientation) {
2684                mCurrentAppOrientation = newOrientation;
2685                updateOrientationListenerLp();
2686            }
2687        }
2688    }
2689
2690    public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
2691        final boolean hapticsDisabled = Settings.System.getInt(mContext.getContentResolver(),
2692                Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 0;
2693        if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
2694            return false;
2695        }
2696        long[] pattern = null;
2697        switch (effectId) {
2698            case HapticFeedbackConstants.LONG_PRESS:
2699                pattern = mLongPressVibePattern;
2700                break;
2701            case HapticFeedbackConstants.VIRTUAL_KEY:
2702                pattern = mVirtualKeyVibePattern;
2703                break;
2704            case HapticFeedbackConstants.KEYBOARD_TAP:
2705                pattern = mKeyboardTapVibePattern;
2706                break;
2707            case HapticFeedbackConstants.SAFE_MODE_DISABLED:
2708                pattern = mSafeModeDisabledVibePattern;
2709                break;
2710            case HapticFeedbackConstants.SAFE_MODE_ENABLED:
2711                pattern = mSafeModeEnabledVibePattern;
2712                break;
2713            default:
2714                return false;
2715        }
2716        if (pattern.length == 1) {
2717            // One-shot vibration
2718            mVibrator.vibrate(pattern[0]);
2719        } else {
2720            // Pattern vibration
2721            mVibrator.vibrate(pattern, -1);
2722        }
2723        return true;
2724    }
2725
2726    public void screenOnStoppedLw() {
2727        if (!mKeyguardMediator.isShowingAndNotHidden() && mPowerManager.isScreenOn()) {
2728            long curTime = SystemClock.uptimeMillis();
2729            mPowerManager.userActivity(curTime, false, LocalPowerManager.OTHER_EVENT);
2730        }
2731    }
2732
2733    public boolean allowKeyRepeat() {
2734        // disable key repeat when screen is off
2735        return mScreenOn;
2736    }
2737}
2738