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