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