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