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