OSDN Git Service

am 41bb0637: am 76e85eec: am 3bc9971d: am 95d6e32b: am 86f9a93e: Merge "Allow FLAG_SH...
[android-x86/frameworks-base.git] / policy / src / com / android / internal / policy / impl / PhoneWindowManager.java
1 /*
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 package com.android.internal.policy.impl;
17
18 import android.app.ActivityManager;
19 import android.app.ActivityManagerNative;
20 import android.app.ProgressDialog;
21 import android.app.SearchManager;
22 import android.app.UiModeManager;
23 import android.content.ActivityNotFoundException;
24 import android.content.BroadcastReceiver;
25 import android.content.ComponentName;
26 import android.content.ContentResolver;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.content.ServiceConnection;
31 import android.content.pm.ActivityInfo;
32 import android.content.pm.PackageManager;
33 import android.content.res.CompatibilityInfo;
34 import android.content.res.Configuration;
35 import android.content.res.Resources;
36 import android.content.res.TypedArray;
37 import android.database.ContentObserver;
38 import android.graphics.PixelFormat;
39 import android.graphics.Rect;
40 import android.media.AudioManager;
41 import android.media.IAudioService;
42 import android.media.Ringtone;
43 import android.media.RingtoneManager;
44 import android.os.Bundle;
45 import android.os.FactoryTest;
46 import android.os.Handler;
47 import android.os.IBinder;
48 import android.os.IRemoteCallback;
49 import android.os.Looper;
50 import android.os.Message;
51 import android.os.Messenger;
52 import android.os.PowerManager;
53 import android.os.RemoteException;
54 import android.os.ServiceManager;
55 import android.os.SystemClock;
56 import android.os.SystemProperties;
57 import android.os.UEventObserver;
58 import android.os.UserHandle;
59 import android.os.Vibrator;
60 import android.provider.Settings;
61
62 import com.android.internal.R;
63 import com.android.internal.policy.PolicyManager;
64 import com.android.internal.policy.impl.keyguard.KeyguardViewManager;
65 import com.android.internal.policy.impl.keyguard.KeyguardViewMediator;
66 import com.android.internal.statusbar.IStatusBarService;
67 import com.android.internal.telephony.ITelephony;
68 import com.android.internal.widget.PointerLocationView;
69
70 import android.util.DisplayMetrics;
71 import android.util.EventLog;
72 import android.util.Log;
73 import android.util.Slog;
74 import android.util.SparseArray;
75 import android.view.Display;
76 import android.view.Gravity;
77 import android.view.HapticFeedbackConstants;
78 import android.view.IApplicationToken;
79 import android.view.IWindowManager;
80 import android.view.InputChannel;
81 import android.view.InputDevice;
82 import android.view.InputEvent;
83 import android.view.InputEventReceiver;
84 import android.view.KeyCharacterMap;
85 import android.view.KeyEvent;
86 import android.view.MotionEvent;
87 import android.view.WindowManagerGlobal;
88 import android.view.WindowOrientationListener;
89 import android.view.Surface;
90 import android.view.View;
91 import android.view.ViewConfiguration;
92 import android.view.Window;
93 import android.view.WindowManager;
94 import static android.view.WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW;
95 import static android.view.WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;
96 import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
97 import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
98 import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
99 import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
100 import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
101 import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
102 import static android.view.WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON;
103 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
104 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
105 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
106 import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
107 import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
108 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA;
109 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY;
110 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
111 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
112 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL;
113 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
114 import static android.view.WindowManager.LayoutParams.TYPE_DISPLAY_OVERLAY;
115 import static android.view.WindowManager.LayoutParams.TYPE_DRAG;
116 import static android.view.WindowManager.LayoutParams.TYPE_DREAM;
117 import static android.view.WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER;
118 import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD;
119 import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
120 import static android.view.WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY;
121 import static android.view.WindowManager.LayoutParams.TYPE_PHONE;
122 import static android.view.WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
123 import static android.view.WindowManager.LayoutParams.TYPE_RECENTS_OVERLAY;
124 import static android.view.WindowManager.LayoutParams.TYPE_SEARCH_BAR;
125 import static android.view.WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
126 import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
127 import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
128 import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
129 import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG;
130 import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
131 import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
132 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
133 import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
134 import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
135 import static android.view.WindowManager.LayoutParams.TYPE_TOAST;
136 import static android.view.WindowManager.LayoutParams.TYPE_UNIVERSE_BACKGROUND;
137 import static android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY;
138 import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
139 import static android.view.WindowManager.LayoutParams.TYPE_POINTER;
140 import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR;
141 import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL;
142 import static android.view.WindowManager.LayoutParams.TYPE_BOOT_PROGRESS;
143 import android.view.WindowManagerPolicy;
144 import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_ABSENT;
145 import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_OPEN;
146 import static android.view.WindowManagerPolicy.WindowManagerFuncs.LID_CLOSED;
147 import android.view.KeyCharacterMap.FallbackAction;
148 import android.view.accessibility.AccessibilityEvent;
149 import android.view.animation.Animation;
150 import android.view.animation.AnimationUtils;
151
152 import java.io.File;
153 import java.io.FileReader;
154 import java.io.IOException;
155 import java.io.PrintWriter;
156 import java.util.HashSet;
157
158 /**
159  * WindowManagerPolicy implementation for the Android phone UI.  This
160  * introduces a new method suffix, Lp, for an internal lock of the
161  * PhoneWindowManager.  This is used to protect some internal state, and
162  * can be acquired with either thw Lw and Li lock held, so has the restrictions
163  * of both of those when held.
164  */
165 public class PhoneWindowManager implements WindowManagerPolicy {
166     static final String TAG = "WindowManager";
167     static final boolean DEBUG = false;
168     static final boolean localLOGV = false;
169     static final boolean DEBUG_LAYOUT = false;
170     static final boolean DEBUG_INPUT = false;
171     static final boolean DEBUG_STARTING_WINDOW = false;
172     static final boolean SHOW_STARTING_ANIMATIONS = true;
173     static final boolean SHOW_PROCESSES_ON_ALT_MENU = false;
174
175     static final int LONG_PRESS_POWER_NOTHING = 0;
176     static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
177     static final int LONG_PRESS_POWER_SHUT_OFF = 2;
178     static final int LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM = 3;
179
180     // These need to match the documentation/constant in
181     // core/res/res/values/config.xml
182     static final int LONG_PRESS_HOME_NOTHING = 0;
183     static final int LONG_PRESS_HOME_RECENT_DIALOG = 1;
184     static final int LONG_PRESS_HOME_RECENT_SYSTEM_UI = 2;
185
186     static final int APPLICATION_MEDIA_SUBLAYER = -2;
187     static final int APPLICATION_MEDIA_OVERLAY_SUBLAYER = -1;
188     static final int APPLICATION_PANEL_SUBLAYER = 1;
189     static final int APPLICATION_SUB_PANEL_SUBLAYER = 2;
190
191     static public final String SYSTEM_DIALOG_REASON_KEY = "reason";
192     static public final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
193     static public final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
194     static public final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
195     static public final String SYSTEM_DIALOG_REASON_ASSIST = "assist";
196
197     /**
198      * These are the system UI flags that, when changing, can cause the layout
199      * of the screen to change.
200      */
201     static final int SYSTEM_UI_CHANGING_LAYOUT =
202             View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
203
204     /* Table of Application Launch keys.  Maps from key codes to intent categories.
205      *
206      * These are special keys that are used to launch particular kinds of applications,
207      * such as a web browser.  HID defines nearly a hundred of them in the Consumer (0x0C)
208      * usage page.  We don't support quite that many yet...
209      */
210     static SparseArray<String> sApplicationLaunchKeyCategories;
211     static {
212         sApplicationLaunchKeyCategories = new SparseArray<String>();
213         sApplicationLaunchKeyCategories.append(
214                 KeyEvent.KEYCODE_EXPLORER, Intent.CATEGORY_APP_BROWSER);
215         sApplicationLaunchKeyCategories.append(
216                 KeyEvent.KEYCODE_ENVELOPE, Intent.CATEGORY_APP_EMAIL);
217         sApplicationLaunchKeyCategories.append(
218                 KeyEvent.KEYCODE_CONTACTS, Intent.CATEGORY_APP_CONTACTS);
219         sApplicationLaunchKeyCategories.append(
220                 KeyEvent.KEYCODE_CALENDAR, Intent.CATEGORY_APP_CALENDAR);
221         sApplicationLaunchKeyCategories.append(
222                 KeyEvent.KEYCODE_MUSIC, Intent.CATEGORY_APP_MUSIC);
223         sApplicationLaunchKeyCategories.append(
224                 KeyEvent.KEYCODE_CALCULATOR, Intent.CATEGORY_APP_CALCULATOR);
225     }
226
227     /**
228      * Lock protecting internal state.  Must not call out into window
229      * manager with lock held.  (This lock will be acquired in places
230      * where the window manager is calling in with its own lock held.)
231      */
232     final Object mLock = new Object();
233
234     Context mContext;
235     IWindowManager mWindowManager;
236     WindowManagerFuncs mWindowManagerFuncs;
237     PowerManager mPowerManager;
238     IStatusBarService mStatusBarService;
239     final Object mServiceAquireLock = new Object();
240     Vibrator mVibrator; // Vibrator for giving feedback of orientation changes
241     SearchManager mSearchManager;
242
243     // Vibrator pattern for haptic feedback of a long press.
244     long[] mLongPressVibePattern;
245
246     // Vibrator pattern for haptic feedback of virtual key press.
247     long[] mVirtualKeyVibePattern;
248     
249     // Vibrator pattern for a short vibration.
250     long[] mKeyboardTapVibePattern;
251
252     // Vibrator pattern for haptic feedback during boot when safe mode is disabled.
253     long[] mSafeModeDisabledVibePattern;
254     
255     // Vibrator pattern for haptic feedback during boot when safe mode is enabled.
256     long[] mSafeModeEnabledVibePattern;
257
258     /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
259     boolean mEnableShiftMenuBugReports = false;
260
261     boolean mHeadless;
262     boolean mSafeMode;
263     WindowState mStatusBar = null;
264     boolean mHasSystemNavBar;
265     int mStatusBarHeight;
266     WindowState mNavigationBar = null;
267     boolean mHasNavigationBar = false;
268     boolean mCanHideNavigationBar = false;
269     boolean mNavigationBarCanMove = false; // can the navigation bar ever move to the side?
270     boolean mNavigationBarOnBottom = true; // is the navigation bar on the bottom *right now*?
271     int[] mNavigationBarHeightForRotation = new int[4];
272     int[] mNavigationBarWidthForRotation = new int[4];
273
274     WindowState mKeyguard = null;
275     KeyguardViewMediator mKeyguardMediator;
276     GlobalActions mGlobalActions;
277     volatile boolean mPowerKeyHandled; // accessed from input reader and handler thread
278     boolean mPendingPowerKeyUpCanceled;
279     Handler mHandler;
280     WindowState mLastInputMethodWindow = null;
281     WindowState mLastInputMethodTargetWindow = null;
282
283     static final int RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS = 0;
284     static final int RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW = 1;
285     static final int RECENT_APPS_BEHAVIOR_DISMISS = 2;
286     static final int RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH = 3;
287
288     RecentApplicationsDialog mRecentAppsDialog;
289     int mRecentAppsDialogHeldModifiers;
290     boolean mLanguageSwitchKeyPressed;
291
292     int mLidState = LID_ABSENT;
293     boolean mHaveBuiltInKeyboard;
294
295     boolean mSystemReady;
296     boolean mSystemBooted;
297     boolean mHdmiPlugged;
298     int mDockMode = Intent.EXTRA_DOCK_STATE_UNDOCKED;
299     int mLidOpenRotation;
300     int mCarDockRotation;
301     int mDeskDockRotation;
302     int mHdmiRotation;
303     boolean mHdmiRotationLock;
304
305     int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE;
306     int mUserRotation = Surface.ROTATION_0;
307     boolean mAccelerometerDefault;
308
309     int mAllowAllRotations = -1;
310     boolean mCarDockEnablesAccelerometer;
311     boolean mDeskDockEnablesAccelerometer;
312     int mLidKeyboardAccessibility;
313     int mLidNavigationAccessibility;
314     boolean mLidControlsSleep;
315     int mLongPressOnPowerBehavior = -1;
316     boolean mScreenOnEarly = false;
317     boolean mScreenOnFully = false;
318     boolean mOrientationSensorEnabled = false;
319     int mCurrentAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
320     boolean mHasSoftInput = false;
321     
322     int mPointerLocationMode = 0; // guarded by mLock
323
324     // The last window we were told about in focusChanged.
325     WindowState mFocusedWindow;
326     IApplicationToken mFocusedApp;
327
328     private static final class PointerLocationInputEventReceiver extends InputEventReceiver {
329         private final PointerLocationView mView;
330
331         public PointerLocationInputEventReceiver(InputChannel inputChannel, Looper looper,
332                 PointerLocationView view) {
333             super(inputChannel, looper);
334             mView = view;
335         }
336
337         @Override
338         public void onInputEvent(InputEvent event) {
339             boolean handled = false;
340             try {
341                 if (event instanceof MotionEvent
342                         && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
343                     final MotionEvent motionEvent = (MotionEvent)event;
344                     mView.addPointerEvent(motionEvent);
345                     handled = true;
346                 }
347             } finally {
348                 finishInputEvent(event, handled);
349             }
350         }
351     }
352
353     // Pointer location view state, only modified on the mHandler Looper.
354     PointerLocationInputEventReceiver mPointerLocationInputEventReceiver;
355     PointerLocationView mPointerLocationView;
356     InputChannel mPointerLocationInputChannel;
357
358     // The current size of the screen; really; (ir)regardless of whether the status
359     // bar can be hidden or not
360     int mUnrestrictedScreenLeft, mUnrestrictedScreenTop;
361     int mUnrestrictedScreenWidth, mUnrestrictedScreenHeight;
362     // The current size of the screen; these may be different than (0,0)-(dw,dh)
363     // if the status bar can't be hidden; in that case it effectively carves out
364     // that area of the display from all other windows.
365     int mRestrictedScreenLeft, mRestrictedScreenTop;
366     int mRestrictedScreenWidth, mRestrictedScreenHeight;
367     // During layout, the current screen borders accounting for any currently
368     // visible system UI elements.
369     int mSystemLeft, mSystemTop, mSystemRight, mSystemBottom;
370     // For applications requesting stable content insets, these are them.
371     int mStableLeft, mStableTop, mStableRight, mStableBottom;
372     // For applications requesting stable content insets but have also set the
373     // fullscreen window flag, these are the stable dimensions without the status bar.
374     int mStableFullscreenLeft, mStableFullscreenTop;
375     int mStableFullscreenRight, mStableFullscreenBottom;
376     // During layout, the current screen borders with all outer decoration
377     // (status bar, input method dock) accounted for.
378     int mCurLeft, mCurTop, mCurRight, mCurBottom;
379     // During layout, the frame in which content should be displayed
380     // to the user, accounting for all screen decoration except for any
381     // space they deem as available for other content.  This is usually
382     // the same as mCur*, but may be larger if the screen decor has supplied
383     // content insets.
384     int mContentLeft, mContentTop, mContentRight, mContentBottom;
385     // During layout, the current screen borders along which input method
386     // windows are placed.
387     int mDockLeft, mDockTop, mDockRight, mDockBottom;
388     // During layout, the layer at which the doc window is placed.
389     int mDockLayer;
390     // During layout, this is the layer of the status bar.
391     int mStatusBarLayer;
392     int mLastSystemUiFlags;
393     // Bits that we are in the process of clearing, so we want to prevent
394     // them from being set by applications until everything has been updated
395     // to have them clear.
396     int mResettingSystemUiFlags = 0;
397     // Bits that we are currently always keeping cleared.
398     int mForceClearedSystemUiFlags = 0;
399     // What we last reported to system UI about whether the compatibility
400     // menu needs to be displayed.
401     boolean mLastFocusNeedsMenu = false;
402
403     FakeWindow mHideNavFakeWindow = null;
404
405     static final Rect mTmpParentFrame = new Rect();
406     static final Rect mTmpDisplayFrame = new Rect();
407     static final Rect mTmpContentFrame = new Rect();
408     static final Rect mTmpVisibleFrame = new Rect();
409     static final Rect mTmpNavigationFrame = new Rect();
410     
411     WindowState mTopFullscreenOpaqueWindowState;
412     HashSet<IApplicationToken> mAppsToBeHidden = new HashSet<IApplicationToken>();
413     boolean mTopIsFullscreen;
414     boolean mForceStatusBar;
415     boolean mForceStatusBarFromKeyguard;
416     boolean mHideLockScreen;
417     boolean mForcingShowNavBar;
418     int mForcingShowNavBarLayer;
419
420     // States of keyguard dismiss.
421     private static final int DISMISS_KEYGUARD_NONE = 0; // Keyguard not being dismissed.
422     private static final int DISMISS_KEYGUARD_START = 1; // Keyguard needs to be dismissed.
423     private static final int DISMISS_KEYGUARD_CONTINUE = 2; // Keyguard has been dismissed.
424     int mDismissKeyguard = DISMISS_KEYGUARD_NONE;
425
426     /** The window that is currently dismissing the keyguard. Dismissing the keyguard must only
427      * be done once per window. */
428     private WindowState mWinDismissingKeyguard;
429
430     boolean mShowingLockscreen;
431     boolean mShowingDream;
432     boolean mDreamingLockscreen;
433     boolean mHomePressed;
434     boolean mHomeLongPressed;
435     Intent mHomeIntent;
436     Intent mCarDockIntent;
437     Intent mDeskDockIntent;
438     boolean mSearchKeyShortcutPending;
439     boolean mConsumeSearchKeyUp;
440     boolean mAssistKeyLongPressed;
441
442     // support for activating the lock screen while the screen is on
443     boolean mAllowLockscreenWhenOn;
444     int mLockScreenTimeout;
445     boolean mLockScreenTimerActive;
446
447     // Behavior of ENDCALL Button.  (See Settings.System.END_BUTTON_BEHAVIOR.)
448     int mEndcallBehavior;
449
450     // Behavior of POWER button while in-call and screen on.
451     // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.)
452     int mIncallPowerBehavior;
453
454     Display mDisplay;
455
456     int mLandscapeRotation = 0;  // default landscape rotation
457     int mSeascapeRotation = 0;   // "other" landscape rotation, 180 degrees from mLandscapeRotation
458     int mPortraitRotation = 0;   // default portrait rotation
459     int mUpsideDownRotation = 0; // "other" portrait rotation
460
461     // What we do when the user long presses on home
462     private int mLongPressOnHomeBehavior = -1;
463
464     // Screenshot trigger states
465     // Time to volume and power must be pressed within this interval of each other.
466     private static final long SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS = 150;
467     // Increase the chord delay when taking a screenshot from the keyguard
468     private static final float KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER = 2.5f;
469     private boolean mScreenshotChordEnabled;
470     private boolean mVolumeDownKeyTriggered;
471     private long mVolumeDownKeyTime;
472     private boolean mVolumeDownKeyConsumedByScreenshotChord;
473     private boolean mVolumeUpKeyTriggered;
474     private boolean mPowerKeyTriggered;
475     private long mPowerKeyTime;
476
477     SettingsObserver mSettingsObserver;
478     ShortcutManager mShortcutManager;
479     PowerManager.WakeLock mBroadcastWakeLock;
480     boolean mHavePendingMediaKeyRepeatWithWakeLock;
481
482     // Fallback actions by key code.
483     private final SparseArray<KeyCharacterMap.FallbackAction> mFallbackActions =
484             new SparseArray<KeyCharacterMap.FallbackAction>();
485
486     private static final int MSG_ENABLE_POINTER_LOCATION = 1;
487     private static final int MSG_DISABLE_POINTER_LOCATION = 2;
488     private static final int MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK = 3;
489     private static final int MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK = 4;
490
491     private class PolicyHandler extends Handler {
492         @Override
493         public void handleMessage(Message msg) {
494             switch (msg.what) {
495                 case MSG_ENABLE_POINTER_LOCATION:
496                     enablePointerLocation();
497                     break;
498                 case MSG_DISABLE_POINTER_LOCATION:
499                     disablePointerLocation();
500                     break;
501                 case MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK:
502                     dispatchMediaKeyWithWakeLock((KeyEvent)msg.obj);
503                     break;
504                 case MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK:
505                     dispatchMediaKeyRepeatWithWakeLock((KeyEvent)msg.obj);
506                     break;
507             }
508         }
509     }
510
511     private UEventObserver mHDMIObserver = new UEventObserver() {
512         @Override
513         public void onUEvent(UEventObserver.UEvent event) {
514             setHdmiPlugged("1".equals(event.get("SWITCH_STATE")));
515         }
516     };
517
518     class SettingsObserver extends ContentObserver {
519         SettingsObserver(Handler handler) {
520             super(handler);
521         }
522
523         void observe() {
524             // Observe all users' changes
525             ContentResolver resolver = mContext.getContentResolver();
526             resolver.registerContentObserver(Settings.System.getUriFor(
527                     Settings.System.END_BUTTON_BEHAVIOR), false, this,
528                     UserHandle.USER_ALL);
529             resolver.registerContentObserver(Settings.Secure.getUriFor(
530                     Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this,
531                     UserHandle.USER_ALL);
532             resolver.registerContentObserver(Settings.System.getUriFor(
533                     Settings.System.ACCELEROMETER_ROTATION), false, this,
534                     UserHandle.USER_ALL);
535             resolver.registerContentObserver(Settings.System.getUriFor(
536                     Settings.System.USER_ROTATION), false, this,
537                     UserHandle.USER_ALL);
538             resolver.registerContentObserver(Settings.System.getUriFor(
539                     Settings.System.SCREEN_OFF_TIMEOUT), false, this,
540                     UserHandle.USER_ALL);
541             resolver.registerContentObserver(Settings.System.getUriFor(
542                     Settings.System.POINTER_LOCATION), false, this,
543                     UserHandle.USER_ALL);
544             resolver.registerContentObserver(Settings.Secure.getUriFor(
545                     Settings.Secure.DEFAULT_INPUT_METHOD), false, this,
546                     UserHandle.USER_ALL);
547             resolver.registerContentObserver(Settings.System.getUriFor(
548                     "fancy_rotation_anim"), false, this,
549                     UserHandle.USER_ALL);
550             updateSettings();
551         }
552
553         @Override public void onChange(boolean selfChange) {
554             updateSettings();
555             updateRotation(false);
556         }
557     }
558     
559     class MyOrientationListener extends WindowOrientationListener {
560         MyOrientationListener(Context context) {
561             super(context);
562         }
563         
564         @Override
565         public void onProposedRotationChanged(int rotation) {
566             if (localLOGV) Log.v(TAG, "onProposedRotationChanged, rotation=" + rotation);
567             updateRotation(false);
568         }
569     }
570     MyOrientationListener mOrientationListener;
571
572     IStatusBarService getStatusBarService() {
573         synchronized (mServiceAquireLock) {
574             if (mStatusBarService == null) {
575                 mStatusBarService = IStatusBarService.Stub.asInterface(
576                         ServiceManager.getService("statusbar"));
577             }
578             return mStatusBarService;
579         }
580     }
581
582     /*
583      * We always let the sensor be switched on by default except when
584      * the user has explicitly disabled sensor based rotation or when the
585      * screen is switched off.
586      */
587     boolean needSensorRunningLp() {
588         if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
589                 || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
590                 || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
591                 || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
592             // If the application has explicitly requested to follow the
593             // orientation, then we need to turn the sensor or.
594             return true;
595         }
596         if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) ||
597                 (mDeskDockEnablesAccelerometer && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
598                         || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
599                         || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK))) {
600             // enable accelerometer if we are docked in a dock that enables accelerometer
601             // orientation management,
602             return true;
603         }
604         if (mUserRotationMode == USER_ROTATION_LOCKED) {
605             // If the setting for using the sensor by default is enabled, then
606             // we will always leave it on.  Note that the user could go to
607             // a window that forces an orientation that does not use the
608             // sensor and in theory we could turn it off... however, when next
609             // turning it on we won't have a good value for the current
610             // orientation for a little bit, which can cause orientation
611             // changes to lag, so we'd like to keep it always on.  (It will
612             // still be turned off when the screen is off.)
613             return false;
614         }
615         return true;
616     }
617     
618     /*
619      * Various use cases for invoking this function
620      * screen turning off, should always disable listeners if already enabled
621      * screen turned on and current app has sensor based orientation, enable listeners 
622      * if not already enabled
623      * screen turned on and current app does not have sensor orientation, disable listeners if
624      * already enabled
625      * screen turning on and current app has sensor based orientation, enable listeners if needed
626      * screen turning on and current app has nosensor based orientation, do nothing
627      */
628     void updateOrientationListenerLp() {
629         if (!mOrientationListener.canDetectOrientation()) {
630             // If sensor is turned off or nonexistent for some reason
631             return;
632         }
633         //Could have been invoked due to screen turning on or off or
634         //change of the currently visible window's orientation
635         if (localLOGV) Log.v(TAG, "Screen status="+mScreenOnEarly+
636                 ", current orientation="+mCurrentAppOrientation+
637                 ", SensorEnabled="+mOrientationSensorEnabled);
638         boolean disable = true;
639         if (mScreenOnEarly) {
640             if (needSensorRunningLp()) {
641                 disable = false;
642                 //enable listener if not already enabled
643                 if (!mOrientationSensorEnabled) {
644                     mOrientationListener.enable();
645                     if(localLOGV) Log.v(TAG, "Enabling listeners");
646                     mOrientationSensorEnabled = true;
647                 }
648             } 
649         } 
650         //check if sensors need to be disabled
651         if (disable && mOrientationSensorEnabled) {
652             mOrientationListener.disable();
653             if(localLOGV) Log.v(TAG, "Disabling listeners");
654             mOrientationSensorEnabled = false;
655         }
656     }
657
658     private void interceptPowerKeyDown(boolean handled) {
659         mPowerKeyHandled = handled;
660         if (!handled) {
661             mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
662         }
663     }
664
665     private boolean interceptPowerKeyUp(boolean canceled) {
666         if (!mPowerKeyHandled) {
667             mHandler.removeCallbacks(mPowerLongPress);
668             return !canceled;
669         }
670         return false;
671     }
672
673     private void cancelPendingPowerKeyAction() {
674         if (!mPowerKeyHandled) {
675             mHandler.removeCallbacks(mPowerLongPress);
676         }
677         if (mPowerKeyTriggered) {
678             mPendingPowerKeyUpCanceled = true;
679         }
680     }
681
682     private void interceptScreenshotChord() {
683         if (mScreenshotChordEnabled
684                 && mVolumeDownKeyTriggered && mPowerKeyTriggered && !mVolumeUpKeyTriggered) {
685             final long now = SystemClock.uptimeMillis();
686             if (now <= mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS
687                     && now <= mPowerKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS) {
688                 mVolumeDownKeyConsumedByScreenshotChord = true;
689                 cancelPendingPowerKeyAction();
690
691                 mHandler.postDelayed(mScreenshotChordLongPress, getScreenshotChordLongPressDelay());
692             }
693         }
694     }
695
696     private long getScreenshotChordLongPressDelay() {
697         if (mKeyguardMediator.isShowing()) {
698             // Double the time it takes to take a screenshot from the keyguard
699             return (long) (KEYGUARD_SCREENSHOT_CHORD_DELAY_MULTIPLIER *
700                     ViewConfiguration.getGlobalActionKeyTimeout());
701         } else {
702             return ViewConfiguration.getGlobalActionKeyTimeout();
703         }
704     }
705
706     private void cancelPendingScreenshotChordAction() {
707         mHandler.removeCallbacks(mScreenshotChordLongPress);
708     }
709
710     private final Runnable mPowerLongPress = new Runnable() {
711         @Override
712         public void run() {
713             // The context isn't read
714             if (mLongPressOnPowerBehavior < 0) {
715                 mLongPressOnPowerBehavior = mContext.getResources().getInteger(
716                         com.android.internal.R.integer.config_longPressOnPowerBehavior);
717             }
718             int resolvedBehavior = mLongPressOnPowerBehavior;
719             if (FactoryTest.isLongPressOnPowerOffEnabled()) {
720                 resolvedBehavior = LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM;
721             }
722
723             switch (resolvedBehavior) {
724             case LONG_PRESS_POWER_NOTHING:
725                 break;
726             case LONG_PRESS_POWER_GLOBAL_ACTIONS:
727                 mPowerKeyHandled = true;
728                 if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
729                     performAuditoryFeedbackForAccessibilityIfNeed();
730                 }
731                 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
732                 showGlobalActionsDialog();
733                 break;
734             case LONG_PRESS_POWER_SHUT_OFF:
735             case LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM:
736                 mPowerKeyHandled = true;
737                 performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
738                 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
739                 mWindowManagerFuncs.shutdown(resolvedBehavior == LONG_PRESS_POWER_SHUT_OFF);
740                 break;
741             }
742         }
743     };
744
745     private final Runnable mScreenshotChordLongPress = new Runnable() {
746         public void run() {
747             takeScreenshot();
748         }
749     };
750
751     void showGlobalActionsDialog() {
752         if (mGlobalActions == null) {
753             mGlobalActions = new GlobalActions(mContext, mWindowManagerFuncs);
754         }
755         final boolean keyguardShowing = keyguardIsShowingTq();
756         mGlobalActions.showDialog(keyguardShowing, isDeviceProvisioned());
757         if (keyguardShowing) {
758             // since it took two seconds of long press to bring this up,
759             // poke the wake lock so they have some time to see the dialog.
760             mKeyguardMediator.userActivity();
761         }
762     }
763
764     boolean isDeviceProvisioned() {
765         return Settings.Global.getInt(
766                 mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0;
767     }
768
769     private void handleLongPressOnHome() {
770         // We can't initialize this in init() since the configuration hasn't been loaded yet.
771         if (mLongPressOnHomeBehavior < 0) {
772             mLongPressOnHomeBehavior
773                     = mContext.getResources().getInteger(R.integer.config_longPressOnHomeBehavior);
774             if (mLongPressOnHomeBehavior < LONG_PRESS_HOME_NOTHING ||
775                     mLongPressOnHomeBehavior > LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
776                 mLongPressOnHomeBehavior = LONG_PRESS_HOME_NOTHING;
777             }
778         }
779
780         if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) {
781             performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
782             sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
783
784             // Eat the longpress so it won't dismiss the recent apps dialog when
785             // the user lets go of the home key
786             mHomeLongPressed = true;
787         }
788
789         if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_DIALOG) {
790             showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS);
791         } else if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
792             try {
793                 IStatusBarService statusbar = getStatusBarService();
794                 if (statusbar != null) {
795                     statusbar.toggleRecentApps();
796                 }
797             } catch (RemoteException e) {
798                 Slog.e(TAG, "RemoteException when showing recent apps", e);
799                 // re-acquire status bar service next time it is needed.
800                 mStatusBarService = null;
801             }
802         }
803     }
804
805     /**
806      * Create (if necessary) and show or dismiss the recent apps dialog according
807      * according to the requested behavior.
808      */
809     void showOrHideRecentAppsDialog(final int behavior) {
810         mHandler.post(new Runnable() {
811             @Override
812             public void run() {
813                 if (mRecentAppsDialog == null) {
814                     mRecentAppsDialog = new RecentApplicationsDialog(mContext);
815                 }
816                 if (mRecentAppsDialog.isShowing()) {
817                     switch (behavior) {
818                         case RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS:
819                         case RECENT_APPS_BEHAVIOR_DISMISS:
820                             mRecentAppsDialog.dismiss();
821                             break;
822                         case RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH:
823                             mRecentAppsDialog.dismissAndSwitch();
824                             break;
825                         case RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW:
826                         default:
827                             break;
828                     }
829                 } else {
830                     switch (behavior) {
831                         case RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS:
832                             mRecentAppsDialog.show();
833                             break;
834                         case RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW:
835                             try {
836                                 mWindowManager.setInTouchMode(false);
837                             } catch (RemoteException e) {
838                             }
839                             mRecentAppsDialog.show();
840                             break;
841                         case RECENT_APPS_BEHAVIOR_DISMISS:
842                         case RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH:
843                         default:
844                             break;
845                     }
846                 }
847             }
848         });
849     }
850
851     /** {@inheritDoc} */
852     public void init(Context context, IWindowManager windowManager,
853             WindowManagerFuncs windowManagerFuncs) {
854         mContext = context;
855         mWindowManager = windowManager;
856         mWindowManagerFuncs = windowManagerFuncs;
857         mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
858         if (!mHeadless) {
859             // don't create KeyguardViewMediator if headless
860             mKeyguardMediator = new KeyguardViewMediator(context, null);
861         }
862         mHandler = new PolicyHandler();
863         mOrientationListener = new MyOrientationListener(mContext);
864         try {
865             mOrientationListener.setCurrentRotation(windowManager.getRotation());
866         } catch (RemoteException ex) { }
867         mSettingsObserver = new SettingsObserver(mHandler);
868         mSettingsObserver.observe();
869         mShortcutManager = new ShortcutManager(context, mHandler);
870         mShortcutManager.observe();
871         mHomeIntent =  new Intent(Intent.ACTION_MAIN, null);
872         mHomeIntent.addCategory(Intent.CATEGORY_HOME);
873         mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
874                 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
875         mCarDockIntent =  new Intent(Intent.ACTION_MAIN, null);
876         mCarDockIntent.addCategory(Intent.CATEGORY_CAR_DOCK);
877         mCarDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
878                 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
879         mDeskDockIntent =  new Intent(Intent.ACTION_MAIN, null);
880         mDeskDockIntent.addCategory(Intent.CATEGORY_DESK_DOCK);
881         mDeskDockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
882                 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
883
884         mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
885         mBroadcastWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
886                 "PhoneWindowManager.mBroadcastWakeLock");
887         mEnableShiftMenuBugReports = "1".equals(SystemProperties.get("ro.debuggable"));
888         mLidOpenRotation = readRotation(
889                 com.android.internal.R.integer.config_lidOpenRotation);
890         mCarDockRotation = readRotation(
891                 com.android.internal.R.integer.config_carDockRotation);
892         mDeskDockRotation = readRotation(
893                 com.android.internal.R.integer.config_deskDockRotation);
894         mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
895                 com.android.internal.R.bool.config_carDockEnablesAccelerometer);
896         mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
897                 com.android.internal.R.bool.config_deskDockEnablesAccelerometer);
898         mLidKeyboardAccessibility = mContext.getResources().getInteger(
899                 com.android.internal.R.integer.config_lidKeyboardAccessibility);
900         mLidNavigationAccessibility = mContext.getResources().getInteger(
901                 com.android.internal.R.integer.config_lidNavigationAccessibility);
902         mLidControlsSleep = mContext.getResources().getBoolean(
903                 com.android.internal.R.bool.config_lidControlsSleep);
904         // register for dock events
905         IntentFilter filter = new IntentFilter();
906         filter.addAction(UiModeManager.ACTION_ENTER_CAR_MODE);
907         filter.addAction(UiModeManager.ACTION_EXIT_CAR_MODE);
908         filter.addAction(UiModeManager.ACTION_ENTER_DESK_MODE);
909         filter.addAction(UiModeManager.ACTION_EXIT_DESK_MODE);
910         filter.addAction(Intent.ACTION_DOCK_EVENT);
911         Intent intent = context.registerReceiver(mDockReceiver, filter);
912         if (intent != null) {
913             // Retrieve current sticky dock event broadcast.
914             mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
915                     Intent.EXTRA_DOCK_STATE_UNDOCKED);
916         }
917
918         // register for dream-related broadcasts
919         filter = new IntentFilter();
920         filter.addAction(Intent.ACTION_DREAMING_STARTED);
921         filter.addAction(Intent.ACTION_DREAMING_STOPPED);
922         context.registerReceiver(mDreamReceiver, filter);
923
924         // register for multiuser-relevant broadcasts
925         filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
926         context.registerReceiver(mMultiuserReceiver, filter);
927
928         mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
929         mLongPressVibePattern = getLongIntArray(mContext.getResources(),
930                 com.android.internal.R.array.config_longPressVibePattern);
931         mVirtualKeyVibePattern = getLongIntArray(mContext.getResources(),
932                 com.android.internal.R.array.config_virtualKeyVibePattern);
933         mKeyboardTapVibePattern = getLongIntArray(mContext.getResources(),
934                 com.android.internal.R.array.config_keyboardTapVibePattern);
935         mSafeModeDisabledVibePattern = getLongIntArray(mContext.getResources(),
936                 com.android.internal.R.array.config_safeModeDisabledVibePattern);
937         mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
938                 com.android.internal.R.array.config_safeModeEnabledVibePattern);
939
940         mScreenshotChordEnabled = mContext.getResources().getBoolean(
941                 com.android.internal.R.bool.config_enableScreenshotChord);
942
943         // Controls rotation and the like.
944         initializeHdmiState();
945
946         // Match current screen state.
947         if (mPowerManager.isScreenOn()) {
948             screenTurningOn(null);
949         } else {
950             screenTurnedOff(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
951         }
952     }
953
954     public void setInitialDisplaySize(Display display, int width, int height, int density) {
955         mDisplay = display;
956
957         int shortSize, longSize;
958         if (width > height) {
959             shortSize = height;
960             longSize = width;
961             mLandscapeRotation = Surface.ROTATION_0;
962             mSeascapeRotation = Surface.ROTATION_180;
963             if (mContext.getResources().getBoolean(
964                     com.android.internal.R.bool.config_reverseDefaultRotation)) {
965                 mPortraitRotation = Surface.ROTATION_90;
966                 mUpsideDownRotation = Surface.ROTATION_270;
967             } else {
968                 mPortraitRotation = Surface.ROTATION_270;
969                 mUpsideDownRotation = Surface.ROTATION_90;
970             }
971         } else {
972             shortSize = width;
973             longSize = height;
974             mPortraitRotation = Surface.ROTATION_0;
975             mUpsideDownRotation = Surface.ROTATION_180;
976             if (mContext.getResources().getBoolean(
977                     com.android.internal.R.bool.config_reverseDefaultRotation)) {
978                 mLandscapeRotation = Surface.ROTATION_270;
979                 mSeascapeRotation = Surface.ROTATION_90;
980             } else {
981                 mLandscapeRotation = Surface.ROTATION_90;
982                 mSeascapeRotation = Surface.ROTATION_270;
983             }
984         }
985
986         mStatusBarHeight = mContext.getResources().getDimensionPixelSize(
987                 com.android.internal.R.dimen.status_bar_height);
988
989         // Height of the navigation bar when presented horizontally at bottom
990         mNavigationBarHeightForRotation[mPortraitRotation] =
991         mNavigationBarHeightForRotation[mUpsideDownRotation] =
992                 mContext.getResources().getDimensionPixelSize(
993                         com.android.internal.R.dimen.navigation_bar_height);
994         mNavigationBarHeightForRotation[mLandscapeRotation] =
995         mNavigationBarHeightForRotation[mSeascapeRotation] =
996                 mContext.getResources().getDimensionPixelSize(
997                         com.android.internal.R.dimen.navigation_bar_height_landscape);
998
999         // Width of the navigation bar when presented vertically along one side
1000         mNavigationBarWidthForRotation[mPortraitRotation] =
1001         mNavigationBarWidthForRotation[mUpsideDownRotation] =
1002         mNavigationBarWidthForRotation[mLandscapeRotation] =
1003         mNavigationBarWidthForRotation[mSeascapeRotation] =
1004                 mContext.getResources().getDimensionPixelSize(
1005                         com.android.internal.R.dimen.navigation_bar_width);
1006
1007         // SystemUI (status bar) layout policy
1008         int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / density;
1009
1010         if (shortSizeDp < 600) {
1011             // 0-599dp: "phone" UI with a separate status & navigation bar
1012             mHasSystemNavBar = false;
1013             mNavigationBarCanMove = true;
1014         } else if (shortSizeDp < 720) {
1015             // 600+dp: "phone" UI with modifications for larger screens
1016             mHasSystemNavBar = false;
1017             mNavigationBarCanMove = false;
1018         }
1019
1020         if (!mHasSystemNavBar) {
1021             mHasNavigationBar = mContext.getResources().getBoolean(
1022                     com.android.internal.R.bool.config_showNavigationBar);
1023             // Allow a system property to override this. Used by the emulator.
1024             // See also hasNavigationBar().
1025             String navBarOverride = SystemProperties.get("qemu.hw.mainkeys");
1026             if (! "".equals(navBarOverride)) {
1027                 if      (navBarOverride.equals("1")) mHasNavigationBar = false;
1028                 else if (navBarOverride.equals("0")) mHasNavigationBar = true;
1029             }
1030         } else {
1031             mHasNavigationBar = false;
1032         }
1033
1034         if (mHasSystemNavBar) {
1035             // The system bar is always at the bottom.  If you are watching
1036             // a video in landscape, we don't need to hide it if we can still
1037             // show a 16:9 aspect ratio with it.
1038             int longSizeDp = longSize * DisplayMetrics.DENSITY_DEFAULT / density;
1039             int barHeightDp = mNavigationBarHeightForRotation[mLandscapeRotation]
1040                     * DisplayMetrics.DENSITY_DEFAULT / density;
1041             int aspect = ((shortSizeDp-barHeightDp) * 16) / longSizeDp;
1042             // We have computed the aspect ratio with the bar height taken
1043             // out to be 16:aspect.  If this is less than 9, then hiding
1044             // the navigation bar will provide more useful space for wide
1045             // screen movies.
1046             mCanHideNavigationBar = aspect < 9;
1047         } else if (mHasNavigationBar) {
1048             // The navigation bar is at the right in landscape; it seems always
1049             // useful to hide it for showing a video.
1050             mCanHideNavigationBar = true;
1051         } else {
1052             mCanHideNavigationBar = false;
1053         }
1054
1055         // For demo purposes, allow the rotation of the HDMI display to be controlled.
1056         // By default, HDMI locks rotation to landscape.
1057         if ("portrait".equals(SystemProperties.get("persist.demo.hdmirotation"))) {
1058             mHdmiRotation = mPortraitRotation;
1059         } else {
1060             mHdmiRotation = mLandscapeRotation;
1061         }
1062         mHdmiRotationLock = SystemProperties.getBoolean("persist.demo.hdmirotationlock", true);
1063     }
1064
1065     public void updateSettings() {
1066         ContentResolver resolver = mContext.getContentResolver();
1067         boolean updateRotation = false;
1068         synchronized (mLock) {
1069             mEndcallBehavior = Settings.System.getIntForUser(resolver,
1070                     Settings.System.END_BUTTON_BEHAVIOR,
1071                     Settings.System.END_BUTTON_BEHAVIOR_DEFAULT,
1072                     UserHandle.USER_CURRENT);
1073             mIncallPowerBehavior = Settings.Secure.getIntForUser(resolver,
1074                     Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
1075                     Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT,
1076                     UserHandle.USER_CURRENT);
1077
1078             // Configure rotation lock.
1079             int userRotation = Settings.System.getIntForUser(resolver,
1080                     Settings.System.USER_ROTATION, Surface.ROTATION_0,
1081                     UserHandle.USER_CURRENT);
1082             if (mUserRotation != userRotation) {
1083                 mUserRotation = userRotation;
1084                 updateRotation = true;
1085             }
1086             int userRotationMode = Settings.System.getIntForUser(resolver,
1087                     Settings.System.ACCELEROMETER_ROTATION, 0, UserHandle.USER_CURRENT) != 0 ?
1088                             WindowManagerPolicy.USER_ROTATION_FREE :
1089                                     WindowManagerPolicy.USER_ROTATION_LOCKED;
1090             if (mUserRotationMode != userRotationMode) {
1091                 mUserRotationMode = userRotationMode;
1092                 updateRotation = true;
1093                 updateOrientationListenerLp();
1094             }
1095
1096             if (mSystemReady) {
1097                 int pointerLocation = Settings.System.getIntForUser(resolver,
1098                         Settings.System.POINTER_LOCATION, 0, UserHandle.USER_CURRENT);
1099                 if (mPointerLocationMode != pointerLocation) {
1100                     mPointerLocationMode = pointerLocation;
1101                     mHandler.sendEmptyMessage(pointerLocation != 0 ?
1102                             MSG_ENABLE_POINTER_LOCATION : MSG_DISABLE_POINTER_LOCATION);
1103                 }
1104             }
1105             // use screen off timeout setting as the timeout for the lockscreen
1106             mLockScreenTimeout = Settings.System.getIntForUser(resolver,
1107                     Settings.System.SCREEN_OFF_TIMEOUT, 0, UserHandle.USER_CURRENT);
1108             String imId = Settings.Secure.getStringForUser(resolver,
1109                     Settings.Secure.DEFAULT_INPUT_METHOD, UserHandle.USER_CURRENT);
1110             boolean hasSoftInput = imId != null && imId.length() > 0;
1111             if (mHasSoftInput != hasSoftInput) {
1112                 mHasSoftInput = hasSoftInput;
1113                 updateRotation = true;
1114             }
1115         }
1116         if (updateRotation) {
1117             updateRotation(true);
1118         }
1119     }
1120
1121     private void enablePointerLocation() {
1122         if (mPointerLocationView == null) {
1123             mPointerLocationView = new PointerLocationView(mContext);
1124             mPointerLocationView.setPrintCoords(false);
1125
1126             WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1127                     WindowManager.LayoutParams.MATCH_PARENT,
1128                     WindowManager.LayoutParams.MATCH_PARENT);
1129             lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
1130             lp.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
1131                     | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
1132                     | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1133                     | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
1134             if (ActivityManager.isHighEndGfx()) {
1135                 lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1136                 lp.privateFlags |=
1137                         WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED;
1138             }
1139             lp.format = PixelFormat.TRANSLUCENT;
1140             lp.setTitle("PointerLocation");
1141             WindowManager wm = (WindowManager)
1142                     mContext.getSystemService(Context.WINDOW_SERVICE);
1143             lp.inputFeatures |= WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL;
1144             wm.addView(mPointerLocationView, lp);
1145
1146             mPointerLocationInputChannel =
1147                     mWindowManagerFuncs.monitorInput("PointerLocationView");
1148             mPointerLocationInputEventReceiver =
1149                     new PointerLocationInputEventReceiver(mPointerLocationInputChannel,
1150                             Looper.myLooper(), mPointerLocationView);
1151         }
1152     }
1153
1154     private void disablePointerLocation() {
1155         if (mPointerLocationInputEventReceiver != null) {
1156             mPointerLocationInputEventReceiver.dispose();
1157             mPointerLocationInputEventReceiver = null;
1158         }
1159
1160         if (mPointerLocationInputChannel != null) {
1161             mPointerLocationInputChannel.dispose();
1162             mPointerLocationInputChannel = null;
1163         }
1164
1165         if (mPointerLocationView != null) {
1166             WindowManager wm = (WindowManager)
1167                     mContext.getSystemService(Context.WINDOW_SERVICE);
1168             wm.removeView(mPointerLocationView);
1169             mPointerLocationView = null;
1170         }
1171     }
1172
1173     private int readRotation(int resID) {
1174         try {
1175             int rotation = mContext.getResources().getInteger(resID);
1176             switch (rotation) {
1177                 case 0:
1178                     return Surface.ROTATION_0;
1179                 case 90:
1180                     return Surface.ROTATION_90;
1181                 case 180:
1182                     return Surface.ROTATION_180;
1183                 case 270:
1184                     return Surface.ROTATION_270;
1185             }
1186         } catch (Resources.NotFoundException e) {
1187             // fall through
1188         }
1189         return -1;
1190     }
1191
1192     /** {@inheritDoc} */
1193     @Override
1194     public int checkAddPermission(WindowManager.LayoutParams attrs) {
1195         int type = attrs.type;
1196         
1197         if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
1198                 || type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) {
1199             return WindowManagerGlobal.ADD_OKAY;
1200         }
1201         String permission = null;
1202         switch (type) {
1203             case TYPE_TOAST:
1204                 // XXX right now the app process has complete control over
1205                 // this...  should introduce a token to let the system
1206                 // monitor/control what they are doing.
1207                 break;
1208             case TYPE_DREAM:
1209             case TYPE_INPUT_METHOD:
1210             case TYPE_WALLPAPER:
1211                 // The window manager will check these.
1212                 break;
1213             case TYPE_PHONE:
1214             case TYPE_PRIORITY_PHONE:
1215             case TYPE_SYSTEM_ALERT:
1216             case TYPE_SYSTEM_ERROR:
1217             case TYPE_SYSTEM_OVERLAY:
1218                 permission = android.Manifest.permission.SYSTEM_ALERT_WINDOW;
1219                 break;
1220             default:
1221                 permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
1222         }
1223         if (permission != null) {
1224             if (mContext.checkCallingOrSelfPermission(permission)
1225                     != PackageManager.PERMISSION_GRANTED) {
1226                 return WindowManagerGlobal.ADD_PERMISSION_DENIED;
1227             }
1228         }
1229         return WindowManagerGlobal.ADD_OKAY;
1230     }
1231
1232     @Override
1233     public boolean checkShowToOwnerOnly(WindowManager.LayoutParams attrs) {
1234
1235         // If this switch statement is modified, modify the comment in the declarations of
1236         // the type in {@link WindowManager.LayoutParams} as well.
1237         switch (attrs.type) {
1238             default:
1239                 // These are the windows that by default are shown only to the user that created
1240                 // them. If this needs to be overridden, set
1241                 // {@link WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS} in
1242                 // {@link WindowManager.LayoutParams}. Note that permission
1243                 // {@link android.Manifest.permission.INTERNAL_SYSTEM_WINDOW} is required as well.
1244                 if ((attrs.privateFlags & PRIVATE_FLAG_SHOW_FOR_ALL_USERS) == 0) {
1245                     return true;
1246                 }
1247                 break;
1248
1249             // These are the windows that by default are shown to all users. However, to
1250             // protect against spoofing, check permissions below.
1251             case TYPE_APPLICATION_STARTING:
1252             case TYPE_BOOT_PROGRESS:
1253             case TYPE_DISPLAY_OVERLAY:
1254             case TYPE_HIDDEN_NAV_CONSUMER:
1255             case TYPE_KEYGUARD:
1256             case TYPE_KEYGUARD_DIALOG:
1257             case TYPE_MAGNIFICATION_OVERLAY:
1258             case TYPE_NAVIGATION_BAR:
1259             case TYPE_NAVIGATION_BAR_PANEL:
1260             case TYPE_PHONE:
1261             case TYPE_POINTER:
1262             case TYPE_PRIORITY_PHONE:
1263             case TYPE_RECENTS_OVERLAY:
1264             case TYPE_SEARCH_BAR:
1265             case TYPE_STATUS_BAR:
1266             case TYPE_STATUS_BAR_PANEL:
1267             case TYPE_STATUS_BAR_SUB_PANEL:
1268             case TYPE_SYSTEM_DIALOG:
1269             case TYPE_UNIVERSE_BACKGROUND:
1270             case TYPE_VOLUME_OVERLAY:
1271                 break;
1272         }
1273
1274         // Check if third party app has set window to system window type.
1275         return mContext.checkCallingOrSelfPermission(
1276                 android.Manifest.permission.INTERNAL_SYSTEM_WINDOW)
1277                         != PackageManager.PERMISSION_GRANTED;
1278     }
1279
1280     public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
1281         switch (attrs.type) {
1282             case TYPE_SYSTEM_OVERLAY:
1283             case TYPE_SECURE_SYSTEM_OVERLAY:
1284             case TYPE_TOAST:
1285                 // These types of windows can't receive input events.
1286                 attrs.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1287                         | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
1288                 attrs.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
1289                 break;
1290         }
1291     }
1292     
1293     void readLidState() {
1294         mLidState = mWindowManagerFuncs.getLidState();
1295     }
1296     
1297     private boolean isHidden(int accessibilityMode) {
1298         switch (accessibilityMode) {
1299             case 1:
1300                 return mLidState == LID_CLOSED;
1301             case 2:
1302                 return mLidState == LID_OPEN;
1303             default:
1304                 return false;
1305         }
1306     }
1307
1308     private boolean isBuiltInKeyboardVisible() {
1309         return mHaveBuiltInKeyboard && !isHidden(mLidKeyboardAccessibility);
1310     }
1311
1312     /** {@inheritDoc} */
1313     public void adjustConfigurationLw(Configuration config, int keyboardPresence,
1314             int navigationPresence) {
1315         mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
1316
1317         readLidState();
1318         applyLidSwitchState();
1319
1320         if (config.keyboard == Configuration.KEYBOARD_NOKEYS
1321                 || (keyboardPresence == PRESENCE_INTERNAL
1322                         && isHidden(mLidKeyboardAccessibility))) {
1323             config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
1324             if (!mHasSoftInput) {
1325                 config.keyboardHidden = Configuration.KEYBOARDHIDDEN_YES;
1326             }
1327         }
1328
1329         if (config.navigation == Configuration.NAVIGATION_NONAV
1330                 || (navigationPresence == PRESENCE_INTERNAL
1331                         && isHidden(mLidNavigationAccessibility))) {
1332             config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
1333         }
1334     }
1335
1336     /** {@inheritDoc} */
1337     public int windowTypeToLayerLw(int type) {
1338         if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
1339             return 2;
1340         }
1341         switch (type) {
1342         case TYPE_UNIVERSE_BACKGROUND:
1343             return 1;
1344         case TYPE_WALLPAPER:
1345             // wallpaper is at the bottom, though the window manager may move it.
1346             return 2;
1347         case TYPE_PHONE:
1348             return 3;
1349         case TYPE_SEARCH_BAR:
1350             return 4;
1351         case TYPE_RECENTS_OVERLAY:
1352         case TYPE_SYSTEM_DIALOG:
1353             return 5;
1354         case TYPE_TOAST:
1355             // toasts and the plugged-in battery thing
1356             return 6;
1357         case TYPE_PRIORITY_PHONE:
1358             // SIM errors and unlock.  Not sure if this really should be in a high layer.
1359             return 7;
1360         case TYPE_DREAM:
1361             // used for Dreams (screensavers with TYPE_DREAM windows)
1362             return 8;
1363         case TYPE_SYSTEM_ALERT:
1364             // like the ANR / app crashed dialogs
1365             return 9;
1366         case TYPE_INPUT_METHOD:
1367             // on-screen keyboards and other such input method user interfaces go here.
1368             return 10;
1369         case TYPE_INPUT_METHOD_DIALOG:
1370             // on-screen keyboards and other such input method user interfaces go here.
1371             return 11;
1372         case TYPE_KEYGUARD:
1373             // the keyguard; nothing on top of these can take focus, since they are
1374             // responsible for power management when displayed.
1375             return 12;
1376         case TYPE_KEYGUARD_DIALOG:
1377             return 13;
1378         case TYPE_STATUS_BAR_SUB_PANEL:
1379             return 14;
1380         case TYPE_STATUS_BAR:
1381             return 15;
1382         case TYPE_STATUS_BAR_PANEL:
1383             return 16;
1384         case TYPE_VOLUME_OVERLAY:
1385             // the on-screen volume indicator and controller shown when the user
1386             // changes the device volume
1387             return 17;
1388         case TYPE_SYSTEM_OVERLAY:
1389             // the on-screen volume indicator and controller shown when the user
1390             // changes the device volume
1391             return 18;
1392         case TYPE_NAVIGATION_BAR:
1393             // the navigation bar, if available, shows atop most things
1394             return 19;
1395         case TYPE_NAVIGATION_BAR_PANEL:
1396             // some panels (e.g. search) need to show on top of the navigation bar
1397             return 20;
1398         case TYPE_SYSTEM_ERROR:
1399             // system-level error dialogs
1400             return 21;
1401         case TYPE_MAGNIFICATION_OVERLAY:
1402             // used to highlight the magnified portion of a display
1403             return 22;
1404         case TYPE_DISPLAY_OVERLAY:
1405             // used to simulate secondary display devices
1406             return 23;
1407         case TYPE_DRAG:
1408             // the drag layer: input for drag-and-drop is associated with this window,
1409             // which sits above all other focusable windows
1410             return 24;
1411         case TYPE_SECURE_SYSTEM_OVERLAY:
1412             return 25;
1413         case TYPE_BOOT_PROGRESS:
1414             return 26;
1415         case TYPE_POINTER:
1416             // the (mouse) pointer layer
1417             return 27;
1418         case TYPE_HIDDEN_NAV_CONSUMER:
1419             return 28;
1420         }
1421         Log.e(TAG, "Unknown window type: " + type);
1422         return 2;
1423     }
1424
1425     /** {@inheritDoc} */
1426     public int subWindowTypeToLayerLw(int type) {
1427         switch (type) {
1428         case TYPE_APPLICATION_PANEL:
1429         case TYPE_APPLICATION_ATTACHED_DIALOG:
1430             return APPLICATION_PANEL_SUBLAYER;
1431         case TYPE_APPLICATION_MEDIA:
1432             return APPLICATION_MEDIA_SUBLAYER;
1433         case TYPE_APPLICATION_MEDIA_OVERLAY:
1434             return APPLICATION_MEDIA_OVERLAY_SUBLAYER;
1435         case TYPE_APPLICATION_SUB_PANEL:
1436             return APPLICATION_SUB_PANEL_SUBLAYER;
1437         }
1438         Log.e(TAG, "Unknown sub-window type: " + type);
1439         return 0;
1440     }
1441
1442     public int getMaxWallpaperLayer() {
1443         return windowTypeToLayerLw(TYPE_STATUS_BAR);
1444     }
1445
1446     public int getAboveUniverseLayer() {
1447         return windowTypeToLayerLw(TYPE_SYSTEM_ERROR);
1448     }
1449
1450     public boolean hasSystemNavBar() {
1451         return mHasSystemNavBar;
1452     }
1453
1454     public int getNonDecorDisplayWidth(int fullWidth, int fullHeight, int rotation) {
1455         if (mHasNavigationBar) {
1456             // For a basic navigation bar, when we are in landscape mode we place
1457             // the navigation bar to the side.
1458             if (mNavigationBarCanMove && fullWidth > fullHeight) {
1459                 return fullWidth - mNavigationBarWidthForRotation[rotation];
1460             }
1461         }
1462         return fullWidth;
1463     }
1464
1465     public int getNonDecorDisplayHeight(int fullWidth, int fullHeight, int rotation) {
1466         if (mHasSystemNavBar) {
1467             // For the system navigation bar, we always place it at the bottom.
1468             return fullHeight - mNavigationBarHeightForRotation[rotation];
1469         }
1470         if (mHasNavigationBar) {
1471             // For a basic navigation bar, when we are in portrait mode we place
1472             // the navigation bar to the bottom.
1473             if (!mNavigationBarCanMove || fullWidth < fullHeight) {
1474                 return fullHeight - mNavigationBarHeightForRotation[rotation];
1475             }
1476         }
1477         return fullHeight;
1478     }
1479
1480     public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation) {
1481         return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation);
1482     }
1483
1484     public int getConfigDisplayHeight(int fullWidth, int fullHeight, int rotation) {
1485         // If we don't have a system nav bar, then there is a separate status
1486         // bar at the top of the display.  We don't count that as part of the
1487         // fixed decor, since it can hide; however, for purposes of configurations,
1488         // we do want to exclude it since applications can't generally use that part
1489         // of the screen.
1490         if (!mHasSystemNavBar) {
1491             return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation) - mStatusBarHeight;
1492         }
1493         return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation);
1494     }
1495
1496     @Override
1497     public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) {
1498         return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD;
1499     }
1500
1501     @Override
1502     public boolean canBeForceHidden(WindowState win, WindowManager.LayoutParams attrs) {
1503         switch (attrs.type) {
1504             case TYPE_STATUS_BAR:
1505             case TYPE_NAVIGATION_BAR:
1506             case TYPE_WALLPAPER:
1507             case TYPE_DREAM:
1508             case TYPE_UNIVERSE_BACKGROUND:
1509             case TYPE_KEYGUARD:
1510                 return false;
1511             default:
1512                 return true;
1513         }
1514     }
1515
1516     /** {@inheritDoc} */
1517     @Override
1518     public View addStartingWindow(IBinder appToken, String packageName, int theme,
1519             CompatibilityInfo compatInfo, CharSequence nonLocalizedLabel, int labelRes,
1520             int icon, int windowFlags) {
1521         if (!SHOW_STARTING_ANIMATIONS) {
1522             return null;
1523         }
1524         if (packageName == null) {
1525             return null;
1526         }
1527
1528         WindowManager wm = null;
1529         View view = null;
1530
1531         try {
1532             Context context = mContext;
1533             if (DEBUG_STARTING_WINDOW) Slog.d(TAG, "addStartingWindow " + packageName
1534                     + ": nonLocalizedLabel=" + nonLocalizedLabel + " theme="
1535                     + Integer.toHexString(theme));
1536             if (theme != context.getThemeResId() || labelRes != 0) {
1537                 try {
1538                     context = context.createPackageContext(packageName, 0);
1539                     context.setTheme(theme);
1540                 } catch (PackageManager.NameNotFoundException e) {
1541                     // Ignore
1542                 }
1543             }
1544
1545             Window win = PolicyManager.makeNewWindow(context);
1546             final TypedArray ta = win.getWindowStyle();
1547             if (ta.getBoolean(
1548                         com.android.internal.R.styleable.Window_windowDisablePreview, false)
1549                 || ta.getBoolean(
1550                         com.android.internal.R.styleable.Window_windowShowWallpaper,false)) {
1551                 return null;
1552             }
1553
1554             Resources r = context.getResources();
1555             win.setTitle(r.getText(labelRes, nonLocalizedLabel));
1556
1557             win.setType(
1558                 WindowManager.LayoutParams.TYPE_APPLICATION_STARTING);
1559             // Force the window flags: this is a fake window, so it is not really
1560             // touchable or focusable by the user.  We also add in the ALT_FOCUSABLE_IM
1561             // flag because we do know that the next window will take input
1562             // focus, so we want to get the IME window up on top of us right away.
1563             win.setFlags(
1564                 windowFlags|
1565                 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
1566                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
1567                 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
1568                 windowFlags|
1569                 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
1570                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
1571                 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
1572
1573             if (!compatInfo.supportsScreen()) {
1574                 win.addFlags(WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW);
1575             }
1576
1577             win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
1578                     WindowManager.LayoutParams.MATCH_PARENT);
1579
1580             final WindowManager.LayoutParams params = win.getAttributes();
1581             params.token = appToken;
1582             params.packageName = packageName;
1583             params.windowAnimations = win.getWindowStyle().getResourceId(
1584                     com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
1585             params.privateFlags |=
1586                     WindowManager.LayoutParams.PRIVATE_FLAG_FAKE_HARDWARE_ACCELERATED;
1587             params.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
1588             params.setTitle("Starting " + packageName);
1589
1590             wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
1591             view = win.getDecorView();
1592
1593             if (win.isFloating()) {
1594                 // Whoops, there is no way to display an animation/preview
1595                 // of such a thing!  After all that work...  let's skip it.
1596                 // (Note that we must do this here because it is in
1597                 // getDecorView() where the theme is evaluated...  maybe
1598                 // we should peek the floating attribute from the theme
1599                 // earlier.)
1600                 return null;
1601             }
1602
1603             if (DEBUG_STARTING_WINDOW) Slog.d(
1604                 TAG, "Adding starting window for " + packageName
1605                 + " / " + appToken + ": "
1606                 + (view.getParent() != null ? view : null));
1607
1608             wm.addView(view, params);
1609
1610             // Only return the view if it was successfully added to the
1611             // window manager... which we can tell by it having a parent.
1612             return view.getParent() != null ? view : null;
1613         } catch (WindowManager.BadTokenException e) {
1614             // ignore
1615             Log.w(TAG, appToken + " already running, starting window not displayed");
1616         } catch (RuntimeException e) {
1617             // don't crash if something else bad happens, for example a
1618             // failure loading resources because we are loading from an app
1619             // on external storage that has been unmounted.
1620             Log.w(TAG, appToken + " failed creating starting window", e);
1621         } finally {
1622             if (view != null && view.getParent() == null) {
1623                 Log.w(TAG, "view not successfully added to wm, removing view");
1624                 wm.removeViewImmediate(view);
1625             }
1626         }
1627
1628         return null;
1629     }
1630
1631     /** {@inheritDoc} */
1632     public void removeStartingWindow(IBinder appToken, View window) {
1633         if (DEBUG_STARTING_WINDOW) {
1634             RuntimeException e = new RuntimeException("here");
1635             e.fillInStackTrace();
1636             Log.v(TAG, "Removing starting window for " + appToken + ": " + window, e);
1637         }
1638
1639         if (window != null) {
1640             WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
1641             wm.removeView(window);
1642         }
1643     }
1644
1645     /**
1646      * Preflight adding a window to the system.
1647      * 
1648      * Currently enforces that three window types are singletons:
1649      * <ul>
1650      * <li>STATUS_BAR_TYPE</li>
1651      * <li>KEYGUARD_TYPE</li>
1652      * </ul>
1653      * 
1654      * @param win The window to be added
1655      * @param attrs Information about the window to be added
1656      * 
1657      * @return If ok, WindowManagerImpl.ADD_OKAY.  If too many singletons,
1658      * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
1659      */
1660     public int prepareAddWindowLw(WindowState win, WindowManager.LayoutParams attrs) {
1661         switch (attrs.type) {
1662             case TYPE_STATUS_BAR:
1663                 mContext.enforceCallingOrSelfPermission(
1664                         android.Manifest.permission.STATUS_BAR_SERVICE,
1665                         "PhoneWindowManager");
1666                 if (mStatusBar != null) {
1667                     if (mStatusBar.isAlive()) {
1668                         return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
1669                     }
1670                 }
1671                 mStatusBar = win;
1672                 break;
1673             case TYPE_NAVIGATION_BAR:
1674                 mContext.enforceCallingOrSelfPermission(
1675                         android.Manifest.permission.STATUS_BAR_SERVICE,
1676                         "PhoneWindowManager");
1677                 if (mNavigationBar != null) {
1678                     if (mNavigationBar.isAlive()) {
1679                         return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
1680                     }
1681                 }
1682                 mNavigationBar = win;
1683                 if (DEBUG_LAYOUT) Log.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
1684                 break;
1685             case TYPE_NAVIGATION_BAR_PANEL:
1686                 mContext.enforceCallingOrSelfPermission(
1687                         android.Manifest.permission.STATUS_BAR_SERVICE,
1688                         "PhoneWindowManager");
1689                 break;
1690             case TYPE_STATUS_BAR_PANEL:
1691                 mContext.enforceCallingOrSelfPermission(
1692                         android.Manifest.permission.STATUS_BAR_SERVICE,
1693                         "PhoneWindowManager");
1694                 break;
1695             case TYPE_STATUS_BAR_SUB_PANEL:
1696                 mContext.enforceCallingOrSelfPermission(
1697                         android.Manifest.permission.STATUS_BAR_SERVICE,
1698                         "PhoneWindowManager");
1699                 break;
1700             case TYPE_KEYGUARD:
1701                 if (mKeyguard != null) {
1702                     return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
1703                 }
1704                 mKeyguard = win;
1705                 break;
1706         }
1707         return WindowManagerGlobal.ADD_OKAY;
1708     }
1709
1710     /** {@inheritDoc} */
1711     public void removeWindowLw(WindowState win) {
1712         if (mStatusBar == win) {
1713             mStatusBar = null;
1714         } else if (mKeyguard == win) {
1715             mKeyguard = null;
1716         } else if (mNavigationBar == win) {
1717             mNavigationBar = null;
1718         }
1719     }
1720
1721     static final boolean PRINT_ANIM = false;
1722     
1723     /** {@inheritDoc} */
1724     public int selectAnimationLw(WindowState win, int transit) {
1725         if (PRINT_ANIM) Log.i(TAG, "selectAnimation in " + win
1726               + ": transit=" + transit);
1727         if (win == mStatusBar) {
1728             if (transit == TRANSIT_EXIT || transit == TRANSIT_HIDE) {
1729                 return R.anim.dock_top_exit;
1730             } else if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) {
1731                 return R.anim.dock_top_enter;
1732             }
1733         } else if (win == mNavigationBar) {
1734             // This can be on either the bottom or the right.
1735             if (mNavigationBarOnBottom) {
1736                 if (transit == TRANSIT_EXIT || transit == TRANSIT_HIDE) {
1737                     return R.anim.dock_bottom_exit;
1738                 } else if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) {
1739                     return R.anim.dock_bottom_enter;
1740                 }
1741             } else {
1742                 if (transit == TRANSIT_EXIT || transit == TRANSIT_HIDE) {
1743                     return R.anim.dock_right_exit;
1744                 } else if (transit == TRANSIT_ENTER || transit == TRANSIT_SHOW) {
1745                     return R.anim.dock_right_enter;
1746                 }
1747             }
1748         } if (transit == TRANSIT_PREVIEW_DONE) {
1749             if (win.hasAppShownWindows()) {
1750                 if (PRINT_ANIM) Log.i(TAG, "**** STARTING EXIT");
1751                 return com.android.internal.R.anim.app_starting_exit;
1752             }
1753         } else if (win.getAttrs().type == TYPE_DREAM && mDreamingLockscreen
1754                 && transit == TRANSIT_ENTER) {
1755             // Special case: we are animating in a dream, while the keyguard
1756             // is shown.  We don't want an animation on the dream, because
1757             // we need it shown immediately with the keyguard animating away
1758             // to reveal it.
1759             return -1;
1760         }
1761
1762         return 0;
1763     }
1764
1765     public Animation createForceHideEnterAnimation(boolean onWallpaper) {
1766         return AnimationUtils.loadAnimation(mContext, onWallpaper
1767                 ? com.android.internal.R.anim.lock_screen_wallpaper_behind_enter
1768                 : com.android.internal.R.anim.lock_screen_behind_enter);
1769     }
1770     
1771     static ITelephony getTelephonyService() {
1772         return ITelephony.Stub.asInterface(
1773                 ServiceManager.checkService(Context.TELEPHONY_SERVICE));
1774     }
1775
1776     static IAudioService getAudioService() {
1777         IAudioService audioService = IAudioService.Stub.asInterface(
1778                 ServiceManager.checkService(Context.AUDIO_SERVICE));
1779         if (audioService == null) {
1780             Log.w(TAG, "Unable to find IAudioService interface.");
1781         }
1782         return audioService;
1783     }
1784
1785     boolean keyguardOn() {
1786         return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode();
1787     }
1788
1789     private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
1790             WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
1791             WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
1792         };
1793
1794     /** {@inheritDoc} */
1795     @Override
1796     public long interceptKeyBeforeDispatching(WindowState win, KeyEvent event, int policyFlags) {
1797         final boolean keyguardOn = keyguardOn();
1798         final int keyCode = event.getKeyCode();
1799         final int repeatCount = event.getRepeatCount();
1800         final int metaState = event.getMetaState();
1801         final int flags = event.getFlags();
1802         final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
1803         final boolean canceled = event.isCanceled();
1804
1805         if (DEBUG_INPUT) {
1806             Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
1807                     + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
1808                     + " canceled=" + canceled);
1809         }
1810
1811         // If we think we might have a volume down & power key chord on the way
1812         // but we're not sure, then tell the dispatcher to wait a little while and
1813         // try again later before dispatching.
1814         if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
1815             if (mVolumeDownKeyTriggered && !mPowerKeyTriggered) {
1816                 final long now = SystemClock.uptimeMillis();
1817                 final long timeoutTime = mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
1818                 if (now < timeoutTime) {
1819                     return timeoutTime - now;
1820                 }
1821             }
1822             if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
1823                     && mVolumeDownKeyConsumedByScreenshotChord) {
1824                 if (!down) {
1825                     mVolumeDownKeyConsumedByScreenshotChord = false;
1826                 }
1827                 return -1;
1828             }
1829         }
1830
1831         // First we always handle the home key here, so applications
1832         // can never break it, although if keyguard is on, we do let
1833         // it handle it, because that gives us the correct 5 second
1834         // timeout.
1835         if (keyCode == KeyEvent.KEYCODE_HOME) {
1836
1837             // If we have released the home key, and didn't do anything else
1838             // while it was pressed, then it is time to go home!
1839             if (!down) {
1840                 final boolean homeWasLongPressed = mHomeLongPressed;
1841                 mHomePressed = false;
1842                 mHomeLongPressed = false;
1843                 if (!homeWasLongPressed) {
1844                     if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
1845                         try {
1846                             IStatusBarService statusbar = getStatusBarService();
1847                             if (statusbar != null) {
1848                                 statusbar.cancelPreloadRecentApps();
1849                             }
1850                         } catch (RemoteException e) {
1851                             Slog.e(TAG, "RemoteException when showing recent apps", e);
1852                             // re-acquire status bar service next time it is needed.
1853                             mStatusBarService = null;
1854                         }
1855                     }
1856
1857                     mHomePressed = false;
1858                     if (!canceled) {
1859                         // If an incoming call is ringing, HOME is totally disabled.
1860                         // (The user is already on the InCallScreen at this point,
1861                         // and his ONLY options are to answer or reject the call.)
1862                         boolean incomingRinging = false;
1863                         try {
1864                             ITelephony telephonyService = getTelephonyService();
1865                             if (telephonyService != null) {
1866                                 incomingRinging = telephonyService.isRinging();
1867                             }
1868                         } catch (RemoteException ex) {
1869                             Log.w(TAG, "RemoteException from getPhoneInterface()", ex);
1870                         }
1871
1872                         if (incomingRinging) {
1873                             Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
1874                         } else {
1875                             launchHomeFromHotKey();
1876                         }
1877                     } else {
1878                         Log.i(TAG, "Ignoring HOME; event canceled.");
1879                     }
1880                     return -1;
1881                 }
1882             }
1883
1884             // If a system window has focus, then it doesn't make sense
1885             // right now to interact with applications.
1886             WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
1887             if (attrs != null) {
1888                 final int type = attrs.type;
1889                 if (type == WindowManager.LayoutParams.TYPE_KEYGUARD
1890                         || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {
1891                     // the "app" is keyguard, so give it the key
1892                     return 0;
1893                 }
1894                 final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
1895                 for (int i=0; i<typeCount; i++) {
1896                     if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
1897                         // don't do anything, but also don't pass it to the app
1898                         return -1;
1899                     }
1900                 }
1901             }
1902             if (down) {
1903                 if (!mHomePressed && mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
1904                     try {
1905                         IStatusBarService statusbar = getStatusBarService();
1906                         if (statusbar != null) {
1907                             statusbar.preloadRecentApps();
1908                         }
1909                     } catch (RemoteException e) {
1910                         Slog.e(TAG, "RemoteException when preloading recent apps", e);
1911                         // re-acquire status bar service next time it is needed.
1912                         mStatusBarService = null;
1913                     }
1914                 }
1915                 if (repeatCount == 0) {
1916                     mHomePressed = true;
1917                 } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
1918                     if (!keyguardOn) {
1919                         handleLongPressOnHome();
1920                     }
1921                 }
1922             }
1923             return -1;
1924         } else if (keyCode == KeyEvent.KEYCODE_MENU) {
1925             // Hijack modified menu keys for debugging features
1926             final int chordBug = KeyEvent.META_SHIFT_ON;
1927
1928             if (down && repeatCount == 0) {
1929                 if (mEnableShiftMenuBugReports && (metaState & chordBug) == chordBug) {
1930                     Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
1931                     mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT,
1932                             null, null, null, 0, null, null);
1933                     return -1;
1934                 } else if (SHOW_PROCESSES_ON_ALT_MENU &&
1935                         (metaState & KeyEvent.META_ALT_ON) == KeyEvent.META_ALT_ON) {
1936                     Intent service = new Intent();
1937                     service.setClassName(mContext, "com.android.server.LoadAverageService");
1938                     ContentResolver res = mContext.getContentResolver();
1939                     boolean shown = Settings.Global.getInt(
1940                             res, Settings.Global.SHOW_PROCESSES, 0) != 0;
1941                     if (!shown) {
1942                         mContext.startService(service);
1943                     } else {
1944                         mContext.stopService(service);
1945                     }
1946                     Settings.Global.putInt(
1947                             res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
1948                     return -1;
1949                 }
1950             }
1951         } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
1952             if (down) {
1953                 if (repeatCount == 0) {
1954                     mSearchKeyShortcutPending = true;
1955                     mConsumeSearchKeyUp = false;
1956                 }
1957             } else {
1958                 mSearchKeyShortcutPending = false;
1959                 if (mConsumeSearchKeyUp) {
1960                     mConsumeSearchKeyUp = false;
1961                     return -1;
1962                 }
1963             }
1964             return 0;
1965         } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
1966             if (down && repeatCount == 0 && !keyguardOn) {
1967                 showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS);
1968             }
1969             return -1;
1970         } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
1971             if (down) {
1972                 if (repeatCount == 0) {
1973                     mAssistKeyLongPressed = false;
1974                 } else if (repeatCount == 1) {
1975                     mAssistKeyLongPressed = true;
1976                     if (!keyguardOn) {
1977                          launchAssistLongPressAction();
1978                     }
1979                 }
1980             } else {
1981                 if (mAssistKeyLongPressed) {
1982                     mAssistKeyLongPressed = false;
1983                 } else {
1984                     if (!keyguardOn) {
1985                         launchAssistAction();
1986                     }
1987                 }
1988             }
1989             return -1;
1990         }
1991
1992         // Shortcuts are invoked through Search+key, so intercept those here
1993         // Any printing key that is chorded with Search should be consumed
1994         // even if no shortcut was invoked.  This prevents text from being
1995         // inadvertently inserted when using a keyboard that has built-in macro
1996         // shortcut keys (that emit Search+x) and some of them are not registered.
1997         if (mSearchKeyShortcutPending) {
1998             final KeyCharacterMap kcm = event.getKeyCharacterMap();
1999             if (kcm.isPrintingKey(keyCode)) {
2000                 mConsumeSearchKeyUp = true;
2001                 mSearchKeyShortcutPending = false;
2002                 if (down && repeatCount == 0 && !keyguardOn) {
2003                     Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode, metaState);
2004                     if (shortcutIntent != null) {
2005                         shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2006                         try {
2007                             mContext.startActivity(shortcutIntent);
2008                         } catch (ActivityNotFoundException ex) {
2009                             Slog.w(TAG, "Dropping shortcut key combination because "
2010                                     + "the activity to which it is registered was not found: "
2011                                     + "SEARCH+" + KeyEvent.keyCodeToString(keyCode), ex);
2012                         }
2013                     } else {
2014                         Slog.i(TAG, "Dropping unregistered shortcut key combination: "
2015                                 + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
2016                     }
2017                 }
2018                 return -1;
2019             }
2020         }
2021
2022         // Invoke shortcuts using Meta.
2023         if (down && repeatCount == 0 && !keyguardOn
2024                 && (metaState & KeyEvent.META_META_ON) != 0) {
2025             final KeyCharacterMap kcm = event.getKeyCharacterMap();
2026             if (kcm.isPrintingKey(keyCode)) {
2027                 Intent shortcutIntent = mShortcutManager.getIntent(kcm, keyCode,
2028                         metaState & ~(KeyEvent.META_META_ON
2029                                 | KeyEvent.META_META_LEFT_ON | KeyEvent.META_META_RIGHT_ON));
2030                 if (shortcutIntent != null) {
2031                     shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2032                     try {
2033                         mContext.startActivity(shortcutIntent);
2034                     } catch (ActivityNotFoundException ex) {
2035                         Slog.w(TAG, "Dropping shortcut key combination because "
2036                                 + "the activity to which it is registered was not found: "
2037                                 + "META+" + KeyEvent.keyCodeToString(keyCode), ex);
2038                     }
2039                     return -1;
2040                 }
2041             }
2042         }
2043
2044         // Handle application launch keys.
2045         if (down && repeatCount == 0 && !keyguardOn) {
2046             String category = sApplicationLaunchKeyCategories.get(keyCode);
2047             if (category != null) {
2048                 Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, category);
2049                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2050                 try {
2051                     mContext.startActivity(intent);
2052                 } catch (ActivityNotFoundException ex) {
2053                     Slog.w(TAG, "Dropping application launch key because "
2054                             + "the activity to which it is registered was not found: "
2055                             + "keyCode=" + keyCode + ", category=" + category, ex);
2056                 }
2057                 return -1;
2058             }
2059         }
2060
2061         // Display task switcher for ALT-TAB or Meta-TAB.
2062         if (down && repeatCount == 0 && keyCode == KeyEvent.KEYCODE_TAB) {
2063             if (mRecentAppsDialogHeldModifiers == 0 && !keyguardOn) {
2064                 final int shiftlessModifiers = event.getModifiers() & ~KeyEvent.META_SHIFT_MASK;
2065                 if (KeyEvent.metaStateHasModifiers(shiftlessModifiers, KeyEvent.META_ALT_ON)
2066                         || KeyEvent.metaStateHasModifiers(
2067                                 shiftlessModifiers, KeyEvent.META_META_ON)) {
2068                     mRecentAppsDialogHeldModifiers = shiftlessModifiers;
2069                     showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW);
2070                     return -1;
2071                 }
2072             }
2073         } else if (!down && mRecentAppsDialogHeldModifiers != 0
2074                 && (metaState & mRecentAppsDialogHeldModifiers) == 0) {
2075             mRecentAppsDialogHeldModifiers = 0;
2076             showOrHideRecentAppsDialog(keyguardOn ? RECENT_APPS_BEHAVIOR_DISMISS :
2077                     RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH);
2078         }
2079
2080         // Handle keyboard language switching.
2081         if (down && repeatCount == 0
2082                 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
2083                         || (keyCode == KeyEvent.KEYCODE_SPACE
2084                                 && (metaState & KeyEvent.META_CTRL_MASK) != 0))) {
2085             int direction = (metaState & KeyEvent.META_SHIFT_MASK) != 0 ? -1 : 1;
2086             mWindowManagerFuncs.switchKeyboardLayout(event.getDeviceId(), direction);
2087             return -1;
2088         }
2089         if (mLanguageSwitchKeyPressed && !down
2090                 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
2091                         || keyCode == KeyEvent.KEYCODE_SPACE)) {
2092             mLanguageSwitchKeyPressed = false;
2093             return -1;
2094         }
2095
2096         // Let the application handle the key.
2097         return 0;
2098     }
2099
2100     /** {@inheritDoc} */
2101     @Override
2102     public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
2103         // Note: This method is only called if the initial down was unhandled.
2104         if (DEBUG_INPUT) {
2105             Slog.d(TAG, "Unhandled key: win=" + win + ", action=" + event.getAction()
2106                     + ", flags=" + event.getFlags()
2107                     + ", keyCode=" + event.getKeyCode()
2108                     + ", scanCode=" + event.getScanCode()
2109                     + ", metaState=" + event.getMetaState()
2110                     + ", repeatCount=" + event.getRepeatCount()
2111                     + ", policyFlags=" + policyFlags);
2112         }
2113
2114         KeyEvent fallbackEvent = null;
2115         if ((event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
2116             final KeyCharacterMap kcm = event.getKeyCharacterMap();
2117             final int keyCode = event.getKeyCode();
2118             final int metaState = event.getMetaState();
2119             final boolean initialDown = event.getAction() == KeyEvent.ACTION_DOWN
2120                     && event.getRepeatCount() == 0;
2121
2122             // Check for fallback actions specified by the key character map.
2123             final FallbackAction fallbackAction;
2124             if (initialDown) {
2125                 fallbackAction = kcm.getFallbackAction(keyCode, metaState);
2126             } else {
2127                 fallbackAction = mFallbackActions.get(keyCode);
2128             }
2129
2130             if (fallbackAction != null) {
2131                 if (DEBUG_INPUT) {
2132                     Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
2133                             + " metaState=" + Integer.toHexString(fallbackAction.metaState));
2134                 }
2135
2136                 final int flags = event.getFlags() | KeyEvent.FLAG_FALLBACK;
2137                 fallbackEvent = KeyEvent.obtain(
2138                         event.getDownTime(), event.getEventTime(),
2139                         event.getAction(), fallbackAction.keyCode,
2140                         event.getRepeatCount(), fallbackAction.metaState,
2141                         event.getDeviceId(), event.getScanCode(),
2142                         flags, event.getSource(), null);
2143
2144                 if (!interceptFallback(win, fallbackEvent, policyFlags)) {
2145                     fallbackEvent.recycle();
2146                     fallbackEvent = null;
2147                 }
2148
2149                 if (initialDown) {
2150                     mFallbackActions.put(keyCode, fallbackAction);
2151                 } else if (event.getAction() == KeyEvent.ACTION_UP) {
2152                     mFallbackActions.remove(keyCode);
2153                     fallbackAction.recycle();
2154                 }
2155             }
2156         }
2157
2158         if (DEBUG_INPUT) {
2159             if (fallbackEvent == null) {
2160                 Slog.d(TAG, "No fallback.");
2161             } else {
2162                 Slog.d(TAG, "Performing fallback: " + fallbackEvent);
2163             }
2164         }
2165         return fallbackEvent;
2166     }
2167
2168     private boolean interceptFallback(WindowState win, KeyEvent fallbackEvent, int policyFlags) {
2169         int actions = interceptKeyBeforeQueueing(fallbackEvent, policyFlags, true);
2170         if ((actions & ACTION_PASS_TO_USER) != 0) {
2171             long delayMillis = interceptKeyBeforeDispatching(
2172                     win, fallbackEvent, policyFlags);
2173             if (delayMillis == 0) {
2174                 return true;
2175             }
2176         }
2177         return false;
2178     }
2179
2180     private void launchAssistLongPressAction() {
2181         performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
2182         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
2183
2184         // launch the search activity
2185         Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
2186         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2187         try {
2188             // TODO: This only stops the factory-installed search manager.  
2189             // Need to formalize an API to handle others
2190             SearchManager searchManager = getSearchManager();
2191             if (searchManager != null) {
2192                 searchManager.stopSearch();
2193             }
2194             mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
2195         } catch (ActivityNotFoundException e) {
2196             Slog.w(TAG, "No activity to handle assist long press action.", e);
2197         }
2198     }
2199
2200     private void launchAssistAction() {
2201         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
2202         Intent intent = ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE))
2203                 .getAssistIntent(mContext, UserHandle.USER_CURRENT);
2204         if (intent != null) {
2205             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
2206                     | Intent.FLAG_ACTIVITY_SINGLE_TOP
2207                     | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2208             try {
2209                 mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
2210             } catch (ActivityNotFoundException e) {
2211                 Slog.w(TAG, "No activity to handle assist action.", e);
2212             }
2213         }
2214     }
2215
2216     private SearchManager getSearchManager() {
2217         if (mSearchManager == null) {
2218             mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
2219         }
2220         return mSearchManager;
2221     }
2222
2223     /**
2224      * A home key -> launch home action was detected.  Take the appropriate action
2225      * given the situation with the keyguard.
2226      */
2227     void launchHomeFromHotKey() {
2228         if (mKeyguardMediator != null && mKeyguardMediator.isShowingAndNotHidden()) {
2229             // don't launch home if keyguard showing
2230         } else if (!mHideLockScreen && mKeyguardMediator.isInputRestricted()) {
2231             // when in keyguard restricted mode, must first verify unlock
2232             // before launching home
2233             mKeyguardMediator.verifyUnlock(new OnKeyguardExitResult() {
2234                 public void onKeyguardExitResult(boolean success) {
2235                     if (success) {
2236                         try {
2237                             ActivityManagerNative.getDefault().stopAppSwitches();
2238                         } catch (RemoteException e) {
2239                         }
2240                         sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
2241                         startDockOrHome();
2242                     }
2243                 }
2244             });
2245         } else {
2246             // no keyguard stuff to worry about, just launch home!
2247             try {
2248                 ActivityManagerNative.getDefault().stopAppSwitches();
2249             } catch (RemoteException e) {
2250             }
2251             sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
2252             startDockOrHome();
2253         }
2254     }
2255
2256     /**
2257      * A delayed callback use to determine when it is okay to re-allow applications
2258      * to use certain system UI flags.  This is used to prevent applications from
2259      * spamming system UI changes that prevent the navigation bar from being shown.
2260      */
2261     final Runnable mAllowSystemUiDelay = new Runnable() {
2262         @Override public void run() {
2263         }
2264     };
2265
2266     /**
2267      * Input handler used while nav bar is hidden.  Captures any touch on the screen,
2268      * to determine when the nav bar should be shown and prevent applications from
2269      * receiving those touches.
2270      */
2271     final class HideNavInputEventReceiver extends InputEventReceiver {
2272         public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
2273             super(inputChannel, looper);
2274         }
2275
2276         @Override
2277         public void onInputEvent(InputEvent event) {
2278             boolean handled = false;
2279             try {
2280                 if (event instanceof MotionEvent
2281                         && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2282                     final MotionEvent motionEvent = (MotionEvent)event;
2283                     if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
2284                         // When the user taps down, we re-show the nav bar.
2285                         boolean changed = false;
2286                         synchronized (mLock) {
2287                             // Any user activity always causes us to show the
2288                             // navigation controls, if they had been hidden.
2289                             // We also clear the low profile and only content
2290                             // flags so that tapping on the screen will atomically
2291                             // restore all currently hidden screen decorations.
2292                             int newVal = mResettingSystemUiFlags |
2293                                     View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2294                                     View.SYSTEM_UI_FLAG_LOW_PROFILE |
2295                                     View.SYSTEM_UI_FLAG_FULLSCREEN;
2296                             if (mResettingSystemUiFlags != newVal) {
2297                                 mResettingSystemUiFlags = newVal;
2298                                 changed = true;
2299                             }
2300                             // We don't allow the system's nav bar to be hidden
2301                             // again for 1 second, to prevent applications from
2302                             // spamming us and keeping it from being shown.
2303                             newVal = mForceClearedSystemUiFlags |
2304                                     View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
2305                             if (mForceClearedSystemUiFlags != newVal) {
2306                                 mForceClearedSystemUiFlags = newVal;
2307                                 changed = true;
2308                                 mHandler.postDelayed(new Runnable() {
2309                                     @Override public void run() {
2310                                         synchronized (mLock) {
2311                                             // Clear flags.
2312                                             mForceClearedSystemUiFlags &=
2313                                                     ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
2314                                         }
2315                                         mWindowManagerFuncs.reevaluateStatusBarVisibility();
2316                                     }
2317                                 }, 1000);
2318                             }
2319                         }
2320                         if (changed) {
2321                             mWindowManagerFuncs.reevaluateStatusBarVisibility();
2322                         }
2323                     }
2324                 }
2325             } finally {
2326                 finishInputEvent(event, handled);
2327             }
2328         }
2329     }
2330     final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
2331             new InputEventReceiver.Factory() {
2332         @Override
2333         public InputEventReceiver createInputEventReceiver(
2334                 InputChannel inputChannel, Looper looper) {
2335             return new HideNavInputEventReceiver(inputChannel, looper);
2336         }
2337     };
2338
2339     @Override
2340     public int adjustSystemUiVisibilityLw(int visibility) {
2341         // Reset any bits in mForceClearingStatusBarVisibility that
2342         // are now clear.
2343         mResettingSystemUiFlags &= visibility;
2344         // Clear any bits in the new visibility that are currently being
2345         // force cleared, before reporting it.
2346         return visibility & ~mResettingSystemUiFlags
2347                 & ~mForceClearedSystemUiFlags;
2348     }
2349
2350     @Override
2351     public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
2352         final int fl = attrs.flags;
2353         final int systemUiVisibility = (attrs.systemUiVisibility|attrs.subtreeSystemUiVisibility);
2354
2355         if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR))
2356                 == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)) {
2357             int availRight, availBottom;
2358             if (mCanHideNavigationBar &&
2359                     (systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0) {
2360                 availRight = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
2361                 availBottom = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
2362             } else {
2363                 availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
2364                 availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
2365             }
2366             if ((systemUiVisibility & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
2367                 if ((fl & FLAG_FULLSCREEN) != 0) {
2368                     contentInset.set(mStableFullscreenLeft, mStableFullscreenTop,
2369                             availRight - mStableFullscreenRight,
2370                             availBottom - mStableFullscreenBottom);
2371                 } else {
2372                     contentInset.set(mStableLeft, mStableTop,
2373                             availRight - mStableRight, availBottom - mStableBottom);
2374                 }
2375             } else if ((fl & FLAG_FULLSCREEN) != 0) {
2376                 contentInset.setEmpty();
2377             } else if ((systemUiVisibility & (View.SYSTEM_UI_FLAG_FULLSCREEN
2378                         | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)) == 0) {
2379                 contentInset.set(mCurLeft, mCurTop,
2380                         availRight - mCurRight, availBottom - mCurBottom);
2381             } else {
2382                 contentInset.set(mCurLeft, mCurTop,
2383                         availRight - mCurRight, availBottom - mCurBottom);
2384             }
2385             return;
2386         }
2387         contentInset.setEmpty();
2388     }
2389
2390     /** {@inheritDoc} */
2391     @Override
2392     public void beginLayoutLw(boolean isDefaultDisplay, int displayWidth, int displayHeight,
2393                               int displayRotation) {
2394         mUnrestrictedScreenLeft = mUnrestrictedScreenTop = 0;
2395         mUnrestrictedScreenWidth = displayWidth;
2396         mUnrestrictedScreenHeight = displayHeight;
2397         mRestrictedScreenLeft = mRestrictedScreenTop = 0;
2398         mRestrictedScreenWidth = displayWidth;
2399         mRestrictedScreenHeight = displayHeight;
2400         mDockLeft = mContentLeft = mStableLeft = mStableFullscreenLeft
2401                 = mSystemLeft = mCurLeft = 0;
2402         mDockTop = mContentTop = mStableTop = mStableFullscreenTop
2403                 = mSystemTop = mCurTop = 0;
2404         mDockRight = mContentRight = mStableRight = mStableFullscreenRight
2405                 = mSystemRight = mCurRight = displayWidth;
2406         mDockBottom = mContentBottom = mStableBottom = mStableFullscreenBottom
2407                 = mSystemBottom = mCurBottom = displayHeight;
2408         mDockLayer = 0x10000000;
2409         mStatusBarLayer = -1;
2410
2411         // start with the current dock rect, which will be (0,0,displayWidth,displayHeight)
2412         final Rect pf = mTmpParentFrame;
2413         final Rect df = mTmpDisplayFrame;
2414         final Rect vf = mTmpVisibleFrame;
2415         pf.left = df.left = vf.left = mDockLeft;
2416         pf.top = df.top = vf.top = mDockTop;
2417         pf.right = df.right = vf.right = mDockRight;
2418         pf.bottom = df.bottom = vf.bottom = mDockBottom;
2419
2420         if (isDefaultDisplay) {
2421             // For purposes of putting out fake window up to steal focus, we will
2422             // drive nav being hidden only by whether it is requested.
2423             boolean navVisible = (mLastSystemUiFlags&View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
2424
2425             // When the navigation bar isn't visible, we put up a fake
2426             // input window to catch all touch events.  This way we can
2427             // detect when the user presses anywhere to bring back the nav
2428             // bar and ensure the application doesn't see the event.
2429             if (navVisible) {
2430                 if (mHideNavFakeWindow != null) {
2431                     mHideNavFakeWindow.dismiss();
2432                     mHideNavFakeWindow = null;
2433                 }
2434             } else if (mHideNavFakeWindow == null) {
2435                 mHideNavFakeWindow = mWindowManagerFuncs.addFakeWindow(
2436                         mHandler.getLooper(), mHideNavInputEventReceiverFactory,
2437                         "hidden nav", WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER,
2438                         0, false, false, true);
2439             }
2440
2441             // For purposes of positioning and showing the nav bar, if we have
2442             // decided that it can't be hidden (because of the screen aspect ratio),
2443             // then take that into account.
2444             navVisible |= !mCanHideNavigationBar;
2445
2446             if (mNavigationBar != null) {
2447                 // Force the navigation bar to its appropriate place and
2448                 // size.  We need to do this directly, instead of relying on
2449                 // it to bubble up from the nav bar, because this needs to
2450                 // change atomically with screen rotations.
2451                 mNavigationBarOnBottom = (!mNavigationBarCanMove || displayWidth < displayHeight);
2452                 if (mNavigationBarOnBottom) {
2453                     // It's a system nav bar or a portrait screen; nav bar goes on bottom.
2454                     int top = displayHeight - mNavigationBarHeightForRotation[displayRotation];
2455                     mTmpNavigationFrame.set(0, top, displayWidth, displayHeight);
2456                     mStableBottom = mStableFullscreenBottom = mTmpNavigationFrame.top;
2457                     if (navVisible) {
2458                         mNavigationBar.showLw(true);
2459                         mDockBottom = mTmpNavigationFrame.top;
2460                         mRestrictedScreenHeight = mDockBottom - mDockTop;
2461                     } else {
2462                         // We currently want to hide the navigation UI.
2463                         mNavigationBar.hideLw(true);
2464                     }
2465                     if (navVisible && !mNavigationBar.isAnimatingLw()) {
2466                         // If the nav bar is currently requested to be visible,
2467                         // and not in the process of animating on or off, then
2468                         // we can tell the app that it is covered by it.
2469                         mSystemBottom = mTmpNavigationFrame.top;
2470                     }
2471                 } else {
2472                     // Landscape screen; nav bar goes to the right.
2473                     int left = displayWidth - mNavigationBarWidthForRotation[displayRotation];
2474                     mTmpNavigationFrame.set(left, 0, displayWidth, displayHeight);
2475                     mStableRight = mStableFullscreenRight = mTmpNavigationFrame.left;
2476                     if (navVisible) {
2477                         mNavigationBar.showLw(true);
2478                         mDockRight = mTmpNavigationFrame.left;
2479                         mRestrictedScreenWidth = mDockRight - mDockLeft;
2480                     } else {
2481                         // We currently want to hide the navigation UI.
2482                         mNavigationBar.hideLw(true);
2483                     }
2484                     if (navVisible && !mNavigationBar.isAnimatingLw()) {
2485                         // If the nav bar is currently requested to be visible,
2486                         // and not in the process of animating on or off, then
2487                         // we can tell the app that it is covered by it.
2488                         mSystemRight = mTmpNavigationFrame.left;
2489                     }
2490                 }
2491                 // Make sure the content and current rectangles are updated to
2492                 // account for the restrictions from the navigation bar.
2493                 mContentTop = mCurTop = mDockTop;
2494                 mContentBottom = mCurBottom = mDockBottom;
2495                 mContentLeft = mCurLeft = mDockLeft;
2496                 mContentRight = mCurRight = mDockRight;
2497                 mStatusBarLayer = mNavigationBar.getSurfaceLayer();
2498                 // And compute the final frame.
2499                 mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
2500                         mTmpNavigationFrame, mTmpNavigationFrame);
2501                 if (DEBUG_LAYOUT) Log.i(TAG, "mNavigationBar frame: " + mTmpNavigationFrame);
2502             }
2503             if (DEBUG_LAYOUT) Log.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
2504                     mDockLeft, mDockTop, mDockRight, mDockBottom));
2505
2506             // decide where the status bar goes ahead of time
2507             if (mStatusBar != null) {
2508                 // apply any navigation bar insets
2509                 pf.left = df.left = mUnrestrictedScreenLeft;
2510                 pf.top = df.top = mUnrestrictedScreenTop;
2511                 pf.right = df.right = mUnrestrictedScreenWidth - mUnrestrictedScreenLeft;
2512                 pf.bottom = df.bottom = mUnrestrictedScreenHeight - mUnrestrictedScreenTop;
2513                 vf.left = mStableLeft;
2514                 vf.top = mStableTop;
2515                 vf.right = mStableRight;
2516                 vf.bottom = mStableBottom;
2517
2518                 mStatusBarLayer = mStatusBar.getSurfaceLayer();
2519
2520                 // Let the status bar determine its size.
2521                 mStatusBar.computeFrameLw(pf, df, vf, vf);
2522
2523                 // For layout, the status bar is always at the top with our fixed height.
2524                 mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
2525
2526                 // If the status bar is hidden, we don't want to cause
2527                 // windows behind it to scroll.
2528                 if (mStatusBar.isVisibleLw()) {
2529                     // Status bar may go away, so the screen area it occupies
2530                     // is available to apps but just covering them when the
2531                     // status bar is visible.
2532                     mDockTop = mUnrestrictedScreenTop + mStatusBarHeight;
2533
2534                     mContentTop = mCurTop = mDockTop;
2535                     mContentBottom = mCurBottom = mDockBottom;
2536                     mContentLeft = mCurLeft = mDockLeft;
2537                     mContentRight = mCurRight = mDockRight;
2538
2539                     if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: " +
2540                         String.format(
2541                             "dock=[%d,%d][%d,%d] content=[%d,%d][%d,%d] cur=[%d,%d][%d,%d]",
2542                             mDockLeft, mDockTop, mDockRight, mDockBottom,
2543                             mContentLeft, mContentTop, mContentRight, mContentBottom,
2544                             mCurLeft, mCurTop, mCurRight, mCurBottom));
2545                 }
2546                 if (mStatusBar.isVisibleLw() && !mStatusBar.isAnimatingLw()) {
2547                     // If the status bar is currently requested to be visible,
2548                     // and not in the process of animating on or off, then
2549                     // we can tell the app that it is covered by it.
2550                     mSystemTop = mUnrestrictedScreenTop + mStatusBarHeight;
2551                 }
2552             }
2553         }
2554     }
2555
2556     /** {@inheritDoc} */
2557     public int getSystemDecorRectLw(Rect systemRect) {
2558         systemRect.left = mSystemLeft;
2559         systemRect.top = mSystemTop;
2560         systemRect.right = mSystemRight;
2561         systemRect.bottom = mSystemBottom;
2562         if (mStatusBar != null) return mStatusBar.getSurfaceLayer();
2563         if (mNavigationBar != null) return mNavigationBar.getSurfaceLayer();
2564         return 0;
2565     }
2566
2567     void setAttachedWindowFrames(WindowState win, int fl, int adjust,
2568             WindowState attached, boolean insetDecors, Rect pf, Rect df, Rect cf, Rect vf) {
2569         if (win.getSurfaceLayer() > mDockLayer && attached.getSurfaceLayer() < mDockLayer) {
2570             // Here's a special case: if this attached window is a panel that is
2571             // above the dock window, and the window it is attached to is below
2572             // the dock window, then the frames we computed for the window it is
2573             // attached to can not be used because the dock is effectively part
2574             // of the underlying window and the attached window is floating on top
2575             // of the whole thing.  So, we ignore the attached window and explicitly
2576             // compute the frames that would be appropriate without the dock.
2577             df.left = cf.left = vf.left = mDockLeft;
2578             df.top = cf.top = vf.top = mDockTop;
2579             df.right = cf.right = vf.right = mDockRight;
2580             df.bottom = cf.bottom = vf.bottom = mDockBottom;
2581         } else {
2582             // The effective display frame of the attached window depends on
2583             // whether it is taking care of insetting its content.  If not,
2584             // we need to use the parent's content frame so that the entire
2585             // window is positioned within that content.  Otherwise we can use
2586             // the display frame and let the attached window take care of
2587             // positioning its content appropriately.
2588             if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2589                 cf.set(attached.getDisplayFrameLw());
2590             } else {
2591                 // If the window is resizing, then we want to base the content
2592                 // frame on our attached content frame to resize...  however,
2593                 // things can be tricky if the attached window is NOT in resize
2594                 // mode, in which case its content frame will be larger.
2595                 // Ungh.  So to deal with that, make sure the content frame
2596                 // we end up using is not covering the IM dock.
2597                 cf.set(attached.getContentFrameLw());
2598                 if (attached.getSurfaceLayer() < mDockLayer) {
2599                     if (cf.left < mContentLeft) cf.left = mContentLeft;
2600                     if (cf.top < mContentTop) cf.top = mContentTop;
2601                     if (cf.right > mContentRight) cf.right = mContentRight;
2602                     if (cf.bottom > mContentBottom) cf.bottom = mContentBottom;
2603                 }
2604             }
2605             df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
2606             vf.set(attached.getVisibleFrameLw());
2607         }
2608         // The LAYOUT_IN_SCREEN flag is used to determine whether the attached
2609         // window should be positioned relative to its parent or the entire
2610         // screen.
2611         pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
2612                 ? attached.getFrameLw() : df);
2613     }
2614
2615     private void applyStableConstraints(int sysui, int fl, Rect r) {
2616         if ((sysui & View.SYSTEM_UI_FLAG_LAYOUT_STABLE) != 0) {
2617             // If app is requesting a stable layout, don't let the
2618             // content insets go below the stable values.
2619             if ((fl & FLAG_FULLSCREEN) != 0) {
2620                 if (r.left < mStableFullscreenLeft) r.left = mStableFullscreenLeft;
2621                 if (r.top < mStableFullscreenTop) r.top = mStableFullscreenTop;
2622                 if (r.right > mStableFullscreenRight) r.right = mStableFullscreenRight;
2623                 if (r.bottom > mStableFullscreenBottom) r.bottom = mStableFullscreenBottom;
2624             } else {
2625                 if (r.left < mStableLeft) r.left = mStableLeft;
2626                 if (r.top < mStableTop) r.top = mStableTop;
2627                 if (r.right > mStableRight) r.right = mStableRight;
2628                 if (r.bottom > mStableBottom) r.bottom = mStableBottom;
2629             }
2630         }
2631     }
2632
2633     /** {@inheritDoc} */
2634     @Override
2635     public void layoutWindowLw(WindowState win, WindowManager.LayoutParams attrs,
2636             WindowState attached) {
2637         // we've already done the status bar
2638         if (win == mStatusBar || win == mNavigationBar) {
2639             return;
2640         }
2641         final boolean isDefaultDisplay = win.isDefaultDisplay();
2642         final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
2643                 (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
2644         if (needsToOffsetInputMethodTarget) {
2645             if (DEBUG_LAYOUT) {
2646                 Slog.i(TAG, "Offset ime target window by the last ime window state");
2647             }
2648             offsetInputMethodWindowLw(mLastInputMethodWindow);
2649         }
2650
2651         final int fl = attrs.flags;
2652         final int sim = attrs.softInputMode;
2653         final int sysUiFl = win.getSystemUiVisibility();
2654
2655         final Rect pf = mTmpParentFrame;
2656         final Rect df = mTmpDisplayFrame;
2657         final Rect cf = mTmpContentFrame;
2658         final Rect vf = mTmpVisibleFrame;
2659
2660         final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
2661                 && mNavigationBar != null && mNavigationBar.isVisibleLw());
2662
2663         final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
2664
2665         if (!isDefaultDisplay) {
2666             if (attached != null) {
2667                 // If this window is attached to another, our display
2668                 // frame is the same as the one we are attached to.
2669                 setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, cf, vf);
2670             } else {
2671                 // Give the window full screen.
2672                 pf.left = df.left = cf.left = mUnrestrictedScreenLeft;
2673                 pf.top = df.top = cf.top = mUnrestrictedScreenTop;
2674                 pf.right = df.right = cf.right
2675                         = mUnrestrictedScreenLeft + mUnrestrictedScreenWidth;
2676                 pf.bottom = df.bottom = cf.bottom
2677                         = mUnrestrictedScreenTop + mUnrestrictedScreenHeight;
2678             }
2679         } else  if (attrs.type == TYPE_INPUT_METHOD) {
2680             pf.left = df.left = cf.left = vf.left = mDockLeft;
2681             pf.top = df.top = cf.top = vf.top = mDockTop;
2682             pf.right = df.right = cf.right = vf.right = mDockRight;
2683             pf.bottom = df.bottom = cf.bottom = vf.bottom = mDockBottom;
2684             // IM dock windows always go to the bottom of the screen.
2685             attrs.gravity = Gravity.BOTTOM;
2686             mDockLayer = win.getSurfaceLayer();
2687         } else {
2688             if ((fl & (FLAG_LAYOUT_IN_SCREEN | FLAG_FULLSCREEN | FLAG_LAYOUT_INSET_DECOR))
2689                     == (FLAG_LAYOUT_IN_SCREEN | FLAG_LAYOUT_INSET_DECOR)
2690                     && (sysUiFl & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
2691                 if (DEBUG_LAYOUT)
2692                     Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() 
2693                             + "): IN_SCREEN, INSET_DECOR, !FULLSCREEN");
2694                 // This is the case for a normal activity window: we want it
2695                 // to cover all of the screen space, and it can take care of
2696                 // moving its contents to account for screen decorations that
2697                 // intrude into that space.
2698                 if (attached != null) {
2699                     // If this window is attached to another, our display
2700                     // frame is the same as the one we are attached to.
2701                     setAttachedWindowFrames(win, fl, adjust, attached, true, pf, df, cf, vf);
2702                 } else {
2703                     if (attrs.type == TYPE_STATUS_BAR_PANEL
2704                             || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
2705                         // Status bar panels are the only windows who can go on top of
2706                         // the status bar.  They are protected by the STATUS_BAR_SERVICE
2707                         // permission, so they have the same privileges as the status
2708                         // bar itself.
2709                         //
2710                         // However, they should still dodge the navigation bar if it exists.
2711
2712                         pf.left = df.left = hasNavBar ? mDockLeft : mUnrestrictedScreenLeft;
2713                         pf.top = df.top = mUnrestrictedScreenTop;
2714                         pf.right = df.right = hasNavBar
2715                                             ? mRestrictedScreenLeft+mRestrictedScreenWidth
2716                                             : mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2717                         pf.bottom = df.bottom = hasNavBar
2718                                               ? mRestrictedScreenTop+mRestrictedScreenHeight
2719                                               : mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2720
2721                         if (DEBUG_LAYOUT) {
2722                             Log.v(TAG, String.format(
2723                                         "Laying out status bar window: (%d,%d - %d,%d)",
2724                                         pf.left, pf.top, pf.right, pf.bottom));
2725                         }
2726                     } else if (mCanHideNavigationBar
2727                             && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
2728                             && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
2729                             && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
2730                         // Asking for layout as if the nav bar is hidden, lets the
2731                         // application extend into the unrestricted screen area.  We
2732                         // only do this for application windows to ensure no window that
2733                         // can be above the nav bar can do this.
2734                         pf.left = df.left = mUnrestrictedScreenLeft;
2735                         pf.top = df.top = mUnrestrictedScreenTop;
2736                         pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2737                         pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2738                     } else {
2739                         pf.left = df.left = mRestrictedScreenLeft;
2740                         pf.top = df.top = mRestrictedScreenTop;
2741                         pf.right = df.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
2742                         pf.bottom = df.bottom = mRestrictedScreenTop+mRestrictedScreenHeight;
2743                     }
2744
2745                     if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2746                         cf.left = mDockLeft;
2747                         cf.top = mDockTop;
2748                         cf.right = mDockRight;
2749                         cf.bottom = mDockBottom;
2750                     } else {
2751                         cf.left = mContentLeft;
2752                         cf.top = mContentTop;
2753                         cf.right = mContentRight;
2754                         cf.bottom = mContentBottom;
2755                     }
2756
2757                     applyStableConstraints(sysUiFl, fl, cf);
2758                     if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2759                         vf.left = mCurLeft;
2760                         vf.top = mCurTop;
2761                         vf.right = mCurRight;
2762                         vf.bottom = mCurBottom;
2763                     } else {
2764                         vf.set(cf);
2765                     }
2766                 }
2767             } else if ((fl & FLAG_LAYOUT_IN_SCREEN) != 0 || (sysUiFl
2768                     & (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
2769                             | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)) != 0) {
2770                 if (DEBUG_LAYOUT)
2771                     Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): IN_SCREEN");
2772                 // A window that has requested to fill the entire screen just
2773                 // gets everything, period.
2774                 if (attrs.type == TYPE_STATUS_BAR_PANEL
2775                         || attrs.type == TYPE_STATUS_BAR_SUB_PANEL) {
2776                     pf.left = df.left = cf.left = hasNavBar ? mDockLeft : mUnrestrictedScreenLeft;
2777                     pf.top = df.top = cf.top = mUnrestrictedScreenTop;
2778                     pf.right = df.right = cf.right = hasNavBar
2779                                         ? mRestrictedScreenLeft+mRestrictedScreenWidth
2780                                         : mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2781                     pf.bottom = df.bottom = cf.bottom = hasNavBar
2782                                           ? mRestrictedScreenTop+mRestrictedScreenHeight
2783                                           : mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2784                     if (DEBUG_LAYOUT) {
2785                         Log.v(TAG, String.format(
2786                                     "Laying out IN_SCREEN status bar window: (%d,%d - %d,%d)",
2787                                     pf.left, pf.top, pf.right, pf.bottom));
2788                     }
2789                 } else if (attrs.type == TYPE_NAVIGATION_BAR
2790                         || attrs.type == TYPE_NAVIGATION_BAR_PANEL) {
2791                     // The navigation bar has Real Ultimate Power.
2792                     pf.left = df.left = mUnrestrictedScreenLeft;
2793                     pf.top = df.top = mUnrestrictedScreenTop;
2794                     pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2795                     pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2796                     if (DEBUG_LAYOUT) {
2797                         Log.v(TAG, String.format(
2798                                     "Laying out navigation bar window: (%d,%d - %d,%d)",
2799                                     pf.left, pf.top, pf.right, pf.bottom));
2800                     }
2801                 } else if ((attrs.type == TYPE_SECURE_SYSTEM_OVERLAY
2802                                 || attrs.type == TYPE_BOOT_PROGRESS)
2803                         && ((fl & FLAG_FULLSCREEN) != 0)) {
2804                     // Fullscreen secure system overlays get what they ask for.
2805                     pf.left = df.left = mUnrestrictedScreenLeft;
2806                     pf.top = df.top = mUnrestrictedScreenTop;
2807                     pf.right = df.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2808                     pf.bottom = df.bottom = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2809                 } else if (attrs.type == TYPE_BOOT_PROGRESS
2810                         || attrs.type == TYPE_UNIVERSE_BACKGROUND) {
2811                     // Boot progress screen always covers entire display.
2812                     pf.left = df.left = cf.left = mUnrestrictedScreenLeft;
2813                     pf.top = df.top = cf.top = mUnrestrictedScreenTop;
2814                     pf.right = df.right = cf.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2815                     pf.bottom = df.bottom = cf.bottom
2816                             = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2817                 } else if (mCanHideNavigationBar
2818                         && (sysUiFl & View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) != 0
2819                         && attrs.type >= WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW
2820                         && attrs.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
2821                     // Asking for layout as if the nav bar is hidden, lets the
2822                     // application extend into the unrestricted screen area.  We
2823                     // only do this for application windows to ensure no window that
2824                     // can be above the nav bar can do this.
2825                     // XXX This assumes that an app asking for this will also
2826                     // ask for layout in only content.  We can't currently figure out
2827                     // what the screen would be if only laying out to hide the nav bar.
2828                     pf.left = df.left = cf.left = mUnrestrictedScreenLeft;
2829                     pf.top = df.top = cf.top = mUnrestrictedScreenTop;
2830                     pf.right = df.right = cf.right = mUnrestrictedScreenLeft+mUnrestrictedScreenWidth;
2831                     pf.bottom = df.bottom = cf.bottom
2832                             = mUnrestrictedScreenTop+mUnrestrictedScreenHeight;
2833                 } else {
2834                     pf.left = df.left = cf.left = mRestrictedScreenLeft;
2835                     pf.top = df.top = cf.top = mRestrictedScreenTop;
2836                     pf.right = df.right = cf.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
2837                     pf.bottom = df.bottom = cf.bottom
2838                             = mRestrictedScreenTop+mRestrictedScreenHeight;
2839                 }
2840
2841                 applyStableConstraints(sysUiFl, fl, cf);
2842
2843                 if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2844                     vf.left = mCurLeft;
2845                     vf.top = mCurTop;
2846                     vf.right = mCurRight;
2847                     vf.bottom = mCurBottom;
2848                 } else {
2849                     vf.set(cf);
2850                 }
2851             } else if (attached != null) {
2852                 if (DEBUG_LAYOUT)
2853                     Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): attached to " + attached);
2854                 // A child window should be placed inside of the same visible
2855                 // frame that its parent had.
2856                 setAttachedWindowFrames(win, fl, adjust, attached, false, pf, df, cf, vf);
2857             } else {
2858                 if (DEBUG_LAYOUT)
2859                     Log.v(TAG, "layoutWindowLw(" + attrs.getTitle() + "): normal window");
2860                 // Otherwise, a normal window must be placed inside the content
2861                 // of all screen decorations.
2862                 if (attrs.type == TYPE_STATUS_BAR_PANEL) {
2863                     // Status bar panels are the only windows who can go on top of
2864                     // the status bar.  They are protected by the STATUS_BAR_SERVICE
2865                     // permission, so they have the same privileges as the status
2866                     // bar itself.
2867                     pf.left = df.left = cf.left = mRestrictedScreenLeft;
2868                     pf.top = df.top = cf.top = mRestrictedScreenTop;
2869                     pf.right = df.right = cf.right = mRestrictedScreenLeft+mRestrictedScreenWidth;
2870                     pf.bottom = df.bottom = cf.bottom
2871                             = mRestrictedScreenTop+mRestrictedScreenHeight;
2872                 } else {
2873                     pf.left = mContentLeft;
2874                     pf.top = mContentTop;
2875                     pf.right = mContentRight;
2876                     pf.bottom = mContentBottom;
2877                     if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2878                         df.left = cf.left = mDockLeft;
2879                         df.top = cf.top = mDockTop;
2880                         df.right = cf.right = mDockRight;
2881                         df.bottom = cf.bottom = mDockBottom;
2882                     } else {
2883                         df.left = cf.left = mContentLeft;
2884                         df.top = cf.top = mContentTop;
2885                         df.right = cf.right = mContentRight;
2886                         df.bottom = cf.bottom = mContentBottom;
2887                     }
2888                     if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2889                         vf.left = mCurLeft;
2890                         vf.top = mCurTop;
2891                         vf.right = mCurRight;
2892                         vf.bottom = mCurBottom;
2893                     } else {
2894                         vf.set(cf);
2895                     }
2896                 }
2897             }
2898         }
2899
2900         if ((fl & FLAG_LAYOUT_NO_LIMITS) != 0) {
2901             df.left = df.top = cf.left = cf.top = vf.left = vf.top = -10000;
2902             df.right = df.bottom = cf.right = cf.bottom = vf.right = vf.bottom = 10000;
2903         }
2904
2905         if (DEBUG_LAYOUT) Log.v(TAG, "Compute frame " + attrs.getTitle()
2906                 + ": sim=#" + Integer.toHexString(sim)
2907                 + " attach=" + attached + " type=" + attrs.type 
2908                 + String.format(" flags=0x%08x", fl)
2909                 + " pf=" + pf.toShortString() + " df=" + df.toShortString()
2910                 + " cf=" + cf.toShortString() + " vf=" + vf.toShortString());
2911
2912         win.computeFrameLw(pf, df, cf, vf);
2913
2914         // Dock windows carve out the bottom of the screen, so normal windows
2915         // can't appear underneath them.
2916         if (attrs.type == TYPE_INPUT_METHOD && win.isVisibleOrBehindKeyguardLw()
2917                 && !win.getGivenInsetsPendingLw()) {
2918             setLastInputMethodWindowLw(null, null);
2919             offsetInputMethodWindowLw(win);
2920         }
2921     }
2922
2923     private void offsetInputMethodWindowLw(WindowState win) {
2924         int top = win.getContentFrameLw().top;
2925         top += win.getGivenContentInsetsLw().top;
2926         if (mContentBottom > top) {
2927             mContentBottom = top;
2928         }
2929         top = win.getVisibleFrameLw().top;
2930         top += win.getGivenVisibleInsetsLw().top;
2931         if (mCurBottom > top) {
2932             mCurBottom = top;
2933         }
2934         if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
2935                 + mDockBottom + " mContentBottom="
2936                 + mContentBottom + " mCurBottom=" + mCurBottom);
2937     }
2938
2939     /** {@inheritDoc} */
2940     @Override
2941     public void finishLayoutLw() {
2942         return;
2943     }
2944
2945     /** {@inheritDoc} */
2946     @Override
2947     public void beginPostLayoutPolicyLw(int displayWidth, int displayHeight) {
2948         mTopFullscreenOpaqueWindowState = null;
2949         mAppsToBeHidden.clear();
2950         mForceStatusBar = false;
2951         mForceStatusBarFromKeyguard = false;
2952         mForcingShowNavBar = false;
2953         mForcingShowNavBarLayer = -1;
2954         
2955         mHideLockScreen = false;
2956         mAllowLockscreenWhenOn = false;
2957         mDismissKeyguard = DISMISS_KEYGUARD_NONE;
2958         mShowingLockscreen = false;
2959         mShowingDream = false;
2960     }
2961
2962     /** {@inheritDoc} */
2963     @Override
2964     public void applyPostLayoutPolicyLw(WindowState win,
2965                                 WindowManager.LayoutParams attrs) {
2966         if (DEBUG_LAYOUT) Slog.i(TAG, "Win " + win + ": isVisibleOrBehindKeyguardLw="
2967                 + win.isVisibleOrBehindKeyguardLw());
2968         if (mTopFullscreenOpaqueWindowState == null && (win.getAttrs().privateFlags
2969                 &WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_SHOW_NAV_BAR) != 0) {
2970             if (mForcingShowNavBarLayer < 0) {
2971                 mForcingShowNavBar = true;
2972                 mForcingShowNavBarLayer = win.getSurfaceLayer();
2973             }
2974         }
2975         if (mTopFullscreenOpaqueWindowState == null &&
2976                 win.isVisibleOrBehindKeyguardLw() && !win.isGoneForLayoutLw()) {
2977             if ((attrs.flags & FLAG_FORCE_NOT_FULLSCREEN) != 0) {
2978                 if (attrs.type == TYPE_KEYGUARD) {
2979                     mForceStatusBarFromKeyguard = true;
2980                 } else {
2981                     mForceStatusBar = true;
2982                 }
2983             }
2984             if (attrs.type == TYPE_KEYGUARD) {
2985                 mShowingLockscreen = true;
2986             }
2987             boolean appWindow = attrs.type >= FIRST_APPLICATION_WINDOW
2988                     && attrs.type <= LAST_APPLICATION_WINDOW;
2989             if (attrs.type == TYPE_DREAM) {
2990                 // If the lockscreen was showing when the dream started then wait
2991                 // for the dream to draw before hiding the lockscreen.
2992                 if (!mDreamingLockscreen
2993                         || (win.isVisibleLw() && win.hasDrawnLw())) {
2994                     mShowingDream = true;
2995                     appWindow = true;
2996                 }
2997             }
2998
2999             final boolean showWhenLocked = (attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0;
3000             if (appWindow) {
3001                 if (showWhenLocked) {
3002                     mAppsToBeHidden.remove(win.getAppToken());
3003                 } else {
3004                     mAppsToBeHidden.add(win.getAppToken());
3005                 }
3006                 if (attrs.x == 0 && attrs.y == 0
3007                         && attrs.width == WindowManager.LayoutParams.MATCH_PARENT
3008                         && attrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
3009                     if (DEBUG_LAYOUT) Slog.v(TAG, "Fullscreen window: " + win);
3010                     mTopFullscreenOpaqueWindowState = win;
3011                     if (mAppsToBeHidden.isEmpty()) {
3012                         if (showWhenLocked) {
3013                             if (DEBUG_LAYOUT) Slog.v(TAG, "Setting mHideLockScreen to true by win " + win);
3014                             mHideLockScreen = true;
3015                             mForceStatusBarFromKeyguard = false;
3016                         }
3017                         if ((attrs.flags & FLAG_DISMISS_KEYGUARD) != 0
3018                                 && mDismissKeyguard == DISMISS_KEYGUARD_NONE) {
3019                             if (DEBUG_LAYOUT) Slog.v(TAG, "Setting mDismissKeyguard true by win " + win);
3020                             mDismissKeyguard = mWinDismissingKeyguard == win ?
3021                                     DISMISS_KEYGUARD_CONTINUE : DISMISS_KEYGUARD_START;
3022                             mWinDismissingKeyguard = win;
3023                             mForceStatusBarFromKeyguard = false;
3024                         }
3025                     }
3026                     if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
3027                         mAllowLockscreenWhenOn = true;
3028                     }
3029                 }
3030             }
3031         }
3032     }
3033
3034     /** {@inheritDoc} */
3035     @Override
3036     public int finishPostLayoutPolicyLw() {
3037         int changes = 0;
3038         boolean topIsFullscreen = false;
3039
3040         final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
3041                 ? mTopFullscreenOpaqueWindowState.getAttrs()
3042                 : null;
3043
3044         // If we are not currently showing a dream then remember the current
3045         // lockscreen state.  We will use this to determine whether the dream
3046         // started while the lockscreen was showing and remember this state
3047         // while the dream is showing.
3048         if (!mShowingDream) {
3049             mDreamingLockscreen = mShowingLockscreen;
3050         }
3051
3052         if (mStatusBar != null) {
3053             if (DEBUG_LAYOUT) Log.i(TAG, "force=" + mForceStatusBar
3054                     + " forcefkg=" + mForceStatusBarFromKeyguard
3055                     + " top=" + mTopFullscreenOpaqueWindowState);
3056             if (mForceStatusBar || mForceStatusBarFromKeyguard) {
3057                 if (DEBUG_LAYOUT) Log.v(TAG, "Showing status bar: forced");
3058                 if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
3059             } else if (mTopFullscreenOpaqueWindowState != null) {
3060                 if (localLOGV) {
3061                     Log.d(TAG, "frame: " + mTopFullscreenOpaqueWindowState.getFrameLw()
3062                             + " shown frame: " + mTopFullscreenOpaqueWindowState.getShownFrameLw());
3063                     Log.d(TAG, "attr: " + mTopFullscreenOpaqueWindowState.getAttrs()
3064                             + " lp.flags=0x" + Integer.toHexString(lp.flags));
3065                 }
3066                 topIsFullscreen = (lp.flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0
3067                         || (mLastSystemUiFlags & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
3068                 // The subtle difference between the window for mTopFullscreenOpaqueWindowState
3069                 // and mTopIsFullscreen is that that mTopIsFullscreen is set only if the window
3070                 // has the FLAG_FULLSCREEN set.  Not sure if there is another way that to be the
3071                 // case though.
3072                 if (topIsFullscreen) {
3073                     if (DEBUG_LAYOUT) Log.v(TAG, "** HIDING status bar");
3074                     if (mStatusBar.hideLw(true)) {
3075                         changes |= FINISH_LAYOUT_REDO_LAYOUT;
3076
3077                         mHandler.post(new Runnable() {
3078                             @Override
3079                             public void run() {
3080                             try {
3081                                 IStatusBarService statusbar = getStatusBarService();
3082                                 if (statusbar != null) {
3083                                     statusbar.collapsePanels();
3084                                 }
3085                             } catch (RemoteException ex) {
3086                                 // re-acquire status bar service next time it is needed.
3087                                 mStatusBarService = null;
3088                             }
3089                         }});
3090                     } else if (DEBUG_LAYOUT) {
3091                         Log.v(TAG, "Preventing status bar from hiding by policy");
3092                     }
3093                 } else {
3094                     if (DEBUG_LAYOUT) Log.v(TAG, "** SHOWING status bar: top is not fullscreen");
3095                     if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
3096                 }
3097             }
3098         }
3099
3100         mTopIsFullscreen = topIsFullscreen;
3101
3102         // Hide the key guard if a visible window explicitly specifies that it wants to be
3103         // displayed when the screen is locked.
3104         if (mKeyguard != null) {
3105             if (localLOGV) Log.v(TAG, "finishPostLayoutPolicyLw: mHideKeyguard="
3106                     + mHideLockScreen);
3107             if (mDismissKeyguard != DISMISS_KEYGUARD_NONE && !isKeyguardSecure()) {
3108                 if (mKeyguard.hideLw(true)) {
3109                     changes |= FINISH_LAYOUT_REDO_LAYOUT
3110                             | FINISH_LAYOUT_REDO_CONFIG
3111                             | FINISH_LAYOUT_REDO_WALLPAPER;
3112                 }
3113                 if (mKeyguardMediator.isShowing()) {
3114                     mHandler.post(new Runnable() {
3115                         @Override
3116                         public void run() {
3117                             mKeyguardMediator.keyguardDone(false, false);
3118                         }
3119                     });
3120                 }
3121             } else if (mHideLockScreen) {
3122                 if (mKeyguard.hideLw(true)) {
3123                     changes |= FINISH_LAYOUT_REDO_LAYOUT
3124                             | FINISH_LAYOUT_REDO_CONFIG
3125                             | FINISH_LAYOUT_REDO_WALLPAPER;
3126                 }
3127                 mKeyguardMediator.setHidden(true);
3128             } else if (mDismissKeyguard != DISMISS_KEYGUARD_NONE) {
3129                 // This is the case of keyguard isSecure() and not mHideLockScreen.
3130                 if (mDismissKeyguard == DISMISS_KEYGUARD_START) {
3131                     // Only launch the next keyguard unlock window once per window.
3132                     if (mKeyguard.showLw(true)) {
3133                         changes |= FINISH_LAYOUT_REDO_LAYOUT
3134                                 | FINISH_LAYOUT_REDO_CONFIG
3135                                 | FINISH_LAYOUT_REDO_WALLPAPER;
3136                     }
3137                     mKeyguardMediator.setHidden(false);
3138                     mHandler.post(new Runnable() {
3139                         @Override
3140                         public void run() {
3141                             mKeyguardMediator.dismiss();
3142                         }
3143                     });
3144                 }
3145             } else {
3146                 mWinDismissingKeyguard = null;
3147                 if (mKeyguard.showLw(true)) {
3148                     changes |= FINISH_LAYOUT_REDO_LAYOUT
3149                             | FINISH_LAYOUT_REDO_CONFIG
3150                             | FINISH_LAYOUT_REDO_WALLPAPER;
3151                 }
3152                 mKeyguardMediator.setHidden(false);
3153             }
3154         }
3155
3156         if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
3157             // If the navigation bar has been hidden or shown, we need to do another
3158             // layout pass to update that window.
3159             changes |= FINISH_LAYOUT_REDO_LAYOUT;
3160         }
3161
3162         // update since mAllowLockscreenWhenOn might have changed
3163         updateLockScreenTimeout();
3164         return changes;
3165     }
3166
3167     public boolean allowAppAnimationsLw() {
3168         if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) {
3169             // If keyguard is currently visible, no reason to animate
3170             // behind it.
3171             return false;
3172         }
3173         return true;
3174     }
3175
3176     public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
3177         mFocusedWindow = newFocus;
3178         if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
3179             // If the navigation bar has been hidden or shown, we need to do another
3180             // layout pass to update that window.
3181             return FINISH_LAYOUT_REDO_LAYOUT;
3182         }
3183         return 0;
3184     }
3185
3186     /** {@inheritDoc} */
3187     public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
3188         // do nothing if headless
3189         if (mHeadless) return;
3190
3191         // lid changed state
3192         final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
3193         if (newLidState == mLidState) {
3194             return;
3195         }
3196
3197         mLidState = newLidState;
3198         applyLidSwitchState();
3199         updateRotation(true);
3200
3201         if (lidOpen) {
3202             if (keyguardIsShowingTq()) {
3203                 mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(KeyEvent.KEYCODE_POWER);
3204             } else {
3205                 mPowerManager.wakeUp(SystemClock.uptimeMillis());
3206             }
3207         } else if (!mLidControlsSleep) {
3208             mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
3209         }
3210     }
3211
3212     void setHdmiPlugged(boolean plugged) {
3213         if (mHdmiPlugged != plugged) {
3214             mHdmiPlugged = plugged;
3215             updateRotation(true, true);
3216             Intent intent = new Intent(ACTION_HDMI_PLUGGED);
3217             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3218             intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
3219             mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3220         }
3221     }
3222
3223     void initializeHdmiState() {
3224         boolean plugged = false;
3225         // watch for HDMI plug messages if the hdmi switch exists
3226         if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
3227             mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
3228
3229             final String filename = "/sys/class/switch/hdmi/state";
3230             FileReader reader = null;
3231             try {
3232                 reader = new FileReader(filename);
3233                 char[] buf = new char[15];
3234                 int n = reader.read(buf);
3235                 if (n > 1) {
3236                     plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
3237                 }
3238             } catch (IOException ex) {
3239                 Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3240             } catch (NumberFormatException ex) {
3241                 Slog.w(TAG, "Couldn't read hdmi state from " + filename + ": " + ex);
3242             } finally {
3243                 if (reader != null) {
3244                     try {
3245                         reader.close();
3246                     } catch (IOException ex) {
3247                     }
3248                 }
3249             }
3250         }
3251         // This dance forces the code in setHdmiPlugged to run.
3252         // Always do this so the sticky intent is stuck (to false) if there is no hdmi.
3253         mHdmiPlugged = !plugged;
3254         setHdmiPlugged(!mHdmiPlugged);
3255     }
3256
3257     /**
3258      * @return Whether music is being played right now.
3259      */
3260     boolean isMusicActive() {
3261         final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
3262         if (am == null) {
3263             Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
3264             return false;
3265         }
3266         return am.isMusicActive();
3267     }
3268
3269     /**
3270      * Tell the audio service to adjust the volume appropriate to the event.
3271      * @param keycode
3272      */
3273     void handleVolumeKey(int stream, int keycode) {
3274         IAudioService audioService = getAudioService();
3275         if (audioService == null) {
3276             return;
3277         }
3278         try {
3279             // since audio is playing, we shouldn't have to hold a wake lock
3280             // during the call, but we do it as a precaution for the rare possibility
3281             // that the music stops right before we call this
3282             // TODO: Actually handle MUTE.
3283             mBroadcastWakeLock.acquire();
3284             audioService.adjustStreamVolume(stream,
3285                 keycode == KeyEvent.KEYCODE_VOLUME_UP
3286                             ? AudioManager.ADJUST_RAISE
3287                             : AudioManager.ADJUST_LOWER,
3288                     0);
3289         } catch (RemoteException e) {
3290             Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
3291         } finally {
3292             mBroadcastWakeLock.release();
3293         }
3294     }
3295
3296     final Object mScreenshotLock = new Object();
3297     ServiceConnection mScreenshotConnection = null;
3298
3299     final Runnable mScreenshotTimeout = new Runnable() {
3300         @Override public void run() {
3301             synchronized (mScreenshotLock) {
3302                 if (mScreenshotConnection != null) {
3303                     mContext.unbindService(mScreenshotConnection);
3304                     mScreenshotConnection = null;
3305                 }
3306             }
3307         }
3308     };
3309
3310     // Assume this is called from the Handler thread.
3311     private void takeScreenshot() {
3312         synchronized (mScreenshotLock) {
3313             if (mScreenshotConnection != null) {
3314                 return;
3315             }
3316             ComponentName cn = new ComponentName("com.android.systemui",
3317                     "com.android.systemui.screenshot.TakeScreenshotService");
3318             Intent intent = new Intent();
3319             intent.setComponent(cn);
3320             ServiceConnection conn = new ServiceConnection() {
3321                 @Override
3322                 public void onServiceConnected(ComponentName name, IBinder service) {
3323                     synchronized (mScreenshotLock) {
3324                         if (mScreenshotConnection != this) {
3325                             return;
3326                         }
3327                         Messenger messenger = new Messenger(service);
3328                         Message msg = Message.obtain(null, 1);
3329                         final ServiceConnection myConn = this;
3330                         Handler h = new Handler(mHandler.getLooper()) {
3331                             @Override
3332                             public void handleMessage(Message msg) {
3333                                 synchronized (mScreenshotLock) {
3334                                     if (mScreenshotConnection == myConn) {
3335                                         mContext.unbindService(mScreenshotConnection);
3336                                         mScreenshotConnection = null;
3337                                         mHandler.removeCallbacks(mScreenshotTimeout);
3338                                     }
3339                                 }
3340                             }
3341                         };
3342                         msg.replyTo = new Messenger(h);
3343                         msg.arg1 = msg.arg2 = 0;
3344                         if (mStatusBar != null && mStatusBar.isVisibleLw())
3345                             msg.arg1 = 1;
3346                         if (mNavigationBar != null && mNavigationBar.isVisibleLw())
3347                             msg.arg2 = 1;
3348                         try {
3349                             messenger.send(msg);
3350                         } catch (RemoteException e) {
3351                         }
3352                     }
3353                 }
3354                 @Override
3355                 public void onServiceDisconnected(ComponentName name) {}
3356             };
3357             if (mContext.bindService(
3358                     intent, conn, Context.BIND_AUTO_CREATE, UserHandle.USER_CURRENT)) {
3359                 mScreenshotConnection = conn;
3360                 mHandler.postDelayed(mScreenshotTimeout, 10000);
3361             }
3362         }
3363     }
3364
3365     /** {@inheritDoc} */
3366     @Override
3367     public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
3368         if (!mSystemBooted) {
3369             // If we have not yet booted, don't let key events do anything.
3370             return 0;
3371         }
3372
3373         final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
3374         final boolean canceled = event.isCanceled();
3375         final int keyCode = event.getKeyCode();
3376
3377         final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
3378
3379         // If screen is off then we treat the case where the keyguard is open but hidden
3380         // the same as if it were open and in front.
3381         // This will prevent any keys other than the power button from waking the screen
3382         // when the keyguard is hidden by another activity.
3383         final boolean keyguardActive = (mKeyguardMediator == null ? false :
3384                                             (isScreenOn ?
3385                                                 mKeyguardMediator.isShowingAndNotHidden() :
3386                                                 mKeyguardMediator.isShowing()));
3387
3388         if (keyCode == KeyEvent.KEYCODE_POWER) {
3389             policyFlags |= WindowManagerPolicy.FLAG_WAKE;
3390         }
3391         final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE
3392                 | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3393
3394         if (DEBUG_INPUT) {
3395             Log.d(TAG, "interceptKeyTq keycode=" + keyCode
3396                     + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive
3397                     + " policyFlags=" + Integer.toHexString(policyFlags)
3398                     + " isWakeKey=" + isWakeKey);
3399         }
3400
3401         if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
3402                 && event.getRepeatCount() == 0) {
3403             performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
3404         }
3405
3406         // Basic policy based on screen state and keyguard.
3407         // FIXME: This policy isn't quite correct.  We shouldn't care whether the screen
3408         //        is on or off, really.  We should care about whether the device is in an
3409         //        interactive state or is in suspend pretending to be "off".
3410         //        The primary screen might be turned off due to proximity sensor or
3411         //        because we are presenting media on an auxiliary screen or remotely controlling
3412         //        the device some other way (which is why we have an exemption here for injected
3413         //        events).
3414         int result;
3415         if ((isScreenOn && !mHeadless) || (isInjected && !isWakeKey)) {
3416             // When the screen is on or if the key is injected pass the key to the application.
3417             result = ACTION_PASS_TO_USER;
3418         } else {
3419             // When the screen is off and the key is not injected, determine whether
3420             // to wake the device but don't pass the key to the application.
3421             result = 0;
3422             if (down && isWakeKey && isWakeKeyWhenScreenOff(keyCode)) {
3423                 if (keyguardActive) {
3424                     // If the keyguard is showing, let it wake the device when ready.
3425                     mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(keyCode);
3426                 } else {
3427                     // Otherwise, wake the device ourselves.
3428                     result |= ACTION_WAKE_UP;
3429                 }
3430             }
3431         }
3432
3433         // Handle special keys.
3434         switch (keyCode) {
3435             case KeyEvent.KEYCODE_VOLUME_DOWN:
3436             case KeyEvent.KEYCODE_VOLUME_UP:
3437             case KeyEvent.KEYCODE_VOLUME_MUTE: {
3438                 if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
3439                     if (down) {
3440                         if (isScreenOn && !mVolumeDownKeyTriggered
3441                                 && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3442                             mVolumeDownKeyTriggered = true;
3443                             mVolumeDownKeyTime = event.getDownTime();
3444                             mVolumeDownKeyConsumedByScreenshotChord = false;
3445                             cancelPendingPowerKeyAction();
3446                             interceptScreenshotChord();
3447                         }
3448                     } else {
3449                         mVolumeDownKeyTriggered = false;
3450                         cancelPendingScreenshotChordAction();
3451                     }
3452                 } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
3453                     if (down) {
3454                         if (isScreenOn && !mVolumeUpKeyTriggered
3455                                 && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3456                             mVolumeUpKeyTriggered = true;
3457                             cancelPendingPowerKeyAction();
3458                             cancelPendingScreenshotChordAction();
3459                         }
3460                     } else {
3461                         mVolumeUpKeyTriggered = false;
3462                         cancelPendingScreenshotChordAction();
3463                     }
3464                 }
3465                 if (down) {
3466                     ITelephony telephonyService = getTelephonyService();
3467                     if (telephonyService != null) {
3468                         try {
3469                             if (telephonyService.isRinging()) {
3470                                 // If an incoming call is ringing, either VOLUME key means
3471                                 // "silence ringer".  We handle these keys here, rather than
3472                                 // in the InCallScreen, to make sure we'll respond to them
3473                                 // even if the InCallScreen hasn't come to the foreground yet.
3474                                 // Look for the DOWN event here, to agree with the "fallback"
3475                                 // behavior in the InCallScreen.
3476                                 Log.i(TAG, "interceptKeyBeforeQueueing:"
3477                                       + " VOLUME key-down while ringing: Silence ringer!");
3478
3479                                 // Silence the ringer.  (It's safe to call this
3480                                 // even if the ringer has already been silenced.)
3481                                 telephonyService.silenceRinger();
3482
3483                                 // And *don't* pass this key thru to the current activity
3484                                 // (which is probably the InCallScreen.)
3485                                 result &= ~ACTION_PASS_TO_USER;
3486                                 break;
3487                             }
3488                             if (telephonyService.isOffhook()
3489                                     && (result & ACTION_PASS_TO_USER) == 0) {
3490                                 // If we are in call but we decided not to pass the key to
3491                                 // the application, handle the volume change here.
3492                                 handleVolumeKey(AudioManager.STREAM_VOICE_CALL, keyCode);
3493                                 break;
3494                             }
3495                         } catch (RemoteException ex) {
3496                             Log.w(TAG, "ITelephony threw RemoteException", ex);
3497                         }
3498                     }
3499
3500                     if (isMusicActive() && (result & ACTION_PASS_TO_USER) == 0) {
3501                         // If music is playing but we decided not to pass the key to the
3502                         // application, handle the volume change here.
3503                         handleVolumeKey(AudioManager.STREAM_MUSIC, keyCode);
3504                         break;
3505                     }
3506                 }
3507                 break;
3508             }
3509
3510             case KeyEvent.KEYCODE_ENDCALL: {
3511                 result &= ~ACTION_PASS_TO_USER;
3512                 if (down) {
3513                     ITelephony telephonyService = getTelephonyService();
3514                     boolean hungUp = false;
3515                     if (telephonyService != null) {
3516                         try {
3517                             hungUp = telephonyService.endCall();
3518                         } catch (RemoteException ex) {
3519                             Log.w(TAG, "ITelephony threw RemoteException", ex);
3520                         }
3521                     }
3522                     interceptPowerKeyDown(!isScreenOn || hungUp);
3523                 } else {
3524                     if (interceptPowerKeyUp(canceled)) {
3525                         if ((mEndcallBehavior
3526                                 & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
3527                             if (goHome()) {
3528                                 break;
3529                             }
3530                         }
3531                         if ((mEndcallBehavior
3532                                 & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
3533                             result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3534                         }
3535                     }
3536                 }
3537                 break;
3538             }
3539
3540             case KeyEvent.KEYCODE_POWER: {
3541                 result &= ~ACTION_PASS_TO_USER;
3542                 if (down) {
3543                     if (isScreenOn && !mPowerKeyTriggered
3544                             && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3545                         mPowerKeyTriggered = true;
3546                         mPowerKeyTime = event.getDownTime();
3547                         interceptScreenshotChord();
3548                     }
3549
3550                     ITelephony telephonyService = getTelephonyService();
3551                     boolean hungUp = false;
3552                     if (telephonyService != null) {
3553                         try {
3554                             if (telephonyService.isRinging()) {
3555                                 // Pressing Power while there's a ringing incoming
3556                                 // call should silence the ringer.
3557                                 telephonyService.silenceRinger();
3558                             } else if ((mIncallPowerBehavior
3559                                     & Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP) != 0
3560                                     && telephonyService.isOffhook()) {
3561                                 // Otherwise, if "Power button ends call" is enabled,
3562                                 // the Power button will hang up any current active call.
3563                                 hungUp = telephonyService.endCall();
3564                             }
3565                         } catch (RemoteException ex) {
3566                             Log.w(TAG, "ITelephony threw RemoteException", ex);
3567                         }
3568                     }
3569                     interceptPowerKeyDown(!isScreenOn || hungUp
3570                             || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered);
3571                 } else {
3572                     mPowerKeyTriggered = false;
3573                     cancelPendingScreenshotChordAction();
3574                     if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) {
3575                         result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3576                     }
3577                     mPendingPowerKeyUpCanceled = false;
3578                 }
3579                 break;
3580             }
3581
3582             case KeyEvent.KEYCODE_MEDIA_PLAY:
3583             case KeyEvent.KEYCODE_MEDIA_PAUSE:
3584             case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3585                 if (down) {
3586                     ITelephony telephonyService = getTelephonyService();
3587                     if (telephonyService != null) {
3588                         try {
3589                             if (!telephonyService.isIdle()) {
3590                                 // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
3591                                 // to avoid music playback.
3592                                 break;
3593                             }
3594                         } catch (RemoteException ex) {
3595                             Log.w(TAG, "ITelephony threw RemoteException", ex);
3596                         }
3597                     }
3598                 }
3599             case KeyEvent.KEYCODE_HEADSETHOOK:
3600             case KeyEvent.KEYCODE_MUTE:
3601             case KeyEvent.KEYCODE_MEDIA_STOP:
3602             case KeyEvent.KEYCODE_MEDIA_NEXT:
3603             case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
3604             case KeyEvent.KEYCODE_MEDIA_REWIND:
3605             case KeyEvent.KEYCODE_MEDIA_RECORD:
3606             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: {
3607                 if ((result & ACTION_PASS_TO_USER) == 0) {
3608                     // Only do this if we would otherwise not pass it to the user. In that
3609                     // case, the PhoneWindow class will do the same thing, except it will
3610                     // only do it if the showing app doesn't process the key on its own.
3611                     // Note that we need to make a copy of the key event here because the
3612                     // original key event will be recycled when we return.
3613                     mBroadcastWakeLock.acquire();
3614                     Message msg = mHandler.obtainMessage(MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK,
3615                             new KeyEvent(event));
3616                     msg.setAsynchronous(true);
3617                     msg.sendToTarget();
3618                 }
3619                 break;
3620             }
3621
3622             case KeyEvent.KEYCODE_CALL: {
3623                 if (down) {
3624                     ITelephony telephonyService = getTelephonyService();
3625                     if (telephonyService != null) {
3626                         try {
3627                             if (telephonyService.isRinging()) {
3628                                 Log.i(TAG, "interceptKeyBeforeQueueing:"
3629                                       + " CALL key-down while ringing: Answer the call!");
3630                                 telephonyService.answerRingingCall();
3631
3632                                 // And *don't* pass this key thru to the current activity
3633                                 // (which is presumably the InCallScreen.)
3634                                 result &= ~ACTION_PASS_TO_USER;
3635                             }
3636                         } catch (RemoteException ex) {
3637                             Log.w(TAG, "ITelephony threw RemoteException", ex);
3638                         }
3639                     }
3640                 }
3641                 break;
3642             }
3643         }
3644         return result;
3645     }
3646
3647     /**
3648      * When the screen is off we ignore some keys that might otherwise typically
3649      * be considered wake keys.  We filter them out here.
3650      *
3651      * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
3652      * is always considered a wake key.
3653      */
3654     private boolean isWakeKeyWhenScreenOff(int keyCode) {
3655         switch (keyCode) {
3656             // ignore volume keys unless docked
3657             case KeyEvent.KEYCODE_VOLUME_UP:
3658             case KeyEvent.KEYCODE_VOLUME_DOWN:
3659             case KeyEvent.KEYCODE_VOLUME_MUTE:
3660                 return mDockMode != Intent.EXTRA_DOCK_STATE_UNDOCKED;
3661
3662             // ignore media and camera keys
3663             case KeyEvent.KEYCODE_MUTE:
3664             case KeyEvent.KEYCODE_HEADSETHOOK:
3665             case KeyEvent.KEYCODE_MEDIA_PLAY:
3666             case KeyEvent.KEYCODE_MEDIA_PAUSE:
3667             case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3668             case KeyEvent.KEYCODE_MEDIA_STOP:
3669             case KeyEvent.KEYCODE_MEDIA_NEXT:
3670             case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
3671             case KeyEvent.KEYCODE_MEDIA_REWIND:
3672             case KeyEvent.KEYCODE_MEDIA_RECORD:
3673             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
3674             case KeyEvent.KEYCODE_CAMERA:
3675                 return false;
3676         }
3677         return true;
3678     }
3679
3680
3681     /** {@inheritDoc} */
3682     @Override
3683     public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
3684         int result = 0;
3685
3686         final boolean isWakeMotion = (policyFlags
3687                 & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3688         if (isWakeMotion) {
3689             if (mKeyguardMediator != null && mKeyguardMediator.isShowing()) {
3690                 // If the keyguard is showing, let it decide what to do with the wake motion.
3691                 mKeyguardMediator.onWakeMotionWhenKeyguardShowingTq();
3692             } else {
3693                 // Otherwise, wake the device ourselves.
3694                 result |= ACTION_WAKE_UP;
3695             }
3696         }
3697         return result;
3698     }
3699
3700     void dispatchMediaKeyWithWakeLock(KeyEvent event) {
3701         if (DEBUG_INPUT) {
3702             Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
3703         }
3704
3705         if (mHavePendingMediaKeyRepeatWithWakeLock) {
3706             if (DEBUG_INPUT) {
3707                 Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
3708             }
3709
3710             mHandler.removeMessages(MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK);
3711             mHavePendingMediaKeyRepeatWithWakeLock = false;
3712             mBroadcastWakeLock.release(); // pending repeat was holding onto the wake lock
3713         }
3714
3715         dispatchMediaKeyWithWakeLockToAudioService(event);
3716
3717         if (event.getAction() == KeyEvent.ACTION_DOWN
3718                 && event.getRepeatCount() == 0) {
3719             mHavePendingMediaKeyRepeatWithWakeLock = true;
3720
3721             Message msg = mHandler.obtainMessage(
3722                     MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK, event);
3723             msg.setAsynchronous(true);
3724             mHandler.sendMessageDelayed(msg, ViewConfiguration.getKeyRepeatTimeout());
3725         } else {
3726             mBroadcastWakeLock.release();
3727         }
3728     }
3729
3730     void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
3731         mHavePendingMediaKeyRepeatWithWakeLock = false;
3732
3733         KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
3734                 SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
3735         if (DEBUG_INPUT) {
3736             Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
3737         }
3738
3739         dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
3740         mBroadcastWakeLock.release();
3741     }
3742
3743     void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
3744         if (ActivityManagerNative.isSystemReady()) {
3745             IAudioService audioService = getAudioService();
3746             if (audioService != null) {
3747                 try {
3748                     audioService.dispatchMediaKeyEventUnderWakelock(event);
3749                 } catch (RemoteException e) {
3750                     Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e);
3751                 }
3752             }
3753         }
3754     }
3755
3756     BroadcastReceiver mDockReceiver = new BroadcastReceiver() {
3757         public void onReceive(Context context, Intent intent) {
3758             if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
3759                 mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3760                         Intent.EXTRA_DOCK_STATE_UNDOCKED);
3761             }
3762             updateRotation(true);
3763             updateOrientationListenerLp();
3764         }
3765     };
3766
3767     BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
3768         @Override
3769         public void onReceive(Context context, Intent intent) {
3770             if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
3771                 if (mKeyguardMediator != null) {
3772                     mKeyguardMediator.onDreamingStarted();
3773                 }
3774             } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
3775                 if (mKeyguardMediator != null) {
3776                     mKeyguardMediator.onDreamingStopped();
3777                 }
3778             }
3779         }
3780     };
3781
3782     BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
3783         @Override
3784         public void onReceive(Context context, Intent intent) {
3785             if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
3786                 // tickle the settings observer: this first ensures that we're
3787                 // observing the relevant settings for the newly-active user,
3788                 // and then updates our own bookkeeping based on the now-
3789                 // current user.
3790                 mSettingsObserver.onChange(false);
3791
3792                 // force a re-application of focused window sysui visibility.
3793                 // the window may never have been shown for this user
3794                 // e.g. the keyguard when going through the new-user setup flow
3795                 synchronized(mLock) {
3796                     mLastSystemUiFlags = 0;
3797                     updateSystemUiVisibilityLw();
3798                 }
3799             }
3800         }
3801     };
3802
3803     @Override
3804     public void screenTurnedOff(int why) {
3805         EventLog.writeEvent(70000, 0);
3806         synchronized (mLock) {
3807             mScreenOnEarly = false;
3808             mScreenOnFully = false;
3809         }
3810         if (mKeyguardMediator != null) {
3811             mKeyguardMediator.onScreenTurnedOff(why);
3812         }
3813         synchronized (mLock) {
3814             updateOrientationListenerLp();
3815             updateLockScreenTimeout();
3816         }
3817     }
3818
3819     @Override
3820     public void screenTurningOn(final ScreenOnListener screenOnListener) {
3821         EventLog.writeEvent(70000, 1);
3822         if (false) {
3823             RuntimeException here = new RuntimeException("here");
3824             here.fillInStackTrace();
3825             Slog.i(TAG, "Screen turning on...", here);
3826         }
3827
3828         synchronized (mLock) {
3829             mScreenOnEarly = true;
3830             updateOrientationListenerLp();
3831             updateLockScreenTimeout();
3832         }
3833
3834         waitForKeyguard(screenOnListener);
3835     }
3836
3837     private void waitForKeyguard(final ScreenOnListener screenOnListener) {
3838         if (mKeyguardMediator != null) {
3839             if (screenOnListener != null) {
3840                 mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() {
3841                     @Override
3842                     public void onShown(IBinder windowToken) {
3843                         waitForKeyguardWindowDrawn(windowToken, screenOnListener);
3844                     }
3845                 });
3846                 return;
3847             } else {
3848                 mKeyguardMediator.onScreenTurnedOn(null);
3849             }
3850         } else {
3851             Slog.i(TAG, "No keyguard mediator!");
3852         }
3853         finishScreenTurningOn(screenOnListener);
3854     }
3855
3856     private void waitForKeyguardWindowDrawn(IBinder windowToken,
3857             final ScreenOnListener screenOnListener) {
3858         if (windowToken != null) {
3859             try {
3860                 if (mWindowManager.waitForWindowDrawn(
3861                         windowToken, new IRemoteCallback.Stub() {
3862                     @Override
3863                     public void sendResult(Bundle data) {
3864                         Slog.i(TAG, "Lock screen displayed!");
3865                         finishScreenTurningOn(screenOnListener);
3866                     }
3867                 })) {
3868                     return;
3869                 }
3870             } catch (RemoteException ex) {
3871                 // Can't happen in system process.
3872             }
3873         }
3874
3875         Slog.i(TAG, "No lock screen!");
3876         finishScreenTurningOn(screenOnListener);
3877     }
3878
3879     private void finishScreenTurningOn(ScreenOnListener screenOnListener) {
3880         synchronized (mLock) {
3881             mScreenOnFully = true;
3882         }
3883
3884         try {
3885             mWindowManager.setEventDispatching(true);
3886         } catch (RemoteException unhandled) {
3887         }
3888
3889         if (screenOnListener != null) {
3890             screenOnListener.onScreenOn();
3891         }
3892     }
3893
3894     @Override
3895     public boolean isScreenOnEarly() {
3896         return mScreenOnEarly;
3897     }
3898
3899     @Override
3900     public boolean isScreenOnFully() {
3901         return mScreenOnFully;
3902     }
3903
3904     /** {@inheritDoc} */
3905     public void enableKeyguard(boolean enabled) {
3906         if (mKeyguardMediator != null) {
3907             mKeyguardMediator.setKeyguardEnabled(enabled);
3908         }
3909     }
3910
3911     /** {@inheritDoc} */
3912     public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
3913         if (mKeyguardMediator != null) {
3914             mKeyguardMediator.verifyUnlock(callback);
3915         }
3916     }
3917
3918     private boolean keyguardIsShowingTq() {
3919         if (mKeyguardMediator == null) return false;
3920         return mKeyguardMediator.isShowingAndNotHidden();
3921     }
3922
3923
3924     /** {@inheritDoc} */
3925     public boolean isKeyguardLocked() {
3926         return keyguardOn();
3927     }
3928
3929     /** {@inheritDoc} */
3930     public boolean isKeyguardSecure() {
3931         if (mKeyguardMediator == null) return false;
3932         return mKeyguardMediator.isSecure();
3933     }
3934
3935     /** {@inheritDoc} */
3936     public boolean inKeyguardRestrictedKeyInputMode() {
3937         if (mKeyguardMediator == null) return false;
3938         return mKeyguardMediator.isInputRestricted();
3939     }
3940
3941     public void dismissKeyguardLw() {
3942         if (mKeyguardMediator.isShowing()) {
3943             mHandler.post(new Runnable() {
3944                 public void run() {
3945                     if (mKeyguardMediator.isDismissable()) {
3946                         // Can we just finish the keyguard straight away?
3947                         mKeyguardMediator.keyguardDone(false, true);
3948                     } else {
3949                         // ask the keyguard to prompt the user to authenticate if necessary
3950                         mKeyguardMediator.dismiss();
3951                     }
3952                 }
3953             });
3954         }
3955     }
3956
3957     void sendCloseSystemWindows() {
3958         sendCloseSystemWindows(mContext, null);
3959     }
3960
3961     void sendCloseSystemWindows(String reason) {
3962         sendCloseSystemWindows(mContext, reason);
3963     }
3964
3965     static void sendCloseSystemWindows(Context context, String reason) {
3966         if (ActivityManagerNative.isSystemReady()) {
3967             try {
3968                 ActivityManagerNative.getDefault().closeSystemDialogs(reason);
3969             } catch (RemoteException e) {
3970             }
3971         }
3972     }
3973
3974     @Override
3975     public int rotationForOrientationLw(int orientation, int lastRotation) {
3976         if (false) {
3977             Slog.v(TAG, "rotationForOrientationLw(orient="
3978                         + orientation + ", last=" + lastRotation
3979                         + "); user=" + mUserRotation + " "
3980                         + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
3981                             ? "USER_ROTATION_LOCKED" : "")
3982                         );
3983         }
3984
3985         synchronized (mLock) {
3986             int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
3987             if (sensorRotation < 0) {
3988                 sensorRotation = lastRotation;
3989             }
3990
3991             final int preferredRotation;
3992             if (mLidState == LID_OPEN && mLidOpenRotation >= 0) {
3993                 // Ignore sensor when lid switch is open and rotation is forced.
3994                 preferredRotation = mLidOpenRotation;
3995             } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
3996                     && (mCarDockEnablesAccelerometer || mCarDockRotation >= 0)) {
3997                 // Ignore sensor when in car dock unless explicitly enabled.
3998                 // This case can override the behavior of NOSENSOR, and can also
3999                 // enable 180 degree rotation while docked.
4000                 preferredRotation = mCarDockEnablesAccelerometer
4001                         ? sensorRotation : mCarDockRotation;
4002             } else if ((mDockMode == Intent.EXTRA_DOCK_STATE_DESK
4003                     || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
4004                     || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK)
4005                     && (mDeskDockEnablesAccelerometer || mDeskDockRotation >= 0)) {
4006                 // Ignore sensor when in desk dock unless explicitly enabled.
4007                 // This case can override the behavior of NOSENSOR, and can also
4008                 // enable 180 degree rotation while docked.
4009                 preferredRotation = mDeskDockEnablesAccelerometer
4010                         ? sensorRotation : mDeskDockRotation;
4011             } else if (mHdmiPlugged && mHdmiRotationLock) {
4012                 // Ignore sensor when plugged into HDMI.
4013                 // Note that the dock orientation overrides the HDMI orientation.
4014                 preferredRotation = mHdmiRotation;
4015             } else if ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_FREE
4016                             && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
4017                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED))
4018                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
4019                     || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
4020                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
4021                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
4022                 // Otherwise, use sensor only if requested by the application or enabled
4023                 // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
4024                 if (mAllowAllRotations < 0) {
4025                     // Can't read this during init() because the context doesn't
4026                     // have display metrics at that time so we cannot determine
4027                     // tablet vs. phone then.
4028                     mAllowAllRotations = mContext.getResources().getBoolean(
4029                             com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
4030                 }
4031                 if (sensorRotation != Surface.ROTATION_180
4032                         || mAllowAllRotations == 1
4033                         || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
4034                     preferredRotation = sensorRotation;
4035                 } else {
4036                     preferredRotation = lastRotation;
4037                 }
4038             } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED
4039                     && orientation != ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
4040                 // Apply rotation lock.  Does not apply to NOSENSOR.
4041                 // The idea is that the user rotation expresses a weak preference for the direction
4042                 // of gravity and as NOSENSOR is never affected by gravity, then neither should
4043                 // NOSENSOR be affected by rotation lock (although it will be affected by docks).
4044                 preferredRotation = mUserRotation;
4045             } else {
4046                 // No overriding preference.
4047                 // We will do exactly what the application asked us to do.
4048                 preferredRotation = -1;
4049             }
4050
4051             switch (orientation) {
4052                 case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
4053                     // Return portrait unless overridden.
4054                     if (isAnyPortrait(preferredRotation)) {
4055                         return preferredRotation;
4056                     }
4057                     return mPortraitRotation;
4058
4059                 case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
4060                     // Return landscape unless overridden.
4061                     if (isLandscapeOrSeascape(preferredRotation)) {
4062                         return preferredRotation;
4063                     }
4064                     return mLandscapeRotation;
4065
4066                 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
4067                     // Return reverse portrait unless overridden.
4068                     if (isAnyPortrait(preferredRotation)) {
4069                         return preferredRotation;
4070                     }
4071                     return mUpsideDownRotation;
4072
4073                 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
4074                     // Return seascape unless overridden.
4075                     if (isLandscapeOrSeascape(preferredRotation)) {
4076                         return preferredRotation;
4077                     }
4078                     return mSeascapeRotation;
4079
4080                 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
4081                     // Return either landscape rotation.
4082                     if (isLandscapeOrSeascape(preferredRotation)) {
4083                         return preferredRotation;
4084                     }
4085                     if (isLandscapeOrSeascape(lastRotation)) {
4086                         return lastRotation;
4087                     }
4088                     return mLandscapeRotation;
4089
4090                 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
4091                     // Return either portrait rotation.
4092                     if (isAnyPortrait(preferredRotation)) {
4093                         return preferredRotation;
4094                     }
4095                     if (isAnyPortrait(lastRotation)) {
4096                         return lastRotation;
4097                     }
4098                     return mPortraitRotation;
4099
4100                 default:
4101                     // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
4102                     // just return the preferred orientation we already calculated.
4103                     if (preferredRotation >= 0) {
4104                         return preferredRotation;
4105                     }
4106                     return Surface.ROTATION_0;
4107             }
4108         }
4109     }
4110
4111     @Override
4112     public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
4113         switch (orientation) {
4114             case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
4115             case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
4116             case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
4117                 return isAnyPortrait(rotation);
4118
4119             case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
4120             case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
4121             case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
4122                 return isLandscapeOrSeascape(rotation);
4123
4124             default:
4125                 return true;
4126         }
4127     }
4128
4129     @Override
4130     public void setRotationLw(int rotation) {
4131         mOrientationListener.setCurrentRotation(rotation);
4132     }
4133
4134     private boolean isLandscapeOrSeascape(int rotation) {
4135         return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
4136     }
4137
4138     private boolean isAnyPortrait(int rotation) {
4139         return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
4140     }
4141
4142
4143     // User rotation: to be used when all else fails in assigning an orientation to the device
4144     public void setUserRotationMode(int mode, int rot) {
4145         ContentResolver res = mContext.getContentResolver();
4146
4147         // mUserRotationMode and mUserRotation will be assigned by the content observer
4148         if (mode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
4149             Settings.System.putIntForUser(res,
4150                     Settings.System.USER_ROTATION,
4151                     rot,
4152                     UserHandle.USER_CURRENT);
4153             Settings.System.putIntForUser(res,
4154                     Settings.System.ACCELEROMETER_ROTATION,
4155                     0,
4156                     UserHandle.USER_CURRENT);
4157         } else {
4158             Settings.System.putIntForUser(res,
4159                     Settings.System.ACCELEROMETER_ROTATION,
4160                     1,
4161                     UserHandle.USER_CURRENT);
4162         }
4163     }
4164
4165     public void setSafeMode(boolean safeMode) {
4166         mSafeMode = safeMode;
4167         performHapticFeedbackLw(null, safeMode
4168                 ? HapticFeedbackConstants.SAFE_MODE_ENABLED
4169                 : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
4170     }
4171     
4172     static long[] getLongIntArray(Resources r, int resid) {
4173         int[] ar = r.getIntArray(resid);
4174         if (ar == null) {
4175             return null;
4176         }
4177         long[] out = new long[ar.length];
4178         for (int i=0; i<ar.length; i++) {
4179             out[i] = ar[i];
4180         }
4181         return out;
4182     }
4183     
4184     /** {@inheritDoc} */
4185     public void systemReady() {
4186         if (mKeyguardMediator != null) {
4187             // tell the keyguard
4188             mKeyguardMediator.onSystemReady();
4189         }
4190         synchronized (mLock) {
4191             updateOrientationListenerLp();
4192             mSystemReady = true;
4193             mHandler.post(new Runnable() {
4194                 public void run() {
4195                     updateSettings();
4196                 }
4197             });
4198         }
4199     }
4200
4201     /** {@inheritDoc} */
4202     public void systemBooted() {
4203         synchronized (mLock) {
4204             mSystemBooted = true;
4205         }
4206     }
4207
4208     ProgressDialog mBootMsgDialog = null;
4209
4210     /** {@inheritDoc} */
4211     public void showBootMessage(final CharSequence msg, final boolean always) {
4212         if (mHeadless) return;
4213         mHandler.post(new Runnable() {
4214             @Override public void run() {
4215                 if (mBootMsgDialog == null) {
4216                     mBootMsgDialog = new ProgressDialog(mContext) {
4217                         // This dialog will consume all events coming in to
4218                         // it, to avoid it trying to do things too early in boot.
4219                         @Override public boolean dispatchKeyEvent(KeyEvent event) {
4220                             return true;
4221                         }
4222                         @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4223                             return true;
4224                         }
4225                         @Override public boolean dispatchTouchEvent(MotionEvent ev) {
4226                             return true;
4227                         }
4228                         @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
4229                             return true;
4230                         }
4231                         @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
4232                             return true;
4233                         }
4234                         @Override public boolean dispatchPopulateAccessibilityEvent(
4235                                 AccessibilityEvent event) {
4236                             return true;
4237                         }
4238                     };
4239                     mBootMsgDialog.setTitle(R.string.android_upgrading_title);
4240                     mBootMsgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
4241                     mBootMsgDialog.setIndeterminate(true);
4242                     mBootMsgDialog.getWindow().setType(
4243                             WindowManager.LayoutParams.TYPE_BOOT_PROGRESS);
4244                     mBootMsgDialog.getWindow().addFlags(
4245                             WindowManager.LayoutParams.FLAG_DIM_BEHIND
4246                             | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
4247                     mBootMsgDialog.getWindow().setDimAmount(1);
4248                     WindowManager.LayoutParams lp = mBootMsgDialog.getWindow().getAttributes();
4249                     lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
4250                     mBootMsgDialog.getWindow().setAttributes(lp);
4251                     mBootMsgDialog.setCancelable(false);
4252                     mBootMsgDialog.show();
4253                 }
4254                 mBootMsgDialog.setMessage(msg);
4255             }
4256         });
4257     }
4258
4259     /** {@inheritDoc} */
4260     public void hideBootMessages() {
4261         mHandler.post(new Runnable() {
4262             @Override public void run() {
4263                 if (mBootMsgDialog != null) {
4264                     mBootMsgDialog.dismiss();
4265                     mBootMsgDialog = null;
4266                 }
4267             }
4268         });
4269     }
4270
4271     /** {@inheritDoc} */
4272     public void userActivity() {
4273         // ***************************************
4274         // NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE
4275         // ***************************************
4276         // THIS IS CALLED FROM DEEP IN THE POWER MANAGER
4277         // WITH ITS LOCKS HELD.
4278         //
4279         // This code must be VERY careful about the locks
4280         // it acquires.
4281         // In fact, the current code acquires way too many,
4282         // and probably has lurking deadlocks.
4283
4284         synchronized (mScreenLockTimeout) {
4285             if (mLockScreenTimerActive) {
4286                 // reset the timer
4287                 mHandler.removeCallbacks(mScreenLockTimeout);
4288                 mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4289             }
4290         }
4291     }
4292
4293     class ScreenLockTimeout implements Runnable {
4294         Bundle options;
4295
4296         @Override
4297         public void run() {
4298             synchronized (this) {
4299                 if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
4300                 if (mKeyguardMediator != null) {
4301                     mKeyguardMediator.doKeyguardTimeout(options);
4302                 }
4303                 mLockScreenTimerActive = false;
4304                 options = null;
4305             }
4306         }
4307
4308         public void setLockOptions(Bundle options) {
4309             this.options = options;
4310         }
4311     }
4312
4313     ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
4314
4315     public void lockNow(Bundle options) {
4316         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
4317         mHandler.removeCallbacks(mScreenLockTimeout);
4318         if (options != null) {
4319             // In case multiple calls are made to lockNow, we don't wipe out the options
4320             // until the runnable actually executes.
4321             mScreenLockTimeout.setLockOptions(options);
4322         }
4323         mHandler.post(mScreenLockTimeout);
4324     }
4325
4326     private void updateLockScreenTimeout() {
4327         synchronized (mScreenLockTimeout) {
4328             boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly &&
4329                     mKeyguardMediator != null && mKeyguardMediator.isSecure());
4330             if (mLockScreenTimerActive != enable) {
4331                 if (enable) {
4332                     if (localLOGV) Log.v(TAG, "setting lockscreen timer");
4333                     mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4334                 } else {
4335                     if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
4336                     mHandler.removeCallbacks(mScreenLockTimeout);
4337                 }
4338                 mLockScreenTimerActive = enable;
4339             }
4340         }
4341     }
4342
4343     /** {@inheritDoc} */
4344     public void enableScreenAfterBoot() {
4345         readLidState();
4346         applyLidSwitchState();
4347         updateRotation(true);
4348     }
4349
4350     private void applyLidSwitchState() {
4351         if (mLidState == LID_CLOSED && mLidControlsSleep) {
4352             mPowerManager.goToSleep(SystemClock.uptimeMillis());
4353         }
4354     }
4355
4356     void updateRotation(boolean alwaysSendConfiguration) {
4357         try {
4358             //set orientation on WindowManager
4359             mWindowManager.updateRotation(alwaysSendConfiguration, false);
4360         } catch (RemoteException e) {
4361             // Ignore
4362         }
4363     }
4364
4365     void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
4366         try {
4367             //set orientation on WindowManager
4368             mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
4369         } catch (RemoteException e) {
4370             // Ignore
4371         }
4372     }
4373
4374     void startDockOrHome() {
4375         // We don't have dock home anymore. Home is home. If you lived here, you'd be home by now.
4376         mContext.startActivityAsUser(mHomeIntent, UserHandle.CURRENT);
4377     }
4378     
4379     /**
4380      * goes to the home screen
4381      * @return whether it did anything
4382      */
4383     boolean goHome() {
4384         if (false) {
4385             // This code always brings home to the front.
4386             try {
4387                 ActivityManagerNative.getDefault().stopAppSwitches();
4388             } catch (RemoteException e) {
4389             }
4390             sendCloseSystemWindows();
4391             startDockOrHome();
4392         } else {
4393             // This code brings home to the front or, if it is already
4394             // at the front, puts the device to sleep.
4395             try {
4396                 if (SystemProperties.getInt("persist.sys.uts-test-mode", 0) == 1) {
4397                     /// Roll back EndcallBehavior as the cupcake design to pass P1 lab entry.
4398                     Log.d(TAG, "UTS-TEST-MODE");
4399                 } else {
4400                     ActivityManagerNative.getDefault().stopAppSwitches();
4401                     sendCloseSystemWindows();
4402                 }
4403                 int result = ActivityManagerNative.getDefault()
4404                         .startActivityAsUser(null, mHomeIntent,
4405                                 mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
4406                                 null, null, 0,
4407                                 ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4408                                 null, null, null, UserHandle.USER_CURRENT);
4409                 if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4410                     return false;
4411                 }
4412             } catch (RemoteException ex) {
4413                 // bummer, the activity manager, which is in this process, is dead
4414             }
4415         }
4416         return true;
4417     }
4418     
4419     public void setCurrentOrientationLw(int newOrientation) {
4420         synchronized (mLock) {
4421             if (newOrientation != mCurrentAppOrientation) {
4422                 mCurrentAppOrientation = newOrientation;
4423                 updateOrientationListenerLp();
4424             }
4425         }
4426     }
4427
4428     private void performAuditoryFeedbackForAccessibilityIfNeed() {
4429         if (!isGlobalAccessibilityGestureEnabled()) {
4430             return;
4431         }
4432         AudioManager audioManager = (AudioManager) mContext.getSystemService(
4433                 Context.AUDIO_SERVICE);
4434         if (audioManager.isSilentMode()) {
4435             return;
4436         }
4437         Ringtone ringTone = RingtoneManager.getRingtone(mContext,
4438                 Settings.System.DEFAULT_NOTIFICATION_URI);
4439         ringTone.setStreamType(AudioManager.STREAM_MUSIC);
4440         ringTone.play();
4441     }
4442     private boolean isGlobalAccessibilityGestureEnabled() {
4443         return Settings.Global.getInt(mContext.getContentResolver(),
4444                 Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
4445     }
4446
4447     public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
4448         if (!mVibrator.hasVibrator()) {
4449             return false;
4450         }
4451         final boolean hapticsDisabled = Settings.System.getIntForUser(mContext.getContentResolver(),
4452                 Settings.System.HAPTIC_FEEDBACK_ENABLED, 0, UserHandle.USER_CURRENT) == 0;
4453         if (!always && (hapticsDisabled || mKeyguardMediator.isShowingAndNotHidden())) {
4454             return false;
4455         }
4456         long[] pattern = null;
4457         switch (effectId) {
4458             case HapticFeedbackConstants.LONG_PRESS:
4459                 pattern = mLongPressVibePattern;
4460                 break;
4461             case HapticFeedbackConstants.VIRTUAL_KEY:
4462                 pattern = mVirtualKeyVibePattern;
4463                 break;
4464             case HapticFeedbackConstants.KEYBOARD_TAP:
4465                 pattern = mKeyboardTapVibePattern;
4466                 break;
4467             case HapticFeedbackConstants.SAFE_MODE_DISABLED:
4468                 pattern = mSafeModeDisabledVibePattern;
4469                 break;
4470             case HapticFeedbackConstants.SAFE_MODE_ENABLED:
4471                 pattern = mSafeModeEnabledVibePattern;
4472                 break;
4473             default:
4474                 return false;
4475         }
4476         if (pattern.length == 1) {
4477             // One-shot vibration
4478             mVibrator.vibrate(pattern[0]);
4479         } else {
4480             // Pattern vibration
4481             mVibrator.vibrate(pattern, -1);
4482         }
4483         return true;
4484     }
4485
4486     @Override
4487     public void keepScreenOnStartedLw() {
4488     }
4489
4490     @Override
4491     public void keepScreenOnStoppedLw() {
4492         if (mKeyguardMediator != null && !mKeyguardMediator.isShowingAndNotHidden()) {
4493             long curTime = SystemClock.uptimeMillis();
4494             mPowerManager.userActivity(curTime, false);
4495         }
4496     }
4497
4498     private int updateSystemUiVisibilityLw() {
4499         // If there is no window focused, there will be nobody to handle the events
4500         // anyway, so just hang on in whatever state we're in until things settle down.
4501         if (mFocusedWindow == null) {
4502             return 0;
4503         }
4504         if (mFocusedWindow.getAttrs().type == TYPE_KEYGUARD && mHideLockScreen == true) {
4505             // We are updating at a point where the keyguard has gotten
4506             // focus, but we were last in a state where the top window is
4507             // hiding it.  This is probably because the keyguard as been
4508             // shown while the top window was displayed, so we want to ignore
4509             // it here because this is just a very transient change and it
4510             // will quickly lose focus once it correctly gets hidden.
4511             return 0;
4512         }
4513         int tmpVisibility = mFocusedWindow.getSystemUiVisibility()
4514                 & ~mResettingSystemUiFlags
4515                 & ~mForceClearedSystemUiFlags;
4516         if (mForcingShowNavBar && mFocusedWindow.getSurfaceLayer() < mForcingShowNavBarLayer) {
4517             tmpVisibility &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
4518         }
4519         final int visibility = tmpVisibility;
4520         int diff = visibility ^ mLastSystemUiFlags;
4521         final boolean needsMenu = mFocusedWindow.getNeedsMenuLw(mTopFullscreenOpaqueWindowState);
4522         if (diff == 0 && mLastFocusNeedsMenu == needsMenu
4523                 && mFocusedApp == mFocusedWindow.getAppToken()) {
4524             return 0;
4525         }
4526         mLastSystemUiFlags = visibility;
4527         mLastFocusNeedsMenu = needsMenu;
4528         mFocusedApp = mFocusedWindow.getAppToken();
4529         mHandler.post(new Runnable() {
4530                 public void run() {
4531                     try {
4532                         IStatusBarService statusbar = getStatusBarService();
4533                         if (statusbar != null) {
4534                             statusbar.setSystemUiVisibility(visibility, 0xffffffff);
4535                             statusbar.topAppWindowChanged(needsMenu);
4536                         }
4537                     } catch (RemoteException e) {
4538                         // re-acquire status bar service next time it is needed.
4539                         mStatusBarService = null;
4540                     }
4541                 }
4542             });
4543         return diff;
4544     }
4545
4546     // Use this instead of checking config_showNavigationBar so that it can be consistently
4547     // overridden by qemu.hw.mainkeys in the emulator.
4548     public boolean hasNavigationBar() {
4549         return mHasNavigationBar;
4550     }
4551
4552     @Override
4553     public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
4554         mLastInputMethodWindow = ime;
4555         mLastInputMethodTargetWindow = target;
4556     }
4557
4558     @Override
4559     public boolean canMagnifyWindowLw(WindowManager.LayoutParams attrs) {
4560         switch (attrs.type) {
4561             case WindowManager.LayoutParams.TYPE_INPUT_METHOD:
4562             case WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG:
4563             case WindowManager.LayoutParams.TYPE_NAVIGATION_BAR:
4564             case WindowManager.LayoutParams.TYPE_MAGNIFICATION_OVERLAY: {
4565                 return false;
4566             }
4567         }
4568         return true;
4569     }
4570
4571     @Override
4572     public void setCurrentUserLw(int newUserId) {
4573         if (mKeyguardMediator != null) {
4574             mKeyguardMediator.setCurrentUser(newUserId);
4575         }
4576         if (mStatusBarService != null) {
4577             try {
4578                 mStatusBarService.setCurrentUser(newUserId);
4579             } catch (RemoteException e) {
4580                 // oh well
4581             }
4582         }
4583         setLastInputMethodWindowLw(null, null);
4584     }
4585
4586     @Override
4587     public void showAssistant() {
4588         mKeyguardMediator.showAssistant();
4589     }
4590
4591     @Override
4592     public void dump(String prefix, PrintWriter pw, String[] args) {
4593         pw.print(prefix); pw.print("mSafeMode="); pw.print(mSafeMode);
4594                 pw.print(" mSystemReady="); pw.print(mSystemReady);
4595                 pw.print(" mSystemBooted="); pw.println(mSystemBooted);
4596         pw.print(prefix); pw.print("mLidState="); pw.print(mLidState);
4597                 pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
4598                 pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
4599         if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
4600                 || mForceClearedSystemUiFlags != 0) {
4601             pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
4602                     pw.print(Integer.toHexString(mLastSystemUiFlags));
4603                     pw.print(" mResettingSystemUiFlags=0x");
4604                     pw.print(Integer.toHexString(mResettingSystemUiFlags));
4605                     pw.print(" mForceClearedSystemUiFlags=0x");
4606                     pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
4607         }
4608         if (mLastFocusNeedsMenu) {
4609             pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
4610                     pw.println(mLastFocusNeedsMenu);
4611         }
4612         pw.print(prefix); pw.print("mDockMode="); pw.print(mDockMode);
4613                 pw.print(" mCarDockRotation="); pw.print(mCarDockRotation);
4614                 pw.print(" mDeskDockRotation="); pw.println(mDeskDockRotation);
4615         pw.print(prefix); pw.print("mUserRotationMode="); pw.print(mUserRotationMode);
4616                 pw.print(" mUserRotation="); pw.print(mUserRotation);
4617                 pw.print(" mAllowAllRotations="); pw.println(mAllowAllRotations);
4618         pw.print(prefix); pw.print("mCurrentAppOrientation="); pw.println(mCurrentAppOrientation);
4619         pw.print(prefix); pw.print("mCarDockEnablesAccelerometer=");
4620                 pw.print(mCarDockEnablesAccelerometer);
4621                 pw.print(" mDeskDockEnablesAccelerometer=");
4622                 pw.println(mDeskDockEnablesAccelerometer);
4623         pw.print(prefix); pw.print("mLidKeyboardAccessibility=");
4624                 pw.print(mLidKeyboardAccessibility);
4625                 pw.print(" mLidNavigationAccessibility="); pw.print(mLidNavigationAccessibility);
4626                 pw.print(" mLidControlsSleep="); pw.println(mLidControlsSleep);
4627         pw.print(prefix); pw.print("mLongPressOnPowerBehavior=");
4628                 pw.print(mLongPressOnPowerBehavior);
4629                 pw.print(" mHasSoftInput="); pw.println(mHasSoftInput);
4630         pw.print(prefix); pw.print("mScreenOnEarly="); pw.print(mScreenOnEarly);
4631                 pw.print(" mScreenOnFully="); pw.print(mScreenOnFully);
4632                 pw.print(" mOrientationSensorEnabled="); pw.println(mOrientationSensorEnabled);
4633         pw.print(prefix); pw.print("mUnrestrictedScreen=("); pw.print(mUnrestrictedScreenLeft);
4634                 pw.print(","); pw.print(mUnrestrictedScreenTop);
4635                 pw.print(") "); pw.print(mUnrestrictedScreenWidth);
4636                 pw.print("x"); pw.println(mUnrestrictedScreenHeight);
4637         pw.print(prefix); pw.print("mRestrictedScreen=("); pw.print(mRestrictedScreenLeft);
4638                 pw.print(","); pw.print(mRestrictedScreenTop);
4639                 pw.print(") "); pw.print(mRestrictedScreenWidth);
4640                 pw.print("x"); pw.println(mRestrictedScreenHeight);
4641         pw.print(prefix); pw.print("mStableFullscreen=("); pw.print(mStableFullscreenLeft);
4642                 pw.print(","); pw.print(mStableFullscreenTop);
4643                 pw.print(")-("); pw.print(mStableFullscreenRight);
4644                 pw.print(","); pw.print(mStableFullscreenBottom); pw.println(")");
4645         pw.print(prefix); pw.print("mStable=("); pw.print(mStableLeft);
4646                 pw.print(","); pw.print(mStableTop);
4647                 pw.print(")-("); pw.print(mStableRight);
4648                 pw.print(","); pw.print(mStableBottom); pw.println(")");
4649         pw.print(prefix); pw.print("mSystem=("); pw.print(mSystemLeft);
4650                 pw.print(","); pw.print(mSystemTop);
4651                 pw.print(")-("); pw.print(mSystemRight);
4652                 pw.print(","); pw.print(mSystemBottom); pw.println(")");
4653         pw.print(prefix); pw.print("mCur=("); pw.print(mCurLeft);
4654                 pw.print(","); pw.print(mCurTop);
4655                 pw.print(")-("); pw.print(mCurRight);
4656                 pw.print(","); pw.print(mCurBottom); pw.println(")");
4657         pw.print(prefix); pw.print("mContent=("); pw.print(mContentLeft);
4658                 pw.print(","); pw.print(mContentTop);
4659                 pw.print(")-("); pw.print(mContentRight);
4660                 pw.print(","); pw.print(mContentBottom); pw.println(")");
4661         pw.print(prefix); pw.print("mDock=("); pw.print(mDockLeft);
4662                 pw.print(","); pw.print(mDockTop);
4663                 pw.print(")-("); pw.print(mDockRight);
4664                 pw.print(","); pw.print(mDockBottom); pw.println(")");
4665         pw.print(prefix); pw.print("mDockLayer="); pw.print(mDockLayer);
4666                 pw.print(" mStatusBarLayer="); pw.println(mStatusBarLayer);
4667         pw.print(prefix); pw.print("mShowingLockscreen="); pw.print(mShowingLockscreen);
4668                 pw.print(" mShowingDream="); pw.print(mShowingDream);
4669                 pw.print(" mDreamingLockscreen="); pw.println(mDreamingLockscreen);
4670         if (mLastInputMethodWindow != null) {
4671             pw.print(prefix); pw.print("mLastInputMethodWindow=");
4672                     pw.println(mLastInputMethodWindow);
4673         }
4674         if (mLastInputMethodTargetWindow != null) {
4675             pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
4676                     pw.println(mLastInputMethodTargetWindow);
4677         }
4678         if (mStatusBar != null) {
4679             pw.print(prefix); pw.print("mStatusBar=");
4680                     pw.println(mStatusBar);
4681         }
4682         if (mNavigationBar != null) {
4683             pw.print(prefix); pw.print("mNavigationBar=");
4684                     pw.println(mNavigationBar);
4685         }
4686         if (mKeyguard != null) {
4687             pw.print(prefix); pw.print("mKeyguard=");
4688                     pw.println(mKeyguard);
4689         }
4690         if (mFocusedWindow != null) {
4691             pw.print(prefix); pw.print("mFocusedWindow=");
4692                     pw.println(mFocusedWindow);
4693         }
4694         if (mFocusedApp != null) {
4695             pw.print(prefix); pw.print("mFocusedApp=");
4696                     pw.println(mFocusedApp);
4697         }
4698         if (mWinDismissingKeyguard != null) {
4699             pw.print(prefix); pw.print("mWinDismissingKeyguard=");
4700                     pw.println(mWinDismissingKeyguard);
4701         }
4702         if (mTopFullscreenOpaqueWindowState != null) {
4703             pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
4704                     pw.println(mTopFullscreenOpaqueWindowState);
4705         }
4706         if (mForcingShowNavBar) {
4707             pw.print(prefix); pw.print("mForcingShowNavBar=");
4708                     pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
4709                     pw.println(mForcingShowNavBarLayer);
4710         }
4711         pw.print(prefix); pw.print("mTopIsFullscreen="); pw.print(mTopIsFullscreen);
4712                 pw.print(" mHideLockScreen="); pw.println(mHideLockScreen);
4713         pw.print(prefix); pw.print("mForceStatusBar="); pw.print(mForceStatusBar);
4714                 pw.print(" mForceStatusBarFromKeyguard=");
4715                 pw.println(mForceStatusBarFromKeyguard);
4716         pw.print(prefix); pw.print("mDismissKeyguard="); pw.print(mDismissKeyguard);
4717                 pw.print(" mWinDismissingKeyguard="); pw.print(mWinDismissingKeyguard);
4718                 pw.print(" mHomePressed="); pw.println(mHomePressed);
4719         pw.print(prefix); pw.print("mAllowLockscreenWhenOn="); pw.print(mAllowLockscreenWhenOn);
4720                 pw.print(" mLockScreenTimeout="); pw.print(mLockScreenTimeout);
4721                 pw.print(" mLockScreenTimerActive="); pw.println(mLockScreenTimerActive);
4722         pw.print(prefix); pw.print("mEndcallBehavior="); pw.print(mEndcallBehavior);
4723                 pw.print(" mIncallPowerBehavior="); pw.print(mIncallPowerBehavior);
4724                 pw.print(" mLongPressOnHomeBehavior="); pw.println(mLongPressOnHomeBehavior);
4725         pw.print(prefix); pw.print("mLandscapeRotation="); pw.print(mLandscapeRotation);
4726                 pw.print(" mSeascapeRotation="); pw.println(mSeascapeRotation);
4727         pw.print(prefix); pw.print("mPortraitRotation="); pw.print(mPortraitRotation);
4728                 pw.print(" mUpsideDownRotation="); pw.println(mUpsideDownRotation);
4729         pw.print(prefix); pw.print("mHdmiRotation="); pw.print(mHdmiRotation);
4730                 pw.print(" mHdmiRotationLock="); pw.println(mHdmiRotationLock);
4731     }
4732 }