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