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