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