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