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