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