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