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