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