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