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