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
7 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package com.android.internal.policy.impl;
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;
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;
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;
153 import java.io.FileReader;
154 import java.io.IOException;
155 import java.io.PrintWriter;
156 import java.util.HashSet;
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.
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;
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;
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;
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;
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";
198 * These are the system UI flags that, when changing, can cause the layout
199 * of the screen to change.
201 static final int SYSTEM_UI_CHANGING_LAYOUT =
202 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
204 /* Table of Application Launch keys. Maps from key codes to intent categories.
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...
210 static SparseArray<String> sApplicationLaunchKeyCategories;
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);
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.)
232 final Object mLock = new Object();
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;
243 // Vibrator pattern for haptic feedback of a long press.
244 long[] mLongPressVibePattern;
246 // Vibrator pattern for haptic feedback of virtual key press.
247 long[] mVirtualKeyVibePattern;
249 // Vibrator pattern for a short vibration.
250 long[] mKeyboardTapVibePattern;
252 // Vibrator pattern for haptic feedback during boot when safe mode is disabled.
253 long[] mSafeModeDisabledVibePattern;
255 // Vibrator pattern for haptic feedback during boot when safe mode is enabled.
256 long[] mSafeModeEnabledVibePattern;
258 /** If true, hitting shift & menu will broadcast Intent.ACTION_BUG_REPORT */
259 boolean mEnableShiftMenuBugReports = false;
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];
274 WindowState mKeyguard = null;
275 KeyguardViewMediator mKeyguardMediator;
276 GlobalActions mGlobalActions;
277 volatile boolean mPowerKeyHandled; // accessed from input reader and handler thread
278 boolean mPendingPowerKeyUpCanceled;
280 WindowState mLastInputMethodWindow = null;
281 WindowState mLastInputMethodTargetWindow = null;
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;
288 RecentApplicationsDialog mRecentAppsDialog;
289 int mRecentAppsDialogHeldModifiers;
290 boolean mLanguageSwitchKeyPressed;
292 int mLidState = LID_ABSENT;
293 boolean mHaveBuiltInKeyboard;
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;
303 boolean mHdmiRotationLock;
305 int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE;
306 int mUserRotation = Surface.ROTATION_0;
307 boolean mAccelerometerDefault;
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;
322 int mPointerLocationMode = 0; // guarded by mLock
324 // The last window we were told about in focusChanged.
325 WindowState mFocusedWindow;
326 IApplicationToken mFocusedApp;
328 private static final class PointerLocationInputEventReceiver extends InputEventReceiver {
329 private final PointerLocationView mView;
331 public PointerLocationInputEventReceiver(InputChannel inputChannel, Looper looper,
332 PointerLocationView view) {
333 super(inputChannel, looper);
338 public void onInputEvent(InputEvent event) {
339 boolean handled = false;
341 if (event instanceof MotionEvent
342 && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
343 final MotionEvent motionEvent = (MotionEvent)event;
344 mView.addPointerEvent(motionEvent);
348 finishInputEvent(event, handled);
353 // Pointer location view state, only modified on the mHandler Looper.
354 PointerLocationInputEventReceiver mPointerLocationInputEventReceiver;
355 PointerLocationView mPointerLocationView;
356 InputChannel mPointerLocationInputChannel;
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
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.
390 // During layout, this is the layer of the status bar.
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;
403 FakeWindow mHideNavFakeWindow = null;
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();
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;
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;
426 /** The window that is currently dismissing the keyguard. Dismissing the keyguard must only
427 * be done once per window. */
428 private WindowState mWinDismissingKeyguard;
430 boolean mShowingLockscreen;
431 boolean mShowingDream;
432 boolean mDreamingLockscreen;
433 boolean mHomePressed;
434 boolean mHomeLongPressed;
436 Intent mCarDockIntent;
437 Intent mDeskDockIntent;
438 boolean mSearchKeyShortcutPending;
439 boolean mConsumeSearchKeyUp;
440 boolean mAssistKeyLongPressed;
442 // support for activating the lock screen while the screen is on
443 boolean mAllowLockscreenWhenOn;
444 int mLockScreenTimeout;
445 boolean mLockScreenTimerActive;
447 // Behavior of ENDCALL Button. (See Settings.System.END_BUTTON_BEHAVIOR.)
448 int mEndcallBehavior;
450 // Behavior of POWER button while in-call and screen on.
451 // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.)
452 int mIncallPowerBehavior;
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
461 // What we do when the user long presses on home
462 private int mLongPressOnHomeBehavior = -1;
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;
477 SettingsObserver mSettingsObserver;
478 ShortcutManager mShortcutManager;
479 PowerManager.WakeLock mBroadcastWakeLock;
480 boolean mHavePendingMediaKeyRepeatWithWakeLock;
482 // Fallback actions by key code.
483 private final SparseArray<KeyCharacterMap.FallbackAction> mFallbackActions =
484 new SparseArray<KeyCharacterMap.FallbackAction>();
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;
491 private class PolicyHandler extends Handler {
493 public void handleMessage(Message msg) {
495 case MSG_ENABLE_POINTER_LOCATION:
496 enablePointerLocation();
498 case MSG_DISABLE_POINTER_LOCATION:
499 disablePointerLocation();
501 case MSG_DISPATCH_MEDIA_KEY_WITH_WAKE_LOCK:
502 dispatchMediaKeyWithWakeLock((KeyEvent)msg.obj);
504 case MSG_DISPATCH_MEDIA_KEY_REPEAT_WITH_WAKE_LOCK:
505 dispatchMediaKeyRepeatWithWakeLock((KeyEvent)msg.obj);
511 private UEventObserver mHDMIObserver = new UEventObserver() {
513 public void onUEvent(UEventObserver.UEvent event) {
514 setHdmiPlugged("1".equals(event.get("SWITCH_STATE")));
518 class SettingsObserver extends ContentObserver {
519 SettingsObserver(Handler handler) {
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);
553 @Override public void onChange(boolean selfChange) {
555 updateRotation(false);
559 class MyOrientationListener extends WindowOrientationListener {
560 MyOrientationListener(Context context) {
565 public void onProposedRotationChanged(int rotation) {
566 if (localLOGV) Log.v(TAG, "onProposedRotationChanged, rotation=" + rotation);
567 updateRotation(false);
570 MyOrientationListener mOrientationListener;
572 IStatusBarService getStatusBarService() {
573 synchronized (mServiceAquireLock) {
574 if (mStatusBarService == null) {
575 mStatusBarService = IStatusBarService.Stub.asInterface(
576 ServiceManager.getService("statusbar"));
578 return mStatusBarService;
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.
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.
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,
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.)
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
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
628 void updateOrientationListenerLp() {
629 if (!mOrientationListener.canDetectOrientation()) {
630 // If sensor is turned off or nonexistent for some reason
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()) {
642 //enable listener if not already enabled
643 if (!mOrientationSensorEnabled) {
644 mOrientationListener.enable();
645 if(localLOGV) Log.v(TAG, "Enabling listeners");
646 mOrientationSensorEnabled = true;
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;
658 private void interceptPowerKeyDown(boolean handled) {
659 mPowerKeyHandled = handled;
661 mHandler.postDelayed(mPowerLongPress, ViewConfiguration.getGlobalActionKeyTimeout());
665 private boolean interceptPowerKeyUp(boolean canceled) {
666 if (!mPowerKeyHandled) {
667 mHandler.removeCallbacks(mPowerLongPress);
673 private void cancelPendingPowerKeyAction() {
674 if (!mPowerKeyHandled) {
675 mHandler.removeCallbacks(mPowerLongPress);
677 if (mPowerKeyTriggered) {
678 mPendingPowerKeyUpCanceled = true;
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();
691 mHandler.postDelayed(mScreenshotChordLongPress, getScreenshotChordLongPressDelay());
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());
702 return ViewConfiguration.getGlobalActionKeyTimeout();
706 private void cancelPendingScreenshotChordAction() {
707 mHandler.removeCallbacks(mScreenshotChordLongPress);
710 private final Runnable mPowerLongPress = new Runnable() {
713 // The context isn't read
714 if (mLongPressOnPowerBehavior < 0) {
715 mLongPressOnPowerBehavior = mContext.getResources().getInteger(
716 com.android.internal.R.integer.config_longPressOnPowerBehavior);
718 int resolvedBehavior = mLongPressOnPowerBehavior;
719 if (FactoryTest.isLongPressOnPowerOffEnabled()) {
720 resolvedBehavior = LONG_PRESS_POWER_SHUT_OFF_NO_CONFIRM;
723 switch (resolvedBehavior) {
724 case LONG_PRESS_POWER_NOTHING:
726 case LONG_PRESS_POWER_GLOBAL_ACTIONS:
727 mPowerKeyHandled = true;
728 if (!performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false)) {
729 performAuditoryFeedbackForAccessibilityIfNeed();
731 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
732 showGlobalActionsDialog();
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);
745 private final Runnable mScreenshotChordLongPress = new Runnable() {
751 void showGlobalActionsDialog() {
752 if (mGlobalActions == null) {
753 mGlobalActions = new GlobalActions(mContext, mWindowManagerFuncs);
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();
764 boolean isDeviceProvisioned() {
765 return Settings.Global.getInt(
766 mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0;
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;
780 if (mLongPressOnHomeBehavior != LONG_PRESS_HOME_NOTHING) {
781 performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
782 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_RECENT_APPS);
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;
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) {
793 IStatusBarService statusbar = getStatusBarService();
794 if (statusbar != null) {
795 statusbar.toggleRecentApps();
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;
806 * Create (if necessary) and show or dismiss the recent apps dialog according
807 * according to the requested behavior.
809 void showOrHideRecentAppsDialog(final int behavior) {
810 mHandler.post(new Runnable() {
813 if (mRecentAppsDialog == null) {
814 mRecentAppsDialog = new RecentApplicationsDialog(mContext);
816 if (mRecentAppsDialog.isShowing()) {
818 case RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS:
819 case RECENT_APPS_BEHAVIOR_DISMISS:
820 mRecentAppsDialog.dismiss();
822 case RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH:
823 mRecentAppsDialog.dismissAndSwitch();
825 case RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW:
831 case RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS:
832 mRecentAppsDialog.show();
834 case RECENT_APPS_BEHAVIOR_EXIT_TOUCH_MODE_AND_SHOW:
836 mWindowManager.setInTouchMode(false);
837 } catch (RemoteException e) {
839 mRecentAppsDialog.show();
841 case RECENT_APPS_BEHAVIOR_DISMISS:
842 case RECENT_APPS_BEHAVIOR_DISMISS_AND_SWITCH:
852 public void init(Context context, IWindowManager windowManager,
853 WindowManagerFuncs windowManagerFuncs) {
855 mWindowManager = windowManager;
856 mWindowManagerFuncs = windowManagerFuncs;
857 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
859 // don't create KeyguardViewMediator if headless
860 mKeyguardMediator = new KeyguardViewMediator(context, null);
862 mHandler = new PolicyHandler();
863 mOrientationListener = new MyOrientationListener(mContext);
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);
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);
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);
924 // register for multiuser-relevant broadcasts
925 filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
926 context.registerReceiver(mMultiuserReceiver, filter);
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);
940 mScreenshotChordEnabled = mContext.getResources().getBoolean(
941 com.android.internal.R.bool.config_enableScreenshotChord);
943 // Controls rotation and the like.
944 initializeHdmiState();
946 // Match current screen state.
947 if (mPowerManager.isScreenOn()) {
948 screenTurningOn(null);
950 screenTurnedOff(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
954 public void setInitialDisplaySize(Display display, int width, int height, int density) {
957 int shortSize, longSize;
958 if (width > height) {
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;
968 mPortraitRotation = Surface.ROTATION_270;
969 mUpsideDownRotation = Surface.ROTATION_90;
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;
981 mLandscapeRotation = Surface.ROTATION_90;
982 mSeascapeRotation = Surface.ROTATION_270;
986 mStatusBarHeight = mContext.getResources().getDimensionPixelSize(
987 com.android.internal.R.dimen.status_bar_height);
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);
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);
1007 // SystemUI (status bar) layout policy
1008 int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT / density;
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;
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;
1031 mHasNavigationBar = false;
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
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;
1052 mCanHideNavigationBar = false;
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;
1060 mHdmiRotation = mLandscapeRotation;
1062 mHdmiRotationLock = SystemProperties.getBoolean("persist.demo.hdmirotationlock", true);
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);
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;
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();
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);
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;
1116 if (updateRotation) {
1117 updateRotation(true);
1121 private void enablePointerLocation() {
1122 if (mPointerLocationView == null) {
1123 mPointerLocationView = new PointerLocationView(mContext);
1124 mPointerLocationView.setPrintCoords(false);
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;
1137 WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_HARDWARE_ACCELERATED;
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);
1146 mPointerLocationInputChannel =
1147 mWindowManagerFuncs.monitorInput("PointerLocationView");
1148 mPointerLocationInputEventReceiver =
1149 new PointerLocationInputEventReceiver(mPointerLocationInputChannel,
1150 Looper.myLooper(), mPointerLocationView);
1154 private void disablePointerLocation() {
1155 if (mPointerLocationInputEventReceiver != null) {
1156 mPointerLocationInputEventReceiver.dispose();
1157 mPointerLocationInputEventReceiver = null;
1160 if (mPointerLocationInputChannel != null) {
1161 mPointerLocationInputChannel.dispose();
1162 mPointerLocationInputChannel = null;
1165 if (mPointerLocationView != null) {
1166 WindowManager wm = (WindowManager)
1167 mContext.getSystemService(Context.WINDOW_SERVICE);
1168 wm.removeView(mPointerLocationView);
1169 mPointerLocationView = null;
1173 private int readRotation(int resID) {
1175 int rotation = mContext.getResources().getInteger(resID);
1178 return Surface.ROTATION_0;
1180 return Surface.ROTATION_90;
1182 return Surface.ROTATION_180;
1184 return Surface.ROTATION_270;
1186 } catch (Resources.NotFoundException e) {
1192 /** {@inheritDoc} */
1194 public int checkAddPermission(WindowManager.LayoutParams attrs) {
1195 int type = attrs.type;
1197 if (type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
1198 || type > WindowManager.LayoutParams.LAST_SYSTEM_WINDOW) {
1199 return WindowManagerGlobal.ADD_OKAY;
1201 String permission = null;
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.
1209 case TYPE_INPUT_METHOD:
1210 case TYPE_WALLPAPER:
1211 // The window manager will check these.
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;
1221 permission = android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
1223 if (permission != null) {
1224 if (mContext.checkCallingOrSelfPermission(permission)
1225 != PackageManager.PERMISSION_GRANTED) {
1226 return WindowManagerGlobal.ADD_PERMISSION_DENIED;
1229 return WindowManagerGlobal.ADD_OKAY;
1233 public boolean checkShowToOwnerOnly(WindowManager.LayoutParams attrs) {
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) {
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) {
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:
1256 case TYPE_KEYGUARD_DIALOG:
1257 case TYPE_MAGNIFICATION_OVERLAY:
1258 case TYPE_NAVIGATION_BAR:
1259 case TYPE_NAVIGATION_BAR_PANEL:
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:
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;
1280 public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
1281 switch (attrs.type) {
1282 case TYPE_SYSTEM_OVERLAY:
1283 case TYPE_SECURE_SYSTEM_OVERLAY:
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;
1293 void readLidState() {
1294 mLidState = mWindowManagerFuncs.getLidState();
1297 private boolean isHidden(int accessibilityMode) {
1298 switch (accessibilityMode) {
1300 return mLidState == LID_CLOSED;
1302 return mLidState == LID_OPEN;
1308 private boolean isBuiltInKeyboardVisible() {
1309 return mHaveBuiltInKeyboard && !isHidden(mLidKeyboardAccessibility);
1312 /** {@inheritDoc} */
1313 public void adjustConfigurationLw(Configuration config, int keyboardPresence,
1314 int navigationPresence) {
1315 mHaveBuiltInKeyboard = (keyboardPresence & PRESENCE_INTERNAL) != 0;
1318 applyLidSwitchState();
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;
1329 if (config.navigation == Configuration.NAVIGATION_NONAV
1330 || (navigationPresence == PRESENCE_INTERNAL
1331 && isHidden(mLidNavigationAccessibility))) {
1332 config.navigationHidden = Configuration.NAVIGATIONHIDDEN_YES;
1336 /** {@inheritDoc} */
1337 public int windowTypeToLayerLw(int type) {
1338 if (type >= FIRST_APPLICATION_WINDOW && type <= LAST_APPLICATION_WINDOW) {
1342 case TYPE_UNIVERSE_BACKGROUND:
1344 case TYPE_WALLPAPER:
1345 // wallpaper is at the bottom, though the window manager may move it.
1349 case TYPE_SEARCH_BAR:
1351 case TYPE_RECENTS_OVERLAY:
1352 case TYPE_SYSTEM_DIALOG:
1355 // toasts and the plugged-in battery thing
1357 case TYPE_PRIORITY_PHONE:
1358 // SIM errors and unlock. Not sure if this really should be in a high layer.
1361 // used for Dreams (screensavers with TYPE_DREAM windows)
1363 case TYPE_SYSTEM_ALERT:
1364 // like the ANR / app crashed dialogs
1366 case TYPE_INPUT_METHOD:
1367 // on-screen keyboards and other such input method user interfaces go here.
1369 case TYPE_INPUT_METHOD_DIALOG:
1370 // on-screen keyboards and other such input method user interfaces go here.
1373 // the keyguard; nothing on top of these can take focus, since they are
1374 // responsible for power management when displayed.
1376 case TYPE_KEYGUARD_DIALOG:
1378 case TYPE_STATUS_BAR_SUB_PANEL:
1380 case TYPE_STATUS_BAR:
1382 case TYPE_STATUS_BAR_PANEL:
1384 case TYPE_VOLUME_OVERLAY:
1385 // the on-screen volume indicator and controller shown when the user
1386 // changes the device volume
1388 case TYPE_SYSTEM_OVERLAY:
1389 // the on-screen volume indicator and controller shown when the user
1390 // changes the device volume
1392 case TYPE_NAVIGATION_BAR:
1393 // the navigation bar, if available, shows atop most things
1395 case TYPE_NAVIGATION_BAR_PANEL:
1396 // some panels (e.g. search) need to show on top of the navigation bar
1398 case TYPE_SYSTEM_ERROR:
1399 // system-level error dialogs
1401 case TYPE_MAGNIFICATION_OVERLAY:
1402 // used to highlight the magnified portion of a display
1404 case TYPE_DISPLAY_OVERLAY:
1405 // used to simulate secondary display devices
1408 // the drag layer: input for drag-and-drop is associated with this window,
1409 // which sits above all other focusable windows
1411 case TYPE_SECURE_SYSTEM_OVERLAY:
1413 case TYPE_BOOT_PROGRESS:
1416 // the (mouse) pointer layer
1418 case TYPE_HIDDEN_NAV_CONSUMER:
1421 Log.e(TAG, "Unknown window type: " + type);
1425 /** {@inheritDoc} */
1426 public int subWindowTypeToLayerLw(int 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;
1438 Log.e(TAG, "Unknown sub-window type: " + type);
1442 public int getMaxWallpaperLayer() {
1443 return windowTypeToLayerLw(TYPE_STATUS_BAR);
1446 public int getAboveUniverseLayer() {
1447 return windowTypeToLayerLw(TYPE_SYSTEM_ERROR);
1450 public boolean hasSystemNavBar() {
1451 return mHasSystemNavBar;
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];
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];
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];
1480 public int getConfigDisplayWidth(int fullWidth, int fullHeight, int rotation) {
1481 return getNonDecorDisplayWidth(fullWidth, fullHeight, rotation);
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
1490 if (!mHasSystemNavBar) {
1491 return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation) - mStatusBarHeight;
1493 return getNonDecorDisplayHeight(fullWidth, fullHeight, rotation);
1497 public boolean doesForceHide(WindowState win, WindowManager.LayoutParams attrs) {
1498 return attrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD;
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:
1508 case TYPE_UNIVERSE_BACKGROUND:
1516 /** {@inheritDoc} */
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) {
1524 if (packageName == null) {
1528 WindowManager wm = null;
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) {
1538 context = context.createPackageContext(packageName, 0);
1539 context.setTheme(theme);
1540 } catch (PackageManager.NameNotFoundException e) {
1545 Window win = PolicyManager.makeNewWindow(context);
1546 final TypedArray ta = win.getWindowStyle();
1548 com.android.internal.R.styleable.Window_windowDisablePreview, false)
1550 com.android.internal.R.styleable.Window_windowShowWallpaper,false)) {
1554 Resources r = context.getResources();
1555 win.setTitle(r.getText(labelRes, nonLocalizedLabel));
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.
1565 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
1566 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
1567 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
1569 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE|
1570 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
1571 WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
1573 if (!compatInfo.supportsScreen()) {
1574 win.addFlags(WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW);
1577 win.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
1578 WindowManager.LayoutParams.MATCH_PARENT);
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);
1590 wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
1591 view = win.getDecorView();
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
1603 if (DEBUG_STARTING_WINDOW) Slog.d(
1604 TAG, "Adding starting window for " + packageName
1605 + " / " + appToken + ": "
1606 + (view.getParent() != null ? view : null));
1608 wm.addView(view, params);
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) {
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);
1622 if (view != null && view.getParent() == null) {
1623 Log.w(TAG, "view not successfully added to wm, removing view");
1624 wm.removeViewImmediate(view);
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);
1639 if (window != null) {
1640 WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
1641 wm.removeView(window);
1646 * Preflight adding a window to the system.
1648 * Currently enforces that three window types are singletons:
1650 * <li>STATUS_BAR_TYPE</li>
1651 * <li>KEYGUARD_TYPE</li>
1654 * @param win The window to be added
1655 * @param attrs Information about the window to be added
1657 * @return If ok, WindowManagerImpl.ADD_OKAY. If too many singletons,
1658 * WindowManagerImpl.ADD_MULTIPLE_SINGLETON
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;
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;
1682 mNavigationBar = win;
1683 if (DEBUG_LAYOUT) Log.i(TAG, "NAVIGATION BAR: " + mNavigationBar);
1685 case TYPE_NAVIGATION_BAR_PANEL:
1686 mContext.enforceCallingOrSelfPermission(
1687 android.Manifest.permission.STATUS_BAR_SERVICE,
1688 "PhoneWindowManager");
1690 case TYPE_STATUS_BAR_PANEL:
1691 mContext.enforceCallingOrSelfPermission(
1692 android.Manifest.permission.STATUS_BAR_SERVICE,
1693 "PhoneWindowManager");
1695 case TYPE_STATUS_BAR_SUB_PANEL:
1696 mContext.enforceCallingOrSelfPermission(
1697 android.Manifest.permission.STATUS_BAR_SERVICE,
1698 "PhoneWindowManager");
1701 if (mKeyguard != null) {
1702 return WindowManagerGlobal.ADD_MULTIPLE_SINGLETON;
1707 return WindowManagerGlobal.ADD_OKAY;
1710 /** {@inheritDoc} */
1711 public void removeWindowLw(WindowState win) {
1712 if (mStatusBar == win) {
1714 } else if (mKeyguard == win) {
1716 } else if (mNavigationBar == win) {
1717 mNavigationBar = null;
1721 static final boolean PRINT_ANIM = false;
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;
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;
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;
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;
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
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);
1771 static ITelephony getTelephonyService() {
1772 return ITelephony.Stub.asInterface(
1773 ServiceManager.checkService(Context.TELEPHONY_SERVICE));
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.");
1782 return audioService;
1785 boolean keyguardOn() {
1786 return keyguardIsShowingTq() || inKeyguardRestrictedKeyInputMode();
1789 private static final int[] WINDOW_TYPES_WHERE_HOME_DOESNT_WORK = {
1790 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
1791 WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
1794 /** {@inheritDoc} */
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();
1806 Log.d(TAG, "interceptKeyTi keyCode=" + keyCode + " down=" + down + " repeatCount="
1807 + repeatCount + " keyguardOn=" + keyguardOn + " mHomePressed=" + mHomePressed
1808 + " canceled=" + canceled);
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;
1822 if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
1823 && mVolumeDownKeyConsumedByScreenshotChord) {
1825 mVolumeDownKeyConsumedByScreenshotChord = false;
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
1835 if (keyCode == KeyEvent.KEYCODE_HOME) {
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!
1840 final boolean homeWasLongPressed = mHomeLongPressed;
1841 mHomePressed = false;
1842 mHomeLongPressed = false;
1843 if (!homeWasLongPressed) {
1844 if (mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
1846 IStatusBarService statusbar = getStatusBarService();
1847 if (statusbar != null) {
1848 statusbar.cancelPreloadRecentApps();
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;
1857 mHomePressed = false;
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;
1864 ITelephony telephonyService = getTelephonyService();
1865 if (telephonyService != null) {
1866 incomingRinging = telephonyService.isRinging();
1868 } catch (RemoteException ex) {
1869 Log.w(TAG, "RemoteException from getPhoneInterface()", ex);
1872 if (incomingRinging) {
1873 Log.i(TAG, "Ignoring HOME; there's a ringing incoming call.");
1875 launchHomeFromHotKey();
1878 Log.i(TAG, "Ignoring HOME; event canceled.");
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
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
1903 if (!mHomePressed && mLongPressOnHomeBehavior == LONG_PRESS_HOME_RECENT_SYSTEM_UI) {
1905 IStatusBarService statusbar = getStatusBarService();
1906 if (statusbar != null) {
1907 statusbar.preloadRecentApps();
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;
1915 if (repeatCount == 0) {
1916 mHomePressed = true;
1917 } else if ((event.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
1919 handleLongPressOnHome();
1924 } else if (keyCode == KeyEvent.KEYCODE_MENU) {
1925 // Hijack modified menu keys for debugging features
1926 final int chordBug = KeyEvent.META_SHIFT_ON;
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);
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;
1942 mContext.startService(service);
1944 mContext.stopService(service);
1946 Settings.Global.putInt(
1947 res, Settings.Global.SHOW_PROCESSES, shown ? 0 : 1);
1951 } else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
1953 if (repeatCount == 0) {
1954 mSearchKeyShortcutPending = true;
1955 mConsumeSearchKeyUp = false;
1958 mSearchKeyShortcutPending = false;
1959 if (mConsumeSearchKeyUp) {
1960 mConsumeSearchKeyUp = false;
1965 } else if (keyCode == KeyEvent.KEYCODE_APP_SWITCH) {
1966 if (down && repeatCount == 0 && !keyguardOn) {
1967 showOrHideRecentAppsDialog(RECENT_APPS_BEHAVIOR_SHOW_OR_DISMISS);
1970 } else if (keyCode == KeyEvent.KEYCODE_ASSIST) {
1972 if (repeatCount == 0) {
1973 mAssistKeyLongPressed = false;
1974 } else if (repeatCount == 1) {
1975 mAssistKeyLongPressed = true;
1977 launchAssistLongPressAction();
1981 if (mAssistKeyLongPressed) {
1982 mAssistKeyLongPressed = false;
1985 launchAssistAction();
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);
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);
2014 Slog.i(TAG, "Dropping unregistered shortcut key combination: "
2015 + "SEARCH+" + KeyEvent.keyCodeToString(keyCode));
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);
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);
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);
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);
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);
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);
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);
2089 if (mLanguageSwitchKeyPressed && !down
2090 && (keyCode == KeyEvent.KEYCODE_LANGUAGE_SWITCH
2091 || keyCode == KeyEvent.KEYCODE_SPACE)) {
2092 mLanguageSwitchKeyPressed = false;
2096 // Let the application handle the key.
2100 /** {@inheritDoc} */
2102 public KeyEvent dispatchUnhandledKey(WindowState win, KeyEvent event, int policyFlags) {
2103 // Note: This method is only called if the initial down was unhandled.
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);
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;
2122 // Check for fallback actions specified by the key character map.
2123 final FallbackAction fallbackAction;
2125 fallbackAction = kcm.getFallbackAction(keyCode, metaState);
2127 fallbackAction = mFallbackActions.get(keyCode);
2130 if (fallbackAction != null) {
2132 Slog.d(TAG, "Fallback: keyCode=" + fallbackAction.keyCode
2133 + " metaState=" + Integer.toHexString(fallbackAction.metaState));
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);
2144 if (!interceptFallback(win, fallbackEvent, policyFlags)) {
2145 fallbackEvent.recycle();
2146 fallbackEvent = null;
2150 mFallbackActions.put(keyCode, fallbackAction);
2151 } else if (event.getAction() == KeyEvent.ACTION_UP) {
2152 mFallbackActions.remove(keyCode);
2153 fallbackAction.recycle();
2159 if (fallbackEvent == null) {
2160 Slog.d(TAG, "No fallback.");
2162 Slog.d(TAG, "Performing fallback: " + fallbackEvent);
2165 return fallbackEvent;
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) {
2180 private void launchAssistLongPressAction() {
2181 performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
2182 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_ASSIST);
2184 // launch the search activity
2185 Intent intent = new Intent(Intent.ACTION_SEARCH_LONG_PRESS);
2186 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
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();
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);
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);
2209 mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
2210 } catch (ActivityNotFoundException e) {
2211 Slog.w(TAG, "No activity to handle assist action.", e);
2216 private SearchManager getSearchManager() {
2217 if (mSearchManager == null) {
2218 mSearchManager = (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
2220 return mSearchManager;
2224 * A home key -> launch home action was detected. Take the appropriate action
2225 * given the situation with the keyguard.
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) {
2237 ActivityManagerNative.getDefault().stopAppSwitches();
2238 } catch (RemoteException e) {
2240 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
2246 // no keyguard stuff to worry about, just launch home!
2248 ActivityManagerNative.getDefault().stopAppSwitches();
2249 } catch (RemoteException e) {
2251 sendCloseSystemWindows(SYSTEM_DIALOG_REASON_HOME_KEY);
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.
2261 final Runnable mAllowSystemUiDelay = new Runnable() {
2262 @Override public void run() {
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.
2271 final class HideNavInputEventReceiver extends InputEventReceiver {
2272 public HideNavInputEventReceiver(InputChannel inputChannel, Looper looper) {
2273 super(inputChannel, looper);
2277 public void onInputEvent(InputEvent event) {
2278 boolean handled = false;
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;
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;
2308 mHandler.postDelayed(new Runnable() {
2309 @Override public void run() {
2310 synchronized (mLock) {
2312 mForceClearedSystemUiFlags &=
2313 ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
2315 mWindowManagerFuncs.reevaluateStatusBarVisibility();
2321 mWindowManagerFuncs.reevaluateStatusBarVisibility();
2326 finishInputEvent(event, handled);
2330 final InputEventReceiver.Factory mHideNavInputEventReceiverFactory =
2331 new InputEventReceiver.Factory() {
2333 public InputEventReceiver createInputEventReceiver(
2334 InputChannel inputChannel, Looper looper) {
2335 return new HideNavInputEventReceiver(inputChannel, looper);
2340 public int adjustSystemUiVisibilityLw(int visibility) {
2341 // Reset any bits in mForceClearingStatusBarVisibility that
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;
2351 public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
2352 final int fl = attrs.flags;
2353 final int systemUiVisibility = (attrs.systemUiVisibility|attrs.subtreeSystemUiVisibility);
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;
2363 availRight = mRestrictedScreenLeft + mRestrictedScreenWidth;
2364 availBottom = mRestrictedScreenTop + mRestrictedScreenHeight;
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);
2372 contentInset.set(mStableLeft, mStableTop,
2373 availRight - mStableRight, availBottom - mStableBottom);
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);
2382 contentInset.set(mCurLeft, mCurTop,
2383 availRight - mCurRight, availBottom - mCurBottom);
2387 contentInset.setEmpty();
2390 /** {@inheritDoc} */
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;
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;
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;
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.
2430 if (mHideNavFakeWindow != null) {
2431 mHideNavFakeWindow.dismiss();
2432 mHideNavFakeWindow = null;
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);
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;
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;
2458 mNavigationBar.showLw(true);
2459 mDockBottom = mTmpNavigationFrame.top;
2460 mRestrictedScreenHeight = mDockBottom - mDockTop;
2462 // We currently want to hide the navigation UI.
2463 mNavigationBar.hideLw(true);
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;
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;
2477 mNavigationBar.showLw(true);
2478 mDockRight = mTmpNavigationFrame.left;
2479 mRestrictedScreenWidth = mDockRight - mDockLeft;
2481 // We currently want to hide the navigation UI.
2482 mNavigationBar.hideLw(true);
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;
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);
2503 if (DEBUG_LAYOUT) Log.i(TAG, String.format("mDock rect: (%d,%d - %d,%d)",
2504 mDockLeft, mDockTop, mDockRight, mDockBottom));
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;
2518 mStatusBarLayer = mStatusBar.getSurfaceLayer();
2520 // Let the status bar determine its size.
2521 mStatusBar.computeFrameLw(pf, df, vf, vf);
2523 // For layout, the status bar is always at the top with our fixed height.
2524 mStableTop = mUnrestrictedScreenTop + mStatusBarHeight;
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;
2534 mContentTop = mCurTop = mDockTop;
2535 mContentBottom = mCurBottom = mDockBottom;
2536 mContentLeft = mCurLeft = mDockLeft;
2537 mContentRight = mCurRight = mDockRight;
2539 if (DEBUG_LAYOUT) Log.v(TAG, "Status bar: " +
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));
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;
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();
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;
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());
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;
2605 df.set(insetDecors ? attached.getDisplayFrameLw() : cf);
2606 vf.set(attached.getVisibleFrameLw());
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
2611 pf.set((fl & FLAG_LAYOUT_IN_SCREEN) == 0
2612 ? attached.getFrameLw() : df);
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;
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;
2633 /** {@inheritDoc} */
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) {
2641 final boolean isDefaultDisplay = win.isDefaultDisplay();
2642 final boolean needsToOffsetInputMethodTarget = isDefaultDisplay &&
2643 (win == mLastInputMethodTargetWindow && mLastInputMethodWindow != null);
2644 if (needsToOffsetInputMethodTarget) {
2646 Slog.i(TAG, "Offset ime target window by the last ime window state");
2648 offsetInputMethodWindowLw(mLastInputMethodWindow);
2651 final int fl = attrs.flags;
2652 final int sim = attrs.softInputMode;
2653 final int sysUiFl = win.getSystemUiVisibility();
2655 final Rect pf = mTmpParentFrame;
2656 final Rect df = mTmpDisplayFrame;
2657 final Rect cf = mTmpContentFrame;
2658 final Rect vf = mTmpVisibleFrame;
2660 final boolean hasNavBar = (isDefaultDisplay && mHasNavigationBar
2661 && mNavigationBar != null && mNavigationBar.isVisibleLw());
2663 final int adjust = sim & SOFT_INPUT_MASK_ADJUST;
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);
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;
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();
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) {
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);
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
2710 // However, they should still dodge the navigation bar if it exists.
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;
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));
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;
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;
2745 if (adjust != SOFT_INPUT_ADJUST_RESIZE) {
2746 cf.left = mDockLeft;
2748 cf.right = mDockRight;
2749 cf.bottom = mDockBottom;
2751 cf.left = mContentLeft;
2752 cf.top = mContentTop;
2753 cf.right = mContentRight;
2754 cf.bottom = mContentBottom;
2757 applyStableConstraints(sysUiFl, fl, cf);
2758 if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2761 vf.right = mCurRight;
2762 vf.bottom = mCurBottom;
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) {
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;
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));
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;
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));
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;
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;
2841 applyStableConstraints(sysUiFl, fl, cf);
2843 if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2846 vf.right = mCurRight;
2847 vf.bottom = mCurBottom;
2851 } else if (attached != null) {
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);
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
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;
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;
2883 df.left = cf.left = mContentLeft;
2884 df.top = cf.top = mContentTop;
2885 df.right = cf.right = mContentRight;
2886 df.bottom = cf.bottom = mContentBottom;
2888 if (adjust != SOFT_INPUT_ADJUST_NOTHING) {
2891 vf.right = mCurRight;
2892 vf.bottom = mCurBottom;
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;
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());
2912 win.computeFrameLw(pf, df, cf, vf);
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);
2923 private void offsetInputMethodWindowLw(WindowState win) {
2924 int top = win.getContentFrameLw().top;
2925 top += win.getGivenContentInsetsLw().top;
2926 if (mContentBottom > top) {
2927 mContentBottom = top;
2929 top = win.getVisibleFrameLw().top;
2930 top += win.getGivenVisibleInsetsLw().top;
2931 if (mCurBottom > top) {
2934 if (DEBUG_LAYOUT) Log.v(TAG, "Input method: mDockBottom="
2935 + mDockBottom + " mContentBottom="
2936 + mContentBottom + " mCurBottom=" + mCurBottom);
2939 /** {@inheritDoc} */
2941 public void finishLayoutLw() {
2945 /** {@inheritDoc} */
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;
2955 mHideLockScreen = false;
2956 mAllowLockscreenWhenOn = false;
2957 mDismissKeyguard = DISMISS_KEYGUARD_NONE;
2958 mShowingLockscreen = false;
2959 mShowingDream = false;
2962 /** {@inheritDoc} */
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();
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;
2981 mForceStatusBar = true;
2984 if (attrs.type == TYPE_KEYGUARD) {
2985 mShowingLockscreen = true;
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;
2999 final boolean showWhenLocked = (attrs.flags & FLAG_SHOW_WHEN_LOCKED) != 0;
3001 if (showWhenLocked) {
3002 mAppsToBeHidden.remove(win.getAppToken());
3004 mAppsToBeHidden.add(win.getAppToken());
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;
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;
3026 if ((attrs.flags & FLAG_ALLOW_LOCK_WHILE_SCREEN_ON) != 0) {
3027 mAllowLockscreenWhenOn = true;
3034 /** {@inheritDoc} */
3036 public int finishPostLayoutPolicyLw() {
3038 boolean topIsFullscreen = false;
3040 final WindowManager.LayoutParams lp = (mTopFullscreenOpaqueWindowState != null)
3041 ? mTopFullscreenOpaqueWindowState.getAttrs()
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;
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) {
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));
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
3072 if (topIsFullscreen) {
3073 if (DEBUG_LAYOUT) Log.v(TAG, "** HIDING status bar");
3074 if (mStatusBar.hideLw(true)) {
3075 changes |= FINISH_LAYOUT_REDO_LAYOUT;
3077 mHandler.post(new Runnable() {
3081 IStatusBarService statusbar = getStatusBarService();
3082 if (statusbar != null) {
3083 statusbar.collapsePanels();
3085 } catch (RemoteException ex) {
3086 // re-acquire status bar service next time it is needed.
3087 mStatusBarService = null;
3090 } else if (DEBUG_LAYOUT) {
3091 Log.v(TAG, "Preventing status bar from hiding by policy");
3094 if (DEBUG_LAYOUT) Log.v(TAG, "** SHOWING status bar: top is not fullscreen");
3095 if (mStatusBar.showLw(true)) changes |= FINISH_LAYOUT_REDO_LAYOUT;
3100 mTopIsFullscreen = topIsFullscreen;
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="
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;
3113 if (mKeyguardMediator.isShowing()) {
3114 mHandler.post(new Runnable() {
3117 mKeyguardMediator.keyguardDone(false, false);
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;
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;
3137 mKeyguardMediator.setHidden(false);
3138 mHandler.post(new Runnable() {
3141 mKeyguardMediator.dismiss();
3146 mWinDismissingKeyguard = null;
3147 if (mKeyguard.showLw(true)) {
3148 changes |= FINISH_LAYOUT_REDO_LAYOUT
3149 | FINISH_LAYOUT_REDO_CONFIG
3150 | FINISH_LAYOUT_REDO_WALLPAPER;
3152 mKeyguardMediator.setHidden(false);
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;
3162 // update since mAllowLockscreenWhenOn might have changed
3163 updateLockScreenTimeout();
3167 public boolean allowAppAnimationsLw() {
3168 if (mKeyguard != null && mKeyguard.isVisibleLw() && !mKeyguard.isAnimatingLw()) {
3169 // If keyguard is currently visible, no reason to animate
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;
3186 /** {@inheritDoc} */
3187 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
3188 // do nothing if headless
3189 if (mHeadless) return;
3191 // lid changed state
3192 final int newLidState = lidOpen ? LID_OPEN : LID_CLOSED;
3193 if (newLidState == mLidState) {
3197 mLidState = newLidState;
3198 applyLidSwitchState();
3199 updateRotation(true);
3202 if (keyguardIsShowingTq()) {
3203 mKeyguardMediator.onWakeKeyWhenKeyguardShowingTq(KeyEvent.KEYCODE_POWER);
3205 mPowerManager.wakeUp(SystemClock.uptimeMillis());
3207 } else if (!mLidControlsSleep) {
3208 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
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);
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");
3229 final String filename = "/sys/class/switch/hdmi/state";
3230 FileReader reader = null;
3232 reader = new FileReader(filename);
3233 char[] buf = new char[15];
3234 int n = reader.read(buf);
3236 plugged = 0 != Integer.parseInt(new String(buf, 0, n-1));
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);
3243 if (reader != null) {
3246 } catch (IOException ex) {
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);
3258 * @return Whether music is being played right now.
3260 boolean isMusicActive() {
3261 final AudioManager am = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
3263 Log.w(TAG, "isMusicActive: couldn't get AudioManager reference");
3266 return am.isMusicActive();
3270 * Tell the audio service to adjust the volume appropriate to the event.
3273 void handleVolumeKey(int stream, int keycode) {
3274 IAudioService audioService = getAudioService();
3275 if (audioService == null) {
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,
3289 } catch (RemoteException e) {
3290 Log.w(TAG, "IAudioService.adjustStreamVolume() threw RemoteException " + e);
3292 mBroadcastWakeLock.release();
3296 final Object mScreenshotLock = new Object();
3297 ServiceConnection mScreenshotConnection = null;
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;
3310 // Assume this is called from the Handler thread.
3311 private void takeScreenshot() {
3312 synchronized (mScreenshotLock) {
3313 if (mScreenshotConnection != null) {
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() {
3322 public void onServiceConnected(ComponentName name, IBinder service) {
3323 synchronized (mScreenshotLock) {
3324 if (mScreenshotConnection != this) {
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()) {
3332 public void handleMessage(Message msg) {
3333 synchronized (mScreenshotLock) {
3334 if (mScreenshotConnection == myConn) {
3335 mContext.unbindService(mScreenshotConnection);
3336 mScreenshotConnection = null;
3337 mHandler.removeCallbacks(mScreenshotTimeout);
3342 msg.replyTo = new Messenger(h);
3343 msg.arg1 = msg.arg2 = 0;
3344 if (mStatusBar != null && mStatusBar.isVisibleLw())
3346 if (mNavigationBar != null && mNavigationBar.isVisibleLw())
3349 messenger.send(msg);
3350 } catch (RemoteException e) {
3355 public void onServiceDisconnected(ComponentName name) {}
3357 if (mContext.bindService(
3358 intent, conn, Context.BIND_AUTO_CREATE, UserHandle.USER_CURRENT)) {
3359 mScreenshotConnection = conn;
3360 mHandler.postDelayed(mScreenshotTimeout, 10000);
3365 /** {@inheritDoc} */
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.
3373 final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
3374 final boolean canceled = event.isCanceled();
3375 final int keyCode = event.getKeyCode();
3377 final boolean isInjected = (policyFlags & WindowManagerPolicy.FLAG_INJECTED) != 0;
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 :
3385 mKeyguardMediator.isShowingAndNotHidden() :
3386 mKeyguardMediator.isShowing()));
3388 if (keyCode == KeyEvent.KEYCODE_POWER) {
3389 policyFlags |= WindowManagerPolicy.FLAG_WAKE;
3391 final boolean isWakeKey = (policyFlags & (WindowManagerPolicy.FLAG_WAKE
3392 | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
3395 Log.d(TAG, "interceptKeyTq keycode=" + keyCode
3396 + " screenIsOn=" + isScreenOn + " keyguardActive=" + keyguardActive
3397 + " policyFlags=" + Integer.toHexString(policyFlags)
3398 + " isWakeKey=" + isWakeKey);
3401 if (down && (policyFlags & WindowManagerPolicy.FLAG_VIRTUAL) != 0
3402 && event.getRepeatCount() == 0) {
3403 performHapticFeedbackLw(null, HapticFeedbackConstants.VIRTUAL_KEY, false);
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
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;
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.
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);
3427 // Otherwise, wake the device ourselves.
3428 result |= ACTION_WAKE_UP;
3433 // Handle special keys.
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) {
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();
3449 mVolumeDownKeyTriggered = false;
3450 cancelPendingScreenshotChordAction();
3452 } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
3454 if (isScreenOn && !mVolumeUpKeyTriggered
3455 && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3456 mVolumeUpKeyTriggered = true;
3457 cancelPendingPowerKeyAction();
3458 cancelPendingScreenshotChordAction();
3461 mVolumeUpKeyTriggered = false;
3462 cancelPendingScreenshotChordAction();
3466 ITelephony telephonyService = getTelephonyService();
3467 if (telephonyService != null) {
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!");
3479 // Silence the ringer. (It's safe to call this
3480 // even if the ringer has already been silenced.)
3481 telephonyService.silenceRinger();
3483 // And *don't* pass this key thru to the current activity
3484 // (which is probably the InCallScreen.)
3485 result &= ~ACTION_PASS_TO_USER;
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);
3495 } catch (RemoteException ex) {
3496 Log.w(TAG, "ITelephony threw RemoteException", ex);
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);
3510 case KeyEvent.KEYCODE_ENDCALL: {
3511 result &= ~ACTION_PASS_TO_USER;
3513 ITelephony telephonyService = getTelephonyService();
3514 boolean hungUp = false;
3515 if (telephonyService != null) {
3517 hungUp = telephonyService.endCall();
3518 } catch (RemoteException ex) {
3519 Log.w(TAG, "ITelephony threw RemoteException", ex);
3522 interceptPowerKeyDown(!isScreenOn || hungUp);
3524 if (interceptPowerKeyUp(canceled)) {
3525 if ((mEndcallBehavior
3526 & Settings.System.END_BUTTON_BEHAVIOR_HOME) != 0) {
3531 if ((mEndcallBehavior
3532 & Settings.System.END_BUTTON_BEHAVIOR_SLEEP) != 0) {
3533 result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3540 case KeyEvent.KEYCODE_POWER: {
3541 result &= ~ACTION_PASS_TO_USER;
3543 if (isScreenOn && !mPowerKeyTriggered
3544 && (event.getFlags() & KeyEvent.FLAG_FALLBACK) == 0) {
3545 mPowerKeyTriggered = true;
3546 mPowerKeyTime = event.getDownTime();
3547 interceptScreenshotChord();
3550 ITelephony telephonyService = getTelephonyService();
3551 boolean hungUp = false;
3552 if (telephonyService != null) {
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();
3565 } catch (RemoteException ex) {
3566 Log.w(TAG, "ITelephony threw RemoteException", ex);
3569 interceptPowerKeyDown(!isScreenOn || hungUp
3570 || mVolumeDownKeyTriggered || mVolumeUpKeyTriggered);
3572 mPowerKeyTriggered = false;
3573 cancelPendingScreenshotChordAction();
3574 if (interceptPowerKeyUp(canceled || mPendingPowerKeyUpCanceled)) {
3575 result = (result & ~ACTION_WAKE_UP) | ACTION_GO_TO_SLEEP;
3577 mPendingPowerKeyUpCanceled = false;
3582 case KeyEvent.KEYCODE_MEDIA_PLAY:
3583 case KeyEvent.KEYCODE_MEDIA_PAUSE:
3584 case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
3586 ITelephony telephonyService = getTelephonyService();
3587 if (telephonyService != null) {
3589 if (!telephonyService.isIdle()) {
3590 // Suppress PLAY/PAUSE toggle when phone is ringing or in-call
3591 // to avoid music playback.
3594 } catch (RemoteException ex) {
3595 Log.w(TAG, "ITelephony threw RemoteException", ex);
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);
3622 case KeyEvent.KEYCODE_CALL: {
3624 ITelephony telephonyService = getTelephonyService();
3625 if (telephonyService != null) {
3627 if (telephonyService.isRinging()) {
3628 Log.i(TAG, "interceptKeyBeforeQueueing:"
3629 + " CALL key-down while ringing: Answer the call!");
3630 telephonyService.answerRingingCall();
3632 // And *don't* pass this key thru to the current activity
3633 // (which is presumably the InCallScreen.)
3634 result &= ~ACTION_PASS_TO_USER;
3636 } catch (RemoteException ex) {
3637 Log.w(TAG, "ITelephony threw RemoteException", ex);
3648 * When the screen is off we ignore some keys that might otherwise typically
3649 * be considered wake keys. We filter them out here.
3651 * {@link KeyEvent#KEYCODE_POWER} is notably absent from this list because it
3652 * is always considered a wake key.
3654 private boolean isWakeKeyWhenScreenOff(int 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;
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:
3681 /** {@inheritDoc} */
3683 public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
3686 final boolean isWakeMotion = (policyFlags
3687 & (WindowManagerPolicy.FLAG_WAKE | WindowManagerPolicy.FLAG_WAKE_DROPPED)) != 0;
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();
3693 // Otherwise, wake the device ourselves.
3694 result |= ACTION_WAKE_UP;
3700 void dispatchMediaKeyWithWakeLock(KeyEvent event) {
3702 Slog.d(TAG, "dispatchMediaKeyWithWakeLock: " + event);
3705 if (mHavePendingMediaKeyRepeatWithWakeLock) {
3707 Slog.d(TAG, "dispatchMediaKeyWithWakeLock: canceled repeat");
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
3715 dispatchMediaKeyWithWakeLockToAudioService(event);
3717 if (event.getAction() == KeyEvent.ACTION_DOWN
3718 && event.getRepeatCount() == 0) {
3719 mHavePendingMediaKeyRepeatWithWakeLock = true;
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());
3726 mBroadcastWakeLock.release();
3730 void dispatchMediaKeyRepeatWithWakeLock(KeyEvent event) {
3731 mHavePendingMediaKeyRepeatWithWakeLock = false;
3733 KeyEvent repeatEvent = KeyEvent.changeTimeRepeat(event,
3734 SystemClock.uptimeMillis(), 1, event.getFlags() | KeyEvent.FLAG_LONG_PRESS);
3736 Slog.d(TAG, "dispatchMediaKeyRepeatWithWakeLock: " + repeatEvent);
3739 dispatchMediaKeyWithWakeLockToAudioService(repeatEvent);
3740 mBroadcastWakeLock.release();
3743 void dispatchMediaKeyWithWakeLockToAudioService(KeyEvent event) {
3744 if (ActivityManagerNative.isSystemReady()) {
3745 IAudioService audioService = getAudioService();
3746 if (audioService != null) {
3748 audioService.dispatchMediaKeyEventUnderWakelock(event);
3749 } catch (RemoteException e) {
3750 Log.e(TAG, "dispatchMediaKeyEvent threw exception " + e);
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);
3762 updateRotation(true);
3763 updateOrientationListenerLp();
3767 BroadcastReceiver mDreamReceiver = new BroadcastReceiver() {
3769 public void onReceive(Context context, Intent intent) {
3770 if (Intent.ACTION_DREAMING_STARTED.equals(intent.getAction())) {
3771 if (mKeyguardMediator != null) {
3772 mKeyguardMediator.onDreamingStarted();
3774 } else if (Intent.ACTION_DREAMING_STOPPED.equals(intent.getAction())) {
3775 if (mKeyguardMediator != null) {
3776 mKeyguardMediator.onDreamingStopped();
3782 BroadcastReceiver mMultiuserReceiver = new BroadcastReceiver() {
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-
3790 mSettingsObserver.onChange(false);
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();
3804 public void screenTurnedOff(int why) {
3805 EventLog.writeEvent(70000, 0);
3806 synchronized (mLock) {
3807 mScreenOnEarly = false;
3808 mScreenOnFully = false;
3810 if (mKeyguardMediator != null) {
3811 mKeyguardMediator.onScreenTurnedOff(why);
3813 synchronized (mLock) {
3814 updateOrientationListenerLp();
3815 updateLockScreenTimeout();
3820 public void screenTurningOn(final ScreenOnListener screenOnListener) {
3821 EventLog.writeEvent(70000, 1);
3823 RuntimeException here = new RuntimeException("here");
3824 here.fillInStackTrace();
3825 Slog.i(TAG, "Screen turning on...", here);
3828 synchronized (mLock) {
3829 mScreenOnEarly = true;
3830 updateOrientationListenerLp();
3831 updateLockScreenTimeout();
3834 waitForKeyguard(screenOnListener);
3837 private void waitForKeyguard(final ScreenOnListener screenOnListener) {
3838 if (mKeyguardMediator != null) {
3839 if (screenOnListener != null) {
3840 mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() {
3842 public void onShown(IBinder windowToken) {
3843 waitForKeyguardWindowDrawn(windowToken, screenOnListener);
3848 mKeyguardMediator.onScreenTurnedOn(null);
3851 Slog.i(TAG, "No keyguard mediator!");
3853 finishScreenTurningOn(screenOnListener);
3856 private void waitForKeyguardWindowDrawn(IBinder windowToken,
3857 final ScreenOnListener screenOnListener) {
3858 if (windowToken != null) {
3860 if (mWindowManager.waitForWindowDrawn(
3861 windowToken, new IRemoteCallback.Stub() {
3863 public void sendResult(Bundle data) {
3864 Slog.i(TAG, "Lock screen displayed!");
3865 finishScreenTurningOn(screenOnListener);
3870 } catch (RemoteException ex) {
3871 // Can't happen in system process.
3875 Slog.i(TAG, "No lock screen!");
3876 finishScreenTurningOn(screenOnListener);
3879 private void finishScreenTurningOn(ScreenOnListener screenOnListener) {
3880 synchronized (mLock) {
3881 mScreenOnFully = true;
3885 mWindowManager.setEventDispatching(true);
3886 } catch (RemoteException unhandled) {
3889 if (screenOnListener != null) {
3890 screenOnListener.onScreenOn();
3895 public boolean isScreenOnEarly() {
3896 return mScreenOnEarly;
3900 public boolean isScreenOnFully() {
3901 return mScreenOnFully;
3904 /** {@inheritDoc} */
3905 public void enableKeyguard(boolean enabled) {
3906 if (mKeyguardMediator != null) {
3907 mKeyguardMediator.setKeyguardEnabled(enabled);
3911 /** {@inheritDoc} */
3912 public void exitKeyguardSecurely(OnKeyguardExitResult callback) {
3913 if (mKeyguardMediator != null) {
3914 mKeyguardMediator.verifyUnlock(callback);
3918 private boolean keyguardIsShowingTq() {
3919 if (mKeyguardMediator == null) return false;
3920 return mKeyguardMediator.isShowingAndNotHidden();
3924 /** {@inheritDoc} */
3925 public boolean isKeyguardLocked() {
3926 return keyguardOn();
3929 /** {@inheritDoc} */
3930 public boolean isKeyguardSecure() {
3931 if (mKeyguardMediator == null) return false;
3932 return mKeyguardMediator.isSecure();
3935 /** {@inheritDoc} */
3936 public boolean inKeyguardRestrictedKeyInputMode() {
3937 if (mKeyguardMediator == null) return false;
3938 return mKeyguardMediator.isInputRestricted();
3941 public void dismissKeyguardLw() {
3942 if (mKeyguardMediator.isShowing()) {
3943 mHandler.post(new Runnable() {
3945 if (mKeyguardMediator.isDismissable()) {
3946 // Can we just finish the keyguard straight away?
3947 mKeyguardMediator.keyguardDone(false, true);
3949 // ask the keyguard to prompt the user to authenticate if necessary
3950 mKeyguardMediator.dismiss();
3957 void sendCloseSystemWindows() {
3958 sendCloseSystemWindows(mContext, null);
3961 void sendCloseSystemWindows(String reason) {
3962 sendCloseSystemWindows(mContext, reason);
3965 static void sendCloseSystemWindows(Context context, String reason) {
3966 if (ActivityManagerNative.isSystemReady()) {
3968 ActivityManagerNative.getDefault().closeSystemDialogs(reason);
3969 } catch (RemoteException e) {
3975 public int rotationForOrientationLw(int orientation, int lastRotation) {
3977 Slog.v(TAG, "rotationForOrientationLw(orient="
3978 + orientation + ", last=" + lastRotation
3979 + "); user=" + mUserRotation + " "
3980 + ((mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED)
3981 ? "USER_ROTATION_LOCKED" : "")
3985 synchronized (mLock) {
3986 int sensorRotation = mOrientationListener.getProposedRotation(); // may be -1
3987 if (sensorRotation < 0) {
3988 sensorRotation = lastRotation;
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;
4031 if (sensorRotation != Surface.ROTATION_180
4032 || mAllowAllRotations == 1
4033 || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
4034 preferredRotation = sensorRotation;
4036 preferredRotation = lastRotation;
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;
4046 // No overriding preference.
4047 // We will do exactly what the application asked us to do.
4048 preferredRotation = -1;
4051 switch (orientation) {
4052 case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
4053 // Return portrait unless overridden.
4054 if (isAnyPortrait(preferredRotation)) {
4055 return preferredRotation;
4057 return mPortraitRotation;
4059 case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
4060 // Return landscape unless overridden.
4061 if (isLandscapeOrSeascape(preferredRotation)) {
4062 return preferredRotation;
4064 return mLandscapeRotation;
4066 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
4067 // Return reverse portrait unless overridden.
4068 if (isAnyPortrait(preferredRotation)) {
4069 return preferredRotation;
4071 return mUpsideDownRotation;
4073 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
4074 // Return seascape unless overridden.
4075 if (isLandscapeOrSeascape(preferredRotation)) {
4076 return preferredRotation;
4078 return mSeascapeRotation;
4080 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
4081 // Return either landscape rotation.
4082 if (isLandscapeOrSeascape(preferredRotation)) {
4083 return preferredRotation;
4085 if (isLandscapeOrSeascape(lastRotation)) {
4086 return lastRotation;
4088 return mLandscapeRotation;
4090 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
4091 // Return either portrait rotation.
4092 if (isAnyPortrait(preferredRotation)) {
4093 return preferredRotation;
4095 if (isAnyPortrait(lastRotation)) {
4096 return lastRotation;
4098 return mPortraitRotation;
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;
4106 return Surface.ROTATION_0;
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);
4119 case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
4120 case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
4121 case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
4122 return isLandscapeOrSeascape(rotation);
4130 public void setRotationLw(int rotation) {
4131 mOrientationListener.setCurrentRotation(rotation);
4134 private boolean isLandscapeOrSeascape(int rotation) {
4135 return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
4138 private boolean isAnyPortrait(int rotation) {
4139 return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
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();
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,
4152 UserHandle.USER_CURRENT);
4153 Settings.System.putIntForUser(res,
4154 Settings.System.ACCELEROMETER_ROTATION,
4156 UserHandle.USER_CURRENT);
4158 Settings.System.putIntForUser(res,
4159 Settings.System.ACCELEROMETER_ROTATION,
4161 UserHandle.USER_CURRENT);
4165 public void setSafeMode(boolean safeMode) {
4166 mSafeMode = safeMode;
4167 performHapticFeedbackLw(null, safeMode
4168 ? HapticFeedbackConstants.SAFE_MODE_ENABLED
4169 : HapticFeedbackConstants.SAFE_MODE_DISABLED, true);
4172 static long[] getLongIntArray(Resources r, int resid) {
4173 int[] ar = r.getIntArray(resid);
4177 long[] out = new long[ar.length];
4178 for (int i=0; i<ar.length; i++) {
4184 /** {@inheritDoc} */
4185 public void systemReady() {
4186 if (mKeyguardMediator != null) {
4187 // tell the keyguard
4188 mKeyguardMediator.onSystemReady();
4190 synchronized (mLock) {
4191 updateOrientationListenerLp();
4192 mSystemReady = true;
4193 mHandler.post(new Runnable() {
4201 /** {@inheritDoc} */
4202 public void systemBooted() {
4203 synchronized (mLock) {
4204 mSystemBooted = true;
4208 ProgressDialog mBootMsgDialog = null;
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) {
4222 @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4225 @Override public boolean dispatchTouchEvent(MotionEvent ev) {
4228 @Override public boolean dispatchTrackballEvent(MotionEvent ev) {
4231 @Override public boolean dispatchGenericMotionEvent(MotionEvent ev) {
4234 @Override public boolean dispatchPopulateAccessibilityEvent(
4235 AccessibilityEvent event) {
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();
4254 mBootMsgDialog.setMessage(msg);
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;
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.
4279 // This code must be VERY careful about the locks
4281 // In fact, the current code acquires way too many,
4282 // and probably has lurking deadlocks.
4284 synchronized (mScreenLockTimeout) {
4285 if (mLockScreenTimerActive) {
4287 mHandler.removeCallbacks(mScreenLockTimeout);
4288 mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4293 class ScreenLockTimeout implements Runnable {
4298 synchronized (this) {
4299 if (localLOGV) Log.v(TAG, "mScreenLockTimeout activating keyguard");
4300 if (mKeyguardMediator != null) {
4301 mKeyguardMediator.doKeyguardTimeout(options);
4303 mLockScreenTimerActive = false;
4308 public void setLockOptions(Bundle options) {
4309 this.options = options;
4313 ScreenLockTimeout mScreenLockTimeout = new ScreenLockTimeout();
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);
4323 mHandler.post(mScreenLockTimeout);
4326 private void updateLockScreenTimeout() {
4327 synchronized (mScreenLockTimeout) {
4328 boolean enable = (mAllowLockscreenWhenOn && mScreenOnEarly &&
4329 mKeyguardMediator != null && mKeyguardMediator.isSecure());
4330 if (mLockScreenTimerActive != enable) {
4332 if (localLOGV) Log.v(TAG, "setting lockscreen timer");
4333 mHandler.postDelayed(mScreenLockTimeout, mLockScreenTimeout);
4335 if (localLOGV) Log.v(TAG, "clearing lockscreen timer");
4336 mHandler.removeCallbacks(mScreenLockTimeout);
4338 mLockScreenTimerActive = enable;
4343 /** {@inheritDoc} */
4344 public void enableScreenAfterBoot() {
4346 applyLidSwitchState();
4347 updateRotation(true);
4350 private void applyLidSwitchState() {
4351 if (mLidState == LID_CLOSED && mLidControlsSleep) {
4352 mPowerManager.goToSleep(SystemClock.uptimeMillis());
4356 void updateRotation(boolean alwaysSendConfiguration) {
4358 //set orientation on WindowManager
4359 mWindowManager.updateRotation(alwaysSendConfiguration, false);
4360 } catch (RemoteException e) {
4365 void updateRotation(boolean alwaysSendConfiguration, boolean forceRelayout) {
4367 //set orientation on WindowManager
4368 mWindowManager.updateRotation(alwaysSendConfiguration, forceRelayout);
4369 } catch (RemoteException e) {
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);
4380 * goes to the home screen
4381 * @return whether it did anything
4385 // This code always brings home to the front.
4387 ActivityManagerNative.getDefault().stopAppSwitches();
4388 } catch (RemoteException e) {
4390 sendCloseSystemWindows();
4393 // This code brings home to the front or, if it is already
4394 // at the front, puts the device to sleep.
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");
4400 ActivityManagerNative.getDefault().stopAppSwitches();
4401 sendCloseSystemWindows();
4403 int result = ActivityManagerNative.getDefault()
4404 .startActivityAsUser(null, mHomeIntent,
4405 mHomeIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
4407 ActivityManager.START_FLAG_ONLY_IF_NEEDED,
4408 null, null, null, UserHandle.USER_CURRENT);
4409 if (result == ActivityManager.START_RETURN_INTENT_TO_CALLER) {
4412 } catch (RemoteException ex) {
4413 // bummer, the activity manager, which is in this process, is dead
4419 public void setCurrentOrientationLw(int newOrientation) {
4420 synchronized (mLock) {
4421 if (newOrientation != mCurrentAppOrientation) {
4422 mCurrentAppOrientation = newOrientation;
4423 updateOrientationListenerLp();
4428 private void performAuditoryFeedbackForAccessibilityIfNeed() {
4429 if (!isGlobalAccessibilityGestureEnabled()) {
4432 AudioManager audioManager = (AudioManager) mContext.getSystemService(
4433 Context.AUDIO_SERVICE);
4434 if (audioManager.isSilentMode()) {
4437 Ringtone ringTone = RingtoneManager.getRingtone(mContext,
4438 Settings.System.DEFAULT_NOTIFICATION_URI);
4439 ringTone.setStreamType(AudioManager.STREAM_MUSIC);
4442 private boolean isGlobalAccessibilityGestureEnabled() {
4443 return Settings.Global.getInt(mContext.getContentResolver(),
4444 Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
4447 public boolean performHapticFeedbackLw(WindowState win, int effectId, boolean always) {
4448 if (!mVibrator.hasVibrator()) {
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())) {
4456 long[] pattern = null;
4458 case HapticFeedbackConstants.LONG_PRESS:
4459 pattern = mLongPressVibePattern;
4461 case HapticFeedbackConstants.VIRTUAL_KEY:
4462 pattern = mVirtualKeyVibePattern;
4464 case HapticFeedbackConstants.KEYBOARD_TAP:
4465 pattern = mKeyboardTapVibePattern;
4467 case HapticFeedbackConstants.SAFE_MODE_DISABLED:
4468 pattern = mSafeModeDisabledVibePattern;
4470 case HapticFeedbackConstants.SAFE_MODE_ENABLED:
4471 pattern = mSafeModeEnabledVibePattern;
4476 if (pattern.length == 1) {
4477 // One-shot vibration
4478 mVibrator.vibrate(pattern[0]);
4480 // Pattern vibration
4481 mVibrator.vibrate(pattern, -1);
4487 public void keepScreenOnStartedLw() {
4491 public void keepScreenOnStoppedLw() {
4492 if (mKeyguardMediator != null && !mKeyguardMediator.isShowingAndNotHidden()) {
4493 long curTime = SystemClock.uptimeMillis();
4494 mPowerManager.userActivity(curTime, false);
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) {
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.
4513 int tmpVisibility = mFocusedWindow.getSystemUiVisibility()
4514 & ~mResettingSystemUiFlags
4515 & ~mForceClearedSystemUiFlags;
4516 if (mForcingShowNavBar && mFocusedWindow.getSurfaceLayer() < mForcingShowNavBarLayer) {
4517 tmpVisibility &= ~View.SYSTEM_UI_CLEARABLE_FLAGS;
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()) {
4526 mLastSystemUiFlags = visibility;
4527 mLastFocusNeedsMenu = needsMenu;
4528 mFocusedApp = mFocusedWindow.getAppToken();
4529 mHandler.post(new Runnable() {
4532 IStatusBarService statusbar = getStatusBarService();
4533 if (statusbar != null) {
4534 statusbar.setSystemUiVisibility(visibility, 0xffffffff);
4535 statusbar.topAppWindowChanged(needsMenu);
4537 } catch (RemoteException e) {
4538 // re-acquire status bar service next time it is needed.
4539 mStatusBarService = null;
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;
4553 public void setLastInputMethodWindowLw(WindowState ime, WindowState target) {
4554 mLastInputMethodWindow = ime;
4555 mLastInputMethodTargetWindow = target;
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: {
4572 public void setCurrentUserLw(int newUserId) {
4573 if (mKeyguardMediator != null) {
4574 mKeyguardMediator.setCurrentUser(newUserId);
4576 if (mStatusBarService != null) {
4578 mStatusBarService.setCurrentUser(newUserId);
4579 } catch (RemoteException e) {
4583 setLastInputMethodWindowLw(null, null);
4587 public void showAssistant() {
4588 mKeyguardMediator.showAssistant();
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));
4608 if (mLastFocusNeedsMenu) {
4609 pw.print(prefix); pw.print("mLastFocusNeedsMenu=");
4610 pw.println(mLastFocusNeedsMenu);
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);
4674 if (mLastInputMethodTargetWindow != null) {
4675 pw.print(prefix); pw.print("mLastInputMethodTargetWindow=");
4676 pw.println(mLastInputMethodTargetWindow);
4678 if (mStatusBar != null) {
4679 pw.print(prefix); pw.print("mStatusBar=");
4680 pw.println(mStatusBar);
4682 if (mNavigationBar != null) {
4683 pw.print(prefix); pw.print("mNavigationBar=");
4684 pw.println(mNavigationBar);
4686 if (mKeyguard != null) {
4687 pw.print(prefix); pw.print("mKeyguard=");
4688 pw.println(mKeyguard);
4690 if (mFocusedWindow != null) {
4691 pw.print(prefix); pw.print("mFocusedWindow=");
4692 pw.println(mFocusedWindow);
4694 if (mFocusedApp != null) {
4695 pw.print(prefix); pw.print("mFocusedApp=");
4696 pw.println(mFocusedApp);
4698 if (mWinDismissingKeyguard != null) {
4699 pw.print(prefix); pw.print("mWinDismissingKeyguard=");
4700 pw.println(mWinDismissingKeyguard);
4702 if (mTopFullscreenOpaqueWindowState != null) {
4703 pw.print(prefix); pw.print("mTopFullscreenOpaqueWindowState=");
4704 pw.println(mTopFullscreenOpaqueWindowState);
4706 if (mForcingShowNavBar) {
4707 pw.print(prefix); pw.print("mForcingShowNavBar=");
4708 pw.println(mForcingShowNavBar); pw.print( "mForcingShowNavBarLayer=");
4709 pw.println(mForcingShowNavBarLayer);
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);