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