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