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