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