blob: 32247e75e0668bb93c1cef3987cb10cd6abdd840 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputDispatcher"
Jeff Brown481c1572012-03-09 14:41:15 -080018#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070019
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070023#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070024
25// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown349703e2010-06-22 01:27:15 -070026#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070027
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070028// Log debug messages about the dispatch cycle.
Jeff Brown349703e2010-06-22 01:27:15 -070029#define DEBUG_DISPATCH_CYCLE 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070030
Jeff Brown9c3cda02010-06-15 01:31:58 -070031// Log debug messages about registrations.
Jeff Brown349703e2010-06-22 01:27:15 -070032#define DEBUG_REGISTRATION 0
Jeff Brown9c3cda02010-06-15 01:31:58 -070033
Jeff Brown7fbdc842010-06-17 20:52:56 -070034// Log debug messages about input event injection.
Jeff Brown349703e2010-06-22 01:27:15 -070035#define DEBUG_INJECTION 0
Jeff Brown7fbdc842010-06-17 20:52:56 -070036
Jeff Brownb88102f2010-09-08 11:49:43 -070037// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
Jeff Browna032cc02011-03-07 16:56:21 -080043// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
Jeff Brownb4ff35d2011-01-02 16:37:43 -080046#include "InputDispatcher.h"
47
Jeff Brown481c1572012-03-09 14:41:15 -080048#include <utils/Trace.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070049#include <cutils/log.h>
Mathias Agopianb93a03f82012-02-17 15:34:57 -080050#include <androidfw/PowerManager.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070051
52#include <stddef.h>
53#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070054#include <errno.h>
55#include <limits.h>
Jeff Brown22aa5122012-06-17 12:01:06 -070056#include <time.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070057
Jeff Brownf2f487182010-10-01 17:46:21 -070058#define INDENT " "
59#define INDENT2 " "
Jeff Brown265f1cc2012-06-11 18:01:06 -070060#define INDENT3 " "
61#define INDENT4 " "
Jeff Brownf2f487182010-10-01 17:46:21 -070062
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070063namespace android {
64
Jeff Brownb88102f2010-09-08 11:49:43 -070065// Default input dispatching timeout if there is no focused application or paused window
66// from which to determine an appropriate dispatching timeout.
67const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
68
69// Amount of time to allow for all pending events to be processed when an app switch
70// key is on the way. This is used to preempt input dispatch and drop input events
71// when an application takes too long to respond and the user has pressed an app switch key.
72const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
73
Jeff Brown928e0542011-01-10 11:17:36 -080074// Amount of time to allow for an event to be dispatched (measured since its eventTime)
75// before considering it stale and dropping it.
76const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
77
Jeff Brownd1c48a02012-02-06 19:12:47 -080078// Amount of time to allow touch events to be streamed out to a connection before requiring
79// that the first event be finished. This value extends the ANR timeout by the specified
80// amount. For example, if streaming is allowed to get ahead by one second relative to the
81// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
82const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
83
Jeff Brown265f1cc2012-06-11 18:01:06 -070084// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
85const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
86
Jeff Brown6876f322013-08-07 16:46:50 -070087// Number of recent events to keep for debugging purposes.
88const size_t RECENT_QUEUE_MAX_SIZE = 10;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070089
Jeff Brown7fbdc842010-06-17 20:52:56 -070090static inline nsecs_t now() {
91 return systemTime(SYSTEM_TIME_MONOTONIC);
92}
93
Jeff Brownb88102f2010-09-08 11:49:43 -070094static inline const char* toString(bool value) {
95 return value ? "true" : "false";
96}
97
Jeff Brown01ce2e92010-09-26 22:20:12 -070098static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
99 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
100 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
101}
102
103static bool isValidKeyAction(int32_t action) {
104 switch (action) {
105 case AKEY_EVENT_ACTION_DOWN:
106 case AKEY_EVENT_ACTION_UP:
107 return true;
108 default:
109 return false;
110 }
111}
112
113static bool validateKeyEvent(int32_t action) {
114 if (! isValidKeyAction(action)) {
Steve Block3762c312012-01-06 19:20:56 +0000115 ALOGE("Key event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700116 return false;
117 }
118 return true;
119}
120
Jeff Brownb6997262010-10-08 22:31:17 -0700121static bool isValidMotionAction(int32_t action, size_t pointerCount) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700122 switch (action & AMOTION_EVENT_ACTION_MASK) {
123 case AMOTION_EVENT_ACTION_DOWN:
124 case AMOTION_EVENT_ACTION_UP:
125 case AMOTION_EVENT_ACTION_CANCEL:
126 case AMOTION_EVENT_ACTION_MOVE:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700127 case AMOTION_EVENT_ACTION_OUTSIDE:
Jeff Browna032cc02011-03-07 16:56:21 -0800128 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Browncc0c1592011-02-19 05:07:28 -0800129 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Jeff Browna032cc02011-03-07 16:56:21 -0800130 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Jeff Brown33bbfd22011-02-24 20:55:35 -0800131 case AMOTION_EVENT_ACTION_SCROLL:
Jeff Brown01ce2e92010-09-26 22:20:12 -0700132 return true;
Jeff Brownb6997262010-10-08 22:31:17 -0700133 case AMOTION_EVENT_ACTION_POINTER_DOWN:
134 case AMOTION_EVENT_ACTION_POINTER_UP: {
135 int32_t index = getMotionEventActionPointerIndex(action);
136 return index >= 0 && size_t(index) < pointerCount;
137 }
Jeff Brown01ce2e92010-09-26 22:20:12 -0700138 default:
139 return false;
140 }
141}
142
143static bool validateMotionEvent(int32_t action, size_t pointerCount,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700144 const PointerProperties* pointerProperties) {
Jeff Brownb6997262010-10-08 22:31:17 -0700145 if (! isValidMotionAction(action, pointerCount)) {
Steve Block3762c312012-01-06 19:20:56 +0000146 ALOGE("Motion event has invalid action code 0x%x", action);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700147 return false;
148 }
149 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Steve Block3762c312012-01-06 19:20:56 +0000150 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
Jeff Brown01ce2e92010-09-26 22:20:12 -0700151 pointerCount, MAX_POINTERS);
152 return false;
153 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700154 BitSet32 pointerIdBits;
Jeff Brown01ce2e92010-09-26 22:20:12 -0700155 for (size_t i = 0; i < pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700156 int32_t id = pointerProperties[i].id;
Jeff Brownc3db8582010-10-20 15:33:38 -0700157 if (id < 0 || id > MAX_POINTER_ID) {
Steve Block3762c312012-01-06 19:20:56 +0000158 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
Jeff Brownc3db8582010-10-20 15:33:38 -0700159 id, MAX_POINTER_ID);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700160 return false;
161 }
Jeff Brownc3db8582010-10-20 15:33:38 -0700162 if (pointerIdBits.hasBit(id)) {
Steve Block3762c312012-01-06 19:20:56 +0000163 ALOGE("Motion event has duplicate pointer id %d", id);
Jeff Brownc3db8582010-10-20 15:33:38 -0700164 return false;
165 }
166 pointerIdBits.markBit(id);
Jeff Brown01ce2e92010-09-26 22:20:12 -0700167 }
168 return true;
169}
170
Jeff Brown83d616a2012-09-09 20:33:43 -0700171static bool isMainDisplay(int32_t displayId) {
172 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
173}
174
Jeff Brownfbf09772011-01-16 14:06:57 -0800175static void dumpRegion(String8& dump, const SkRegion& region) {
176 if (region.isEmpty()) {
177 dump.append("<empty>");
178 return;
179 }
180
181 bool first = true;
182 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
183 if (first) {
184 first = false;
185 } else {
186 dump.append("|");
187 }
188 const SkIRect& rect = it.rect();
189 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
190 }
191}
192
Jeff Brownb88102f2010-09-08 11:49:43 -0700193
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700194// --- InputDispatcher ---
195
Jeff Brown9c3cda02010-06-15 01:31:58 -0700196InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Brownb88102f2010-09-08 11:49:43 -0700197 mPolicy(policy),
Jeff Brown928e0542011-01-10 11:17:36 -0800198 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
199 mNextUnblockedEvent(NULL),
Jeff Brownc042ee22012-05-08 13:03:42 -0700200 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Jeff Brown9302c872011-07-13 22:51:29 -0700201 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700202 mLooper = new Looper(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700203
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700204 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700205
Jeff Brown214eaf42011-05-26 19:17:02 -0700206 policy->getDispatcherConfiguration(&mConfig);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700207}
208
209InputDispatcher::~InputDispatcher() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700210 { // acquire lock
211 AutoMutex _l(mLock);
212
213 resetKeyRepeatLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700214 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700215 drainInboundQueueLocked();
216 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700217
Jeff Browncbee6d62012-02-03 20:11:27 -0800218 while (mConnectionsByFd.size() != 0) {
219 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700220 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700221}
222
223void InputDispatcher::dispatchOnce() {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700224 nsecs_t nextWakeupTime = LONG_LONG_MAX;
225 { // acquire lock
226 AutoMutex _l(mLock);
Jeff Brown112b5f52012-01-27 17:32:06 -0800227 mDispatcherIsAliveCondition.broadcast();
228
Jeff Brown074b8b72012-10-31 19:01:31 -0700229 // Run a dispatch loop if there are no pending commands.
230 // The dispatch loop might enqueue commands to run afterwards.
231 if (!haveCommandsLocked()) {
232 dispatchOnceInnerLocked(&nextWakeupTime);
233 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700234
Jeff Brown074b8b72012-10-31 19:01:31 -0700235 // Run all pending commands if there are any.
236 // If any commands were run then force the next poll to wake up immediately.
Jeff Brownb88102f2010-09-08 11:49:43 -0700237 if (runCommandsLockedInterruptible()) {
Jeff Brown074b8b72012-10-31 19:01:31 -0700238 nextWakeupTime = LONG_LONG_MIN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700239 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700240 } // release lock
241
Jeff Brownb88102f2010-09-08 11:49:43 -0700242 // Wait for callback or timeout or wake. (make sure we round up, not down)
243 nsecs_t currentTime = now();
Jeff Brownaa3855d2011-03-17 01:34:19 -0700244 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -0700245 mLooper->pollOnce(timeoutMillis);
Jeff Brownb88102f2010-09-08 11:49:43 -0700246}
247
Jeff Brown214eaf42011-05-26 19:17:02 -0700248void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700249 nsecs_t currentTime = now();
250
251 // Reset the key repeat timer whenever we disallow key events, even if the next event
252 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
253 // out of sleep.
Jeff Brown214eaf42011-05-26 19:17:02 -0700254 if (!mPolicy->isKeyRepeatEnabled()) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700255 resetKeyRepeatLocked();
256 }
257
Jeff Brownb88102f2010-09-08 11:49:43 -0700258 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
259 if (mDispatchFrozen) {
260#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000261 ALOGD("Dispatch frozen. Waiting some more.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700262#endif
263 return;
264 }
265
266 // Optimize latency of app switches.
267 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
268 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
269 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
270 if (mAppSwitchDueTime < *nextWakeupTime) {
271 *nextWakeupTime = mAppSwitchDueTime;
272 }
273
Jeff Brownb88102f2010-09-08 11:49:43 -0700274 // Ready to start a new event.
275 // If we don't already have a pending event, go grab one.
276 if (! mPendingEvent) {
277 if (mInboundQueue.isEmpty()) {
278 if (isAppSwitchDue) {
279 // The inbound queue is empty so the app switch key we were waiting
280 // for will never arrive. Stop waiting for it.
281 resetPendingAppSwitchLocked(false);
282 isAppSwitchDue = false;
283 }
284
285 // Synthesize a key repeat if appropriate.
286 if (mKeyRepeatState.lastKeyEntry) {
287 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
Jeff Brown214eaf42011-05-26 19:17:02 -0700288 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700289 } else {
290 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
291 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
292 }
293 }
294 }
Jeff Browncc4f7db2011-08-30 20:34:48 -0700295
296 // Nothing to do if there is no pending event.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800297 if (!mPendingEvent) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700298 return;
299 }
300 } else {
301 // Inbound queue has at least one entry.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800302 mPendingEvent = mInboundQueue.dequeueAtHead();
Jeff Brown481c1572012-03-09 14:41:15 -0800303 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700304 }
Jeff Browne2fe69e2010-10-18 13:21:23 -0700305
306 // Poke user activity for this event.
307 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
308 pokeUserActivityLocked(mPendingEvent);
309 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800310
311 // Get ready to dispatch the event.
312 resetANRTimeoutsLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700313 }
314
315 // Now we have an event to dispatch.
Jeff Brown928e0542011-01-10 11:17:36 -0800316 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Steve Blockec193de2012-01-09 18:35:44 +0000317 ALOG_ASSERT(mPendingEvent != NULL);
Jeff Brown54a18252010-09-16 14:07:33 -0700318 bool done = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700319 DropReason dropReason = DROP_REASON_NOT_DROPPED;
320 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
321 dropReason = DROP_REASON_POLICY;
322 } else if (!mDispatchEnabled) {
323 dropReason = DROP_REASON_DISABLED;
324 }
Jeff Brown928e0542011-01-10 11:17:36 -0800325
326 if (mNextUnblockedEvent == mPendingEvent) {
327 mNextUnblockedEvent = NULL;
328 }
329
Jeff Brownb88102f2010-09-08 11:49:43 -0700330 switch (mPendingEvent->type) {
331 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
332 ConfigurationChangedEntry* typedEntry =
333 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brown54a18252010-09-16 14:07:33 -0700334 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Brownb6997262010-10-08 22:31:17 -0700335 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
Jeff Brownb88102f2010-09-08 11:49:43 -0700336 break;
337 }
338
Jeff Brown65fd2512011-08-18 11:20:58 -0700339 case EventEntry::TYPE_DEVICE_RESET: {
340 DeviceResetEntry* typedEntry =
341 static_cast<DeviceResetEntry*>(mPendingEvent);
342 done = dispatchDeviceResetLocked(currentTime, typedEntry);
343 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
344 break;
345 }
346
Jeff Brownb88102f2010-09-08 11:49:43 -0700347 case EventEntry::TYPE_KEY: {
348 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700349 if (isAppSwitchDue) {
350 if (isAppSwitchKeyEventLocked(typedEntry)) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700351 resetPendingAppSwitchLocked(true);
Jeff Brownb6997262010-10-08 22:31:17 -0700352 isAppSwitchDue = false;
353 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
354 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700355 }
356 }
Jeff Brown928e0542011-01-10 11:17:36 -0800357 if (dropReason == DROP_REASON_NOT_DROPPED
358 && isStaleEventLocked(currentTime, typedEntry)) {
359 dropReason = DROP_REASON_STALE;
360 }
361 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
362 dropReason = DROP_REASON_BLOCKED;
363 }
Jeff Brown214eaf42011-05-26 19:17:02 -0700364 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700365 break;
366 }
367
368 case EventEntry::TYPE_MOTION: {
369 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownb6997262010-10-08 22:31:17 -0700370 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
371 dropReason = DROP_REASON_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700372 }
Jeff Brown928e0542011-01-10 11:17:36 -0800373 if (dropReason == DROP_REASON_NOT_DROPPED
374 && isStaleEventLocked(currentTime, typedEntry)) {
375 dropReason = DROP_REASON_STALE;
376 }
377 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
378 dropReason = DROP_REASON_BLOCKED;
379 }
Jeff Brownb6997262010-10-08 22:31:17 -0700380 done = dispatchMotionLocked(currentTime, typedEntry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700381 &dropReason, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700382 break;
383 }
384
385 default:
Steve Blockec193de2012-01-09 18:35:44 +0000386 ALOG_ASSERT(false);
Jeff Brownb88102f2010-09-08 11:49:43 -0700387 break;
388 }
389
Jeff Brown54a18252010-09-16 14:07:33 -0700390 if (done) {
Jeff Brownb6997262010-10-08 22:31:17 -0700391 if (dropReason != DROP_REASON_NOT_DROPPED) {
392 dropInboundEventLocked(mPendingEvent, dropReason);
393 }
394
Jeff Brown54a18252010-09-16 14:07:33 -0700395 releasePendingEventLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700396 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
397 }
398}
399
400bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
401 bool needWake = mInboundQueue.isEmpty();
402 mInboundQueue.enqueueAtTail(entry);
Jeff Brown481c1572012-03-09 14:41:15 -0800403 traceInboundQueueLengthLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -0700404
405 switch (entry->type) {
Jeff Brownb6997262010-10-08 22:31:17 -0700406 case EventEntry::TYPE_KEY: {
Jeff Brown928e0542011-01-10 11:17:36 -0800407 // Optimize app switch latency.
408 // If the application takes too long to catch up then we drop all events preceding
409 // the app switch key.
Jeff Brownb6997262010-10-08 22:31:17 -0700410 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
411 if (isAppSwitchKeyEventLocked(keyEntry)) {
412 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
413 mAppSwitchSawKeyDown = true;
414 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
415 if (mAppSwitchSawKeyDown) {
416#if DEBUG_APP_SWITCH
Steve Block5baa3a62011-12-20 16:23:08 +0000417 ALOGD("App switch is pending!");
Jeff Brownb6997262010-10-08 22:31:17 -0700418#endif
419 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
420 mAppSwitchSawKeyDown = false;
421 needWake = true;
422 }
423 }
424 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700425 break;
426 }
Jeff Brown928e0542011-01-10 11:17:36 -0800427
428 case EventEntry::TYPE_MOTION: {
429 // Optimize case where the current application is unresponsive and the user
430 // decides to touch a window in a different application.
431 // If the application takes too long to catch up then we drop all events preceding
432 // the touch into the other window.
433 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
Jeff Brown33bbfd22011-02-24 20:55:35 -0800434 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
Jeff Brown928e0542011-01-10 11:17:36 -0800435 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
436 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Jeff Brown9302c872011-07-13 22:51:29 -0700437 && mInputTargetWaitApplicationHandle != NULL) {
Jeff Brown83d616a2012-09-09 20:33:43 -0700438 int32_t displayId = motionEntry->displayId;
Jeff Brown3241b6b2012-02-03 15:08:02 -0800439 int32_t x = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800440 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -0800441 int32_t y = int32_t(motionEntry->pointerCoords[0].
Jeff Brownebbd5d12011-02-17 13:01:34 -0800442 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown83d616a2012-09-09 20:33:43 -0700443 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -0700444 if (touchedWindowHandle != NULL
445 && touchedWindowHandle->inputApplicationHandle
446 != mInputTargetWaitApplicationHandle) {
Jeff Brown928e0542011-01-10 11:17:36 -0800447 // User touched a different application than the one we are waiting on.
448 // Flag the event, and start pruning the input queue.
449 mNextUnblockedEvent = motionEntry;
450 needWake = true;
451 }
452 }
453 break;
454 }
Jeff Brownb6997262010-10-08 22:31:17 -0700455 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700456
457 return needWake;
458}
459
Jeff Brown6876f322013-08-07 16:46:50 -0700460void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
461 entry->refCount += 1;
462 mRecentQueue.enqueueAtTail(entry);
463 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
464 mRecentQueue.dequeueAtHead()->release();
465 }
466}
467
Jeff Brown83d616a2012-09-09 20:33:43 -0700468sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
469 int32_t x, int32_t y) {
Jeff Brown928e0542011-01-10 11:17:36 -0800470 // Traverse windows from front to back to find touched window.
Jeff Brown9302c872011-07-13 22:51:29 -0700471 size_t numWindows = mWindowHandles.size();
Jeff Brown928e0542011-01-10 11:17:36 -0800472 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -0700473 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -0700474 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -0700475 if (windowInfo->displayId == displayId) {
476 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Brown928e0542011-01-10 11:17:36 -0800477
Jeff Brown83d616a2012-09-09 20:33:43 -0700478 if (windowInfo->visible) {
479 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
480 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
481 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
482 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
483 // Found window.
484 return windowHandle;
485 }
Jeff Brown928e0542011-01-10 11:17:36 -0800486 }
487 }
Jeff Brown928e0542011-01-10 11:17:36 -0800488
Jeff Brown83d616a2012-09-09 20:33:43 -0700489 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
490 // Error window is on top but not visible, so touch is dropped.
491 return NULL;
492 }
Jeff Brown928e0542011-01-10 11:17:36 -0800493 }
494 }
495 return NULL;
496}
497
Jeff Brownb6997262010-10-08 22:31:17 -0700498void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
499 const char* reason;
500 switch (dropReason) {
501 case DROP_REASON_POLICY:
Jeff Browne20c9e02010-10-11 14:20:19 -0700502#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000503 ALOGD("Dropped event because policy consumed it.");
Jeff Browne20c9e02010-10-11 14:20:19 -0700504#endif
Jeff Brown3122e442010-10-11 23:32:49 -0700505 reason = "inbound event was dropped because the policy consumed it";
Jeff Brownb6997262010-10-08 22:31:17 -0700506 break;
507 case DROP_REASON_DISABLED:
Steve Block6215d3f2012-01-04 20:05:49 +0000508 ALOGI("Dropped event because input dispatch is disabled.");
Jeff Brownb6997262010-10-08 22:31:17 -0700509 reason = "inbound event was dropped because input dispatch is disabled";
510 break;
511 case DROP_REASON_APP_SWITCH:
Steve Block6215d3f2012-01-04 20:05:49 +0000512 ALOGI("Dropped event because of pending overdue app switch.");
Jeff Brownb6997262010-10-08 22:31:17 -0700513 reason = "inbound event was dropped because of pending overdue app switch";
514 break;
Jeff Brown928e0542011-01-10 11:17:36 -0800515 case DROP_REASON_BLOCKED:
Steve Block6215d3f2012-01-04 20:05:49 +0000516 ALOGI("Dropped event because the current application is not responding and the user "
Jeff Brown81346812011-06-28 20:08:48 -0700517 "has started interacting with a different application.");
Jeff Brown928e0542011-01-10 11:17:36 -0800518 reason = "inbound event was dropped because the current application is not responding "
Jeff Brown81346812011-06-28 20:08:48 -0700519 "and the user has started interacting with a different application";
Jeff Brown928e0542011-01-10 11:17:36 -0800520 break;
521 case DROP_REASON_STALE:
Steve Block6215d3f2012-01-04 20:05:49 +0000522 ALOGI("Dropped event because it is stale.");
Jeff Brown928e0542011-01-10 11:17:36 -0800523 reason = "inbound event was dropped because it is stale";
524 break;
Jeff Brownb6997262010-10-08 22:31:17 -0700525 default:
Steve Blockec193de2012-01-09 18:35:44 +0000526 ALOG_ASSERT(false);
Jeff Brownb6997262010-10-08 22:31:17 -0700527 return;
528 }
529
530 switch (entry->type) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700531 case EventEntry::TYPE_KEY: {
532 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
533 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700534 break;
Jeff Brownda3d5a92011-03-29 15:11:34 -0700535 }
Jeff Brownb6997262010-10-08 22:31:17 -0700536 case EventEntry::TYPE_MOTION: {
537 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
538 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700539 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
540 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700541 } else {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700542 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
543 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brownb6997262010-10-08 22:31:17 -0700544 }
545 break;
546 }
547 }
548}
549
550bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
Michael Wright75ebb37f2013-03-15 16:27:29 -0700551 return keyCode == AKEYCODE_HOME
552 || keyCode == AKEYCODE_ENDCALL
553 || keyCode == AKEYCODE_APP_SWITCH;
Jeff Brownb88102f2010-09-08 11:49:43 -0700554}
555
Jeff Brownb6997262010-10-08 22:31:17 -0700556bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
557 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
558 && isAppSwitchKeyCode(keyEntry->keyCode)
Jeff Browne20c9e02010-10-11 14:20:19 -0700559 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brownb6997262010-10-08 22:31:17 -0700560 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
561}
562
Jeff Brownb88102f2010-09-08 11:49:43 -0700563bool InputDispatcher::isAppSwitchPendingLocked() {
564 return mAppSwitchDueTime != LONG_LONG_MAX;
565}
566
Jeff Brownb88102f2010-09-08 11:49:43 -0700567void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
568 mAppSwitchDueTime = LONG_LONG_MAX;
569
570#if DEBUG_APP_SWITCH
571 if (handled) {
Steve Block5baa3a62011-12-20 16:23:08 +0000572 ALOGD("App switch has arrived.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700573 } else {
Steve Block5baa3a62011-12-20 16:23:08 +0000574 ALOGD("App switch was abandoned.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700575 }
576#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700577}
578
Jeff Brown928e0542011-01-10 11:17:36 -0800579bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
580 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
581}
582
Jeff Brown074b8b72012-10-31 19:01:31 -0700583bool InputDispatcher::haveCommandsLocked() const {
584 return !mCommandQueue.isEmpty();
585}
586
Jeff Brown9c3cda02010-06-15 01:31:58 -0700587bool InputDispatcher::runCommandsLockedInterruptible() {
588 if (mCommandQueue.isEmpty()) {
589 return false;
590 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700591
Jeff Brown9c3cda02010-06-15 01:31:58 -0700592 do {
593 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
594
595 Command command = commandEntry->command;
596 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
597
Jeff Brown7fbdc842010-06-17 20:52:56 -0700598 commandEntry->connection.clear();
Jeff Brownac386072011-07-20 15:19:50 -0700599 delete commandEntry;
Jeff Brown9c3cda02010-06-15 01:31:58 -0700600 } while (! mCommandQueue.isEmpty());
601 return true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700602}
603
Jeff Brown9c3cda02010-06-15 01:31:58 -0700604InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
Jeff Brownac386072011-07-20 15:19:50 -0700605 CommandEntry* commandEntry = new CommandEntry(command);
Jeff Brown9c3cda02010-06-15 01:31:58 -0700606 mCommandQueue.enqueueAtTail(commandEntry);
607 return commandEntry;
608}
609
Jeff Brownb88102f2010-09-08 11:49:43 -0700610void InputDispatcher::drainInboundQueueLocked() {
611 while (! mInboundQueue.isEmpty()) {
612 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brown54a18252010-09-16 14:07:33 -0700613 releaseInboundEventLocked(entry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700614 }
Jeff Brown481c1572012-03-09 14:41:15 -0800615 traceInboundQueueLengthLocked();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700616}
617
Jeff Brown54a18252010-09-16 14:07:33 -0700618void InputDispatcher::releasePendingEventLocked() {
Jeff Brownb88102f2010-09-08 11:49:43 -0700619 if (mPendingEvent) {
Jeff Browne9bb9be2012-02-06 15:47:55 -0800620 resetANRTimeoutsLocked();
Jeff Brown54a18252010-09-16 14:07:33 -0700621 releaseInboundEventLocked(mPendingEvent);
Jeff Brownb88102f2010-09-08 11:49:43 -0700622 mPendingEvent = NULL;
623 }
624}
625
Jeff Brown54a18252010-09-16 14:07:33 -0700626void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -0700627 InjectionState* injectionState = entry->injectionState;
628 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700629#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +0000630 ALOGD("Injected inbound event was dropped.");
Jeff Brownb88102f2010-09-08 11:49:43 -0700631#endif
632 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
633 }
Jeff Brownabb4d442011-08-15 12:55:32 -0700634 if (entry == mNextUnblockedEvent) {
635 mNextUnblockedEvent = NULL;
636 }
Jeff Brown6876f322013-08-07 16:46:50 -0700637 addRecentEventLocked(entry);
Jeff Brownac386072011-07-20 15:19:50 -0700638 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700639}
640
Jeff Brownb88102f2010-09-08 11:49:43 -0700641void InputDispatcher::resetKeyRepeatLocked() {
642 if (mKeyRepeatState.lastKeyEntry) {
Jeff Brownac386072011-07-20 15:19:50 -0700643 mKeyRepeatState.lastKeyEntry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -0700644 mKeyRepeatState.lastKeyEntry = NULL;
645 }
646}
647
Jeff Brown214eaf42011-05-26 19:17:02 -0700648InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Jeff Brown349703e2010-06-22 01:27:15 -0700649 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
650
Jeff Brown349703e2010-06-22 01:27:15 -0700651 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Browne20c9e02010-10-11 14:20:19 -0700652 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
653 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700654 if (entry->refCount == 1) {
Jeff Brownac386072011-07-20 15:19:50 -0700655 entry->recycle();
Jeff Brown7fbdc842010-06-17 20:52:56 -0700656 entry->eventTime = currentTime;
Jeff Brown7fbdc842010-06-17 20:52:56 -0700657 entry->policyFlags = policyFlags;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700658 entry->repeatCount += 1;
659 } else {
Jeff Brownac386072011-07-20 15:19:50 -0700660 KeyEntry* newEntry = new KeyEntry(currentTime,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700661 entry->deviceId, entry->source, policyFlags,
Jeff Brown7fbdc842010-06-17 20:52:56 -0700662 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700663 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700664
665 mKeyRepeatState.lastKeyEntry = newEntry;
Jeff Brownac386072011-07-20 15:19:50 -0700666 entry->release();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700667
668 entry = newEntry;
669 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700670 entry->syntheticRepeat = true;
671
672 // Increment reference count since we keep a reference to the event in
673 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
674 entry->refCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700675
Jeff Brown214eaf42011-05-26 19:17:02 -0700676 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Jeff Brownb88102f2010-09-08 11:49:43 -0700677 return entry;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700678}
679
Jeff Brownb88102f2010-09-08 11:49:43 -0700680bool InputDispatcher::dispatchConfigurationChangedLocked(
681 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700682#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000683 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700684#endif
685
686 // Reset key repeating in case a keyboard device was added or removed or something.
687 resetKeyRepeatLocked();
688
689 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
690 CommandEntry* commandEntry = postCommandLocked(
691 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
692 commandEntry->eventTime = entry->eventTime;
693 return true;
694}
695
Jeff Brown65fd2512011-08-18 11:20:58 -0700696bool InputDispatcher::dispatchDeviceResetLocked(
697 nsecs_t currentTime, DeviceResetEntry* entry) {
698#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000699 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
Jeff Brown65fd2512011-08-18 11:20:58 -0700700#endif
701
702 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
703 "device was reset");
704 options.deviceId = entry->deviceId;
705 synthesizeCancelationEventsForAllConnectionsLocked(options);
706 return true;
707}
708
Jeff Brown214eaf42011-05-26 19:17:02 -0700709bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Jeff Browne20c9e02010-10-11 14:20:19 -0700710 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700711 // Preprocessing.
712 if (! entry->dispatchInProgress) {
713 if (entry->repeatCount == 0
714 && entry->action == AKEY_EVENT_ACTION_DOWN
715 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
Jeff Brown0029c662011-03-30 02:25:18 -0700716 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700717 if (mKeyRepeatState.lastKeyEntry
718 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
719 // We have seen two identical key downs in a row which indicates that the device
720 // driver is automatically generating key repeats itself. We take note of the
721 // repeat here, but we disable our own next key repeat timer since it is clear that
722 // we will not need to synthesize key repeats ourselves.
723 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
724 resetKeyRepeatLocked();
725 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
726 } else {
727 // Not a repeat. Save key down state in case we do see a repeat later.
728 resetKeyRepeatLocked();
Jeff Brown214eaf42011-05-26 19:17:02 -0700729 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
Jeff Browne46a0a42010-11-02 17:58:22 -0700730 }
731 mKeyRepeatState.lastKeyEntry = entry;
732 entry->refCount += 1;
733 } else if (! entry->syntheticRepeat) {
734 resetKeyRepeatLocked();
735 }
736
Jeff Browne2e01262011-03-02 20:34:30 -0800737 if (entry->repeatCount == 1) {
738 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
739 } else {
740 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
741 }
742
Jeff Browne46a0a42010-11-02 17:58:22 -0700743 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700744
745 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
746 }
747
Jeff Brown905805a2011-10-12 13:57:59 -0700748 // Handle case where the policy asked us to try again later last time.
749 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
750 if (currentTime < entry->interceptKeyWakeupTime) {
751 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
752 *nextWakeupTime = entry->interceptKeyWakeupTime;
753 }
754 return false; // wait until next wakeup
755 }
756 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
757 entry->interceptKeyWakeupTime = 0;
758 }
759
Jeff Brown54a18252010-09-16 14:07:33 -0700760 // Give the policy a chance to intercept the key.
761 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700762 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Jeff Brown54a18252010-09-16 14:07:33 -0700763 CommandEntry* commandEntry = postCommandLocked(
764 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -0700765 if (mFocusedWindowHandle != NULL) {
766 commandEntry->inputWindowHandle = mFocusedWindowHandle;
Jeff Brown54a18252010-09-16 14:07:33 -0700767 }
768 commandEntry->keyEntry = entry;
769 entry->refCount += 1;
770 return false; // wait for the command to run
771 } else {
772 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
773 }
774 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Jeff Browne20c9e02010-10-11 14:20:19 -0700775 if (*dropReason == DROP_REASON_NOT_DROPPED) {
776 *dropReason = DROP_REASON_POLICY;
777 }
Jeff Brown54a18252010-09-16 14:07:33 -0700778 }
779
780 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700781 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700782 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
783 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700784 return true;
785 }
786
Jeff Brownb88102f2010-09-08 11:49:43 -0700787 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800788 Vector<InputTarget> inputTargets;
789 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
790 entry, inputTargets, nextWakeupTime);
791 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
792 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -0700793 }
794
Jeff Browne9bb9be2012-02-06 15:47:55 -0800795 setInjectionResultLocked(entry, injectionResult);
796 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
797 return true;
798 }
799
800 addMonitoringTargetsLocked(inputTargets);
801
Jeff Brownb88102f2010-09-08 11:49:43 -0700802 // Dispatch the key.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800803 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700804 return true;
805}
806
807void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
808#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000809 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownb88102f2010-09-08 11:49:43 -0700810 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Jeff Browne46a0a42010-11-02 17:58:22 -0700811 "repeatCount=%d, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700812 prefix,
813 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
814 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Jeff Browne46a0a42010-11-02 17:58:22 -0700815 entry->repeatCount, entry->downTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700816#endif
817}
818
819bool InputDispatcher::dispatchMotionLocked(
Jeff Browne20c9e02010-10-11 14:20:19 -0700820 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Jeff Browne46a0a42010-11-02 17:58:22 -0700821 // Preprocessing.
822 if (! entry->dispatchInProgress) {
823 entry->dispatchInProgress = true;
Jeff Browne46a0a42010-11-02 17:58:22 -0700824
825 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
826 }
827
Jeff Brown54a18252010-09-16 14:07:33 -0700828 // Clean up if dropping the event.
Jeff Browne20c9e02010-10-11 14:20:19 -0700829 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Jeff Brown3122e442010-10-11 23:32:49 -0700830 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
831 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Jeff Brown54a18252010-09-16 14:07:33 -0700832 return true;
833 }
834
Jeff Brownb88102f2010-09-08 11:49:43 -0700835 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
836
837 // Identify targets.
Jeff Browne9bb9be2012-02-06 15:47:55 -0800838 Vector<InputTarget> inputTargets;
839
Jeff Browncc0c1592011-02-19 05:07:28 -0800840 bool conflictingPointerActions = false;
Jeff Browne9bb9be2012-02-06 15:47:55 -0800841 int32_t injectionResult;
842 if (isPointerEvent) {
843 // Pointer event. (eg. touchscreen)
844 injectionResult = findTouchedWindowTargetsLocked(currentTime,
845 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
846 } else {
847 // Non touch event. (eg. trackball)
848 injectionResult = findFocusedWindowTargetsLocked(currentTime,
849 entry, inputTargets, nextWakeupTime);
Jeff Brownb88102f2010-09-08 11:49:43 -0700850 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800851 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
852 return false;
853 }
854
855 setInjectionResultLocked(entry, injectionResult);
856 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
857 return true;
858 }
859
Jeff Brown83d616a2012-09-09 20:33:43 -0700860 // TODO: support sending secondary display events to input monitors
861 if (isMainDisplay(entry->displayId)) {
862 addMonitoringTargetsLocked(inputTargets);
863 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700864
865 // Dispatch the motion.
Jeff Browncc0c1592011-02-19 05:07:28 -0800866 if (conflictingPointerActions) {
Jeff Brownda3d5a92011-03-29 15:11:34 -0700867 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
868 "conflicting pointer actions");
869 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Browncc0c1592011-02-19 05:07:28 -0800870 }
Jeff Browne9bb9be2012-02-06 15:47:55 -0800871 dispatchEventLocked(currentTime, entry, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -0700872 return true;
873}
874
875
876void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
877#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +0000878 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -0700879 "action=0x%x, flags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700880 "metaState=0x%x, buttonState=0x%x, "
881 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownb88102f2010-09-08 11:49:43 -0700882 prefix,
Jeff Brown85a31762010-09-01 17:01:00 -0700883 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
884 entry->action, entry->flags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700885 entry->metaState, entry->buttonState,
886 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700887 entry->downTime);
888
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700889 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +0000890 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700891 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -0700892 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -0700893 "orientation=%f",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700894 i, entry->pointerProperties[i].id,
895 entry->pointerProperties[i].toolType,
Jeff Brown3241b6b2012-02-03 15:08:02 -0800896 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
897 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
898 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
899 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
900 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
901 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
902 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
903 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
904 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700905 }
906#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700907}
908
Jeff Browne9bb9be2012-02-06 15:47:55 -0800909void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
910 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700911#if DEBUG_DISPATCH_CYCLE
Jeff Brown3241b6b2012-02-03 15:08:02 -0800912 ALOGD("dispatchEventToCurrentInputTargets");
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700913#endif
914
Steve Blockec193de2012-01-09 18:35:44 +0000915 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
Jeff Brown9c3cda02010-06-15 01:31:58 -0700916
Jeff Browne2fe69e2010-10-18 13:21:23 -0700917 pokeUserActivityLocked(eventEntry);
918
Jeff Browne9bb9be2012-02-06 15:47:55 -0800919 for (size_t i = 0; i < inputTargets.size(); i++) {
920 const InputTarget& inputTarget = inputTargets.itemAt(i);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700921
Jeff Brown519e0242010-09-15 15:18:56 -0700922 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700923 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -0800924 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown3241b6b2012-02-03 15:08:02 -0800925 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700926 } else {
Jeff Brownb6997262010-10-08 22:31:17 -0700927#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +0000928 ALOGD("Dropping event delivery to target with channel '%s' because it "
Jeff Brownb6997262010-10-08 22:31:17 -0700929 "is no longer registered with the input dispatcher.",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700930 inputTarget.inputChannel->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -0700931#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700932 }
933 }
934}
935
Jeff Brownb88102f2010-09-08 11:49:43 -0700936int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
Jeff Brown9302c872011-07-13 22:51:29 -0700937 const EventEntry* entry,
938 const sp<InputApplicationHandle>& applicationHandle,
939 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700940 nsecs_t* nextWakeupTime, const char* reason) {
Jeff Brown9302c872011-07-13 22:51:29 -0700941 if (applicationHandle == NULL && windowHandle == NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -0700942 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
943#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700944 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700945#endif
946 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
947 mInputTargetWaitStartTime = currentTime;
948 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
949 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700950 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -0700951 }
952 } else {
953 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
954#if DEBUG_FOCUS
Jeff Brown265f1cc2012-06-11 18:01:06 -0700955 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
956 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
957 reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700958#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -0700959 nsecs_t timeout;
960 if (windowHandle != NULL) {
961 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
962 } else if (applicationHandle != NULL) {
963 timeout = applicationHandle->getDispatchingTimeout(
964 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
965 } else {
966 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
967 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700968
969 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
970 mInputTargetWaitStartTime = currentTime;
971 mInputTargetWaitTimeoutTime = currentTime + timeout;
972 mInputTargetWaitTimeoutExpired = false;
Jeff Brown9302c872011-07-13 22:51:29 -0700973 mInputTargetWaitApplicationHandle.clear();
Jeff Brown928e0542011-01-10 11:17:36 -0800974
Jeff Brown9302c872011-07-13 22:51:29 -0700975 if (windowHandle != NULL) {
976 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800977 }
Jeff Brown9302c872011-07-13 22:51:29 -0700978 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
979 mInputTargetWaitApplicationHandle = applicationHandle;
Jeff Brown928e0542011-01-10 11:17:36 -0800980 }
Jeff Brownb88102f2010-09-08 11:49:43 -0700981 }
982 }
983
984 if (mInputTargetWaitTimeoutExpired) {
985 return INPUT_EVENT_INJECTION_TIMED_OUT;
986 }
987
988 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown9302c872011-07-13 22:51:29 -0700989 onANRLocked(currentTime, applicationHandle, windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -0700990 entry->eventTime, mInputTargetWaitStartTime, reason);
Jeff Brownb88102f2010-09-08 11:49:43 -0700991
992 // Force poll loop to wake up immediately on next iteration once we get the
993 // ANR response back from the policy.
994 *nextWakeupTime = LONG_LONG_MIN;
995 return INPUT_EVENT_INJECTION_PENDING;
996 } else {
997 // Force poll loop to wake up when timeout is due.
998 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
999 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1000 }
1001 return INPUT_EVENT_INJECTION_PENDING;
1002 }
1003}
1004
Jeff Brown519e0242010-09-15 15:18:56 -07001005void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1006 const sp<InputChannel>& inputChannel) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001007 if (newTimeout > 0) {
1008 // Extend the timeout.
1009 mInputTargetWaitTimeoutTime = now() + newTimeout;
1010 } else {
1011 // Give up.
1012 mInputTargetWaitTimeoutExpired = true;
Jeff Brown519e0242010-09-15 15:18:56 -07001013
1014 // Input state will not be realistic. Mark it out of sync.
Jeff Browndc3e0052010-09-16 11:02:16 -07001015 if (inputChannel.get()) {
1016 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1017 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001018 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownf44e3942012-04-20 11:33:27 -07001019 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1020
1021 if (windowHandle != NULL) {
1022 mTouchState.removeWindow(windowHandle);
1023 }
1024
Jeff Brown00045a72010-12-09 18:10:30 -08001025 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brownda3d5a92011-03-29 15:11:34 -07001026 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
Jeff Brown00045a72010-12-09 18:10:30 -08001027 "application not responding");
Jeff Brownda3d5a92011-03-29 15:11:34 -07001028 synthesizeCancelationEventsForConnectionLocked(connection, options);
Jeff Brown00045a72010-12-09 18:10:30 -08001029 }
Jeff Browndc3e0052010-09-16 11:02:16 -07001030 }
Jeff Brown519e0242010-09-15 15:18:56 -07001031 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001032 }
1033}
1034
Jeff Brown519e0242010-09-15 15:18:56 -07001035nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Brownb88102f2010-09-08 11:49:43 -07001036 nsecs_t currentTime) {
1037 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1038 return currentTime - mInputTargetWaitStartTime;
1039 }
1040 return 0;
1041}
1042
1043void InputDispatcher::resetANRTimeoutsLocked() {
1044#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001045 ALOGD("Resetting ANR timeouts.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001046#endif
1047
Jeff Brownb88102f2010-09-08 11:49:43 -07001048 // Reset input target wait timeout.
1049 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Jeff Brown5ea29ab2011-07-27 11:50:51 -07001050 mInputTargetWaitApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07001051}
1052
Jeff Brown01ce2e92010-09-26 22:20:12 -07001053int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001054 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001055 int32_t injectionResult;
1056
1057 // If there is no currently focused window and no focused application
1058 // then drop the event.
Jeff Brown9302c872011-07-13 22:51:29 -07001059 if (mFocusedWindowHandle == NULL) {
1060 if (mFocusedApplicationHandle != NULL) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001061 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001062 mFocusedApplicationHandle, NULL, nextWakeupTime,
1063 "Waiting because no window has focus but there is a "
1064 "focused application that may eventually add a window "
1065 "when it finishes starting up.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001066 goto Unresponsive;
1067 }
1068
Steve Block6215d3f2012-01-04 20:05:49 +00001069 ALOGI("Dropping event because there is no focused window or focused application.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001070 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1071 goto Failed;
1072 }
1073
1074 // Check permissions.
Jeff Brown9302c872011-07-13 22:51:29 -07001075 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001076 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1077 goto Failed;
1078 }
1079
1080 // If the currently focused window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001081 if (mFocusedWindowHandle->getInfo()->paused) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001082 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001083 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1084 "Waiting because the focused window is paused.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001085 goto Unresponsive;
1086 }
1087
Jeff Brown519e0242010-09-15 15:18:56 -07001088 // If the currently focused window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001089 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
Jeff Brown519e0242010-09-15 15:18:56 -07001090 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001091 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1092 "Waiting because the focused window has not finished "
1093 "processing the input events that were previously delivered to it.");
Jeff Brown519e0242010-09-15 15:18:56 -07001094 goto Unresponsive;
1095 }
1096
Jeff Brownb88102f2010-09-08 11:49:43 -07001097 // Success! Output targets.
1098 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brown9302c872011-07-13 22:51:29 -07001099 addWindowTargetLocked(mFocusedWindowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001100 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1101 inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001102
1103 // Done.
1104Failed:
1105Unresponsive:
Jeff Brown519e0242010-09-15 15:18:56 -07001106 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1107 updateDispatchStatisticsLocked(currentTime, entry,
1108 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001109#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001110 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07001111 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001112 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001113#endif
1114 return injectionResult;
1115}
1116
Jeff Brown01ce2e92010-09-26 22:20:12 -07001117int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001118 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1119 bool* outConflictingPointerActions) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001120 enum InjectionPermission {
1121 INJECTION_PERMISSION_UNKNOWN,
1122 INJECTION_PERMISSION_GRANTED,
1123 INJECTION_PERMISSION_DENIED
1124 };
1125
Jeff Brownb88102f2010-09-08 11:49:43 -07001126 nsecs_t startTime = now();
1127
1128 // For security reasons, we defer updating the touch state until we are sure that
1129 // event injection will be allowed.
1130 //
1131 // FIXME In the original code, screenWasOff could never be set to true.
1132 // The reason is that the POLICY_FLAG_WOKE_HERE
1133 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1134 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1135 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1136 // events upon which no preprocessing took place. So policyFlags was always 0.
1137 // In the new native input dispatcher we're a bit more careful about event
1138 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1139 // Unfortunately we obtain undesirable behavior.
1140 //
1141 // Here's what happens:
1142 //
1143 // When the device dims in anticipation of going to sleep, touches
1144 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1145 // the device to brighten and reset the user activity timer.
1146 // Touches on other windows (such as the launcher window)
1147 // are dropped. Then after a moment, the device goes to sleep. Oops.
1148 //
1149 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1150 // instead of POLICY_FLAG_WOKE_HERE...
1151 //
1152 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1153
Jeff Brown83d616a2012-09-09 20:33:43 -07001154 int32_t displayId = entry->displayId;
Jeff Brownb88102f2010-09-08 11:49:43 -07001155 int32_t action = entry->action;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001156 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Brownb88102f2010-09-08 11:49:43 -07001157
1158 // Update the touch state as needed based on the properties of the touch event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001159 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1160 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Jeff Brown9302c872011-07-13 22:51:29 -07001161 sp<InputWindowHandle> newHoverWindowHandle;
Jeff Browncc0c1592011-02-19 05:07:28 -08001162
1163 bool isSplit = mTouchState.split;
Jeff Brown83d616a2012-09-09 20:33:43 -07001164 bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0
Jeff Brown2717eff2011-06-30 23:53:07 -07001165 && (mTouchState.deviceId != entry->deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07001166 || mTouchState.source != entry->source
1167 || mTouchState.displayId != displayId);
Jeff Browna032cc02011-03-07 16:56:21 -08001168 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1169 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1170 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1171 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1172 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1173 || isHoverAction);
Jeff Brown81346812011-06-28 20:08:48 -07001174 bool wrongDevice = false;
Jeff Browna032cc02011-03-07 16:56:21 -08001175 if (newGesture) {
Jeff Browncc0c1592011-02-19 05:07:28 -08001176 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brown81346812011-06-28 20:08:48 -07001177 if (switchedDevice && mTouchState.down && !down) {
1178#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001179 ALOGD("Dropping event because a pointer for a different device is already down.");
Jeff Brown81346812011-06-28 20:08:48 -07001180#endif
Jeff Browncc0c1592011-02-19 05:07:28 -08001181 mTempTouchState.copyFrom(mTouchState);
Jeff Brown81346812011-06-28 20:08:48 -07001182 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1183 switchedDevice = false;
1184 wrongDevice = true;
1185 goto Failed;
Jeff Browncc0c1592011-02-19 05:07:28 -08001186 }
Jeff Brown81346812011-06-28 20:08:48 -07001187 mTempTouchState.reset();
1188 mTempTouchState.down = down;
1189 mTempTouchState.deviceId = entry->deviceId;
1190 mTempTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001191 mTempTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001192 isSplit = false;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001193 } else {
1194 mTempTouchState.copyFrom(mTouchState);
Jeff Browncc0c1592011-02-19 05:07:28 -08001195 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001196
Jeff Browna032cc02011-03-07 16:56:21 -08001197 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001198 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001199
Jeff Brown01ce2e92010-09-26 22:20:12 -07001200 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brown3241b6b2012-02-03 15:08:02 -08001201 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001202 getAxisValue(AMOTION_EVENT_AXIS_X));
Jeff Brown3241b6b2012-02-03 15:08:02 -08001203 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
Jeff Brownebbd5d12011-02-17 13:01:34 -08001204 getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown9302c872011-07-13 22:51:29 -07001205 sp<InputWindowHandle> newTouchedWindowHandle;
1206 sp<InputWindowHandle> topErrorWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001207 bool isTouchModal = false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001208
1209 // Traverse windows from front to back to find touched window and outside targets.
Jeff Brown9302c872011-07-13 22:51:29 -07001210 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001211 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001212 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07001213 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001214 if (windowInfo->displayId != displayId) {
1215 continue; // wrong display
1216 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001217
Jeff Brown83d616a2012-09-09 20:33:43 -07001218 int32_t flags = windowInfo->layoutParamsFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001219 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
Jeff Brown9302c872011-07-13 22:51:29 -07001220 if (topErrorWindowHandle == NULL) {
1221 topErrorWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001222 }
1223 }
1224
Jeff Browncc4f7db2011-08-30 20:34:48 -07001225 if (windowInfo->visible) {
1226 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1227 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1228 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1229 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001230 if (! screenWasOff
Jeff Browncc4f7db2011-08-30 20:34:48 -07001231 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001232 newTouchedWindowHandle = windowHandle;
Jeff Brownb88102f2010-09-08 11:49:43 -07001233 }
1234 break; // found touched window, exit window loop
1235 }
1236 }
1237
Jeff Brown01ce2e92010-09-26 22:20:12 -07001238 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
Jeff Browncc4f7db2011-08-30 20:34:48 -07001239 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Jeff Browna032cc02011-03-07 16:56:21 -08001240 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
Jeff Brown9302c872011-07-13 22:51:29 -07001241 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001242 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1243 }
1244
Jeff Brown9302c872011-07-13 22:51:29 -07001245 mTempTouchState.addOrUpdateWindow(
1246 windowHandle, outsideTargetFlags, BitSet32(0));
Jeff Brownb88102f2010-09-08 11:49:43 -07001247 }
1248 }
1249 }
1250
1251 // If there is an error window but it is not taking focus (typically because
1252 // it is invisible) then wait for it. Any other focused window may in
1253 // fact be in ANR state.
Jeff Brown9302c872011-07-13 22:51:29 -07001254 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001255 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001256 NULL, NULL, nextWakeupTime,
1257 "Waiting because a system error window is about to be displayed.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001258 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1259 goto Unresponsive;
1260 }
1261
Jeff Brown01ce2e92010-09-26 22:20:12 -07001262 // Figure out whether splitting will be allowed for this window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001263 if (newTouchedWindowHandle != NULL
1264 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001265 // New window supports splitting.
1266 isSplit = true;
1267 } else if (isSplit) {
1268 // New window does not support splitting but we have already split events.
Jeff Brown8249fc62012-05-24 18:57:32 -07001269 // Ignore the new window.
1270 newTouchedWindowHandle = NULL;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001271 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001272
Jeff Brown8249fc62012-05-24 18:57:32 -07001273 // Handle the case where we did not find a window.
Jeff Brown9302c872011-07-13 22:51:29 -07001274 if (newTouchedWindowHandle == NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001275 // Try to assign the pointer to the first foreground window we find, if there is one.
1276 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1277 if (newTouchedWindowHandle == NULL) {
1278 // There is no touched window. If this is an initial down event
1279 // then wait for a window to appear that will handle the touch. This is
1280 // to ensure that we report an ANR in the case where an application has started
1281 // but not yet put up a window and the user is starting to get impatient.
1282 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1283 && mFocusedApplicationHandle != NULL) {
Jeff Brown8249fc62012-05-24 18:57:32 -07001284 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001285 mFocusedApplicationHandle, NULL, nextWakeupTime,
1286 "Waiting because there is no touchable window that can "
1287 "handle the event but there is focused application that may "
1288 "eventually add a new window when it finishes starting up.");
Jeff Brown8249fc62012-05-24 18:57:32 -07001289 goto Unresponsive;
1290 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001291
Jeff Brown8249fc62012-05-24 18:57:32 -07001292 ALOGI("Dropping event because there is no touched window.");
1293 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1294 goto Failed;
1295 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001296 }
1297
Jeff Brown19dfc832010-10-05 12:26:23 -07001298 // Set target flags.
Jeff Browna032cc02011-03-07 16:56:21 -08001299 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown19dfc832010-10-05 12:26:23 -07001300 if (isSplit) {
1301 targetFlags |= InputTarget::FLAG_SPLIT;
1302 }
Jeff Brown9302c872011-07-13 22:51:29 -07001303 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown19dfc832010-10-05 12:26:23 -07001304 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1305 }
1306
Jeff Browna032cc02011-03-07 16:56:21 -08001307 // Update hover state.
1308 if (isHoverAction) {
Jeff Brown9302c872011-07-13 22:51:29 -07001309 newHoverWindowHandle = newTouchedWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001310 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
Jeff Brown9302c872011-07-13 22:51:29 -07001311 newHoverWindowHandle = mLastHoverWindowHandle;
Jeff Browna032cc02011-03-07 16:56:21 -08001312 }
1313
Jeff Brown01ce2e92010-09-26 22:20:12 -07001314 // Update the temporary touch state.
1315 BitSet32 pointerIds;
1316 if (isSplit) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001317 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001318 pointerIds.markBit(pointerId);
Jeff Brownb88102f2010-09-08 11:49:43 -07001319 }
Jeff Brown9302c872011-07-13 22:51:29 -07001320 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brownb88102f2010-09-08 11:49:43 -07001321 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001322 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Brownb88102f2010-09-08 11:49:43 -07001323
1324 // If the pointer is not currently down, then ignore the event.
Jeff Brown01ce2e92010-09-26 22:20:12 -07001325 if (! mTempTouchState.down) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001326#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001327 ALOGD("Dropping event because the pointer is not down or we previously "
Jeff Brown76860e32010-10-25 17:37:46 -07001328 "dropped the pointer down event.");
1329#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001330 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001331 goto Failed;
1332 }
Jeff Brown98db5fa2011-06-08 15:37:10 -07001333
1334 // Check whether touches should slip outside of the current foreground window.
1335 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1336 && entry->pointerCount == 1
1337 && mTempTouchState.isSlippery()) {
Jeff Brown3241b6b2012-02-03 15:08:02 -08001338 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1339 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Jeff Brown98db5fa2011-06-08 15:37:10 -07001340
Jeff Brown9302c872011-07-13 22:51:29 -07001341 sp<InputWindowHandle> oldTouchedWindowHandle =
1342 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Brown83d616a2012-09-09 20:33:43 -07001343 sp<InputWindowHandle> newTouchedWindowHandle =
1344 findTouchedWindowAtLocked(displayId, x, y);
Jeff Brown9302c872011-07-13 22:51:29 -07001345 if (oldTouchedWindowHandle != newTouchedWindowHandle
1346 && newTouchedWindowHandle != NULL) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001347#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001348 ALOGD("Touch is slipping out of window %s into window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001349 oldTouchedWindowHandle->getName().string(),
1350 newTouchedWindowHandle->getName().string());
Jeff Brown98db5fa2011-06-08 15:37:10 -07001351#endif
1352 // Make a slippery exit from the old window.
Jeff Brown9302c872011-07-13 22:51:29 -07001353 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Jeff Brown98db5fa2011-06-08 15:37:10 -07001354 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1355
1356 // Make a slippery entrance into the new window.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001357 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001358 isSplit = true;
1359 }
1360
1361 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1362 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1363 if (isSplit) {
1364 targetFlags |= InputTarget::FLAG_SPLIT;
1365 }
Jeff Brown9302c872011-07-13 22:51:29 -07001366 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07001367 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1368 }
1369
1370 BitSet32 pointerIds;
1371 if (isSplit) {
1372 pointerIds.markBit(entry->pointerProperties[0].id);
1373 }
Jeff Brown9302c872011-07-13 22:51:29 -07001374 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001375 }
1376 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001377 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001378
Jeff Brown9302c872011-07-13 22:51:29 -07001379 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Jeff Browna032cc02011-03-07 16:56:21 -08001380 // Let the previous window know that the hover sequence is over.
Jeff Brown9302c872011-07-13 22:51:29 -07001381 if (mLastHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001382#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001383 ALOGD("Sending hover exit event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001384 mLastHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001385#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001386 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001387 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1388 }
1389
1390 // Let the new window know that the hover sequence is starting.
Jeff Brown9302c872011-07-13 22:51:29 -07001391 if (newHoverWindowHandle != NULL) {
Jeff Browna032cc02011-03-07 16:56:21 -08001392#if DEBUG_HOVER
Steve Block5baa3a62011-12-20 16:23:08 +00001393 ALOGD("Sending hover enter event to window %s.",
Jeff Browncc4f7db2011-08-30 20:34:48 -07001394 newHoverWindowHandle->getName().string());
Jeff Browna032cc02011-03-07 16:56:21 -08001395#endif
Jeff Brown9302c872011-07-13 22:51:29 -07001396 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001397 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1398 }
1399 }
1400
Jeff Brown01ce2e92010-09-26 22:20:12 -07001401 // Check permission to inject into all touched foreground windows and ensure there
1402 // is at least one touched foreground window.
1403 {
1404 bool haveForegroundWindow = false;
1405 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1406 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1407 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1408 haveForegroundWindow = true;
Jeff Brown9302c872011-07-13 22:51:29 -07001409 if (! checkInjectionPermission(touchedWindow.windowHandle,
1410 entry->injectionState)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001411 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1412 injectionPermission = INJECTION_PERMISSION_DENIED;
1413 goto Failed;
1414 }
1415 }
1416 }
1417 if (! haveForegroundWindow) {
Jeff Browna2cc28d2011-03-25 11:58:46 -07001418#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001419 ALOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Brownb88102f2010-09-08 11:49:43 -07001420#endif
1421 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001422 goto Failed;
1423 }
1424
Jeff Brown01ce2e92010-09-26 22:20:12 -07001425 // Permission granted to injection into all touched foreground windows.
1426 injectionPermission = INJECTION_PERMISSION_GRANTED;
1427 }
Jeff Brown519e0242010-09-15 15:18:56 -07001428
Kenny Root7a9db182011-06-02 15:16:05 -07001429 // Check whether windows listening for outside touches are owned by the same UID. If it is
1430 // set the policy flag that we will not reveal coordinate information to this window.
1431 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001432 sp<InputWindowHandle> foregroundWindowHandle =
1433 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001434 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Kenny Root7a9db182011-06-02 15:16:05 -07001435 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1436 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1437 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
Jeff Brown9302c872011-07-13 22:51:29 -07001438 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001439 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Jeff Brown9302c872011-07-13 22:51:29 -07001440 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Kenny Root7a9db182011-06-02 15:16:05 -07001441 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1442 }
1443 }
1444 }
1445 }
1446
Jeff Brown01ce2e92010-09-26 22:20:12 -07001447 // Ensure all touched foreground windows are ready for new input.
1448 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1449 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1450 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1451 // If the touched window is paused then keep waiting.
Jeff Browncc4f7db2011-08-30 20:34:48 -07001452 if (touchedWindow.windowHandle->getInfo()->paused) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001453 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001454 NULL, touchedWindow.windowHandle, nextWakeupTime,
1455 "Waiting because the touched window is paused.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001456 goto Unresponsive;
1457 }
1458
1459 // If the touched window is still working on previous events then keep waiting.
Jeff Brown0952c302012-02-13 13:48:59 -08001460 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001461 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brown265f1cc2012-06-11 18:01:06 -07001462 NULL, touchedWindow.windowHandle, nextWakeupTime,
1463 "Waiting because the touched window has not finished "
1464 "processing the input events that were previously delivered to it.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001465 goto Unresponsive;
1466 }
1467 }
1468 }
1469
1470 // If this is the first pointer going down and the touched window has a wallpaper
1471 // then also add the touched wallpaper windows so they are locked in for the duration
1472 // of the touch gesture.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001473 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1474 // engine only supports touch events. We would need to add a mechanism similar
1475 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1476 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brown9302c872011-07-13 22:51:29 -07001477 sp<InputWindowHandle> foregroundWindowHandle =
1478 mTempTouchState.getFirstForegroundWindowHandle();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001479 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Jeff Brown9302c872011-07-13 22:51:29 -07001480 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1481 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
Jeff Brown83d616a2012-09-09 20:33:43 -07001482 const InputWindowInfo* info = windowHandle->getInfo();
1483 if (info->displayId == displayId
1484 && windowHandle->getInfo()->layoutParamsType
1485 == InputWindowInfo::TYPE_WALLPAPER) {
Jeff Brown9302c872011-07-13 22:51:29 -07001486 mTempTouchState.addOrUpdateWindow(windowHandle,
Jeff Browna032cc02011-03-07 16:56:21 -08001487 InputTarget::FLAG_WINDOW_IS_OBSCURED
1488 | InputTarget::FLAG_DISPATCH_AS_IS,
1489 BitSet32(0));
Jeff Brown01ce2e92010-09-26 22:20:12 -07001490 }
1491 }
1492 }
1493 }
1494
Jeff Brownb88102f2010-09-08 11:49:43 -07001495 // Success! Output targets.
1496 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownb88102f2010-09-08 11:49:43 -07001497
Jeff Brown01ce2e92010-09-26 22:20:12 -07001498 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1499 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07001500 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001501 touchedWindow.pointerIds, inputTargets);
Jeff Brownb88102f2010-09-08 11:49:43 -07001502 }
1503
Jeff Browna032cc02011-03-07 16:56:21 -08001504 // Drop the outside or hover touch windows since we will not care about them
1505 // in the next iteration.
1506 mTempTouchState.filterNonAsIsTouchWindows();
Jeff Brown01ce2e92010-09-26 22:20:12 -07001507
Jeff Brownb88102f2010-09-08 11:49:43 -07001508Failed:
1509 // Check injection permission once and for all.
1510 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001511 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001512 injectionPermission = INJECTION_PERMISSION_GRANTED;
1513 } else {
1514 injectionPermission = INJECTION_PERMISSION_DENIED;
1515 }
1516 }
1517
1518 // Update final pieces of touch state if the injector had permission.
1519 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brown95712852011-01-04 19:41:59 -08001520 if (!wrongDevice) {
Jeff Brown81346812011-06-28 20:08:48 -07001521 if (switchedDevice) {
1522#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001523 ALOGD("Conflicting pointer actions: Switched to a different device.");
Jeff Brown81346812011-06-28 20:08:48 -07001524#endif
1525 *outConflictingPointerActions = true;
1526 }
1527
1528 if (isHoverAction) {
1529 // Started hovering, therefore no longer down.
1530 if (mTouchState.down) {
1531#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001532 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
Jeff Brown81346812011-06-28 20:08:48 -07001533#endif
1534 *outConflictingPointerActions = true;
1535 }
1536 mTouchState.reset();
1537 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1538 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1539 mTouchState.deviceId = entry->deviceId;
1540 mTouchState.source = entry->source;
Jeff Brown83d616a2012-09-09 20:33:43 -07001541 mTouchState.displayId = displayId;
Jeff Brown81346812011-06-28 20:08:48 -07001542 }
1543 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1544 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Jeff Brown95712852011-01-04 19:41:59 -08001545 // All pointers up or canceled.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001546 mTouchState.reset();
Jeff Brown95712852011-01-04 19:41:59 -08001547 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1548 // First pointer went down.
1549 if (mTouchState.down) {
Jeff Brownb6997262010-10-08 22:31:17 -07001550#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001551 ALOGD("Conflicting pointer actions: Down received while already down.");
Jeff Brownb6997262010-10-08 22:31:17 -07001552#endif
Jeff Brown81346812011-06-28 20:08:48 -07001553 *outConflictingPointerActions = true;
Jeff Brown95712852011-01-04 19:41:59 -08001554 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001555 mTouchState.copyFrom(mTempTouchState);
Jeff Brown95712852011-01-04 19:41:59 -08001556 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1557 // One pointer went up.
1558 if (isSplit) {
1559 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001560 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
Jeff Brownb88102f2010-09-08 11:49:43 -07001561
Jeff Brown95712852011-01-04 19:41:59 -08001562 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1563 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1564 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1565 touchedWindow.pointerIds.clearBit(pointerId);
1566 if (touchedWindow.pointerIds.isEmpty()) {
1567 mTempTouchState.windows.removeAt(i);
1568 continue;
1569 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001570 }
Jeff Brown95712852011-01-04 19:41:59 -08001571 i += 1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001572 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001573 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001574 mTouchState.copyFrom(mTempTouchState);
1575 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1576 // Discard temporary touch state since it was only valid for this action.
1577 } else {
1578 // Save changes to touch state as-is for all other actions.
1579 mTouchState.copyFrom(mTempTouchState);
Jeff Brownb88102f2010-09-08 11:49:43 -07001580 }
Jeff Browna032cc02011-03-07 16:56:21 -08001581
1582 // Update hover state.
Jeff Brown9302c872011-07-13 22:51:29 -07001583 mLastHoverWindowHandle = newHoverWindowHandle;
Jeff Brown95712852011-01-04 19:41:59 -08001584 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001585 } else {
Jeff Brown01ce2e92010-09-26 22:20:12 -07001586#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001587 ALOGD("Not updating touch focus because injection was denied.");
Jeff Brown01ce2e92010-09-26 22:20:12 -07001588#endif
Jeff Brownb88102f2010-09-08 11:49:43 -07001589 }
1590
1591Unresponsive:
Jeff Brown120a4592010-10-27 18:43:51 -07001592 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1593 mTempTouchState.reset();
1594
Jeff Brown519e0242010-09-15 15:18:56 -07001595 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1596 updateDispatchStatisticsLocked(currentTime, entry,
1597 injectionResult, timeSpentWaitingForApplication);
Jeff Brownb88102f2010-09-08 11:49:43 -07001598#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001599 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Jeff Brown01ce2e92010-09-26 22:20:12 -07001600 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown519e0242010-09-15 15:18:56 -07001601 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07001602#endif
1603 return injectionResult;
1604}
1605
Jeff Brown9302c872011-07-13 22:51:29 -07001606void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Jeff Browne9bb9be2012-02-06 15:47:55 -08001607 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1608 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001609
Jeff Browncc4f7db2011-08-30 20:34:48 -07001610 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Jeff Browne9bb9be2012-02-06 15:47:55 -08001611 InputTarget& target = inputTargets.editTop();
Jeff Browncc4f7db2011-08-30 20:34:48 -07001612 target.inputChannel = windowInfo->inputChannel;
Jeff Brownb88102f2010-09-08 11:49:43 -07001613 target.flags = targetFlags;
Jeff Browncc4f7db2011-08-30 20:34:48 -07001614 target.xOffset = - windowInfo->frameLeft;
1615 target.yOffset = - windowInfo->frameTop;
1616 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001617 target.pointerIds = pointerIds;
Jeff Brownb88102f2010-09-08 11:49:43 -07001618}
1619
Jeff Browne9bb9be2012-02-06 15:47:55 -08001620void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001621 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08001622 inputTargets.push();
Jeff Brownb88102f2010-09-08 11:49:43 -07001623
Jeff Browne9bb9be2012-02-06 15:47:55 -08001624 InputTarget& target = inputTargets.editTop();
Jeff Brownb88102f2010-09-08 11:49:43 -07001625 target.inputChannel = mMonitoringChannels[i];
Jeff Brownb6110c22011-04-01 16:15:13 -07001626 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb88102f2010-09-08 11:49:43 -07001627 target.xOffset = 0;
1628 target.yOffset = 0;
Jeff Brownb6110c22011-04-01 16:15:13 -07001629 target.pointerIds.clear();
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001630 target.scaleFactor = 1.0f;
Jeff Brownb88102f2010-09-08 11:49:43 -07001631 }
1632}
1633
Jeff Brown9302c872011-07-13 22:51:29 -07001634bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07001635 const InjectionState* injectionState) {
1636 if (injectionState
Jeff Browncc4f7db2011-08-30 20:34:48 -07001637 && (windowHandle == NULL
1638 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
Jeff Brownb6997262010-10-08 22:31:17 -07001639 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Jeff Brown9302c872011-07-13 22:51:29 -07001640 if (windowHandle != NULL) {
Steve Block8564c8d2012-01-05 23:22:43 +00001641 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Jeff Brown9302c872011-07-13 22:51:29 -07001642 "owned by uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001643 injectionState->injectorPid, injectionState->injectorUid,
Jeff Browncc4f7db2011-08-30 20:34:48 -07001644 windowHandle->getName().string(),
1645 windowHandle->getInfo()->ownerUid);
Jeff Brownb6997262010-10-08 22:31:17 -07001646 } else {
Steve Block8564c8d2012-01-05 23:22:43 +00001647 ALOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownb6997262010-10-08 22:31:17 -07001648 injectionState->injectorPid, injectionState->injectorUid);
Jeff Brownb88102f2010-09-08 11:49:43 -07001649 }
Jeff Brownb6997262010-10-08 22:31:17 -07001650 return false;
Jeff Brownb88102f2010-09-08 11:49:43 -07001651 }
1652 return true;
1653}
1654
Jeff Brown19dfc832010-10-05 12:26:23 -07001655bool InputDispatcher::isWindowObscuredAtPointLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07001656 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
Jeff Brown83d616a2012-09-09 20:33:43 -07001657 int32_t displayId = windowHandle->getInfo()->displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07001658 size_t numWindows = mWindowHandles.size();
Jeff Brownb88102f2010-09-08 11:49:43 -07001659 for (size_t i = 0; i < numWindows; i++) {
Jeff Brown9302c872011-07-13 22:51:29 -07001660 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1661 if (otherHandle == windowHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001662 break;
1663 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07001664
1665 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Jeff Brown83d616a2012-09-09 20:33:43 -07001666 if (otherInfo->displayId == displayId
1667 && otherInfo->visible && !otherInfo->isTrustedOverlay()
Jeff Browncc4f7db2011-08-30 20:34:48 -07001668 && otherInfo->frameContainsPoint(x, y)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07001669 return true;
1670 }
1671 }
1672 return false;
1673}
1674
Jeff Brownd1c48a02012-02-06 19:12:47 -08001675bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brown0952c302012-02-13 13:48:59 -08001676 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001677 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brown519e0242010-09-15 15:18:56 -07001678 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08001679 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brownd1c48a02012-02-06 19:12:47 -08001680 if (connection->inputPublisherBlocked) {
1681 return false;
1682 }
Jeff Brown0952c302012-02-13 13:48:59 -08001683 if (eventEntry->type == EventEntry::TYPE_KEY) {
1684 // If the event is a key event, then we must wait for all previous events to
1685 // complete before delivering it because previous events may have the
1686 // side-effect of transferring focus to a different window and we want to
1687 // ensure that the following keys are sent to the new window.
1688 //
1689 // Suppose the user touches a button in a window then immediately presses "A".
1690 // If the button causes a pop-up window to appear then we want to ensure that
1691 // the "A" key is delivered to the new pop-up window. This is because users
1692 // often anticipate pending UI changes when typing on a keyboard.
1693 // To obtain this behavior, we must serialize key events with respect to all
1694 // prior input events.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001695 return connection->outboundQueue.isEmpty()
1696 && connection->waitQueue.isEmpty();
1697 }
Jeff Brown0952c302012-02-13 13:48:59 -08001698 // Touch events can always be sent to a window immediately because the user intended
1699 // to touch whatever was visible at the time. Even if focus changes or a new
1700 // window appears moments later, the touch event was meant to be delivered to
1701 // whatever window happened to be on screen at the time.
1702 //
1703 // Generic motion events, such as trackball or joystick events are a little trickier.
1704 // Like key events, generic motion events are delivered to the focused window.
1705 // Unlike key events, generic motion events don't tend to transfer focus to other
1706 // windows and it is not important for them to be serialized. So we prefer to deliver
1707 // generic motion events as soon as possible to improve efficiency and reduce lag
1708 // through batching.
1709 //
1710 // The one case where we pause input event delivery is when the wait queue is piling
1711 // up with lots of events because the application is not responding.
1712 // This condition ensures that ANRs are detected reliably.
Jeff Brownd1c48a02012-02-06 19:12:47 -08001713 if (!connection->waitQueue.isEmpty()
1714 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1715 + STREAM_AHEAD_EVENT_TIMEOUT) {
1716 return false;
1717 }
Jeff Brown519e0242010-09-15 15:18:56 -07001718 }
Jeff Brownd1c48a02012-02-06 19:12:47 -08001719 return true;
Jeff Brown519e0242010-09-15 15:18:56 -07001720}
1721
Jeff Brown9302c872011-07-13 22:51:29 -07001722String8 InputDispatcher::getApplicationWindowLabelLocked(
1723 const sp<InputApplicationHandle>& applicationHandle,
1724 const sp<InputWindowHandle>& windowHandle) {
1725 if (applicationHandle != NULL) {
1726 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001727 String8 label(applicationHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001728 label.append(" - ");
Jeff Browncc4f7db2011-08-30 20:34:48 -07001729 label.append(windowHandle->getName());
Jeff Brown519e0242010-09-15 15:18:56 -07001730 return label;
1731 } else {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001732 return applicationHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001733 }
Jeff Brown9302c872011-07-13 22:51:29 -07001734 } else if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07001735 return windowHandle->getName();
Jeff Brown519e0242010-09-15 15:18:56 -07001736 } else {
1737 return String8("<unknown application or window>");
1738 }
1739}
1740
Jeff Browne2fe69e2010-10-18 13:21:23 -07001741void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Jeff Brown1e3b98d2012-09-30 18:58:59 -07001742 if (mFocusedWindowHandle != NULL) {
1743 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1744 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1745#if DEBUG_DISPATCH_CYCLE
1746 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1747#endif
1748 return;
1749 }
1750 }
1751
Jeff Brownb696de52012-07-27 15:38:50 -07001752 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Jeff Brown4d396052010-10-29 21:50:21 -07001753 switch (eventEntry->type) {
1754 case EventEntry::TYPE_MOTION: {
Jeff Browne2fe69e2010-10-18 13:21:23 -07001755 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
Jeff Brown4d396052010-10-29 21:50:21 -07001756 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1757 return;
1758 }
1759
Jeff Brown56194eb2011-03-02 19:23:13 -08001760 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
Jeff Brownb696de52012-07-27 15:38:50 -07001761 eventType = USER_ACTIVITY_EVENT_TOUCH;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001762 }
Jeff Brown4d396052010-10-29 21:50:21 -07001763 break;
1764 }
1765 case EventEntry::TYPE_KEY: {
1766 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1767 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1768 return;
1769 }
Jeff Brownb696de52012-07-27 15:38:50 -07001770 eventType = USER_ACTIVITY_EVENT_BUTTON;
Jeff Brown4d396052010-10-29 21:50:21 -07001771 break;
1772 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001773 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001774
Jeff Brownb88102f2010-09-08 11:49:43 -07001775 CommandEntry* commandEntry = postCommandLocked(
1776 & InputDispatcher::doPokeUserActivityLockedInterruptible);
Jeff Browne2fe69e2010-10-18 13:21:23 -07001777 commandEntry->eventTime = eventEntry->eventTime;
Jeff Brownb88102f2010-09-08 11:49:43 -07001778 commandEntry->userActivityEventType = eventType;
1779}
1780
Jeff Brown7fbdc842010-06-17 20:52:56 -07001781void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001782 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001783#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001784 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Jeff Brown9cc695c2011-08-23 18:35:04 -07001785 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
Jeff Brown3241b6b2012-02-03 15:08:02 -08001786 "pointerIds=0x%x",
Jeff Brown519e0242010-09-15 15:18:56 -07001787 connection->getInputChannelName(), inputTarget->flags,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001788 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001789 inputTarget->scaleFactor, inputTarget->pointerIds.value);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001790#endif
1791
1792 // Skip this event if the connection status is not normal.
Jeff Brown519e0242010-09-15 15:18:56 -07001793 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001794 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Brownb6997262010-10-08 22:31:17 -07001795#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001796 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Jeff Brownb88102f2010-09-08 11:49:43 -07001797 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Brownb6997262010-10-08 22:31:17 -07001798#endif
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001799 return;
1800 }
1801
Jeff Brown01ce2e92010-09-26 22:20:12 -07001802 // Split a motion event if needed.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001803 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
Steve Blockec193de2012-01-09 18:35:44 +00001804 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
Jeff Brown01ce2e92010-09-26 22:20:12 -07001805
1806 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1807 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1808 MotionEntry* splitMotionEntry = splitMotionEvent(
1809 originalMotionEntry, inputTarget->pointerIds);
Jeff Brown58a2da82011-01-25 16:02:22 -08001810 if (!splitMotionEntry) {
1811 return; // split event was dropped
1812 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07001813#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00001814 ALOGD("channel '%s' ~ Split motion event.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07001815 connection->getInputChannelName());
1816 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1817#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001818 enqueueDispatchEntriesLocked(currentTime, connection,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001819 splitMotionEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001820 splitMotionEntry->release();
1821 return;
Jeff Brown01ce2e92010-09-26 22:20:12 -07001822 }
1823 }
1824
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001825 // Not splitting. Enqueue dispatch entries for the event as is.
Jeff Brown3241b6b2012-02-03 15:08:02 -08001826 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001827}
1828
1829void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001830 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001831 bool wasEmpty = connection->outboundQueue.isEmpty();
1832
Jeff Browna032cc02011-03-07 16:56:21 -08001833 // Enqueue dispatch entries for the requested modes.
1834 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001835 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
Jeff Browna032cc02011-03-07 16:56:21 -08001836 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001837 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
Jeff Browna032cc02011-03-07 16:56:21 -08001838 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001839 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001840 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001841 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001842 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001843 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
Jeff Brown98db5fa2011-06-08 15:37:10 -07001844 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001845 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Jeff Browna032cc02011-03-07 16:56:21 -08001846
1847 // If the outbound queue was previously empty, start the dispatch cycle going.
Jeff Brownb6110c22011-04-01 16:15:13 -07001848 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
Jeff Browna032cc02011-03-07 16:56:21 -08001849 startDispatchCycleLocked(currentTime, connection);
1850 }
1851}
1852
1853void InputDispatcher::enqueueDispatchEntryLocked(
1854 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Brown3241b6b2012-02-03 15:08:02 -08001855 int32_t dispatchMode) {
Jeff Browna032cc02011-03-07 16:56:21 -08001856 int32_t inputTargetFlags = inputTarget->flags;
1857 if (!(inputTargetFlags & dispatchMode)) {
1858 return;
1859 }
1860 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1861
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001862 // This is a new event.
1863 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Brownac386072011-07-20 15:19:50 -07001864 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07001865 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Dianne Hackborne2515ee2011-04-27 18:52:56 -04001866 inputTarget->scaleFactor);
Jeff Brown6ec402b2010-07-28 15:48:59 -07001867
Jeff Brown81346812011-06-28 20:08:48 -07001868 // Apply target flags and update the connection's input state.
1869 switch (eventEntry->type) {
1870 case EventEntry::TYPE_KEY: {
1871 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1872 dispatchEntry->resolvedAction = keyEntry->action;
1873 dispatchEntry->resolvedFlags = keyEntry->flags;
1874
1875 if (!connection->inputState.trackKey(keyEntry,
1876 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1877#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001878 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Jeff Brown81346812011-06-28 20:08:48 -07001879 connection->getInputChannelName());
1880#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001881 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001882 return; // skip the inconsistent event
1883 }
1884 break;
1885 }
1886
1887 case EventEntry::TYPE_MOTION: {
1888 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1889 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1890 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1891 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1892 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1893 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1894 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1895 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1896 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1897 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1898 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1899 } else {
1900 dispatchEntry->resolvedAction = motionEntry->action;
1901 }
1902 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1903 && !connection->inputState.isHovering(
Jeff Brown83d616a2012-09-09 20:33:43 -07001904 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
Jeff Brown81346812011-06-28 20:08:48 -07001905#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001906 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Jeff Brown81346812011-06-28 20:08:48 -07001907 connection->getInputChannelName());
1908#endif
1909 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1910 }
1911
1912 dispatchEntry->resolvedFlags = motionEntry->flags;
1913 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1914 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1915 }
1916
1917 if (!connection->inputState.trackMotion(motionEntry,
1918 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1919#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001920 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Jeff Brown81346812011-06-28 20:08:48 -07001921 connection->getInputChannelName());
1922#endif
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001923 delete dispatchEntry;
Jeff Brown81346812011-06-28 20:08:48 -07001924 return; // skip the inconsistent event
1925 }
1926 break;
1927 }
1928 }
1929
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08001930 // Remember that we are waiting for this dispatch to complete.
1931 if (dispatchEntry->hasForegroundTarget()) {
1932 incrementPendingForegroundDispatchesLocked(eventEntry);
1933 }
1934
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001935 // Enqueue the dispatch entry.
1936 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08001937 traceOutboundQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001938}
1939
Jeff Brown7fbdc842010-06-17 20:52:56 -07001940void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown519e0242010-09-15 15:18:56 -07001941 const sp<Connection>& connection) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001942#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00001943 ALOGD("channel '%s' ~ startDispatchCycle",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001944 connection->getInputChannelName());
1945#endif
1946
Jeff Brownd1c48a02012-02-06 19:12:47 -08001947 while (connection->status == Connection::STATUS_NORMAL
1948 && !connection->outboundQueue.isEmpty()) {
1949 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
Jeff Brown265f1cc2012-06-11 18:01:06 -07001950 dispatchEntry->deliveryTime = currentTime;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001951
Jeff Brownd1c48a02012-02-06 19:12:47 -08001952 // Publish the event.
1953 status_t status;
1954 EventEntry* eventEntry = dispatchEntry->eventEntry;
1955 switch (eventEntry->type) {
1956 case EventEntry::TYPE_KEY: {
1957 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001958
Jeff Brownd1c48a02012-02-06 19:12:47 -08001959 // Publish the key event.
Jeff Brown072ec962012-02-07 14:46:57 -08001960 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08001961 keyEntry->deviceId, keyEntry->source,
1962 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1963 keyEntry->keyCode, keyEntry->scanCode,
1964 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1965 keyEntry->eventTime);
1966 break;
1967 }
Jeff Brownb88102f2010-09-08 11:49:43 -07001968
Jeff Brownd1c48a02012-02-06 19:12:47 -08001969 case EventEntry::TYPE_MOTION: {
1970 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001971
Jeff Brownd1c48a02012-02-06 19:12:47 -08001972 PointerCoords scaledCoords[MAX_POINTERS];
1973 const PointerCoords* usingCoords = motionEntry->pointerCoords;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001974
Jeff Brownd1c48a02012-02-06 19:12:47 -08001975 // Set the X and Y offset depending on the input source.
1976 float xOffset, yOffset, scaleFactor;
1977 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1978 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1979 scaleFactor = dispatchEntry->scaleFactor;
1980 xOffset = dispatchEntry->xOffset * scaleFactor;
1981 yOffset = dispatchEntry->yOffset * scaleFactor;
1982 if (scaleFactor != 1.0f) {
1983 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1984 scaledCoords[i] = motionEntry->pointerCoords[i];
1985 scaledCoords[i].scale(scaleFactor);
1986 }
1987 usingCoords = scaledCoords;
1988 }
1989 } else {
1990 xOffset = 0.0f;
1991 yOffset = 0.0f;
1992 scaleFactor = 1.0f;
1993
1994 // We don't want the dispatch target to know.
1995 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1996 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1997 scaledCoords[i].clear();
1998 }
1999 usingCoords = scaledCoords;
2000 }
2001 }
2002
2003 // Publish the motion event.
Jeff Brown072ec962012-02-07 14:46:57 -08002004 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Jeff Brownd1c48a02012-02-06 19:12:47 -08002005 motionEntry->deviceId, motionEntry->source,
2006 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2007 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
2008 xOffset, yOffset,
2009 motionEntry->xPrecision, motionEntry->yPrecision,
2010 motionEntry->downTime, motionEntry->eventTime,
2011 motionEntry->pointerCount, motionEntry->pointerProperties,
2012 usingCoords);
2013 break;
2014 }
2015
2016 default:
2017 ALOG_ASSERT(false);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002018 return;
2019 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002020
Jeff Brownd1c48a02012-02-06 19:12:47 -08002021 // Check the result.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002022 if (status) {
Jeff Brownd1c48a02012-02-06 19:12:47 -08002023 if (status == WOULD_BLOCK) {
2024 if (connection->waitQueue.isEmpty()) {
2025 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2026 "This is unexpected because the wait queue is empty, so the pipe "
2027 "should be empty and we shouldn't have any problems writing an "
2028 "event to it, status=%d", connection->getInputChannelName(), status);
2029 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2030 } else {
2031 // Pipe is full and we are waiting for the app to finish process some events
2032 // before sending more events to it.
2033#if DEBUG_DISPATCH_CYCLE
2034 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2035 "waiting for the application to catch up",
2036 connection->getInputChannelName());
2037#endif
2038 connection->inputPublisherBlocked = true;
2039 }
2040 } else {
2041 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2042 "status=%d", connection->getInputChannelName(), status);
2043 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2044 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002045 return;
2046 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002047
Jeff Brownd1c48a02012-02-06 19:12:47 -08002048 // Re-enqueue the event on the wait queue.
2049 connection->outboundQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002050 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002051 connection->waitQueue.enqueueAtTail(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08002052 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002053 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002054}
2055
Jeff Brown7fbdc842010-06-17 20:52:56 -07002056void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown072ec962012-02-07 14:46:57 -08002057 const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002058#if DEBUG_DISPATCH_CYCLE
Jeff Brown072ec962012-02-07 14:46:57 -08002059 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2060 connection->getInputChannelName(), seq, toString(handled));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002061#endif
2062
Jeff Brownd1c48a02012-02-06 19:12:47 -08002063 connection->inputPublisherBlocked = false;
2064
Jeff Brown9c3cda02010-06-15 01:31:58 -07002065 if (connection->status == Connection::STATUS_BROKEN
2066 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002067 return;
2068 }
2069
Jeff Brown3915bb82010-11-05 15:02:16 -07002070 // Notify other system components and prepare to start the next dispatch cycle.
Jeff Brown072ec962012-02-07 14:46:57 -08002071 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
Jeff Brownb88102f2010-09-08 11:49:43 -07002072}
2073
Jeff Brownb6997262010-10-08 22:31:17 -07002074void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Jeff Browncc4f7db2011-08-30 20:34:48 -07002075 const sp<Connection>& connection, bool notify) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002076#if DEBUG_DISPATCH_CYCLE
Steve Block5baa3a62011-12-20 16:23:08 +00002077 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002078 connection->getInputChannelName(), toString(notify));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002079#endif
2080
Jeff Brownd1c48a02012-02-06 19:12:47 -08002081 // Clear the dispatch queues.
2082 drainDispatchQueueLocked(&connection->outboundQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002083 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08002084 drainDispatchQueueLocked(&connection->waitQueue);
Jeff Brown481c1572012-03-09 14:41:15 -08002085 traceWaitQueueLengthLocked(connection);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002086
Jeff Brownb6997262010-10-08 22:31:17 -07002087 // The connection appears to be unrecoverably broken.
Jeff Brown9c3cda02010-06-15 01:31:58 -07002088 // Ignore already broken or zombie connections.
Jeff Brownb6997262010-10-08 22:31:17 -07002089 if (connection->status == Connection::STATUS_NORMAL) {
2090 connection->status = Connection::STATUS_BROKEN;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002091
Jeff Browncc4f7db2011-08-30 20:34:48 -07002092 if (notify) {
2093 // Notify other system components.
2094 onDispatchCycleBrokenLocked(currentTime, connection);
2095 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002096 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002097}
2098
Jeff Brownd1c48a02012-02-06 19:12:47 -08002099void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2100 while (!queue->isEmpty()) {
2101 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2102 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brownb88102f2010-09-08 11:49:43 -07002103 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002104}
2105
Jeff Brownd1c48a02012-02-06 19:12:47 -08002106void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2107 if (dispatchEntry->hasForegroundTarget()) {
2108 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2109 }
2110 delete dispatchEntry;
2111}
2112
Jeff Browncbee6d62012-02-03 20:11:27 -08002113int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002114 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2115
2116 { // acquire lock
2117 AutoMutex _l(d->mLock);
2118
Jeff Browncbee6d62012-02-03 20:11:27 -08002119 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002120 if (connectionIndex < 0) {
Steve Block3762c312012-01-06 19:20:56 +00002121 ALOGE("Received spurious receive callback for unknown input channel. "
Jeff Browncbee6d62012-02-03 20:11:27 -08002122 "fd=%d, events=0x%x", fd, events);
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002123 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002124 }
2125
Jeff Browncc4f7db2011-08-30 20:34:48 -07002126 bool notify;
Jeff Browncbee6d62012-02-03 20:11:27 -08002127 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002128 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2129 if (!(events & ALOOPER_EVENT_INPUT)) {
Steve Block8564c8d2012-01-05 23:22:43 +00002130 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002131 "events=0x%x", connection->getInputChannelName(), events);
2132 return 1;
2133 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002134
Jeff Brown1adee112012-02-07 10:25:41 -08002135 nsecs_t currentTime = now();
2136 bool gotOne = false;
2137 status_t status;
2138 for (;;) {
Jeff Brown072ec962012-02-07 14:46:57 -08002139 uint32_t seq;
2140 bool handled;
2141 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002142 if (status) {
2143 break;
2144 }
Jeff Brown072ec962012-02-07 14:46:57 -08002145 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
Jeff Brown1adee112012-02-07 10:25:41 -08002146 gotOne = true;
2147 }
2148 if (gotOne) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002149 d->runCommandsLockedInterruptible();
Jeff Brown1adee112012-02-07 10:25:41 -08002150 if (status == WOULD_BLOCK) {
2151 return 1;
2152 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002153 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002154
Jeff Brown1adee112012-02-07 10:25:41 -08002155 notify = status != DEAD_OBJECT || !connection->monitor;
2156 if (notify) {
2157 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2158 connection->getInputChannelName(), status);
2159 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002160 } else {
2161 // Monitor channels are never explicitly unregistered.
2162 // We do it automatically when the remote endpoint is closed so don't warn
2163 // about them.
2164 notify = !connection->monitor;
2165 if (notify) {
Steve Block8564c8d2012-01-05 23:22:43 +00002166 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Jeff Browncc4f7db2011-08-30 20:34:48 -07002167 "events=0x%x", connection->getInputChannelName(), events);
2168 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002169 }
2170
Jeff Browncc4f7db2011-08-30 20:34:48 -07002171 // Unregister the channel.
2172 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2173 return 0; // remove the callback
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002174 } // release lock
2175}
2176
Jeff Brownb6997262010-10-08 22:31:17 -07002177void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002178 const CancelationOptions& options) {
Jeff Browncbee6d62012-02-03 20:11:27 -08002179 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
Jeff Brownb6997262010-10-08 22:31:17 -07002180 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002181 mConnectionsByFd.valueAt(i), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002182 }
2183}
2184
2185void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002186 const sp<InputChannel>& channel, const CancelationOptions& options) {
Jeff Brownb6997262010-10-08 22:31:17 -07002187 ssize_t index = getConnectionIndexLocked(channel);
2188 if (index >= 0) {
2189 synthesizeCancelationEventsForConnectionLocked(
Jeff Browncbee6d62012-02-03 20:11:27 -08002190 mConnectionsByFd.valueAt(index), options);
Jeff Brownb6997262010-10-08 22:31:17 -07002191 }
2192}
2193
2194void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Jeff Brownda3d5a92011-03-29 15:11:34 -07002195 const sp<Connection>& connection, const CancelationOptions& options) {
Jeff Brownc0cb3dc2012-01-12 18:30:12 -08002196 if (connection->status == Connection::STATUS_BROKEN) {
2197 return;
2198 }
2199
Jeff Brownb6997262010-10-08 22:31:17 -07002200 nsecs_t currentTime = now();
2201
Jeff Brown8b4be5602012-02-06 16:31:05 -08002202 Vector<EventEntry*> cancelationEvents;
Jeff Brownac386072011-07-20 15:19:50 -07002203 connection->inputState.synthesizeCancelationEvents(currentTime,
Jeff Brown8b4be5602012-02-06 16:31:05 -08002204 cancelationEvents, options);
Jeff Brownb6997262010-10-08 22:31:17 -07002205
Jeff Brown8b4be5602012-02-06 16:31:05 -08002206 if (!cancelationEvents.isEmpty()) {
Jeff Brownb6997262010-10-08 22:31:17 -07002207#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002208 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
Jeff Brownda3d5a92011-03-29 15:11:34 -07002209 "with reality: %s, mode=%d.",
Jeff Brown8b4be5602012-02-06 16:31:05 -08002210 connection->getInputChannelName(), cancelationEvents.size(),
Jeff Brownda3d5a92011-03-29 15:11:34 -07002211 options.reason, options.mode);
Jeff Brownb6997262010-10-08 22:31:17 -07002212#endif
Jeff Brown8b4be5602012-02-06 16:31:05 -08002213 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2214 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
Jeff Brownb6997262010-10-08 22:31:17 -07002215 switch (cancelationEventEntry->type) {
2216 case EventEntry::TYPE_KEY:
2217 logOutboundKeyDetailsLocked("cancel - ",
2218 static_cast<KeyEntry*>(cancelationEventEntry));
2219 break;
2220 case EventEntry::TYPE_MOTION:
2221 logOutboundMotionDetailsLocked("cancel - ",
2222 static_cast<MotionEntry*>(cancelationEventEntry));
2223 break;
2224 }
2225
Jeff Brown81346812011-06-28 20:08:48 -07002226 InputTarget target;
Jeff Brown9302c872011-07-13 22:51:29 -07002227 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2228 if (windowHandle != NULL) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07002229 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2230 target.xOffset = -windowInfo->frameLeft;
2231 target.yOffset = -windowInfo->frameTop;
2232 target.scaleFactor = windowInfo->scaleFactor;
Jeff Brownb6997262010-10-08 22:31:17 -07002233 } else {
Jeff Brown81346812011-06-28 20:08:48 -07002234 target.xOffset = 0;
2235 target.yOffset = 0;
2236 target.scaleFactor = 1.0f;
Jeff Brownb6997262010-10-08 22:31:17 -07002237 }
Jeff Brown81346812011-06-28 20:08:48 -07002238 target.inputChannel = connection->inputChannel;
2239 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brownb6997262010-10-08 22:31:17 -07002240
Jeff Brown81346812011-06-28 20:08:48 -07002241 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Jeff Brown3241b6b2012-02-03 15:08:02 -08002242 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownb6997262010-10-08 22:31:17 -07002243
Jeff Brownac386072011-07-20 15:19:50 -07002244 cancelationEventEntry->release();
Jeff Brownb6997262010-10-08 22:31:17 -07002245 }
2246
Jeff Brownd1c48a02012-02-06 19:12:47 -08002247 startDispatchCycleLocked(currentTime, connection);
Jeff Brownb6997262010-10-08 22:31:17 -07002248 }
2249}
2250
Jeff Brown01ce2e92010-09-26 22:20:12 -07002251InputDispatcher::MotionEntry*
2252InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
Steve Blockec193de2012-01-09 18:35:44 +00002253 ALOG_ASSERT(pointerIds.value != 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002254
2255 uint32_t splitPointerIndexMap[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002256 PointerProperties splitPointerProperties[MAX_POINTERS];
Jeff Brown01ce2e92010-09-26 22:20:12 -07002257 PointerCoords splitPointerCoords[MAX_POINTERS];
2258
2259 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2260 uint32_t splitPointerCount = 0;
2261
2262 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2263 originalPointerIndex++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002264 const PointerProperties& pointerProperties =
2265 originalMotionEntry->pointerProperties[originalPointerIndex];
2266 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002267 if (pointerIds.hasBit(pointerId)) {
2268 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002269 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
Jeff Brownace13b12011-03-09 17:39:48 -08002270 splitPointerCoords[splitPointerCount].copyFrom(
Jeff Brown3241b6b2012-02-03 15:08:02 -08002271 originalMotionEntry->pointerCoords[originalPointerIndex]);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002272 splitPointerCount += 1;
2273 }
2274 }
Jeff Brown58a2da82011-01-25 16:02:22 -08002275
2276 if (splitPointerCount != pointerIds.count()) {
2277 // This is bad. We are missing some of the pointers that we expected to deliver.
2278 // Most likely this indicates that we received an ACTION_MOVE events that has
2279 // different pointer ids than we expected based on the previous ACTION_DOWN
2280 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2281 // in this way.
Steve Block8564c8d2012-01-05 23:22:43 +00002282 ALOGW("Dropping split motion event because the pointer count is %d but "
Jeff Brown58a2da82011-01-25 16:02:22 -08002283 "we expected there to be %d pointers. This probably means we received "
2284 "a broken sequence of pointer ids from the input device.",
2285 splitPointerCount, pointerIds.count());
2286 return NULL;
2287 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002288
2289 int32_t action = originalMotionEntry->action;
2290 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2291 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2292 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2293 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002294 const PointerProperties& pointerProperties =
2295 originalMotionEntry->pointerProperties[originalPointerIndex];
2296 uint32_t pointerId = uint32_t(pointerProperties.id);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002297 if (pointerIds.hasBit(pointerId)) {
2298 if (pointerIds.count() == 1) {
2299 // The first/last pointer went down/up.
2300 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2301 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brown9a01d052010-09-27 16:35:11 -07002302 } else {
2303 // A secondary pointer went down/up.
2304 uint32_t splitPointerIndex = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002305 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
Jeff Brown9a01d052010-09-27 16:35:11 -07002306 splitPointerIndex += 1;
2307 }
2308 action = maskedAction | (splitPointerIndex
2309 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002310 }
2311 } else {
2312 // An unrelated pointer changed.
2313 action = AMOTION_EVENT_ACTION_MOVE;
2314 }
2315 }
2316
Jeff Brownac386072011-07-20 15:19:50 -07002317 MotionEntry* splitMotionEntry = new MotionEntry(
Jeff Brown01ce2e92010-09-26 22:20:12 -07002318 originalMotionEntry->eventTime,
2319 originalMotionEntry->deviceId,
2320 originalMotionEntry->source,
2321 originalMotionEntry->policyFlags,
2322 action,
2323 originalMotionEntry->flags,
2324 originalMotionEntry->metaState,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002325 originalMotionEntry->buttonState,
Jeff Brown01ce2e92010-09-26 22:20:12 -07002326 originalMotionEntry->edgeFlags,
2327 originalMotionEntry->xPrecision,
2328 originalMotionEntry->yPrecision,
2329 originalMotionEntry->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002330 originalMotionEntry->displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002331 splitPointerCount, splitPointerProperties, splitPointerCoords);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002332
Jeff Browna032cc02011-03-07 16:56:21 -08002333 if (originalMotionEntry->injectionState) {
2334 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2335 splitMotionEntry->injectionState->refCount += 1;
2336 }
2337
Jeff Brown01ce2e92010-09-26 22:20:12 -07002338 return splitMotionEntry;
2339}
2340
Jeff Brownbe1aa822011-07-27 16:04:54 -07002341void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002342#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002343 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002344#endif
2345
Jeff Brownb88102f2010-09-08 11:49:43 -07002346 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002347 { // acquire lock
2348 AutoMutex _l(mLock);
2349
Jeff Brownbe1aa822011-07-27 16:04:54 -07002350 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
Jeff Brownb88102f2010-09-08 11:49:43 -07002351 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002352 } // release lock
2353
Jeff Brownb88102f2010-09-08 11:49:43 -07002354 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002355 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002356 }
2357}
2358
Jeff Brownbe1aa822011-07-27 16:04:54 -07002359void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002360#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002361 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002362 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002363 args->eventTime, args->deviceId, args->source, args->policyFlags,
2364 args->action, args->flags, args->keyCode, args->scanCode,
2365 args->metaState, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002366#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002367 if (!validateKeyEvent(args->action)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002368 return;
2369 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002370
Jeff Brownbe1aa822011-07-27 16:04:54 -07002371 uint32_t policyFlags = args->policyFlags;
2372 int32_t flags = args->flags;
2373 int32_t metaState = args->metaState;
Jeff Brown1f245102010-11-18 20:53:46 -08002374 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2375 policyFlags |= POLICY_FLAG_VIRTUAL;
2376 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2377 }
Jeff Brown924c4d42011-03-07 16:40:47 -08002378 if (policyFlags & POLICY_FLAG_ALT) {
2379 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2380 }
2381 if (policyFlags & POLICY_FLAG_ALT_GR) {
2382 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2383 }
2384 if (policyFlags & POLICY_FLAG_SHIFT) {
2385 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2386 }
2387 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2388 metaState |= AMETA_CAPS_LOCK_ON;
2389 }
2390 if (policyFlags & POLICY_FLAG_FUNCTION) {
2391 metaState |= AMETA_FUNCTION_ON;
2392 }
Jeff Brown1f245102010-11-18 20:53:46 -08002393
Jeff Browne20c9e02010-10-11 14:20:19 -07002394 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brown1f245102010-11-18 20:53:46 -08002395
2396 KeyEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002397 event.initialize(args->deviceId, args->source, args->action,
2398 flags, args->keyCode, args->scanCode, metaState, 0,
2399 args->downTime, args->eventTime);
Jeff Brown1f245102010-11-18 20:53:46 -08002400
2401 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2402
2403 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2404 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2405 }
Jeff Brownb6997262010-10-08 22:31:17 -07002406
Jeff Brownb88102f2010-09-08 11:49:43 -07002407 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002408 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002409 mLock.lock();
2410
Jeff Brown83d616a2012-09-09 20:33:43 -07002411 if (shouldSendKeyToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002412 mLock.unlock();
2413
2414 policyFlags |= POLICY_FLAG_FILTERED;
2415 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2416 return; // event was consumed by the filter
2417 }
2418
2419 mLock.lock();
2420 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002421
Jeff Brown7fbdc842010-06-17 20:52:56 -07002422 int32_t repeatCount = 0;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002423 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2424 args->deviceId, args->source, policyFlags,
2425 args->action, flags, args->keyCode, args->scanCode,
2426 metaState, repeatCount, args->downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002427
Jeff Brownb88102f2010-09-08 11:49:43 -07002428 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002429 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002430 } // release lock
2431
Jeff Brownb88102f2010-09-08 11:49:43 -07002432 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002433 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002434 }
2435}
2436
Jeff Brown83d616a2012-09-09 20:33:43 -07002437bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2438 return mInputFilterEnabled;
2439}
2440
Jeff Brownbe1aa822011-07-27 16:04:54 -07002441void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002442#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002443 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002444 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
Jeff Brown85a31762010-09-01 17:01:00 -07002445 "xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002446 args->eventTime, args->deviceId, args->source, args->policyFlags,
2447 args->action, args->flags, args->metaState, args->buttonState,
2448 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2449 for (uint32_t i = 0; i < args->pointerCount; i++) {
Steve Block5baa3a62011-12-20 16:23:08 +00002450 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002451 "x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brown85a31762010-09-01 17:01:00 -07002452 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown8d608662010-08-30 03:02:23 -07002453 "orientation=%f",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002454 i, args->pointerProperties[i].id,
2455 args->pointerProperties[i].toolType,
2456 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2457 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2458 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2459 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2460 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2461 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2462 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2463 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2464 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002465 }
2466#endif
Jeff Brownbe1aa822011-07-27 16:04:54 -07002467 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002468 return;
2469 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002470
Jeff Brownbe1aa822011-07-27 16:04:54 -07002471 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002472 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002473 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002474
Jeff Brownb88102f2010-09-08 11:49:43 -07002475 bool needWake;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002476 { // acquire lock
Jeff Brown0029c662011-03-30 02:25:18 -07002477 mLock.lock();
2478
Jeff Brown83d616a2012-09-09 20:33:43 -07002479 if (shouldSendMotionToInputFilterLocked(args)) {
Jeff Brown0029c662011-03-30 02:25:18 -07002480 mLock.unlock();
2481
2482 MotionEvent event;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002483 event.initialize(args->deviceId, args->source, args->action, args->flags,
2484 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2485 args->xPrecision, args->yPrecision,
2486 args->downTime, args->eventTime,
2487 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown0029c662011-03-30 02:25:18 -07002488
2489 policyFlags |= POLICY_FLAG_FILTERED;
2490 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2491 return; // event was consumed by the filter
2492 }
2493
2494 mLock.lock();
2495 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002496
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002497 // Just enqueue a new motion event.
Jeff Brownbe1aa822011-07-27 16:04:54 -07002498 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2499 args->deviceId, args->source, policyFlags,
2500 args->action, args->flags, args->metaState, args->buttonState,
2501 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07002502 args->displayId,
Jeff Brownbe1aa822011-07-27 16:04:54 -07002503 args->pointerCount, args->pointerProperties, args->pointerCoords);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002504
Jeff Brownb88102f2010-09-08 11:49:43 -07002505 needWake = enqueueInboundEventLocked(newEntry);
Jeff Brown0029c662011-03-30 02:25:18 -07002506 mLock.unlock();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002507 } // release lock
2508
Jeff Brownb88102f2010-09-08 11:49:43 -07002509 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002510 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002511 }
2512}
2513
Jeff Brown83d616a2012-09-09 20:33:43 -07002514bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2515 // TODO: support sending secondary display events to input filter
2516 return mInputFilterEnabled && isMainDisplay(args->displayId);
2517}
2518
Jeff Brownbe1aa822011-07-27 16:04:54 -07002519void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Jeff Brownb6997262010-10-08 22:31:17 -07002520#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brownbcc046a2012-09-27 20:46:43 -07002521 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
Jeff Brownbe1aa822011-07-27 16:04:54 -07002522 args->eventTime, args->policyFlags,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002523 args->switchValues, args->switchMask);
Jeff Brownb6997262010-10-08 22:31:17 -07002524#endif
2525
Jeff Brownbe1aa822011-07-27 16:04:54 -07002526 uint32_t policyFlags = args->policyFlags;
Jeff Browne20c9e02010-10-11 14:20:19 -07002527 policyFlags |= POLICY_FLAG_TRUSTED;
Jeff Brownbe1aa822011-07-27 16:04:54 -07002528 mPolicy->notifySwitch(args->eventTime,
Jeff Brownbcc046a2012-09-27 20:46:43 -07002529 args->switchValues, args->switchMask, policyFlags);
Jeff Brownb6997262010-10-08 22:31:17 -07002530}
2531
Jeff Brown65fd2512011-08-18 11:20:58 -07002532void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2533#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002534 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
Jeff Brown65fd2512011-08-18 11:20:58 -07002535 args->eventTime, args->deviceId);
2536#endif
2537
2538 bool needWake;
2539 { // acquire lock
2540 AutoMutex _l(mLock);
2541
2542 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2543 needWake = enqueueInboundEventLocked(newEntry);
2544 } // release lock
2545
2546 if (needWake) {
2547 mLooper->wake();
2548 }
2549}
2550
Jeff Brown7fbdc842010-06-17 20:52:56 -07002551int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brown0029c662011-03-30 02:25:18 -07002552 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2553 uint32_t policyFlags) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002554#if DEBUG_INBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00002555 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brown0029c662011-03-30 02:25:18 -07002556 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2557 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002558#endif
2559
2560 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
Jeff Browne20c9e02010-10-11 14:20:19 -07002561
Jeff Brown0029c662011-03-30 02:25:18 -07002562 policyFlags |= POLICY_FLAG_INJECTED;
Jeff Browne20c9e02010-10-11 14:20:19 -07002563 if (hasInjectionPermission(injectorPid, injectorUid)) {
2564 policyFlags |= POLICY_FLAG_TRUSTED;
2565 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002566
Jeff Brown3241b6b2012-02-03 15:08:02 -08002567 EventEntry* firstInjectedEntry;
2568 EventEntry* lastInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002569 switch (event->getType()) {
2570 case AINPUT_EVENT_TYPE_KEY: {
2571 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2572 int32_t action = keyEvent->getAction();
2573 if (! validateKeyEvent(action)) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002574 return INPUT_EVENT_INJECTION_FAILED;
2575 }
2576
Jeff Brownb6997262010-10-08 22:31:17 -07002577 int32_t flags = keyEvent->getFlags();
Jeff Brown1f245102010-11-18 20:53:46 -08002578 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2579 policyFlags |= POLICY_FLAG_VIRTUAL;
2580 }
2581
Jeff Brown0029c662011-03-30 02:25:18 -07002582 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2583 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2584 }
Jeff Brown1f245102010-11-18 20:53:46 -08002585
2586 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2587 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2588 }
Jeff Brown6ec402b2010-07-28 15:48:59 -07002589
Jeff Brownb6997262010-10-08 22:31:17 -07002590 mLock.lock();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002591 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
Jeff Brown1f245102010-11-18 20:53:46 -08002592 keyEvent->getDeviceId(), keyEvent->getSource(),
2593 policyFlags, action, flags,
2594 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
Jeff Brownb6997262010-10-08 22:31:17 -07002595 keyEvent->getRepeatCount(), keyEvent->getDownTime());
Jeff Brown3241b6b2012-02-03 15:08:02 -08002596 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002597 break;
2598 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002599
Jeff Brownb6997262010-10-08 22:31:17 -07002600 case AINPUT_EVENT_TYPE_MOTION: {
2601 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Brown83d616a2012-09-09 20:33:43 -07002602 int32_t displayId = ADISPLAY_ID_DEFAULT;
Jeff Brownb6997262010-10-08 22:31:17 -07002603 int32_t action = motionEvent->getAction();
2604 size_t pointerCount = motionEvent->getPointerCount();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002605 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2606 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002607 return INPUT_EVENT_INJECTION_FAILED;
2608 }
2609
Jeff Brown0029c662011-03-30 02:25:18 -07002610 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2611 nsecs_t eventTime = motionEvent->getEventTime();
2612 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2613 }
Jeff Brownb6997262010-10-08 22:31:17 -07002614
2615 mLock.lock();
2616 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2617 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Jeff Brown3241b6b2012-02-03 15:08:02 -08002618 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Jeff Brownb6997262010-10-08 22:31:17 -07002619 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2620 action, motionEvent->getFlags(),
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07002621 motionEvent->getMetaState(), motionEvent->getButtonState(),
2622 motionEvent->getEdgeFlags(),
Jeff Brownb6997262010-10-08 22:31:17 -07002623 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002624 motionEvent->getDownTime(), displayId,
2625 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002626 lastInjectedEntry = firstInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002627 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2628 sampleEventTimes += 1;
2629 samplePointerCoords += pointerCount;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002630 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2631 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2632 action, motionEvent->getFlags(),
2633 motionEvent->getMetaState(), motionEvent->getButtonState(),
2634 motionEvent->getEdgeFlags(),
2635 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Jeff Brown83d616a2012-09-09 20:33:43 -07002636 motionEvent->getDownTime(), displayId,
2637 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
Jeff Brown3241b6b2012-02-03 15:08:02 -08002638 lastInjectedEntry->next = nextInjectedEntry;
2639 lastInjectedEntry = nextInjectedEntry;
Jeff Brownb6997262010-10-08 22:31:17 -07002640 }
Jeff Brownb6997262010-10-08 22:31:17 -07002641 break;
2642 }
2643
2644 default:
Steve Block8564c8d2012-01-05 23:22:43 +00002645 ALOGW("Cannot inject event of type %d", event->getType());
Jeff Brownb6997262010-10-08 22:31:17 -07002646 return INPUT_EVENT_INJECTION_FAILED;
2647 }
2648
Jeff Brownac386072011-07-20 15:19:50 -07002649 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
Jeff Brownb6997262010-10-08 22:31:17 -07002650 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2651 injectionState->injectionIsAsync = true;
2652 }
2653
2654 injectionState->refCount += 1;
Jeff Brown3241b6b2012-02-03 15:08:02 -08002655 lastInjectedEntry->injectionState = injectionState;
Jeff Brownb6997262010-10-08 22:31:17 -07002656
Jeff Brown3241b6b2012-02-03 15:08:02 -08002657 bool needWake = false;
2658 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2659 EventEntry* nextEntry = entry->next;
2660 needWake |= enqueueInboundEventLocked(entry);
2661 entry = nextEntry;
2662 }
2663
Jeff Brownb6997262010-10-08 22:31:17 -07002664 mLock.unlock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002665
Jeff Brownb88102f2010-09-08 11:49:43 -07002666 if (needWake) {
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002667 mLooper->wake();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002668 }
2669
2670 int32_t injectionResult;
2671 { // acquire lock
2672 AutoMutex _l(mLock);
2673
Jeff Brown6ec402b2010-07-28 15:48:59 -07002674 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2675 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2676 } else {
2677 for (;;) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002678 injectionResult = injectionState->injectionResult;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002679 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2680 break;
2681 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002682
Jeff Brown7fbdc842010-06-17 20:52:56 -07002683 nsecs_t remainingTimeout = endTime - now();
2684 if (remainingTimeout <= 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002685#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002686 ALOGD("injectInputEvent - Timed out waiting for injection result "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002687 "to become available.");
2688#endif
Jeff Brown7fbdc842010-06-17 20:52:56 -07002689 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2690 break;
2691 }
2692
Jeff Brown6ec402b2010-07-28 15:48:59 -07002693 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2694 }
2695
2696 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2697 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002698 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002699#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002700 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002701 injectionState->pendingForegroundDispatches);
Jeff Brown6ec402b2010-07-28 15:48:59 -07002702#endif
2703 nsecs_t remainingTimeout = endTime - now();
2704 if (remainingTimeout <= 0) {
2705#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002706 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002707 "dispatches to finish.");
2708#endif
2709 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2710 break;
2711 }
2712
2713 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2714 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07002715 }
2716 }
2717
Jeff Brownac386072011-07-20 15:19:50 -07002718 injectionState->release();
Jeff Brown7fbdc842010-06-17 20:52:56 -07002719 } // release lock
2720
Jeff Brown6ec402b2010-07-28 15:48:59 -07002721#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002722 ALOGD("injectInputEvent - Finished with result %d. "
Jeff Brown6ec402b2010-07-28 15:48:59 -07002723 "injectorPid=%d, injectorUid=%d",
2724 injectionResult, injectorPid, injectorUid);
2725#endif
2726
Jeff Brown7fbdc842010-06-17 20:52:56 -07002727 return injectionResult;
2728}
2729
Jeff Brownb6997262010-10-08 22:31:17 -07002730bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2731 return injectorUid == 0
2732 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2733}
2734
Jeff Brown7fbdc842010-06-17 20:52:56 -07002735void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002736 InjectionState* injectionState = entry->injectionState;
2737 if (injectionState) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07002738#if DEBUG_INJECTION
Steve Block5baa3a62011-12-20 16:23:08 +00002739 ALOGD("Setting input event injection result to %d. "
Jeff Brown7fbdc842010-06-17 20:52:56 -07002740 "injectorPid=%d, injectorUid=%d",
Jeff Brown01ce2e92010-09-26 22:20:12 -07002741 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown7fbdc842010-06-17 20:52:56 -07002742#endif
2743
Jeff Brown0029c662011-03-30 02:25:18 -07002744 if (injectionState->injectionIsAsync
2745 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Jeff Brown6ec402b2010-07-28 15:48:59 -07002746 // Log the outcome since the injector did not wait for the injection result.
2747 switch (injectionResult) {
2748 case INPUT_EVENT_INJECTION_SUCCEEDED:
Steve Block71f2cf12011-10-20 11:56:00 +01002749 ALOGV("Asynchronous input event injection succeeded.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002750 break;
2751 case INPUT_EVENT_INJECTION_FAILED:
Steve Block8564c8d2012-01-05 23:22:43 +00002752 ALOGW("Asynchronous input event injection failed.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002753 break;
2754 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Steve Block8564c8d2012-01-05 23:22:43 +00002755 ALOGW("Asynchronous input event injection permission denied.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002756 break;
2757 case INPUT_EVENT_INJECTION_TIMED_OUT:
Steve Block8564c8d2012-01-05 23:22:43 +00002758 ALOGW("Asynchronous input event injection timed out.");
Jeff Brown6ec402b2010-07-28 15:48:59 -07002759 break;
2760 }
2761 }
2762
Jeff Brown01ce2e92010-09-26 22:20:12 -07002763 injectionState->injectionResult = injectionResult;
Jeff Brown7fbdc842010-06-17 20:52:56 -07002764 mInjectionResultAvailableCondition.broadcast();
2765 }
2766}
2767
Jeff Brown01ce2e92010-09-26 22:20:12 -07002768void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2769 InjectionState* injectionState = entry->injectionState;
2770 if (injectionState) {
2771 injectionState->pendingForegroundDispatches += 1;
2772 }
2773}
2774
Jeff Brown519e0242010-09-15 15:18:56 -07002775void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002776 InjectionState* injectionState = entry->injectionState;
2777 if (injectionState) {
2778 injectionState->pendingForegroundDispatches -= 1;
Jeff Brown6ec402b2010-07-28 15:48:59 -07002779
Jeff Brown01ce2e92010-09-26 22:20:12 -07002780 if (injectionState->pendingForegroundDispatches == 0) {
2781 mInjectionSyncFinishedCondition.broadcast();
2782 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002783 }
2784}
2785
Jeff Brown9302c872011-07-13 22:51:29 -07002786sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2787 const sp<InputChannel>& inputChannel) const {
2788 size_t numWindows = mWindowHandles.size();
2789 for (size_t i = 0; i < numWindows; i++) {
2790 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002791 if (windowHandle->getInputChannel() == inputChannel) {
Jeff Brown9302c872011-07-13 22:51:29 -07002792 return windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07002793 }
2794 }
2795 return NULL;
2796}
2797
Jeff Brown9302c872011-07-13 22:51:29 -07002798bool InputDispatcher::hasWindowHandleLocked(
2799 const sp<InputWindowHandle>& windowHandle) const {
2800 size_t numWindows = mWindowHandles.size();
2801 for (size_t i = 0; i < numWindows; i++) {
2802 if (mWindowHandles.itemAt(i) == windowHandle) {
2803 return true;
2804 }
2805 }
2806 return false;
2807}
2808
2809void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002810#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002811 ALOGD("setInputWindows");
Jeff Brownb88102f2010-09-08 11:49:43 -07002812#endif
2813 { // acquire lock
2814 AutoMutex _l(mLock);
2815
Jeff Browncc4f7db2011-08-30 20:34:48 -07002816 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
Jeff Brown9302c872011-07-13 22:51:29 -07002817 mWindowHandles = inputWindowHandles;
Jeff Brownb6997262010-10-08 22:31:17 -07002818
Jeff Brown9302c872011-07-13 22:51:29 -07002819 sp<InputWindowHandle> newFocusedWindowHandle;
2820 bool foundHoveredWindow = false;
2821 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2822 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07002823 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
Jeff Brown9302c872011-07-13 22:51:29 -07002824 mWindowHandles.removeAt(i--);
2825 continue;
2826 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002827 if (windowHandle->getInfo()->hasFocus) {
Jeff Brown9302c872011-07-13 22:51:29 -07002828 newFocusedWindowHandle = windowHandle;
2829 }
2830 if (windowHandle == mLastHoverWindowHandle) {
2831 foundHoveredWindow = true;
Jeff Brownb88102f2010-09-08 11:49:43 -07002832 }
2833 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07002834
Jeff Brown9302c872011-07-13 22:51:29 -07002835 if (!foundHoveredWindow) {
2836 mLastHoverWindowHandle = NULL;
2837 }
2838
2839 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2840 if (mFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002841#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002842 ALOGD("Focus left window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002843 mFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002844#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002845 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2846 if (focusedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002847 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2848 "focus left window");
2849 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002850 focusedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002851 }
Jeff Brownb6997262010-10-08 22:31:17 -07002852 }
Jeff Brown9302c872011-07-13 22:51:29 -07002853 if (newFocusedWindowHandle != NULL) {
Jeff Brownb6997262010-10-08 22:31:17 -07002854#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002855 ALOGD("Focus entered window: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002856 newFocusedWindowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002857#endif
Jeff Brown9302c872011-07-13 22:51:29 -07002858 }
2859 mFocusedWindowHandle = newFocusedWindowHandle;
Jeff Brownb6997262010-10-08 22:31:17 -07002860 }
2861
Jeff Brown9302c872011-07-13 22:51:29 -07002862 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07002863 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07002864 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Jeff Brownb6997262010-10-08 22:31:17 -07002865#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002866 ALOGD("Touched window was removed: %s",
Jeff Browncc4f7db2011-08-30 20:34:48 -07002867 touchedWindow.windowHandle->getName().string());
Jeff Brownb6997262010-10-08 22:31:17 -07002868#endif
Jeff Browncc4f7db2011-08-30 20:34:48 -07002869 sp<InputChannel> touchedInputChannel =
2870 touchedWindow.windowHandle->getInputChannel();
2871 if (touchedInputChannel != NULL) {
Christopher Tated9be36c2011-08-16 16:09:33 -07002872 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2873 "touched window was removed");
2874 synthesizeCancelationEventsForInputChannelLocked(
Jeff Browncc4f7db2011-08-30 20:34:48 -07002875 touchedInputChannel, options);
Christopher Tated9be36c2011-08-16 16:09:33 -07002876 }
Jeff Brown9302c872011-07-13 22:51:29 -07002877 mTouchState.windows.removeAt(i--);
Jeff Brown01ce2e92010-09-26 22:20:12 -07002878 }
2879 }
Jeff Browncc4f7db2011-08-30 20:34:48 -07002880
2881 // Release information for windows that are no longer present.
2882 // This ensures that unused input channels are released promptly.
2883 // Otherwise, they might stick around until the window handle is destroyed
2884 // which might not happen until the next GC.
2885 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2886 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2887 if (!hasWindowHandleLocked(oldWindowHandle)) {
2888#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002889 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
Jeff Browncc4f7db2011-08-30 20:34:48 -07002890#endif
2891 oldWindowHandle->releaseInfo();
2892 }
2893 }
Jeff Brownb88102f2010-09-08 11:49:43 -07002894 } // release lock
2895
2896 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002897 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002898}
2899
Jeff Brown9302c872011-07-13 22:51:29 -07002900void InputDispatcher::setFocusedApplication(
2901 const sp<InputApplicationHandle>& inputApplicationHandle) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002902#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002903 ALOGD("setFocusedApplication");
Jeff Brownb88102f2010-09-08 11:49:43 -07002904#endif
2905 { // acquire lock
2906 AutoMutex _l(mLock);
2907
Jeff Browncc4f7db2011-08-30 20:34:48 -07002908 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002909 if (mFocusedApplicationHandle != inputApplicationHandle) {
2910 if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002911 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002912 mFocusedApplicationHandle->releaseInfo();
Jeff Brown5ea29ab2011-07-27 11:50:51 -07002913 }
2914 mFocusedApplicationHandle = inputApplicationHandle;
2915 }
2916 } else if (mFocusedApplicationHandle != NULL) {
Jeff Browne9bb9be2012-02-06 15:47:55 -08002917 resetANRTimeoutsLocked();
Jeff Browncc4f7db2011-08-30 20:34:48 -07002918 mFocusedApplicationHandle->releaseInfo();
Jeff Brown9302c872011-07-13 22:51:29 -07002919 mFocusedApplicationHandle.clear();
Jeff Brownb88102f2010-09-08 11:49:43 -07002920 }
2921
2922#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002923 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002924#endif
2925 } // release lock
2926
2927 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002928 mLooper->wake();
Jeff Brownb88102f2010-09-08 11:49:43 -07002929}
2930
Jeff Brownb88102f2010-09-08 11:49:43 -07002931void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2932#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002933 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07002934#endif
2935
2936 bool changed;
2937 { // acquire lock
2938 AutoMutex _l(mLock);
2939
2940 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
Jeff Brown120a4592010-10-27 18:43:51 -07002941 if (mDispatchFrozen && !frozen) {
Jeff Brownb88102f2010-09-08 11:49:43 -07002942 resetANRTimeoutsLocked();
2943 }
2944
Jeff Brown120a4592010-10-27 18:43:51 -07002945 if (mDispatchEnabled && !enabled) {
2946 resetAndDropEverythingLocked("dispatcher is being disabled");
2947 }
2948
Jeff Brownb88102f2010-09-08 11:49:43 -07002949 mDispatchEnabled = enabled;
2950 mDispatchFrozen = frozen;
2951 changed = true;
2952 } else {
2953 changed = false;
2954 }
2955
2956#if DEBUG_FOCUS
Jeff Brownb6997262010-10-08 22:31:17 -07002957 //logDispatchStateLocked();
Jeff Brownb88102f2010-09-08 11:49:43 -07002958#endif
2959 } // release lock
2960
2961 if (changed) {
2962 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07002963 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002964 }
2965}
2966
Jeff Brown0029c662011-03-30 02:25:18 -07002967void InputDispatcher::setInputFilterEnabled(bool enabled) {
2968#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002969 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
Jeff Brown0029c662011-03-30 02:25:18 -07002970#endif
2971
2972 { // acquire lock
2973 AutoMutex _l(mLock);
2974
2975 if (mInputFilterEnabled == enabled) {
2976 return;
2977 }
2978
2979 mInputFilterEnabled = enabled;
2980 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2981 } // release lock
2982
2983 // Wake up poll loop since there might be work to do to drop everything.
2984 mLooper->wake();
2985}
2986
Jeff Browne6504122010-09-27 14:52:15 -07002987bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2988 const sp<InputChannel>& toChannel) {
2989#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00002990 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Jeff Browne6504122010-09-27 14:52:15 -07002991 fromChannel->getName().string(), toChannel->getName().string());
2992#endif
2993 { // acquire lock
2994 AutoMutex _l(mLock);
2995
Jeff Brown9302c872011-07-13 22:51:29 -07002996 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2997 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2998 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
Jeff Browne6504122010-09-27 14:52:15 -07002999#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003000 ALOGD("Cannot transfer focus because from or to window not found.");
Jeff Browne6504122010-09-27 14:52:15 -07003001#endif
3002 return false;
3003 }
Jeff Brown9302c872011-07-13 22:51:29 -07003004 if (fromWindowHandle == toWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003005#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003006 ALOGD("Trivial transfer to same window.");
Jeff Browne6504122010-09-27 14:52:15 -07003007#endif
3008 return true;
3009 }
Jeff Brown83d616a2012-09-09 20:33:43 -07003010 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3011#if DEBUG_FOCUS
3012 ALOGD("Cannot transfer focus because windows are on different displays.");
3013#endif
3014 return false;
3015 }
Jeff Browne6504122010-09-27 14:52:15 -07003016
3017 bool found = false;
3018 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3019 const TouchedWindow& touchedWindow = mTouchState.windows[i];
Jeff Brown9302c872011-07-13 22:51:29 -07003020 if (touchedWindow.windowHandle == fromWindowHandle) {
Jeff Browne6504122010-09-27 14:52:15 -07003021 int32_t oldTargetFlags = touchedWindow.targetFlags;
3022 BitSet32 pointerIds = touchedWindow.pointerIds;
3023
3024 mTouchState.windows.removeAt(i);
3025
Jeff Brown46e75292010-11-10 16:53:45 -08003026 int32_t newTargetFlags = oldTargetFlags
Jeff Browna032cc02011-03-07 16:56:21 -08003027 & (InputTarget::FLAG_FOREGROUND
3028 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brown9302c872011-07-13 22:51:29 -07003029 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Jeff Browne6504122010-09-27 14:52:15 -07003030
3031 found = true;
3032 break;
3033 }
3034 }
3035
3036 if (! found) {
3037#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003038 ALOGD("Focus transfer failed because from window did not have focus.");
Jeff Browne6504122010-09-27 14:52:15 -07003039#endif
3040 return false;
3041 }
3042
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003043 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3044 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3045 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003046 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3047 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003048
3049 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Jeff Brownda3d5a92011-03-29 15:11:34 -07003050 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003051 "transferring touch focus from this window to another window");
Jeff Brownda3d5a92011-03-29 15:11:34 -07003052 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Jeff Brown9c9f1a32010-10-11 18:32:20 -07003053 }
3054
Jeff Browne6504122010-09-27 14:52:15 -07003055#if DEBUG_FOCUS
3056 logDispatchStateLocked();
3057#endif
3058 } // release lock
3059
3060 // Wake up poll loop since it may need to make new input dispatching choices.
3061 mLooper->wake();
3062 return true;
3063}
3064
Jeff Brown120a4592010-10-27 18:43:51 -07003065void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3066#if DEBUG_FOCUS
Steve Block5baa3a62011-12-20 16:23:08 +00003067 ALOGD("Resetting and dropping all events (%s).", reason);
Jeff Brown120a4592010-10-27 18:43:51 -07003068#endif
3069
Jeff Brownda3d5a92011-03-29 15:11:34 -07003070 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3071 synthesizeCancelationEventsForAllConnectionsLocked(options);
Jeff Brown120a4592010-10-27 18:43:51 -07003072
3073 resetKeyRepeatLocked();
3074 releasePendingEventLocked();
3075 drainInboundQueueLocked();
Jeff Browne9bb9be2012-02-06 15:47:55 -08003076 resetANRTimeoutsLocked();
Jeff Brown120a4592010-10-27 18:43:51 -07003077
3078 mTouchState.reset();
Jeff Brown9302c872011-07-13 22:51:29 -07003079 mLastHoverWindowHandle.clear();
Jeff Brown120a4592010-10-27 18:43:51 -07003080}
3081
Jeff Brownb88102f2010-09-08 11:49:43 -07003082void InputDispatcher::logDispatchStateLocked() {
3083 String8 dump;
3084 dumpDispatchStateLocked(dump);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003085
3086 char* text = dump.lockBuffer(dump.size());
3087 char* start = text;
3088 while (*start != '\0') {
3089 char* end = strchr(start, '\n');
3090 if (*end == '\n') {
3091 *(end++) = '\0';
3092 }
Steve Block5baa3a62011-12-20 16:23:08 +00003093 ALOGD("%s", start);
Jeff Brown2a95c2a2010-09-16 12:31:46 -07003094 start = end;
3095 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003096}
3097
3098void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003099 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3100 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Jeff Brownb88102f2010-09-08 11:49:43 -07003101
Jeff Brown9302c872011-07-13 22:51:29 -07003102 if (mFocusedApplicationHandle != NULL) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003103 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003104 mFocusedApplicationHandle->getName().string(),
3105 mFocusedApplicationHandle->getDispatchingTimeout(
3106 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
Jeff Brownb88102f2010-09-08 11:49:43 -07003107 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003108 dump.append(INDENT "FocusedApplication: <null>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003109 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003110 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003111 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
Jeff Brownf2f487182010-10-01 17:46:21 -07003112
3113 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3114 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
Jeff Brown95712852011-01-04 19:41:59 -08003115 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
Jeff Brown58a2da82011-01-25 16:02:22 -08003116 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
Jeff Brown83d616a2012-09-09 20:33:43 -07003117 dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId);
Jeff Brownf2f487182010-10-01 17:46:21 -07003118 if (!mTouchState.windows.isEmpty()) {
3119 dump.append(INDENT "TouchedWindows:\n");
3120 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3121 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3122 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003123 i, touchedWindow.windowHandle->getName().string(),
3124 touchedWindow.pointerIds.value,
Jeff Brownf2f487182010-10-01 17:46:21 -07003125 touchedWindow.targetFlags);
3126 }
3127 } else {
3128 dump.append(INDENT "TouchedWindows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003129 }
3130
Jeff Brown9302c872011-07-13 22:51:29 -07003131 if (!mWindowHandles.isEmpty()) {
Jeff Brownf2f487182010-10-01 17:46:21 -07003132 dump.append(INDENT "Windows:\n");
Jeff Brown9302c872011-07-13 22:51:29 -07003133 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3134 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003135 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3136
Jeff Brown83d616a2012-09-09 20:33:43 -07003137 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3138 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
Jeff Brownf2f487182010-10-01 17:46:21 -07003139 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003140 "frame=[%d,%d][%d,%d], scale=%f, "
Jeff Brownfbf09772011-01-16 14:06:57 -08003141 "touchableRegion=",
Jeff Brown83d616a2012-09-09 20:33:43 -07003142 i, windowInfo->name.string(), windowInfo->displayId,
Jeff Browncc4f7db2011-08-30 20:34:48 -07003143 toString(windowInfo->paused),
3144 toString(windowInfo->hasFocus),
3145 toString(windowInfo->hasWallpaper),
3146 toString(windowInfo->visible),
3147 toString(windowInfo->canReceiveKeys),
3148 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3149 windowInfo->layer,
3150 windowInfo->frameLeft, windowInfo->frameTop,
3151 windowInfo->frameRight, windowInfo->frameBottom,
3152 windowInfo->scaleFactor);
3153 dumpRegion(dump, windowInfo->touchableRegion);
3154 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
Jeff Brownfbf09772011-01-16 14:06:57 -08003155 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003156 windowInfo->ownerPid, windowInfo->ownerUid,
3157 windowInfo->dispatchingTimeout / 1000000.0);
Jeff Brownf2f487182010-10-01 17:46:21 -07003158 }
3159 } else {
3160 dump.append(INDENT "Windows: <none>\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003161 }
3162
Jeff Brownf2f487182010-10-01 17:46:21 -07003163 if (!mMonitoringChannels.isEmpty()) {
3164 dump.append(INDENT "MonitoringChannels:\n");
3165 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3166 const sp<InputChannel>& channel = mMonitoringChannels[i];
3167 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3168 }
3169 } else {
3170 dump.append(INDENT "MonitoringChannels: <none>\n");
3171 }
Jeff Brown519e0242010-09-15 15:18:56 -07003172
Jeff Brown265f1cc2012-06-11 18:01:06 -07003173 nsecs_t currentTime = now();
3174
Jeff Brown6876f322013-08-07 16:46:50 -07003175 // Dump recently dispatched or dropped events from oldest to newest.
3176 if (!mRecentQueue.isEmpty()) {
3177 dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3178 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3179 dump.append(INDENT2);
3180 entry->appendDescription(dump);
3181 dump.appendFormat(", age=%0.1fms\n",
3182 (currentTime - entry->eventTime) * 0.000001f);
3183 }
3184 } else {
3185 dump.append(INDENT "RecentQueue: <empty>\n");
3186 }
3187
3188 // Dump event currently being dispatched.
3189 if (mPendingEvent) {
3190 dump.append(INDENT "PendingEvent:\n");
3191 dump.append(INDENT2);
3192 mPendingEvent->appendDescription(dump);
3193 dump.appendFormat(", age=%0.1fms\n",
3194 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3195 } else {
3196 dump.append(INDENT "PendingEvent: <none>\n");
3197 }
3198
3199 // Dump inbound events from oldest to newest.
Jeff Brown265f1cc2012-06-11 18:01:06 -07003200 if (!mInboundQueue.isEmpty()) {
3201 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3202 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3203 dump.append(INDENT2);
3204 entry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003205 dump.appendFormat(", age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003206 (currentTime - entry->eventTime) * 0.000001f);
3207 }
3208 } else {
3209 dump.append(INDENT "InboundQueue: <empty>\n");
3210 }
3211
3212 if (!mConnectionsByFd.isEmpty()) {
3213 dump.append(INDENT "Connections:\n");
3214 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3215 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3216 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3217 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3218 i, connection->getInputChannelName(), connection->getWindowName(),
3219 connection->getStatusLabel(), toString(connection->monitor),
3220 toString(connection->inputPublisherBlocked));
3221
3222 if (!connection->outboundQueue.isEmpty()) {
3223 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3224 connection->outboundQueue.count());
3225 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3226 entry = entry->next) {
3227 dump.append(INDENT4);
3228 entry->eventEntry->appendDescription(dump);
Jeff Brown22aa5122012-06-17 12:01:06 -07003229 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003230 entry->targetFlags, entry->resolvedAction,
3231 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3232 }
3233 } else {
3234 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3235 }
3236
3237 if (!connection->waitQueue.isEmpty()) {
3238 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3239 connection->waitQueue.count());
3240 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3241 entry = entry->next) {
3242 dump.append(INDENT4);
3243 entry->eventEntry->appendDescription(dump);
3244 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
Jeff Brown22aa5122012-06-17 12:01:06 -07003245 "age=%0.1fms, wait=%0.1fms\n",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003246 entry->targetFlags, entry->resolvedAction,
3247 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3248 (currentTime - entry->deliveryTime) * 0.000001f);
3249 }
3250 } else {
3251 dump.append(INDENT3 "WaitQueue: <empty>\n");
3252 }
3253 }
3254 } else {
3255 dump.append(INDENT "Connections: <none>\n");
3256 }
Jeff Brownf2f487182010-10-01 17:46:21 -07003257
Jeff Brownb88102f2010-09-08 11:49:43 -07003258 if (isAppSwitchPendingLocked()) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003259 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
Jeff Brownb88102f2010-09-08 11:49:43 -07003260 (mAppSwitchDueTime - now()) / 1000000.0);
3261 } else {
Jeff Brownf2f487182010-10-01 17:46:21 -07003262 dump.append(INDENT "AppSwitch: not pending\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003263 }
Jeff Brown22aa5122012-06-17 12:01:06 -07003264
3265 dump.append(INDENT "Configuration:\n");
3266 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3267 mConfig.keyRepeatDelay * 0.000001f);
3268 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3269 mConfig.keyRepeatTimeout * 0.000001f);
Jeff Brownb88102f2010-09-08 11:49:43 -07003270}
3271
Jeff Brown928e0542011-01-10 11:17:36 -08003272status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3273 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003274#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003275 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
Jeff Brownb88102f2010-09-08 11:49:43 -07003276 toString(monitor));
Jeff Brown9c3cda02010-06-15 01:31:58 -07003277#endif
3278
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003279 { // acquire lock
3280 AutoMutex _l(mLock);
3281
Jeff Brown519e0242010-09-15 15:18:56 -07003282 if (getConnectionIndexLocked(inputChannel) >= 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003283 ALOGW("Attempted to register already registered input channel '%s'",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003284 inputChannel->getName().string());
3285 return BAD_VALUE;
3286 }
3287
Jeff Browncc4f7db2011-08-30 20:34:48 -07003288 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003289
Jeff Brown91e32892012-02-14 15:56:29 -08003290 int fd = inputChannel->getFd();
Jeff Browncbee6d62012-02-03 20:11:27 -08003291 mConnectionsByFd.add(fd, connection);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003292
Jeff Brownb88102f2010-09-08 11:49:43 -07003293 if (monitor) {
3294 mMonitoringChannels.push(inputChannel);
3295 }
3296
Jeff Browncbee6d62012-02-03 20:11:27 -08003297 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003298 } // release lock
Jeff Brown074b8b72012-10-31 19:01:31 -07003299
3300 // Wake the looper because some connections have changed.
3301 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003302 return OK;
3303}
3304
3305status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07003306#if DEBUG_REGISTRATION
Steve Block5baa3a62011-12-20 16:23:08 +00003307 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown9c3cda02010-06-15 01:31:58 -07003308#endif
3309
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003310 { // acquire lock
3311 AutoMutex _l(mLock);
3312
Jeff Browncc4f7db2011-08-30 20:34:48 -07003313 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3314 if (status) {
3315 return status;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003316 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003317 } // release lock
3318
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003319 // Wake the poll loop because removing the connection may have changed the current
3320 // synchronization state.
Jeff Brown4fe6c3e2010-09-13 23:17:30 -07003321 mLooper->wake();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003322 return OK;
3323}
3324
Jeff Browncc4f7db2011-08-30 20:34:48 -07003325status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3326 bool notify) {
3327 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3328 if (connectionIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +00003329 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Jeff Browncc4f7db2011-08-30 20:34:48 -07003330 inputChannel->getName().string());
3331 return BAD_VALUE;
3332 }
3333
Jeff Browncbee6d62012-02-03 20:11:27 -08003334 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3335 mConnectionsByFd.removeItemsAt(connectionIndex);
Jeff Browncc4f7db2011-08-30 20:34:48 -07003336
3337 if (connection->monitor) {
3338 removeMonitorChannelLocked(inputChannel);
3339 }
3340
Jeff Browncbee6d62012-02-03 20:11:27 -08003341 mLooper->removeFd(inputChannel->getFd());
Jeff Browncc4f7db2011-08-30 20:34:48 -07003342
3343 nsecs_t currentTime = now();
3344 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3345
Jeff Browncc4f7db2011-08-30 20:34:48 -07003346 connection->status = Connection::STATUS_ZOMBIE;
3347 return OK;
3348}
3349
3350void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3351 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3352 if (mMonitoringChannels[i] == inputChannel) {
3353 mMonitoringChannels.removeAt(i);
3354 break;
3355 }
3356 }
3357}
3358
Jeff Brown519e0242010-09-15 15:18:56 -07003359ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003360 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
Jeff Brown2cbecea2010-08-17 15:59:26 -07003361 if (connectionIndex >= 0) {
Jeff Browncbee6d62012-02-03 20:11:27 -08003362 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Jeff Brown2cbecea2010-08-17 15:59:26 -07003363 if (connection->inputChannel.get() == inputChannel.get()) {
3364 return connectionIndex;
3365 }
3366 }
3367
3368 return -1;
3369}
3370
Jeff Brown9c3cda02010-06-15 01:31:58 -07003371void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown072ec962012-02-07 14:46:57 -08003372 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
Jeff Brown3915bb82010-11-05 15:02:16 -07003373 CommandEntry* commandEntry = postCommandLocked(
3374 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3375 commandEntry->connection = connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003376 commandEntry->eventTime = currentTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003377 commandEntry->seq = seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003378 commandEntry->handled = handled;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003379}
3380
Jeff Brown9c3cda02010-06-15 01:31:58 -07003381void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown7fbdc842010-06-17 20:52:56 -07003382 nsecs_t currentTime, const sp<Connection>& connection) {
Steve Block3762c312012-01-06 19:20:56 +00003383 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003384 connection->getInputChannelName());
3385
Jeff Brown9c3cda02010-06-15 01:31:58 -07003386 CommandEntry* commandEntry = postCommandLocked(
3387 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003388 commandEntry->connection = connection;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003389}
3390
Jeff Brown519e0242010-09-15 15:18:56 -07003391void InputDispatcher::onANRLocked(
Jeff Brown9302c872011-07-13 22:51:29 -07003392 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3393 const sp<InputWindowHandle>& windowHandle,
Jeff Brown265f1cc2012-06-11 18:01:06 -07003394 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
Jeff Brown22aa5122012-06-17 12:01:06 -07003395 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3396 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
Steve Block6215d3f2012-01-04 20:05:49 +00003397 ALOGI("Application is not responding: %s. "
Jeff Brown22aa5122012-06-17 12:01:06 -07003398 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Jeff Brown9302c872011-07-13 22:51:29 -07003399 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
Jeff Brown22aa5122012-06-17 12:01:06 -07003400 dispatchLatency, waitDuration, reason);
3401
3402 // Capture a record of the InputDispatcher state at the time of the ANR.
3403 time_t t = time(NULL);
3404 struct tm tm;
3405 localtime_r(&t, &tm);
3406 char timestr[64];
3407 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3408 mLastANRState.clear();
3409 mLastANRState.append(INDENT "ANR:\n");
3410 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3411 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3412 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3413 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3414 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3415 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3416 dumpDispatchStateLocked(mLastANRState);
Jeff Brown519e0242010-09-15 15:18:56 -07003417
3418 CommandEntry* commandEntry = postCommandLocked(
3419 & InputDispatcher::doNotifyANRLockedInterruptible);
Jeff Brown9302c872011-07-13 22:51:29 -07003420 commandEntry->inputApplicationHandle = applicationHandle;
3421 commandEntry->inputWindowHandle = windowHandle;
Jeff Brown519e0242010-09-15 15:18:56 -07003422}
3423
Jeff Brownb88102f2010-09-08 11:49:43 -07003424void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3425 CommandEntry* commandEntry) {
3426 mLock.unlock();
3427
3428 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3429
3430 mLock.lock();
3431}
3432
Jeff Brown9c3cda02010-06-15 01:31:58 -07003433void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3434 CommandEntry* commandEntry) {
Jeff Brown7fbdc842010-06-17 20:52:56 -07003435 sp<Connection> connection = commandEntry->connection;
Jeff Brown9c3cda02010-06-15 01:31:58 -07003436
Jeff Brown7fbdc842010-06-17 20:52:56 -07003437 if (connection->status != Connection::STATUS_ZOMBIE) {
3438 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003439
Jeff Brown928e0542011-01-10 11:17:36 -08003440 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
Jeff Brown7fbdc842010-06-17 20:52:56 -07003441
3442 mLock.lock();
3443 }
Jeff Brown9c3cda02010-06-15 01:31:58 -07003444}
3445
Jeff Brown519e0242010-09-15 15:18:56 -07003446void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown9c3cda02010-06-15 01:31:58 -07003447 CommandEntry* commandEntry) {
Jeff Brown519e0242010-09-15 15:18:56 -07003448 mLock.unlock();
Jeff Brown9c3cda02010-06-15 01:31:58 -07003449
Jeff Brown519e0242010-09-15 15:18:56 -07003450 nsecs_t newTimeout = mPolicy->notifyANR(
Jeff Brown928e0542011-01-10 11:17:36 -08003451 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003452
Jeff Brown519e0242010-09-15 15:18:56 -07003453 mLock.lock();
Jeff Brown7fbdc842010-06-17 20:52:56 -07003454
Jeff Brown9302c872011-07-13 22:51:29 -07003455 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3456 commandEntry->inputWindowHandle != NULL
Jeff Browncc4f7db2011-08-30 20:34:48 -07003457 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
Jeff Brown9c3cda02010-06-15 01:31:58 -07003458}
3459
Jeff Brownb88102f2010-09-08 11:49:43 -07003460void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3461 CommandEntry* commandEntry) {
3462 KeyEntry* entry = commandEntry->keyEntry;
Jeff Brown1f245102010-11-18 20:53:46 -08003463
3464 KeyEvent event;
3465 initializeKeyEvent(&event, entry);
Jeff Brownb88102f2010-09-08 11:49:43 -07003466
3467 mLock.unlock();
3468
Jeff Brown905805a2011-10-12 13:57:59 -07003469 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
Jeff Brown1f245102010-11-18 20:53:46 -08003470 &event, entry->policyFlags);
Jeff Brownb88102f2010-09-08 11:49:43 -07003471
3472 mLock.lock();
3473
Jeff Brown905805a2011-10-12 13:57:59 -07003474 if (delay < 0) {
3475 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3476 } else if (!delay) {
3477 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3478 } else {
3479 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3480 entry->interceptKeyWakeupTime = now() + delay;
3481 }
Jeff Brownac386072011-07-20 15:19:50 -07003482 entry->release();
Jeff Brownb88102f2010-09-08 11:49:43 -07003483}
3484
Jeff Brown3915bb82010-11-05 15:02:16 -07003485void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3486 CommandEntry* commandEntry) {
3487 sp<Connection> connection = commandEntry->connection;
Jeff Brown265f1cc2012-06-11 18:01:06 -07003488 nsecs_t finishTime = commandEntry->eventTime;
Jeff Brown072ec962012-02-07 14:46:57 -08003489 uint32_t seq = commandEntry->seq;
Jeff Brown3915bb82010-11-05 15:02:16 -07003490 bool handled = commandEntry->handled;
3491
Jeff Brown072ec962012-02-07 14:46:57 -08003492 // Handle post-event policy actions.
3493 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3494 if (dispatchEntry) {
Jeff Brown265f1cc2012-06-11 18:01:06 -07003495 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3496 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3497 String8 msg;
Jeff Brown22aa5122012-06-17 12:01:06 -07003498 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
Jeff Brown265f1cc2012-06-11 18:01:06 -07003499 connection->getWindowName(), eventDuration * 0.000001f);
3500 dispatchEntry->eventEntry->appendDescription(msg);
3501 ALOGI("%s", msg.string());
3502 }
3503
Jeff Brownd1c48a02012-02-06 19:12:47 -08003504 bool restartEvent;
Jeff Brownd1c48a02012-02-06 19:12:47 -08003505 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3506 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3507 restartEvent = afterKeyEventLockedInterruptible(connection,
3508 dispatchEntry, keyEntry, handled);
3509 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3510 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3511 restartEvent = afterMotionEventLockedInterruptible(connection,
3512 dispatchEntry, motionEntry, handled);
3513 } else {
3514 restartEvent = false;
3515 }
3516
3517 // Dequeue the event and start the next cycle.
3518 // Note that because the lock might have been released, it is possible that the
3519 // contents of the wait queue to have been drained, so we need to double-check
3520 // a few things.
Jeff Brown072ec962012-02-07 14:46:57 -08003521 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3522 connection->waitQueue.dequeue(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003523 traceWaitQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003524 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3525 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Jeff Brown481c1572012-03-09 14:41:15 -08003526 traceOutboundQueueLengthLocked(connection);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003527 } else {
3528 releaseDispatchEntryLocked(dispatchEntry);
Jeff Brown49ed71d2010-12-06 17:13:33 -08003529 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003530 }
Jeff Brown3915bb82010-11-05 15:02:16 -07003531
Jeff Brownd1c48a02012-02-06 19:12:47 -08003532 // Start the next dispatch cycle for this connection.
3533 startDispatchCycleLocked(now(), connection);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003534 }
3535}
3536
3537bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3538 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3539 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3540 // Get the fallback key state.
3541 // Clear it out after dispatching the UP.
3542 int32_t originalKeyCode = keyEntry->keyCode;
3543 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3544 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3545 connection->inputState.removeFallbackKey(originalKeyCode);
3546 }
3547
3548 if (handled || !dispatchEntry->hasForegroundTarget()) {
3549 // If the application handles the original key for which we previously
3550 // generated a fallback or if the window is not a foreground window,
3551 // then cancel the associated fallback key, if any.
3552 if (fallbackKeyCode != -1) {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003553 // Dispatch the unhandled key to the policy with the cancel flag.
3554#if DEBUG_OUTBOUND_EVENT_DETAILS
3555 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3556 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3557 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3558 keyEntry->policyFlags);
3559#endif
3560 KeyEvent event;
3561 initializeKeyEvent(&event, keyEntry);
3562 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3563
3564 mLock.unlock();
3565
3566 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3567 &event, keyEntry->policyFlags, &event);
3568
3569 mLock.lock();
3570
3571 // Cancel the fallback key.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003572 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3573 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3574 "application handled the original non-fallback key "
3575 "or is no longer a foreground target, "
3576 "canceling previously dispatched fallback key");
3577 options.keyCode = fallbackKeyCode;
3578 synthesizeCancelationEventsForConnectionLocked(connection, options);
3579 }
3580 connection->inputState.removeFallbackKey(originalKeyCode);
3581 }
3582 } else {
3583 // If the application did not handle a non-fallback key, first check
3584 // that we are in a good state to perform unhandled key event processing
3585 // Then ask the policy what to do with it.
3586 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3587 && keyEntry->repeatCount == 0;
3588 if (fallbackKeyCode == -1 && !initialDown) {
3589#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003590 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003591 "since this is not an initial down. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003592 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3593 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3594 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003595#endif
3596 return false;
3597 }
3598
3599 // Dispatch the unhandled key to the policy.
3600#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003601 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003602 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3603 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3604 keyEntry->policyFlags);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003605#endif
3606 KeyEvent event;
3607 initializeKeyEvent(&event, keyEntry);
3608
3609 mLock.unlock();
3610
3611 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3612 &event, keyEntry->policyFlags, &event);
3613
3614 mLock.lock();
3615
3616 if (connection->status != Connection::STATUS_NORMAL) {
3617 connection->inputState.removeFallbackKey(originalKeyCode);
Jeff Brownd1c48a02012-02-06 19:12:47 -08003618 return false;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003619 }
3620
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003621 // Latch the fallback keycode for this key on an initial down.
3622 // The fallback keycode cannot change at any other point in the lifecycle.
3623 if (initialDown) {
3624 if (fallback) {
3625 fallbackKeyCode = event.getKeyCode();
3626 } else {
3627 fallbackKeyCode = AKEYCODE_UNKNOWN;
3628 }
3629 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3630 }
3631
Steve Blockec193de2012-01-09 18:35:44 +00003632 ALOG_ASSERT(fallbackKeyCode != -1);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003633
3634 // Cancel the fallback key if the policy decides not to send it anymore.
3635 // We will continue to dispatch the key to the policy but we will no
3636 // longer dispatch a fallback key to the application.
3637 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3638 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3639#if DEBUG_OUTBOUND_EVENT_DETAILS
3640 if (fallback) {
Steve Block5baa3a62011-12-20 16:23:08 +00003641 ALOGD("Unhandled key event: Policy requested to send key %d"
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003642 "as a fallback for %d, but on the DOWN it had requested "
3643 "to send %d instead. Fallback canceled.",
3644 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3645 } else {
Jeff Brownfd23e3e2012-05-09 13:34:28 -07003646 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003647 "but on the DOWN it had requested to send %d. "
3648 "Fallback canceled.",
3649 originalKeyCode, fallbackKeyCode);
3650 }
3651#endif
3652
3653 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3654 "canceling fallback, policy no longer desires it");
3655 options.keyCode = fallbackKeyCode;
3656 synthesizeCancelationEventsForConnectionLocked(connection, options);
3657
3658 fallback = false;
3659 fallbackKeyCode = AKEYCODE_UNKNOWN;
3660 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3661 connection->inputState.setFallbackKey(originalKeyCode,
3662 fallbackKeyCode);
3663 }
3664 }
3665
3666#if DEBUG_OUTBOUND_EVENT_DETAILS
3667 {
3668 String8 msg;
3669 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3670 connection->inputState.getFallbackKeys();
3671 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3672 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3673 fallbackKeys.valueAt(i));
3674 }
Steve Block5baa3a62011-12-20 16:23:08 +00003675 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003676 fallbackKeys.size(), msg.string());
3677 }
3678#endif
3679
3680 if (fallback) {
3681 // Restart the dispatch cycle using the fallback key.
3682 keyEntry->eventTime = event.getEventTime();
3683 keyEntry->deviceId = event.getDeviceId();
3684 keyEntry->source = event.getSource();
3685 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3686 keyEntry->keyCode = fallbackKeyCode;
3687 keyEntry->scanCode = event.getScanCode();
3688 keyEntry->metaState = event.getMetaState();
3689 keyEntry->repeatCount = event.getRepeatCount();
3690 keyEntry->downTime = event.getDownTime();
3691 keyEntry->syntheticRepeat = false;
3692
3693#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003694 ALOGD("Unhandled key event: Dispatching fallback key. "
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003695 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3696 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3697#endif
Jeff Brownd1c48a02012-02-06 19:12:47 -08003698 return true; // restart the event
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003699 } else {
3700#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00003701 ALOGD("Unhandled key event: No fallback key.");
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003702#endif
3703 }
3704 }
3705 }
3706 return false;
3707}
3708
3709bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3710 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3711 return false;
Jeff Brown3915bb82010-11-05 15:02:16 -07003712}
3713
Jeff Brownb88102f2010-09-08 11:49:43 -07003714void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3715 mLock.unlock();
3716
Jeff Brown01ce2e92010-09-26 22:20:12 -07003717 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Brownb88102f2010-09-08 11:49:43 -07003718
3719 mLock.lock();
3720}
3721
Jeff Brown3915bb82010-11-05 15:02:16 -07003722void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3723 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3724 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3725 entry->downTime, entry->eventTime);
3726}
3727
Jeff Brown519e0242010-09-15 15:18:56 -07003728void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3729 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3730 // TODO Write some statistics about how long we spend waiting.
Jeff Brownb88102f2010-09-08 11:49:43 -07003731}
3732
Jeff Brown481c1572012-03-09 14:41:15 -08003733void InputDispatcher::traceInboundQueueLengthLocked() {
3734 if (ATRACE_ENABLED()) {
3735 ATRACE_INT("iq", mInboundQueue.count());
3736 }
3737}
3738
3739void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3740 if (ATRACE_ENABLED()) {
3741 char counterName[40];
3742 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3743 ATRACE_INT(counterName, connection->outboundQueue.count());
3744 }
3745}
3746
3747void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3748 if (ATRACE_ENABLED()) {
3749 char counterName[40];
3750 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3751 ATRACE_INT(counterName, connection->waitQueue.count());
3752 }
3753}
3754
Jeff Brownb88102f2010-09-08 11:49:43 -07003755void InputDispatcher::dump(String8& dump) {
Jeff Brown89ef0722011-08-10 16:25:21 -07003756 AutoMutex _l(mLock);
3757
Jeff Brownf2f487182010-10-01 17:46:21 -07003758 dump.append("Input Dispatcher State:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07003759 dumpDispatchStateLocked(dump);
Jeff Brown214eaf42011-05-26 19:17:02 -07003760
Jeff Brown22aa5122012-06-17 12:01:06 -07003761 if (!mLastANRState.isEmpty()) {
3762 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3763 dump.append(mLastANRState);
3764 }
Jeff Brownb88102f2010-09-08 11:49:43 -07003765}
3766
Jeff Brown89ef0722011-08-10 16:25:21 -07003767void InputDispatcher::monitor() {
3768 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3769 mLock.lock();
Jeff Brown112b5f52012-01-27 17:32:06 -08003770 mLooper->wake();
3771 mDispatcherIsAliveCondition.wait(mLock);
Jeff Brown89ef0722011-08-10 16:25:21 -07003772 mLock.unlock();
3773}
3774
Jeff Brown9c3cda02010-06-15 01:31:58 -07003775
Jeff Brown519e0242010-09-15 15:18:56 -07003776// --- InputDispatcher::Queue ---
3777
3778template <typename T>
3779uint32_t InputDispatcher::Queue<T>::count() const {
3780 uint32_t result = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003781 for (const T* entry = head; entry; entry = entry->next) {
Jeff Brown519e0242010-09-15 15:18:56 -07003782 result += 1;
3783 }
3784 return result;
3785}
3786
3787
Jeff Brownac386072011-07-20 15:19:50 -07003788// --- InputDispatcher::InjectionState ---
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003789
Jeff Brownac386072011-07-20 15:19:50 -07003790InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3791 refCount(1),
3792 injectorPid(injectorPid), injectorUid(injectorUid),
3793 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3794 pendingForegroundDispatches(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003795}
3796
Jeff Brownac386072011-07-20 15:19:50 -07003797InputDispatcher::InjectionState::~InjectionState() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07003798}
3799
Jeff Brownac386072011-07-20 15:19:50 -07003800void InputDispatcher::InjectionState::release() {
3801 refCount -= 1;
3802 if (refCount == 0) {
3803 delete this;
3804 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003805 ALOG_ASSERT(refCount > 0);
Jeff Brown01ce2e92010-09-26 22:20:12 -07003806 }
Jeff Brown7fbdc842010-06-17 20:52:56 -07003807}
3808
Jeff Brownac386072011-07-20 15:19:50 -07003809
3810// --- InputDispatcher::EventEntry ---
3811
3812InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3813 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3814 injectionState(NULL), dispatchInProgress(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003815}
3816
Jeff Brownac386072011-07-20 15:19:50 -07003817InputDispatcher::EventEntry::~EventEntry() {
3818 releaseInjectionState();
3819}
3820
3821void InputDispatcher::EventEntry::release() {
3822 refCount -= 1;
3823 if (refCount == 0) {
3824 delete this;
3825 } else {
Steve Blockec193de2012-01-09 18:35:44 +00003826 ALOG_ASSERT(refCount > 0);
Jeff Brownac386072011-07-20 15:19:50 -07003827 }
3828}
3829
3830void InputDispatcher::EventEntry::releaseInjectionState() {
3831 if (injectionState) {
3832 injectionState->release();
3833 injectionState = NULL;
3834 }
3835}
3836
3837
3838// --- InputDispatcher::ConfigurationChangedEntry ---
3839
3840InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3841 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3842}
3843
3844InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3845}
3846
Jeff Brown265f1cc2012-06-11 18:01:06 -07003847void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003848 msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x",
3849 policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003850}
3851
Jeff Brownac386072011-07-20 15:19:50 -07003852
Jeff Brown65fd2512011-08-18 11:20:58 -07003853// --- InputDispatcher::DeviceResetEntry ---
3854
3855InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3856 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3857 deviceId(deviceId) {
3858}
3859
3860InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3861}
3862
Jeff Brown265f1cc2012-06-11 18:01:06 -07003863void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003864 msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
3865 deviceId, policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003866}
3867
Jeff Brown65fd2512011-08-18 11:20:58 -07003868
Jeff Brownac386072011-07-20 15:19:50 -07003869// --- InputDispatcher::KeyEntry ---
3870
3871InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Jeff Brown58a2da82011-01-25 16:02:22 -08003872 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown7fbdc842010-06-17 20:52:56 -07003873 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Jeff Brownac386072011-07-20 15:19:50 -07003874 int32_t repeatCount, nsecs_t downTime) :
3875 EventEntry(TYPE_KEY, eventTime, policyFlags),
3876 deviceId(deviceId), source(source), action(action), flags(flags),
3877 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3878 repeatCount(repeatCount), downTime(downTime),
Jeff Brown905805a2011-10-12 13:57:59 -07003879 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3880 interceptKeyWakeupTime(0) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003881}
3882
Jeff Brownac386072011-07-20 15:19:50 -07003883InputDispatcher::KeyEntry::~KeyEntry() {
3884}
Jeff Brown7fbdc842010-06-17 20:52:56 -07003885
Jeff Brown265f1cc2012-06-11 18:01:06 -07003886void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003887 msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
3888 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3889 "repeatCount=%d), policyFlags=0x%08x",
3890 deviceId, source, action, flags, keyCode, scanCode, metaState,
3891 repeatCount, policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003892}
3893
Jeff Brownac386072011-07-20 15:19:50 -07003894void InputDispatcher::KeyEntry::recycle() {
3895 releaseInjectionState();
3896
3897 dispatchInProgress = false;
3898 syntheticRepeat = false;
3899 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Brown905805a2011-10-12 13:57:59 -07003900 interceptKeyWakeupTime = 0;
Jeff Brownac386072011-07-20 15:19:50 -07003901}
3902
3903
Jeff Brownae9fc032010-08-18 15:51:08 -07003904// --- InputDispatcher::MotionEntry ---
3905
Jeff Brownac386072011-07-20 15:19:50 -07003906InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3907 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3908 int32_t metaState, int32_t buttonState,
3909 int32_t edgeFlags, float xPrecision, float yPrecision,
Jeff Brown83d616a2012-09-09 20:33:43 -07003910 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
Jeff Brownac386072011-07-20 15:19:50 -07003911 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3912 EventEntry(TYPE_MOTION, eventTime, policyFlags),
Jeff Brown3241b6b2012-02-03 15:08:02 -08003913 eventTime(eventTime),
Jeff Brownac386072011-07-20 15:19:50 -07003914 deviceId(deviceId), source(source), action(action), flags(flags),
3915 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3916 xPrecision(xPrecision), yPrecision(yPrecision),
Jeff Brown83d616a2012-09-09 20:33:43 -07003917 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
Jeff Brownac386072011-07-20 15:19:50 -07003918 for (uint32_t i = 0; i < pointerCount; i++) {
3919 this->pointerProperties[i].copyFrom(pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08003920 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownac386072011-07-20 15:19:50 -07003921 }
3922}
3923
3924InputDispatcher::MotionEntry::~MotionEntry() {
Jeff Brownac386072011-07-20 15:19:50 -07003925}
3926
Jeff Brown265f1cc2012-06-11 18:01:06 -07003927void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Jeff Brown6876f322013-08-07 16:46:50 -07003928 msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, "
3929 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, edgeFlags=0x%08x, "
3930 "xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
3931 deviceId, source, action, flags, metaState, buttonState, edgeFlags,
3932 xPrecision, yPrecision, displayId);
3933 for (uint32_t i = 0; i < pointerCount; i++) {
3934 if (i) {
3935 msg.append(", ");
3936 }
3937 msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id,
3938 pointerCoords[i].getX(), pointerCoords[i].getY());
3939 }
3940 msg.appendFormat("]), policyFlags=0x%08x", policyFlags);
Jeff Brown265f1cc2012-06-11 18:01:06 -07003941}
3942
Jeff Brownac386072011-07-20 15:19:50 -07003943
3944// --- InputDispatcher::DispatchEntry ---
3945
Jeff Brown072ec962012-02-07 14:46:57 -08003946volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3947
Jeff Brownac386072011-07-20 15:19:50 -07003948InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3949 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
Jeff Brown072ec962012-02-07 14:46:57 -08003950 seq(nextSeq()),
Jeff Brownac386072011-07-20 15:19:50 -07003951 eventEntry(eventEntry), targetFlags(targetFlags),
3952 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
Jeff Brown265f1cc2012-06-11 18:01:06 -07003953 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
Jeff Brownac386072011-07-20 15:19:50 -07003954 eventEntry->refCount += 1;
3955}
3956
3957InputDispatcher::DispatchEntry::~DispatchEntry() {
3958 eventEntry->release();
3959}
3960
Jeff Brown072ec962012-02-07 14:46:57 -08003961uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3962 // Sequence number 0 is reserved and will never be returned.
3963 uint32_t seq;
3964 do {
3965 seq = android_atomic_inc(&sNextSeqAtomic);
3966 } while (!seq);
3967 return seq;
3968}
3969
Jeff Brownb88102f2010-09-08 11:49:43 -07003970
3971// --- InputDispatcher::InputState ---
3972
Jeff Brownb6997262010-10-08 22:31:17 -07003973InputDispatcher::InputState::InputState() {
Jeff Brownb88102f2010-09-08 11:49:43 -07003974}
3975
3976InputDispatcher::InputState::~InputState() {
3977}
3978
3979bool InputDispatcher::InputState::isNeutral() const {
3980 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3981}
3982
Jeff Brown83d616a2012-09-09 20:33:43 -07003983bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3984 int32_t displayId) const {
Jeff Brown81346812011-06-28 20:08:48 -07003985 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3986 const MotionMemento& memento = mMotionMementos.itemAt(i);
3987 if (memento.deviceId == deviceId
3988 && memento.source == source
Jeff Brown83d616a2012-09-09 20:33:43 -07003989 && memento.displayId == displayId
Jeff Brown81346812011-06-28 20:08:48 -07003990 && memento.hovering) {
3991 return true;
3992 }
3993 }
3994 return false;
3995}
Jeff Brownb88102f2010-09-08 11:49:43 -07003996
Jeff Brown81346812011-06-28 20:08:48 -07003997bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3998 int32_t action, int32_t flags) {
3999 switch (action) {
4000 case AKEY_EVENT_ACTION_UP: {
4001 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4002 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4003 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4004 mFallbackKeys.removeItemsAt(i);
4005 } else {
4006 i += 1;
4007 }
4008 }
4009 }
4010 ssize_t index = findKeyMemento(entry);
4011 if (index >= 0) {
4012 mKeyMementos.removeAt(index);
4013 return true;
4014 }
Jeff Brown68b909d2011-12-07 16:36:01 -08004015 /* FIXME: We can't just drop the key up event because that prevents creating
4016 * popup windows that are automatically shown when a key is held and then
4017 * dismissed when the key is released. The problem is that the popup will
4018 * not have received the original key down, so the key up will be considered
4019 * to be inconsistent with its observed state. We could perhaps handle this
4020 * by synthesizing a key down but that will cause other problems.
4021 *
4022 * So for now, allow inconsistent key up events to be dispatched.
4023 *
Jeff Brown81346812011-06-28 20:08:48 -07004024#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004025 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004026 "keyCode=%d, scanCode=%d",
4027 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4028#endif
4029 return false;
Jeff Brown68b909d2011-12-07 16:36:01 -08004030 */
4031 return true;
Jeff Brown81346812011-06-28 20:08:48 -07004032 }
4033
4034 case AKEY_EVENT_ACTION_DOWN: {
4035 ssize_t index = findKeyMemento(entry);
4036 if (index >= 0) {
4037 mKeyMementos.removeAt(index);
4038 }
4039 addKeyMemento(entry, flags);
4040 return true;
4041 }
4042
4043 default:
4044 return true;
Jeff Brownb88102f2010-09-08 11:49:43 -07004045 }
4046}
4047
Jeff Brown81346812011-06-28 20:08:48 -07004048bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4049 int32_t action, int32_t flags) {
4050 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4051 switch (actionMasked) {
4052 case AMOTION_EVENT_ACTION_UP:
4053 case AMOTION_EVENT_ACTION_CANCEL: {
4054 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4055 if (index >= 0) {
4056 mMotionMementos.removeAt(index);
4057 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004058 }
Jeff Brown81346812011-06-28 20:08:48 -07004059#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004060 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Jeff Brown81346812011-06-28 20:08:48 -07004061 "actionMasked=%d",
4062 entry->deviceId, entry->source, actionMasked);
4063#endif
4064 return false;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004065 }
4066
Jeff Brown81346812011-06-28 20:08:48 -07004067 case AMOTION_EVENT_ACTION_DOWN: {
4068 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4069 if (index >= 0) {
4070 mMotionMementos.removeAt(index);
4071 }
4072 addMotionMemento(entry, flags, false /*hovering*/);
4073 return true;
4074 }
4075
4076 case AMOTION_EVENT_ACTION_POINTER_UP:
4077 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4078 case AMOTION_EVENT_ACTION_MOVE: {
4079 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4080 if (index >= 0) {
4081 MotionMemento& memento = mMotionMementos.editItemAt(index);
4082 memento.setPointers(entry);
4083 return true;
4084 }
Jeff Brown2e45fb62011-06-29 21:19:05 -07004085 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4086 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4087 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4088 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4089 return true;
4090 }
Jeff Brown81346812011-06-28 20:08:48 -07004091#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004092 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Jeff Brown81346812011-06-28 20:08:48 -07004093 "deviceId=%d, source=%08x, actionMasked=%d",
4094 entry->deviceId, entry->source, actionMasked);
4095#endif
4096 return false;
4097 }
4098
4099 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4100 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4101 if (index >= 0) {
4102 mMotionMementos.removeAt(index);
4103 return true;
4104 }
4105#if DEBUG_OUTBOUND_EVENT_DETAILS
Steve Block5baa3a62011-12-20 16:23:08 +00004106 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
Jeff Brown81346812011-06-28 20:08:48 -07004107 entry->deviceId, entry->source);
4108#endif
4109 return false;
4110 }
4111
4112 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4113 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4114 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4115 if (index >= 0) {
4116 mMotionMementos.removeAt(index);
4117 }
4118 addMotionMemento(entry, flags, true /*hovering*/);
4119 return true;
4120 }
4121
4122 default:
4123 return true;
4124 }
4125}
4126
4127ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004128 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004129 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004130 if (memento.deviceId == entry->deviceId
4131 && memento.source == entry->source
4132 && memento.keyCode == entry->keyCode
4133 && memento.scanCode == entry->scanCode) {
Jeff Brown81346812011-06-28 20:08:48 -07004134 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004135 }
4136 }
Jeff Brown81346812011-06-28 20:08:48 -07004137 return -1;
Jeff Brownb88102f2010-09-08 11:49:43 -07004138}
4139
Jeff Brown81346812011-06-28 20:08:48 -07004140ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4141 bool hovering) const {
Jeff Brownb88102f2010-09-08 11:49:43 -07004142 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brown81346812011-06-28 20:08:48 -07004143 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brownb88102f2010-09-08 11:49:43 -07004144 if (memento.deviceId == entry->deviceId
Jeff Brown81346812011-06-28 20:08:48 -07004145 && memento.source == entry->source
Jeff Brown83d616a2012-09-09 20:33:43 -07004146 && memento.displayId == entry->displayId
Jeff Brown81346812011-06-28 20:08:48 -07004147 && memento.hovering == hovering) {
4148 return i;
Jeff Brownb88102f2010-09-08 11:49:43 -07004149 }
4150 }
Jeff Brown81346812011-06-28 20:08:48 -07004151 return -1;
4152}
Jeff Brownb88102f2010-09-08 11:49:43 -07004153
Jeff Brown81346812011-06-28 20:08:48 -07004154void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4155 mKeyMementos.push();
4156 KeyMemento& memento = mKeyMementos.editTop();
4157 memento.deviceId = entry->deviceId;
4158 memento.source = entry->source;
4159 memento.keyCode = entry->keyCode;
4160 memento.scanCode = entry->scanCode;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004161 memento.metaState = entry->metaState;
Jeff Brown81346812011-06-28 20:08:48 -07004162 memento.flags = flags;
4163 memento.downTime = entry->downTime;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004164 memento.policyFlags = entry->policyFlags;
Jeff Brown81346812011-06-28 20:08:48 -07004165}
4166
4167void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4168 int32_t flags, bool hovering) {
4169 mMotionMementos.push();
4170 MotionMemento& memento = mMotionMementos.editTop();
4171 memento.deviceId = entry->deviceId;
4172 memento.source = entry->source;
4173 memento.flags = flags;
4174 memento.xPrecision = entry->xPrecision;
4175 memento.yPrecision = entry->yPrecision;
4176 memento.downTime = entry->downTime;
Jeff Brown83d616a2012-09-09 20:33:43 -07004177 memento.displayId = entry->displayId;
Jeff Brown81346812011-06-28 20:08:48 -07004178 memento.setPointers(entry);
4179 memento.hovering = hovering;
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004180 memento.policyFlags = entry->policyFlags;
Jeff Brownb88102f2010-09-08 11:49:43 -07004181}
4182
4183void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4184 pointerCount = entry->pointerCount;
4185 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004186 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
Jeff Brown3241b6b2012-02-03 15:08:02 -08004187 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
Jeff Brownb88102f2010-09-08 11:49:43 -07004188 }
4189}
4190
Jeff Brownb6997262010-10-08 22:31:17 -07004191void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Jeff Brownac386072011-07-20 15:19:50 -07004192 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
Jeff Brown81346812011-06-28 20:08:48 -07004193 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004194 const KeyMemento& memento = mKeyMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004195 if (shouldCancelKey(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004196 outEvents.push(new KeyEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004197 memento.deviceId, memento.source, memento.policyFlags,
Jeff Brown49ed71d2010-12-06 17:13:33 -08004198 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004199 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
Jeff Brownb6997262010-10-08 22:31:17 -07004200 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004201 }
4202
Jeff Brown81346812011-06-28 20:08:48 -07004203 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Jeff Brownb88102f2010-09-08 11:49:43 -07004204 const MotionMemento& memento = mMotionMementos.itemAt(i);
Jeff Brown49ed71d2010-12-06 17:13:33 -08004205 if (shouldCancelMotion(memento, options)) {
Jeff Brownac386072011-07-20 15:19:50 -07004206 outEvents.push(new MotionEntry(currentTime,
Jeff Brownfd23e3e2012-05-09 13:34:28 -07004207 memento.deviceId, memento.source, memento.policyFlags,
Jeff Browna032cc02011-03-07 16:56:21 -08004208 memento.hovering
4209 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4210 : AMOTION_EVENT_ACTION_CANCEL,
Jeff Brown81346812011-06-28 20:08:48 -07004211 memento.flags, 0, 0, 0,
Jeff Brownb6997262010-10-08 22:31:17 -07004212 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brown83d616a2012-09-09 20:33:43 -07004213 memento.displayId,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004214 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
Jeff Brownb6997262010-10-08 22:31:17 -07004215 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004216 }
4217}
4218
4219void InputDispatcher::InputState::clear() {
4220 mKeyMementos.clear();
4221 mMotionMementos.clear();
Jeff Brownda3d5a92011-03-29 15:11:34 -07004222 mFallbackKeys.clear();
Jeff Brownb6997262010-10-08 22:31:17 -07004223}
4224
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004225void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4226 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4227 const MotionMemento& memento = mMotionMementos.itemAt(i);
4228 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4229 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4230 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4231 if (memento.deviceId == otherMemento.deviceId
Jeff Brown83d616a2012-09-09 20:33:43 -07004232 && memento.source == otherMemento.source
4233 && memento.displayId == otherMemento.displayId) {
Jeff Brown9c9f1a32010-10-11 18:32:20 -07004234 other.mMotionMementos.removeAt(j);
4235 } else {
4236 j += 1;
4237 }
4238 }
4239 other.mMotionMementos.push(memento);
4240 }
4241 }
4242}
4243
Jeff Brownda3d5a92011-03-29 15:11:34 -07004244int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4245 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4246 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4247}
4248
4249void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4250 int32_t fallbackKeyCode) {
4251 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4252 if (index >= 0) {
4253 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4254 } else {
4255 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4256 }
4257}
4258
4259void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4260 mFallbackKeys.removeItem(originalKeyCode);
4261}
4262
Jeff Brown49ed71d2010-12-06 17:13:33 -08004263bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004264 const CancelationOptions& options) {
4265 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4266 return false;
4267 }
4268
Jeff Brown65fd2512011-08-18 11:20:58 -07004269 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4270 return false;
4271 }
4272
Jeff Brownda3d5a92011-03-29 15:11:34 -07004273 switch (options.mode) {
4274 case CancelationOptions::CANCEL_ALL_EVENTS:
4275 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brownb6997262010-10-08 22:31:17 -07004276 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004277 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004278 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4279 default:
4280 return false;
4281 }
4282}
4283
4284bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
Jeff Brownda3d5a92011-03-29 15:11:34 -07004285 const CancelationOptions& options) {
Jeff Brown65fd2512011-08-18 11:20:58 -07004286 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4287 return false;
4288 }
4289
Jeff Brownda3d5a92011-03-29 15:11:34 -07004290 switch (options.mode) {
4291 case CancelationOptions::CANCEL_ALL_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004292 return true;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004293 case CancelationOptions::CANCEL_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004294 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
Jeff Brownda3d5a92011-03-29 15:11:34 -07004295 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
Jeff Brown49ed71d2010-12-06 17:13:33 -08004296 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4297 default:
4298 return false;
Jeff Brownb6997262010-10-08 22:31:17 -07004299 }
Jeff Brownb88102f2010-09-08 11:49:43 -07004300}
4301
4302
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004303// --- InputDispatcher::Connection ---
4304
Jeff Brown928e0542011-01-10 11:17:36 -08004305InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
Jeff Browncc4f7db2011-08-30 20:34:48 -07004306 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
Jeff Brown928e0542011-01-10 11:17:36 -08004307 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
Jeff Browncc4f7db2011-08-30 20:34:48 -07004308 monitor(monitor),
Jeff Brownd1c48a02012-02-06 19:12:47 -08004309 inputPublisher(inputChannel), inputPublisherBlocked(false) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004310}
4311
4312InputDispatcher::Connection::~Connection() {
4313}
4314
Jeff Brown481c1572012-03-09 14:41:15 -08004315const char* InputDispatcher::Connection::getWindowName() const {
4316 if (inputWindowHandle != NULL) {
4317 return inputWindowHandle->getName().string();
4318 }
4319 if (monitor) {
4320 return "monitor";
4321 }
4322 return "?";
4323}
4324
Jeff Brown9c3cda02010-06-15 01:31:58 -07004325const char* InputDispatcher::Connection::getStatusLabel() const {
4326 switch (status) {
4327 case STATUS_NORMAL:
4328 return "NORMAL";
4329
4330 case STATUS_BROKEN:
4331 return "BROKEN";
4332
Jeff Brown9c3cda02010-06-15 01:31:58 -07004333 case STATUS_ZOMBIE:
4334 return "ZOMBIE";
4335
4336 default:
4337 return "UNKNOWN";
4338 }
4339}
4340
Jeff Brown072ec962012-02-07 14:46:57 -08004341InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4342 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4343 if (entry->seq == seq) {
4344 return entry;
4345 }
4346 }
4347 return NULL;
4348}
4349
Jeff Brownb88102f2010-09-08 11:49:43 -07004350
Jeff Brown9c3cda02010-06-15 01:31:58 -07004351// --- InputDispatcher::CommandEntry ---
4352
Jeff Brownac386072011-07-20 15:19:50 -07004353InputDispatcher::CommandEntry::CommandEntry(Command command) :
Jeff Brown072ec962012-02-07 14:46:57 -08004354 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4355 seq(0), handled(false) {
Jeff Brown9c3cda02010-06-15 01:31:58 -07004356}
4357
4358InputDispatcher::CommandEntry::~CommandEntry() {
4359}
4360
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004361
Jeff Brown01ce2e92010-09-26 22:20:12 -07004362// --- InputDispatcher::TouchState ---
4363
4364InputDispatcher::TouchState::TouchState() :
Jeff Brown83d616a2012-09-09 20:33:43 -07004365 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004366}
4367
4368InputDispatcher::TouchState::~TouchState() {
4369}
4370
4371void InputDispatcher::TouchState::reset() {
4372 down = false;
4373 split = false;
Jeff Brown95712852011-01-04 19:41:59 -08004374 deviceId = -1;
Jeff Brown58a2da82011-01-25 16:02:22 -08004375 source = 0;
Jeff Brown83d616a2012-09-09 20:33:43 -07004376 displayId = -1;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004377 windows.clear();
4378}
4379
4380void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4381 down = other.down;
4382 split = other.split;
Jeff Brown95712852011-01-04 19:41:59 -08004383 deviceId = other.deviceId;
Jeff Brown58a2da82011-01-25 16:02:22 -08004384 source = other.source;
Jeff Brown83d616a2012-09-09 20:33:43 -07004385 displayId = other.displayId;
Jeff Brown9302c872011-07-13 22:51:29 -07004386 windows = other.windows;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004387}
4388
Jeff Brown9302c872011-07-13 22:51:29 -07004389void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
Jeff Brown01ce2e92010-09-26 22:20:12 -07004390 int32_t targetFlags, BitSet32 pointerIds) {
4391 if (targetFlags & InputTarget::FLAG_SPLIT) {
4392 split = true;
4393 }
4394
4395 for (size_t i = 0; i < windows.size(); i++) {
4396 TouchedWindow& touchedWindow = windows.editItemAt(i);
Jeff Brown9302c872011-07-13 22:51:29 -07004397 if (touchedWindow.windowHandle == windowHandle) {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004398 touchedWindow.targetFlags |= targetFlags;
Jeff Brown98db5fa2011-06-08 15:37:10 -07004399 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4400 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4401 }
Jeff Brown01ce2e92010-09-26 22:20:12 -07004402 touchedWindow.pointerIds.value |= pointerIds.value;
4403 return;
4404 }
4405 }
4406
4407 windows.push();
4408
4409 TouchedWindow& touchedWindow = windows.editTop();
Jeff Brown9302c872011-07-13 22:51:29 -07004410 touchedWindow.windowHandle = windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004411 touchedWindow.targetFlags = targetFlags;
4412 touchedWindow.pointerIds = pointerIds;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004413}
4414
Jeff Brownf44e3942012-04-20 11:33:27 -07004415void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4416 for (size_t i = 0; i < windows.size(); i++) {
4417 if (windows.itemAt(i).windowHandle == windowHandle) {
4418 windows.removeAt(i);
4419 return;
4420 }
4421 }
4422}
4423
Jeff Browna032cc02011-03-07 16:56:21 -08004424void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004425 for (size_t i = 0 ; i < windows.size(); ) {
Jeff Browna032cc02011-03-07 16:56:21 -08004426 TouchedWindow& window = windows.editItemAt(i);
Jeff Brown98db5fa2011-06-08 15:37:10 -07004427 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4428 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
Jeff Browna032cc02011-03-07 16:56:21 -08004429 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4430 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004431 i += 1;
Jeff Browna032cc02011-03-07 16:56:21 -08004432 } else {
4433 windows.removeAt(i);
Jeff Brown01ce2e92010-09-26 22:20:12 -07004434 }
4435 }
4436}
4437
Jeff Brown9302c872011-07-13 22:51:29 -07004438sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
Jeff Brown01ce2e92010-09-26 22:20:12 -07004439 for (size_t i = 0; i < windows.size(); i++) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004440 const TouchedWindow& window = windows.itemAt(i);
4441 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brown9302c872011-07-13 22:51:29 -07004442 return window.windowHandle;
Jeff Brown01ce2e92010-09-26 22:20:12 -07004443 }
4444 }
4445 return NULL;
4446}
4447
Jeff Brown98db5fa2011-06-08 15:37:10 -07004448bool InputDispatcher::TouchState::isSlippery() const {
4449 // Must have exactly one foreground window.
4450 bool haveSlipperyForegroundWindow = false;
4451 for (size_t i = 0; i < windows.size(); i++) {
4452 const TouchedWindow& window = windows.itemAt(i);
4453 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Browncc4f7db2011-08-30 20:34:48 -07004454 if (haveSlipperyForegroundWindow
4455 || !(window.windowHandle->getInfo()->layoutParamsFlags
4456 & InputWindowInfo::FLAG_SLIPPERY)) {
Jeff Brown98db5fa2011-06-08 15:37:10 -07004457 return false;
4458 }
4459 haveSlipperyForegroundWindow = true;
4460 }
4461 }
4462 return haveSlipperyForegroundWindow;
4463}
4464
Jeff Brown01ce2e92010-09-26 22:20:12 -07004465
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004466// --- InputDispatcherThread ---
4467
4468InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4469 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4470}
4471
4472InputDispatcherThread::~InputDispatcherThread() {
4473}
4474
4475bool InputDispatcherThread::threadLoop() {
4476 mDispatcher->dispatchOnce();
4477 return true;
4478}
4479
4480} // namespace android