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