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