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