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