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