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