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