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