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