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