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