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