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