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