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