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