blob: 5da16767599b6f21c704dad812515d706243f4e2 [file] [log] [blame]
Jeff Browne839a582010-04-22 18:58:52 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// The input dispatcher.
5//
6#define LOG_TAG "InputDispatcher"
7
8//#define LOG_NDEBUG 0
9
10// Log detailed debug messages about each inbound event notification to the dispatcher.
Jeff Brown50de30a2010-06-22 01:27:15 -070011#define DEBUG_INBOUND_EVENT_DETAILS 0
Jeff Browne839a582010-04-22 18:58:52 -070012
13// Log detailed debug messages about each outbound event processed by the dispatcher.
Jeff Brown50de30a2010-06-22 01:27:15 -070014#define DEBUG_OUTBOUND_EVENT_DETAILS 0
Jeff Browne839a582010-04-22 18:58:52 -070015
16// Log debug messages about batching.
Jeff Brown50de30a2010-06-22 01:27:15 -070017#define DEBUG_BATCHING 0
Jeff Browne839a582010-04-22 18:58:52 -070018
19// Log debug messages about the dispatch cycle.
Jeff Brown50de30a2010-06-22 01:27:15 -070020#define DEBUG_DISPATCH_CYCLE 0
Jeff Browne839a582010-04-22 18:58:52 -070021
Jeff Brown54bc2812010-06-15 01:31:58 -070022// Log debug messages about registrations.
Jeff Brown50de30a2010-06-22 01:27:15 -070023#define DEBUG_REGISTRATION 0
Jeff Brown54bc2812010-06-15 01:31:58 -070024
Jeff Browne839a582010-04-22 18:58:52 -070025// Log debug messages about performance statistics.
Jeff Brown50de30a2010-06-22 01:27:15 -070026#define DEBUG_PERFORMANCE_STATISTICS 0
Jeff Browne839a582010-04-22 18:58:52 -070027
Jeff Brown51d45a72010-06-17 20:52:56 -070028// Log debug messages about input event injection.
Jeff Brown50de30a2010-06-22 01:27:15 -070029#define DEBUG_INJECTION 0
Jeff Brown51d45a72010-06-17 20:52:56 -070030
Jeff Brown542412c2010-08-18 15:51:08 -070031// Log debug messages about input event throttling.
32#define DEBUG_THROTTLING 0
33
Jeff Browna665ca82010-09-08 11:49:43 -070034// Log debug messages about input focus tracking.
35#define DEBUG_FOCUS 0
36
37// Log debug messages about the app switch latency optimization.
38#define DEBUG_APP_SWITCH 0
39
Jeff Browne839a582010-04-22 18:58:52 -070040#include <cutils/log.h>
41#include <ui/InputDispatcher.h>
Jeff Browna665ca82010-09-08 11:49:43 -070042#include <ui/PowerManager.h>
Jeff Browne839a582010-04-22 18:58:52 -070043
44#include <stddef.h>
45#include <unistd.h>
Jeff Browne839a582010-04-22 18:58:52 -070046#include <errno.h>
47#include <limits.h>
Jeff Browne839a582010-04-22 18:58:52 -070048
49namespace android {
50
Jeff Browna665ca82010-09-08 11:49:43 -070051// Delay between reporting long touch events to the power manager.
52const nsecs_t EVENT_IGNORE_DURATION = 300 * 1000000LL; // 300 ms
53
54// Default input dispatching timeout if there is no focused application or paused window
55// from which to determine an appropriate dispatching timeout.
56const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
57
58// Amount of time to allow for all pending events to be processed when an app switch
59// key is on the way. This is used to preempt input dispatch and drop input events
60// when an application takes too long to respond and the user has pressed an app switch key.
61const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
62
Jeff Browne839a582010-04-22 18:58:52 -070063
Jeff Brown51d45a72010-06-17 20:52:56 -070064static inline nsecs_t now() {
65 return systemTime(SYSTEM_TIME_MONOTONIC);
66}
67
Jeff Browna665ca82010-09-08 11:49:43 -070068static inline const char* toString(bool value) {
69 return value ? "true" : "false";
70}
71
Jeff Brownd1b0a2b2010-09-26 22:20:12 -070072static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
73 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
74 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
75}
76
77static bool isValidKeyAction(int32_t action) {
78 switch (action) {
79 case AKEY_EVENT_ACTION_DOWN:
80 case AKEY_EVENT_ACTION_UP:
81 return true;
82 default:
83 return false;
84 }
85}
86
87static bool validateKeyEvent(int32_t action) {
88 if (! isValidKeyAction(action)) {
89 LOGE("Key event has invalid action code 0x%x", action);
90 return false;
91 }
92 return true;
93}
94
95static bool isValidMotionAction(int32_t action) {
96 switch (action & AMOTION_EVENT_ACTION_MASK) {
97 case AMOTION_EVENT_ACTION_DOWN:
98 case AMOTION_EVENT_ACTION_UP:
99 case AMOTION_EVENT_ACTION_CANCEL:
100 case AMOTION_EVENT_ACTION_MOVE:
101 case AMOTION_EVENT_ACTION_POINTER_DOWN:
102 case AMOTION_EVENT_ACTION_POINTER_UP:
103 case AMOTION_EVENT_ACTION_OUTSIDE:
104 return true;
105 default:
106 return false;
107 }
108}
109
110static bool validateMotionEvent(int32_t action, size_t pointerCount,
111 const int32_t* pointerIds) {
112 if (! isValidMotionAction(action)) {
113 LOGE("Motion event has invalid action code 0x%x", action);
114 return false;
115 }
116 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
117 LOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
118 pointerCount, MAX_POINTERS);
119 return false;
120 }
121 for (size_t i = 0; i < pointerCount; i++) {
122 if (pointerIds[i] < 0 || pointerIds[i] > MAX_POINTER_ID) {
123 LOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
124 pointerIds[i], MAX_POINTER_ID);
125 return false;
126 }
127 }
128 return true;
129}
130
Jeff Browna665ca82010-09-08 11:49:43 -0700131
132// --- InputWindow ---
133
134bool InputWindow::visibleFrameIntersects(const InputWindow* other) const {
135 return visibleFrameRight > other->visibleFrameLeft
136 && visibleFrameLeft < other->visibleFrameRight
137 && visibleFrameBottom > other->visibleFrameTop
138 && visibleFrameTop < other->visibleFrameBottom;
139}
140
141bool InputWindow::touchableAreaContainsPoint(int32_t x, int32_t y) const {
142 return x >= touchableAreaLeft && x <= touchableAreaRight
143 && y >= touchableAreaTop && y <= touchableAreaBottom;
144}
145
146
Jeff Browne839a582010-04-22 18:58:52 -0700147// --- InputDispatcher ---
148
Jeff Brown54bc2812010-06-15 01:31:58 -0700149InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Browna665ca82010-09-08 11:49:43 -0700150 mPolicy(policy),
151 mPendingEvent(NULL), mAppSwitchDueTime(LONG_LONG_MAX),
152 mDispatchEnabled(true), mDispatchFrozen(false),
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700153 mFocusedWindow(NULL),
Jeff Browna665ca82010-09-08 11:49:43 -0700154 mFocusedApplication(NULL),
155 mCurrentInputTargetsValid(false),
156 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown59abe7e2010-09-13 23:17:30 -0700157 mLooper = new Looper(false);
Jeff Browne839a582010-04-22 18:58:52 -0700158
Jeff Browna665ca82010-09-08 11:49:43 -0700159 mInboundQueue.headSentinel.refCount = -1;
160 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
161 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Browne839a582010-04-22 18:58:52 -0700162
Jeff Browna665ca82010-09-08 11:49:43 -0700163 mInboundQueue.tailSentinel.refCount = -1;
164 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
165 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Browne839a582010-04-22 18:58:52 -0700166
167 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown54bc2812010-06-15 01:31:58 -0700168
Jeff Brown542412c2010-08-18 15:51:08 -0700169 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
170 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
171 mThrottleState.lastDeviceId = -1;
172
173#if DEBUG_THROTTLING
174 mThrottleState.originalSampleCount = 0;
175 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
176#endif
Jeff Browne839a582010-04-22 18:58:52 -0700177}
178
179InputDispatcher::~InputDispatcher() {
Jeff Browna665ca82010-09-08 11:49:43 -0700180 { // acquire lock
181 AutoMutex _l(mLock);
182
183 resetKeyRepeatLocked();
Jeff Brownd8816c32010-09-16 14:07:33 -0700184 releasePendingEventLocked();
Jeff Browna665ca82010-09-08 11:49:43 -0700185 drainInboundQueueLocked();
186 }
Jeff Browne839a582010-04-22 18:58:52 -0700187
188 while (mConnectionsByReceiveFd.size() != 0) {
189 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
190 }
Jeff Browne839a582010-04-22 18:58:52 -0700191}
192
193void InputDispatcher::dispatchOnce() {
Jeff Brown54bc2812010-06-15 01:31:58 -0700194 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brown61ce3982010-09-07 10:44:57 -0700195 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Browne839a582010-04-22 18:58:52 -0700196
Jeff Browne839a582010-04-22 18:58:52 -0700197 nsecs_t nextWakeupTime = LONG_LONG_MAX;
198 { // acquire lock
199 AutoMutex _l(mLock);
Jeff Browna665ca82010-09-08 11:49:43 -0700200 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Browne839a582010-04-22 18:58:52 -0700201
Jeff Browna665ca82010-09-08 11:49:43 -0700202 if (runCommandsLockedInterruptible()) {
203 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Browne839a582010-04-22 18:58:52 -0700204 }
Jeff Browne839a582010-04-22 18:58:52 -0700205 } // release lock
206
Jeff Browna665ca82010-09-08 11:49:43 -0700207 // Wait for callback or timeout or wake. (make sure we round up, not down)
208 nsecs_t currentTime = now();
209 int32_t timeoutMillis;
210 if (nextWakeupTime > currentTime) {
211 uint64_t timeout = uint64_t(nextWakeupTime - currentTime);
212 timeout = (timeout + 999999LL) / 1000000LL;
213 timeoutMillis = timeout > INT_MAX ? -1 : int32_t(timeout);
214 } else {
215 timeoutMillis = 0;
216 }
217
Jeff Brown59abe7e2010-09-13 23:17:30 -0700218 mLooper->pollOnce(timeoutMillis);
Jeff Browna665ca82010-09-08 11:49:43 -0700219}
220
221void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
222 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
223 nsecs_t currentTime = now();
224
225 // Reset the key repeat timer whenever we disallow key events, even if the next event
226 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
227 // out of sleep.
228 if (keyRepeatTimeout < 0) {
229 resetKeyRepeatLocked();
230 }
231
232 // If dispatching is disabled, drop all events in the queue.
233 if (! mDispatchEnabled) {
234 if (mPendingEvent || ! mInboundQueue.isEmpty()) {
235 LOGI("Dropping pending events because input dispatch is disabled.");
Jeff Brownd8816c32010-09-16 14:07:33 -0700236 releasePendingEventLocked();
Jeff Browna665ca82010-09-08 11:49:43 -0700237 drainInboundQueueLocked();
238 }
Jeff Brown54bc2812010-06-15 01:31:58 -0700239 return;
240 }
241
Jeff Browna665ca82010-09-08 11:49:43 -0700242 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
243 if (mDispatchFrozen) {
244#if DEBUG_FOCUS
245 LOGD("Dispatch frozen. Waiting some more.");
246#endif
247 return;
248 }
249
250 // Optimize latency of app switches.
251 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
252 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
253 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
254 if (mAppSwitchDueTime < *nextWakeupTime) {
255 *nextWakeupTime = mAppSwitchDueTime;
256 }
257
Jeff Browna665ca82010-09-08 11:49:43 -0700258 // Ready to start a new event.
259 // If we don't already have a pending event, go grab one.
260 if (! mPendingEvent) {
261 if (mInboundQueue.isEmpty()) {
262 if (isAppSwitchDue) {
263 // The inbound queue is empty so the app switch key we were waiting
264 // for will never arrive. Stop waiting for it.
265 resetPendingAppSwitchLocked(false);
266 isAppSwitchDue = false;
267 }
268
269 // Synthesize a key repeat if appropriate.
270 if (mKeyRepeatState.lastKeyEntry) {
271 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
272 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
273 } else {
274 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
275 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
276 }
277 }
278 }
279 if (! mPendingEvent) {
280 return;
281 }
282 } else {
283 // Inbound queue has at least one entry.
284 EventEntry* entry = mInboundQueue.headSentinel.next;
285
286 // Throttle the entry if it is a move event and there are no
287 // other events behind it in the queue. Due to movement batching, additional
288 // samples may be appended to this event by the time the throttling timeout
289 // expires.
290 // TODO Make this smarter and consider throttling per device independently.
291 if (entry->type == EventEntry::TYPE_MOTION) {
292 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
293 int32_t deviceId = motionEntry->deviceId;
294 uint32_t source = motionEntry->source;
295 if (! isAppSwitchDue
296 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
297 && motionEntry->action == AMOTION_EVENT_ACTION_MOVE
298 && deviceId == mThrottleState.lastDeviceId
299 && source == mThrottleState.lastSource) {
300 nsecs_t nextTime = mThrottleState.lastEventTime
301 + mThrottleState.minTimeBetweenEvents;
302 if (currentTime < nextTime) {
303 // Throttle it!
304#if DEBUG_THROTTLING
305 LOGD("Throttling - Delaying motion event for "
306 "device 0x%x, source 0x%08x by up to %0.3fms.",
307 deviceId, source, (nextTime - currentTime) * 0.000001);
308#endif
309 if (nextTime < *nextWakeupTime) {
310 *nextWakeupTime = nextTime;
311 }
312 if (mThrottleState.originalSampleCount == 0) {
313 mThrottleState.originalSampleCount =
314 motionEntry->countSamples();
315 }
316 return;
317 }
318 }
319
320#if DEBUG_THROTTLING
321 if (mThrottleState.originalSampleCount != 0) {
322 uint32_t count = motionEntry->countSamples();
323 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
324 count - mThrottleState.originalSampleCount,
325 mThrottleState.originalSampleCount, count);
326 mThrottleState.originalSampleCount = 0;
327 }
328#endif
329
330 mThrottleState.lastEventTime = entry->eventTime < currentTime
331 ? entry->eventTime : currentTime;
332 mThrottleState.lastDeviceId = deviceId;
333 mThrottleState.lastSource = source;
334 }
335
336 mInboundQueue.dequeue(entry);
337 mPendingEvent = entry;
338 }
339 }
340
341 // Now we have an event to dispatch.
342 assert(mPendingEvent != NULL);
Jeff Brownd8816c32010-09-16 14:07:33 -0700343 bool done = false;
Jeff Browna665ca82010-09-08 11:49:43 -0700344 switch (mPendingEvent->type) {
345 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
346 ConfigurationChangedEntry* typedEntry =
347 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
Jeff Brownd8816c32010-09-16 14:07:33 -0700348 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Jeff Browna665ca82010-09-08 11:49:43 -0700349 break;
350 }
351
352 case EventEntry::TYPE_KEY: {
353 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
Jeff Brownd8816c32010-09-16 14:07:33 -0700354 bool appSwitchKey = isAppSwitchKey(typedEntry->keyCode);
355 bool dropEvent = isAppSwitchDue && ! appSwitchKey;
356 done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout, dropEvent,
357 nextWakeupTime);
358 if (done) {
359 if (dropEvent) {
360 LOGI("Dropped key because of pending overdue app switch.");
361 } else if (appSwitchKey) {
Jeff Browna665ca82010-09-08 11:49:43 -0700362 resetPendingAppSwitchLocked(true);
Jeff Browna665ca82010-09-08 11:49:43 -0700363 }
364 }
Jeff Browna665ca82010-09-08 11:49:43 -0700365 break;
366 }
367
368 case EventEntry::TYPE_MOTION: {
369 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Jeff Brownd8816c32010-09-16 14:07:33 -0700370 bool dropEvent = isAppSwitchDue;
371 done = dispatchMotionLocked(currentTime, typedEntry, dropEvent, nextWakeupTime);
372 if (done) {
373 if (dropEvent) {
374 LOGI("Dropped motion because of pending overdue app switch.");
375 }
Jeff Browna665ca82010-09-08 11:49:43 -0700376 }
Jeff Browna665ca82010-09-08 11:49:43 -0700377 break;
378 }
379
380 default:
381 assert(false);
Jeff Browna665ca82010-09-08 11:49:43 -0700382 break;
383 }
384
Jeff Brownd8816c32010-09-16 14:07:33 -0700385 if (done) {
386 releasePendingEventLocked();
Jeff Browna665ca82010-09-08 11:49:43 -0700387 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
388 }
389}
390
391bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
392 bool needWake = mInboundQueue.isEmpty();
393 mInboundQueue.enqueueAtTail(entry);
394
395 switch (entry->type) {
396 case EventEntry::TYPE_KEY:
397 needWake |= detectPendingAppSwitchLocked(static_cast<KeyEntry*>(entry));
398 break;
399 }
400
401 return needWake;
402}
403
404bool InputDispatcher::isAppSwitchKey(int32_t keyCode) {
405 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
406}
407
408bool InputDispatcher::isAppSwitchPendingLocked() {
409 return mAppSwitchDueTime != LONG_LONG_MAX;
410}
411
412bool InputDispatcher::detectPendingAppSwitchLocked(KeyEntry* inboundKeyEntry) {
413 if (inboundKeyEntry->action == AKEY_EVENT_ACTION_UP
414 && ! (inboundKeyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
415 && isAppSwitchKey(inboundKeyEntry->keyCode)
416 && isEventFromReliableSourceLocked(inboundKeyEntry)) {
417#if DEBUG_APP_SWITCH
418 LOGD("App switch is pending!");
419#endif
420 mAppSwitchDueTime = inboundKeyEntry->eventTime + APP_SWITCH_TIMEOUT;
421 return true; // need wake
422 }
423 return false;
424}
425
426void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
427 mAppSwitchDueTime = LONG_LONG_MAX;
428
429#if DEBUG_APP_SWITCH
430 if (handled) {
431 LOGD("App switch has arrived.");
432 } else {
433 LOGD("App switch was abandoned.");
434 }
435#endif
Jeff Browne839a582010-04-22 18:58:52 -0700436}
437
Jeff Brown54bc2812010-06-15 01:31:58 -0700438bool InputDispatcher::runCommandsLockedInterruptible() {
439 if (mCommandQueue.isEmpty()) {
440 return false;
441 }
Jeff Browne839a582010-04-22 18:58:52 -0700442
Jeff Brown54bc2812010-06-15 01:31:58 -0700443 do {
444 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
445
446 Command command = commandEntry->command;
447 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
448
Jeff Brown51d45a72010-06-17 20:52:56 -0700449 commandEntry->connection.clear();
Jeff Brown54bc2812010-06-15 01:31:58 -0700450 mAllocator.releaseCommandEntry(commandEntry);
451 } while (! mCommandQueue.isEmpty());
452 return true;
Jeff Browne839a582010-04-22 18:58:52 -0700453}
454
Jeff Brown54bc2812010-06-15 01:31:58 -0700455InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
456 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
457 mCommandQueue.enqueueAtTail(commandEntry);
458 return commandEntry;
459}
460
Jeff Browna665ca82010-09-08 11:49:43 -0700461void InputDispatcher::drainInboundQueueLocked() {
462 while (! mInboundQueue.isEmpty()) {
463 EventEntry* entry = mInboundQueue.dequeueAtHead();
Jeff Brownd8816c32010-09-16 14:07:33 -0700464 releaseInboundEventLocked(entry);
Jeff Browne839a582010-04-22 18:58:52 -0700465 }
Jeff Browne839a582010-04-22 18:58:52 -0700466}
467
Jeff Brownd8816c32010-09-16 14:07:33 -0700468void InputDispatcher::releasePendingEventLocked() {
Jeff Browna665ca82010-09-08 11:49:43 -0700469 if (mPendingEvent) {
Jeff Brownd8816c32010-09-16 14:07:33 -0700470 releaseInboundEventLocked(mPendingEvent);
Jeff Browna665ca82010-09-08 11:49:43 -0700471 mPendingEvent = NULL;
472 }
473}
474
Jeff Brownd8816c32010-09-16 14:07:33 -0700475void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700476 InjectionState* injectionState = entry->injectionState;
477 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
Jeff Browna665ca82010-09-08 11:49:43 -0700478#if DEBUG_DISPATCH_CYCLE
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700479 LOGD("Injected inbound event was dropped.");
Jeff Browna665ca82010-09-08 11:49:43 -0700480#endif
481 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
482 }
483 mAllocator.releaseEventEntry(entry);
484}
485
486bool InputDispatcher::isEventFromReliableSourceLocked(EventEntry* entry) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700487 InjectionState* injectionState = entry->injectionState;
488 return ! injectionState
489 || injectionState->injectorUid == 0
Jeff Browna665ca82010-09-08 11:49:43 -0700490 || mPolicy->checkInjectEventsPermissionNonReentrant(
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700491 injectionState->injectorPid, injectionState->injectorUid);
Jeff Browna665ca82010-09-08 11:49:43 -0700492}
493
494void InputDispatcher::resetKeyRepeatLocked() {
495 if (mKeyRepeatState.lastKeyEntry) {
496 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
497 mKeyRepeatState.lastKeyEntry = NULL;
498 }
499}
500
501InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brown61ce3982010-09-07 10:44:57 -0700502 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown50de30a2010-06-22 01:27:15 -0700503 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
504
Jeff Brown50de30a2010-06-22 01:27:15 -0700505 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Brown51d45a72010-06-17 20:52:56 -0700506 uint32_t policyFlags = entry->policyFlags & POLICY_FLAG_RAW_MASK;
Jeff Browne839a582010-04-22 18:58:52 -0700507 if (entry->refCount == 1) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700508 mAllocator.recycleKeyEntry(entry);
Jeff Brown51d45a72010-06-17 20:52:56 -0700509 entry->eventTime = currentTime;
Jeff Brown51d45a72010-06-17 20:52:56 -0700510 entry->policyFlags = policyFlags;
Jeff Browne839a582010-04-22 18:58:52 -0700511 entry->repeatCount += 1;
512 } else {
Jeff Brown51d45a72010-06-17 20:52:56 -0700513 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700514 entry->deviceId, entry->source, policyFlags,
Jeff Brown51d45a72010-06-17 20:52:56 -0700515 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brownf16c26d2010-07-02 15:37:36 -0700516 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Browne839a582010-04-22 18:58:52 -0700517
518 mKeyRepeatState.lastKeyEntry = newEntry;
519 mAllocator.releaseKeyEntry(entry);
520
521 entry = newEntry;
522 }
Jeff Browna665ca82010-09-08 11:49:43 -0700523 entry->syntheticRepeat = true;
524
525 // Increment reference count since we keep a reference to the event in
526 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
527 entry->refCount += 1;
Jeff Browne839a582010-04-22 18:58:52 -0700528
Jeff Brownf16c26d2010-07-02 15:37:36 -0700529 if (entry->repeatCount == 1) {
Jeff Brown5c1ed842010-07-14 18:48:53 -0700530 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
Jeff Brownf16c26d2010-07-02 15:37:36 -0700531 }
532
Jeff Brown61ce3982010-09-07 10:44:57 -0700533 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Browna665ca82010-09-08 11:49:43 -0700534 return entry;
Jeff Browne839a582010-04-22 18:58:52 -0700535}
536
Jeff Browna665ca82010-09-08 11:49:43 -0700537bool InputDispatcher::dispatchConfigurationChangedLocked(
538 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Browne839a582010-04-22 18:58:52 -0700539#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Browna665ca82010-09-08 11:49:43 -0700540 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
541#endif
542
543 // Reset key repeating in case a keyboard device was added or removed or something.
544 resetKeyRepeatLocked();
545
546 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
547 CommandEntry* commandEntry = postCommandLocked(
548 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
549 commandEntry->eventTime = entry->eventTime;
550 return true;
551}
552
553bool InputDispatcher::dispatchKeyLocked(
554 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
Jeff Brownd8816c32010-09-16 14:07:33 -0700555 bool dropEvent, nsecs_t* nextWakeupTime) {
556 // Give the policy a chance to intercept the key.
557 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
558 bool trusted;
559 if (! dropEvent && mFocusedWindow) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700560 trusted = checkInjectionPermission(mFocusedWindow, entry->injectionState);
Jeff Brownd8816c32010-09-16 14:07:33 -0700561 } else {
562 trusted = isEventFromReliableSourceLocked(entry);
563 }
564 if (trusted) {
565 CommandEntry* commandEntry = postCommandLocked(
566 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
567 if (! dropEvent && mFocusedWindow) {
568 commandEntry->inputChannel = mFocusedWindow->inputChannel;
569 }
570 commandEntry->keyEntry = entry;
571 entry->refCount += 1;
572 return false; // wait for the command to run
573 } else {
574 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
575 }
576 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
577 resetTargetsLocked();
578 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_SUCCEEDED);
579 return true;
580 }
581
582 // Clean up if dropping the event.
583 if (dropEvent) {
584 resetTargetsLocked();
585 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
586 return true;
587 }
588
Jeff Browna665ca82010-09-08 11:49:43 -0700589 // Preprocessing.
590 if (! entry->dispatchInProgress) {
591 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
592
593 if (entry->repeatCount == 0
594 && entry->action == AKEY_EVENT_ACTION_DOWN
595 && ! entry->isInjected()) {
596 if (mKeyRepeatState.lastKeyEntry
597 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
598 // We have seen two identical key downs in a row which indicates that the device
599 // driver is automatically generating key repeats itself. We take note of the
600 // repeat here, but we disable our own next key repeat timer since it is clear that
601 // we will not need to synthesize key repeats ourselves.
602 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
603 resetKeyRepeatLocked();
604 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
605 } else {
606 // Not a repeat. Save key down state in case we do see a repeat later.
607 resetKeyRepeatLocked();
608 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
609 }
610 mKeyRepeatState.lastKeyEntry = entry;
611 entry->refCount += 1;
612 } else if (! entry->syntheticRepeat) {
613 resetKeyRepeatLocked();
614 }
615
616 entry->dispatchInProgress = true;
Jeff Brownd8816c32010-09-16 14:07:33 -0700617 resetTargetsLocked();
Jeff Browna665ca82010-09-08 11:49:43 -0700618 }
619
620 // Identify targets.
621 if (! mCurrentInputTargetsValid) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700622 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
623 entry, nextWakeupTime);
Jeff Browna665ca82010-09-08 11:49:43 -0700624 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
625 return false;
626 }
627
628 setInjectionResultLocked(entry, injectionResult);
629 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
630 return true;
631 }
632
633 addMonitoringTargetsLocked();
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700634 commitTargetsLocked();
Jeff Browna665ca82010-09-08 11:49:43 -0700635 }
636
637 // Dispatch the key.
638 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
639
640 // Poke user activity.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700641 if (shouldPokeUserActivityForCurrentInputTargetsLocked()) {
642 pokeUserActivityLocked(entry->eventTime, POWER_MANAGER_BUTTON_EVENT);
643 }
Jeff Browna665ca82010-09-08 11:49:43 -0700644 return true;
645}
646
647void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
648#if DEBUG_OUTBOUND_EVENT_DETAILS
649 LOGD("%seventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, "
650 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
651 "downTime=%lld",
652 prefix,
653 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
654 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
655 entry->downTime);
656#endif
657}
658
659bool InputDispatcher::dispatchMotionLocked(
Jeff Brownd8816c32010-09-16 14:07:33 -0700660 nsecs_t currentTime, MotionEntry* entry, bool dropEvent, nsecs_t* nextWakeupTime) {
661 // Clean up if dropping the event.
662 if (dropEvent) {
663 resetTargetsLocked();
664 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
665 return true;
666 }
667
Jeff Browna665ca82010-09-08 11:49:43 -0700668 // Preprocessing.
669 if (! entry->dispatchInProgress) {
670 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
671
672 entry->dispatchInProgress = true;
Jeff Brownd8816c32010-09-16 14:07:33 -0700673 resetTargetsLocked();
Jeff Browna665ca82010-09-08 11:49:43 -0700674 }
675
676 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
677
678 // Identify targets.
679 if (! mCurrentInputTargetsValid) {
Jeff Browna665ca82010-09-08 11:49:43 -0700680 int32_t injectionResult;
681 if (isPointerEvent) {
682 // Pointer event. (eg. touchscreen)
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700683 injectionResult = findTouchedWindowTargetsLocked(currentTime,
684 entry, nextWakeupTime);
Jeff Browna665ca82010-09-08 11:49:43 -0700685 } else {
686 // Non touch event. (eg. trackball)
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700687 injectionResult = findFocusedWindowTargetsLocked(currentTime,
688 entry, nextWakeupTime);
Jeff Browna665ca82010-09-08 11:49:43 -0700689 }
690 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
691 return false;
692 }
693
694 setInjectionResultLocked(entry, injectionResult);
695 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
696 return true;
697 }
698
699 addMonitoringTargetsLocked();
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700700 commitTargetsLocked();
Jeff Browna665ca82010-09-08 11:49:43 -0700701 }
702
703 // Dispatch the motion.
704 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
705
706 // Poke user activity.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700707 if (shouldPokeUserActivityForCurrentInputTargetsLocked()) {
708 int32_t eventType;
709 if (isPointerEvent) {
710 switch (entry->action) {
711 case AMOTION_EVENT_ACTION_DOWN:
Jeff Browna665ca82010-09-08 11:49:43 -0700712 eventType = POWER_MANAGER_TOUCH_EVENT;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700713 break;
714 case AMOTION_EVENT_ACTION_UP:
715 eventType = POWER_MANAGER_TOUCH_UP_EVENT;
716 break;
717 default:
718 if (entry->eventTime - entry->downTime >= EVENT_IGNORE_DURATION) {
719 eventType = POWER_MANAGER_TOUCH_EVENT;
720 } else {
721 eventType = POWER_MANAGER_LONG_TOUCH_EVENT;
722 }
723 break;
Jeff Browna665ca82010-09-08 11:49:43 -0700724 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700725 } else {
726 eventType = POWER_MANAGER_BUTTON_EVENT;
Jeff Browna665ca82010-09-08 11:49:43 -0700727 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700728 pokeUserActivityLocked(entry->eventTime, eventType);
Jeff Browna665ca82010-09-08 11:49:43 -0700729 }
Jeff Browna665ca82010-09-08 11:49:43 -0700730 return true;
731}
732
733
734void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
735#if DEBUG_OUTBOUND_EVENT_DETAILS
736 LOGD("%seventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, "
Jeff Brownaf30ff62010-09-01 17:01:00 -0700737 "action=0x%x, flags=0x%x, "
Jeff Browne839a582010-04-22 18:58:52 -0700738 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Browna665ca82010-09-08 11:49:43 -0700739 prefix,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700740 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
741 entry->action, entry->flags,
Jeff Browne839a582010-04-22 18:58:52 -0700742 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
743 entry->downTime);
744
745 // Print the most recent sample that we have available, this may change due to batching.
746 size_t sampleCount = 1;
Jeff Browna665ca82010-09-08 11:49:43 -0700747 const MotionSample* sample = & entry->firstSample;
Jeff Browne839a582010-04-22 18:58:52 -0700748 for (; sample->next != NULL; sample = sample->next) {
749 sampleCount += 1;
750 }
751 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown38a7fab2010-08-30 03:02:23 -0700752 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brownaf30ff62010-09-01 17:01:00 -0700753 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown38a7fab2010-08-30 03:02:23 -0700754 "orientation=%f",
Jeff Browne839a582010-04-22 18:58:52 -0700755 i, entry->pointerIds[i],
Jeff Brown38a7fab2010-08-30 03:02:23 -0700756 sample->pointerCoords[i].x, sample->pointerCoords[i].y,
757 sample->pointerCoords[i].pressure, sample->pointerCoords[i].size,
758 sample->pointerCoords[i].touchMajor, sample->pointerCoords[i].touchMinor,
759 sample->pointerCoords[i].toolMajor, sample->pointerCoords[i].toolMinor,
760 sample->pointerCoords[i].orientation);
Jeff Browne839a582010-04-22 18:58:52 -0700761 }
762
763 // Keep in mind that due to batching, it is possible for the number of samples actually
764 // dispatched to change before the application finally consumed them.
Jeff Brown5c1ed842010-07-14 18:48:53 -0700765 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Browne839a582010-04-22 18:58:52 -0700766 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
767 }
768#endif
Jeff Browne839a582010-04-22 18:58:52 -0700769}
770
771void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
772 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
773#if DEBUG_DISPATCH_CYCLE
Jeff Brown54bc2812010-06-15 01:31:58 -0700774 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Browne839a582010-04-22 18:58:52 -0700775 "resumeWithAppendedMotionSample=%s",
Jeff Browna665ca82010-09-08 11:49:43 -0700776 toString(resumeWithAppendedMotionSample));
Jeff Browne839a582010-04-22 18:58:52 -0700777#endif
778
Jeff Brown54bc2812010-06-15 01:31:58 -0700779 assert(eventEntry->dispatchInProgress); // should already have been set to true
780
Jeff Browne839a582010-04-22 18:58:52 -0700781 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
782 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
783
Jeff Brown53a415e2010-09-15 15:18:56 -0700784 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Browne839a582010-04-22 18:58:52 -0700785 if (connectionIndex >= 0) {
786 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown51d45a72010-06-17 20:52:56 -0700787 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Browne839a582010-04-22 18:58:52 -0700788 resumeWithAppendedMotionSample);
789 } else {
790 LOGW("Framework requested delivery of an input event to channel '%s' but it "
791 "is not registered with the input dispatcher.",
792 inputTarget.inputChannel->getName().string());
793 }
794 }
795}
796
Jeff Brownd8816c32010-09-16 14:07:33 -0700797void InputDispatcher::resetTargetsLocked() {
Jeff Browna665ca82010-09-08 11:49:43 -0700798 mCurrentInputTargetsValid = false;
799 mCurrentInputTargets.clear();
Jeff Browna665ca82010-09-08 11:49:43 -0700800 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
801}
802
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700803void InputDispatcher::commitTargetsLocked() {
Jeff Browna665ca82010-09-08 11:49:43 -0700804 mCurrentInputTargetsValid = true;
805}
806
807int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
808 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
809 nsecs_t* nextWakeupTime) {
810 if (application == NULL && window == NULL) {
811 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
812#if DEBUG_FOCUS
813 LOGD("Waiting for system to become ready for input.");
814#endif
815 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
816 mInputTargetWaitStartTime = currentTime;
817 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
818 mInputTargetWaitTimeoutExpired = false;
819 }
820 } else {
821 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
822#if DEBUG_FOCUS
Jeff Brown53a415e2010-09-15 15:18:56 -0700823 LOGD("Waiting for application to become ready for input: %s",
824 getApplicationWindowLabelLocked(application, window).string());
Jeff Browna665ca82010-09-08 11:49:43 -0700825#endif
826 nsecs_t timeout = window ? window->dispatchingTimeout :
827 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
828
829 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
830 mInputTargetWaitStartTime = currentTime;
831 mInputTargetWaitTimeoutTime = currentTime + timeout;
832 mInputTargetWaitTimeoutExpired = false;
833 }
834 }
835
836 if (mInputTargetWaitTimeoutExpired) {
837 return INPUT_EVENT_INJECTION_TIMED_OUT;
838 }
839
840 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown53a415e2010-09-15 15:18:56 -0700841 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Browna665ca82010-09-08 11:49:43 -0700842
843 // Force poll loop to wake up immediately on next iteration once we get the
844 // ANR response back from the policy.
845 *nextWakeupTime = LONG_LONG_MIN;
846 return INPUT_EVENT_INJECTION_PENDING;
847 } else {
848 // Force poll loop to wake up when timeout is due.
849 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
850 *nextWakeupTime = mInputTargetWaitTimeoutTime;
851 }
852 return INPUT_EVENT_INJECTION_PENDING;
853 }
854}
855
Jeff Brown53a415e2010-09-15 15:18:56 -0700856void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
857 const sp<InputChannel>& inputChannel) {
Jeff Browna665ca82010-09-08 11:49:43 -0700858 if (newTimeout > 0) {
859 // Extend the timeout.
860 mInputTargetWaitTimeoutTime = now() + newTimeout;
861 } else {
862 // Give up.
863 mInputTargetWaitTimeoutExpired = true;
Jeff Brown53a415e2010-09-15 15:18:56 -0700864
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700865 // Release the touch targets.
866 mTouchState.reset();
Jeff Brown405a1d32010-09-16 12:31:46 -0700867
Jeff Brown53a415e2010-09-15 15:18:56 -0700868 // Input state will not be realistic. Mark it out of sync.
Jeff Brown40ad4702010-09-16 11:02:16 -0700869 if (inputChannel.get()) {
870 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
871 if (connectionIndex >= 0) {
872 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
873 connection->inputState.setOutOfSync();
874 }
Jeff Brown53a415e2010-09-15 15:18:56 -0700875 }
Jeff Browna665ca82010-09-08 11:49:43 -0700876 }
877}
878
Jeff Brown53a415e2010-09-15 15:18:56 -0700879nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Browna665ca82010-09-08 11:49:43 -0700880 nsecs_t currentTime) {
881 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
882 return currentTime - mInputTargetWaitStartTime;
883 }
884 return 0;
885}
886
887void InputDispatcher::resetANRTimeoutsLocked() {
888#if DEBUG_FOCUS
889 LOGD("Resetting ANR timeouts.");
890#endif
891
Jeff Browna665ca82010-09-08 11:49:43 -0700892 // Reset input target wait timeout.
893 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
894}
895
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700896int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
897 const EventEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Browna665ca82010-09-08 11:49:43 -0700898 mCurrentInputTargets.clear();
899
900 int32_t injectionResult;
901
902 // If there is no currently focused window and no focused application
903 // then drop the event.
904 if (! mFocusedWindow) {
905 if (mFocusedApplication) {
906#if DEBUG_FOCUS
907 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown53a415e2010-09-15 15:18:56 -0700908 "focused application that may eventually add a window: %s.",
909 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Browna665ca82010-09-08 11:49:43 -0700910#endif
911 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
912 mFocusedApplication, NULL, nextWakeupTime);
913 goto Unresponsive;
914 }
915
916 LOGI("Dropping event because there is no focused window or focused application.");
917 injectionResult = INPUT_EVENT_INJECTION_FAILED;
918 goto Failed;
919 }
920
921 // Check permissions.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700922 if (! checkInjectionPermission(mFocusedWindow, entry->injectionState)) {
Jeff Browna665ca82010-09-08 11:49:43 -0700923 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
924 goto Failed;
925 }
926
927 // If the currently focused window is paused then keep waiting.
928 if (mFocusedWindow->paused) {
929#if DEBUG_FOCUS
930 LOGD("Waiting because focused window is paused.");
931#endif
932 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
933 mFocusedApplication, mFocusedWindow, nextWakeupTime);
934 goto Unresponsive;
935 }
936
Jeff Brown53a415e2010-09-15 15:18:56 -0700937 // If the currently focused window is still working on previous events then keep waiting.
938 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
939#if DEBUG_FOCUS
940 LOGD("Waiting because focused window still processing previous input.");
941#endif
942 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
943 mFocusedApplication, mFocusedWindow, nextWakeupTime);
944 goto Unresponsive;
945 }
946
Jeff Browna665ca82010-09-08 11:49:43 -0700947 // Success! Output targets.
948 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700949 addWindowTargetLocked(mFocusedWindow, InputTarget::FLAG_FOREGROUND, BitSet32(0));
Jeff Browna665ca82010-09-08 11:49:43 -0700950
951 // Done.
952Failed:
953Unresponsive:
Jeff Brown53a415e2010-09-15 15:18:56 -0700954 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
955 updateDispatchStatisticsLocked(currentTime, entry,
956 injectionResult, timeSpentWaitingForApplication);
Jeff Browna665ca82010-09-08 11:49:43 -0700957#if DEBUG_FOCUS
Jeff Brown53a415e2010-09-15 15:18:56 -0700958 LOGD("findFocusedWindow finished: injectionResult=%d, "
959 "timeSpendWaitingForApplication=%0.1fms",
960 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Browna665ca82010-09-08 11:49:43 -0700961#endif
962 return injectionResult;
963}
964
Jeff Brownd1b0a2b2010-09-26 22:20:12 -0700965int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
966 const MotionEntry* entry, nsecs_t* nextWakeupTime) {
Jeff Browna665ca82010-09-08 11:49:43 -0700967 enum InjectionPermission {
968 INJECTION_PERMISSION_UNKNOWN,
969 INJECTION_PERMISSION_GRANTED,
970 INJECTION_PERMISSION_DENIED
971 };
972
Jeff Browna665ca82010-09-08 11:49:43 -0700973 mCurrentInputTargets.clear();
974
975 nsecs_t startTime = now();
976
977 // For security reasons, we defer updating the touch state until we are sure that
978 // event injection will be allowed.
979 //
980 // FIXME In the original code, screenWasOff could never be set to true.
981 // The reason is that the POLICY_FLAG_WOKE_HERE
982 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
983 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
984 // actually enqueued using the policyFlags that appeared in the final EV_SYN
985 // events upon which no preprocessing took place. So policyFlags was always 0.
986 // In the new native input dispatcher we're a bit more careful about event
987 // preprocessing so the touches we receive can actually have non-zero policyFlags.
988 // Unfortunately we obtain undesirable behavior.
989 //
990 // Here's what happens:
991 //
992 // When the device dims in anticipation of going to sleep, touches
993 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
994 // the device to brighten and reset the user activity timer.
995 // Touches on other windows (such as the launcher window)
996 // are dropped. Then after a moment, the device goes to sleep. Oops.
997 //
998 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
999 // instead of POLICY_FLAG_WOKE_HERE...
1000 //
1001 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1002
1003 int32_t action = entry->action;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001004 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Jeff Browna665ca82010-09-08 11:49:43 -07001005
1006 // Update the touch state as needed based on the properties of the touch event.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001007 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1008 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1009 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1010 mTempTouchState.reset();
1011 mTempTouchState.down = true;
1012 } else {
1013 mTempTouchState.copyFrom(mTouchState);
1014 }
Jeff Browna665ca82010-09-08 11:49:43 -07001015
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001016 bool isSplit = mTempTouchState.split && mTempTouchState.down;
1017 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1018 || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1019 /* Case 1: New splittable pointer going down. */
Jeff Browna665ca82010-09-08 11:49:43 -07001020
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001021 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1022 int32_t x = int32_t(entry->firstSample.pointerCoords[pointerIndex].x);
1023 int32_t y = int32_t(entry->firstSample.pointerCoords[pointerIndex].y);
1024 const InputWindow* newTouchedWindow = NULL;
1025 const InputWindow* topErrorWindow = NULL;
Jeff Browna665ca82010-09-08 11:49:43 -07001026
1027 // Traverse windows from front to back to find touched window and outside targets.
1028 size_t numWindows = mWindows.size();
1029 for (size_t i = 0; i < numWindows; i++) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001030 const InputWindow* window = & mWindows.editItemAt(i);
Jeff Browna665ca82010-09-08 11:49:43 -07001031 int32_t flags = window->layoutParamsFlags;
1032
1033 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
1034 if (! topErrorWindow) {
1035 topErrorWindow = window;
1036 }
1037 }
1038
1039 if (window->visible) {
1040 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
1041 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
1042 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
1043 if (isTouchModal || window->touchableAreaContainsPoint(x, y)) {
1044 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
1045 newTouchedWindow = window;
Jeff Browna665ca82010-09-08 11:49:43 -07001046 }
1047 break; // found touched window, exit window loop
1048 }
1049 }
1050
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001051 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1052 && (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH)) {
1053 mTempTouchState.addOrUpdateWindow(window,
1054 InputTarget::FLAG_OUTSIDE, BitSet32(0));
Jeff Browna665ca82010-09-08 11:49:43 -07001055 }
1056 }
1057 }
1058
1059 // If there is an error window but it is not taking focus (typically because
1060 // it is invisible) then wait for it. Any other focused window may in
1061 // fact be in ANR state.
1062 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
1063#if DEBUG_FOCUS
1064 LOGD("Waiting because system error window is pending.");
1065#endif
1066 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1067 NULL, NULL, nextWakeupTime);
1068 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1069 goto Unresponsive;
1070 }
1071
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001072 // Figure out whether splitting will be allowed for this window.
1073 if (newTouchedWindow->layoutParamsFlags & InputWindow::FLAG_SPLIT_TOUCH) {
1074 // New window supports splitting.
1075 isSplit = true;
1076 } else if (isSplit) {
1077 // New window does not support splitting but we have already split events.
1078 // Assign the pointer to the first foreground window we find.
1079 // (May be NULL which is why we put this code block before the next check.)
1080 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1081 }
1082 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
1083 if (isSplit) {
1084 targetFlags |= InputTarget::FLAG_SPLIT;
1085 }
1086
Jeff Browna665ca82010-09-08 11:49:43 -07001087 // If we did not find a touched window then fail.
1088 if (! newTouchedWindow) {
1089 if (mFocusedApplication) {
1090#if DEBUG_FOCUS
1091 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown53a415e2010-09-15 15:18:56 -07001092 "focused application that may eventually add a new window: %s.",
1093 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Browna665ca82010-09-08 11:49:43 -07001094#endif
1095 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1096 mFocusedApplication, NULL, nextWakeupTime);
Jeff Browna665ca82010-09-08 11:49:43 -07001097 goto Unresponsive;
1098 }
1099
1100 LOGI("Dropping event because there is no touched window or focused application.");
1101 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Browna665ca82010-09-08 11:49:43 -07001102 goto Failed;
1103 }
1104
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001105 // Update the temporary touch state.
1106 BitSet32 pointerIds;
1107 if (isSplit) {
1108 uint32_t pointerId = entry->pointerIds[pointerIndex];
1109 pointerIds.markBit(pointerId);
Jeff Browna665ca82010-09-08 11:49:43 -07001110 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001111 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Browna665ca82010-09-08 11:49:43 -07001112 } else {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001113 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Browna665ca82010-09-08 11:49:43 -07001114
1115 // If the pointer is not currently down, then ignore the event.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001116 if (! mTempTouchState.down) {
Jeff Browna665ca82010-09-08 11:49:43 -07001117 LOGI("Dropping event because the pointer is not down.");
1118 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Browna665ca82010-09-08 11:49:43 -07001119 goto Failed;
1120 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001121 }
Jeff Browna665ca82010-09-08 11:49:43 -07001122
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001123 // Check permission to inject into all touched foreground windows and ensure there
1124 // is at least one touched foreground window.
1125 {
1126 bool haveForegroundWindow = false;
1127 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1128 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1129 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1130 haveForegroundWindow = true;
1131 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1132 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1133 injectionPermission = INJECTION_PERMISSION_DENIED;
1134 goto Failed;
1135 }
1136 }
1137 }
1138 if (! haveForegroundWindow) {
Jeff Browna665ca82010-09-08 11:49:43 -07001139#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001140 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Browna665ca82010-09-08 11:49:43 -07001141#endif
1142 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Browna665ca82010-09-08 11:49:43 -07001143 goto Failed;
1144 }
1145
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001146 // Permission granted to injection into all touched foreground windows.
1147 injectionPermission = INJECTION_PERMISSION_GRANTED;
1148 }
Jeff Brown53a415e2010-09-15 15:18:56 -07001149
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001150 // Ensure all touched foreground windows are ready for new input.
1151 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1152 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1153 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1154 // If the touched window is paused then keep waiting.
1155 if (touchedWindow.window->paused) {
1156#if DEBUG_INPUT_DISPATCHER_POLICY
1157 LOGD("Waiting because touched window is paused.");
Jeff Brown53a415e2010-09-15 15:18:56 -07001158#endif
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001159 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1160 NULL, touchedWindow.window, nextWakeupTime);
1161 goto Unresponsive;
1162 }
1163
1164 // If the touched window is still working on previous events then keep waiting.
1165 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1166#if DEBUG_FOCUS
1167 LOGD("Waiting because touched window still processing previous input.");
1168#endif
1169 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1170 NULL, touchedWindow.window, nextWakeupTime);
1171 goto Unresponsive;
1172 }
1173 }
1174 }
1175
1176 // If this is the first pointer going down and the touched window has a wallpaper
1177 // then also add the touched wallpaper windows so they are locked in for the duration
1178 // of the touch gesture.
1179 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1180 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1181 if (foregroundWindow->hasWallpaper) {
1182 for (size_t i = 0; i < mWindows.size(); i++) {
1183 const InputWindow* window = & mWindows[i];
1184 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
1185 mTempTouchState.addOrUpdateWindow(window, 0, BitSet32(0));
1186 }
1187 }
1188 }
1189 }
1190
1191 // If a touched window has been obscured at any point during the touch gesture, set
1192 // the appropriate flag so we remember it for the entire gesture.
1193 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1194 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1195 if ((touchedWindow.targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) == 0) {
1196 if (isWindowObscuredLocked(touchedWindow.window)) {
1197 touchedWindow.targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1198 }
Jeff Brown53a415e2010-09-15 15:18:56 -07001199 }
Jeff Browna665ca82010-09-08 11:49:43 -07001200 }
1201
1202 // Success! Output targets.
1203 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Browna665ca82010-09-08 11:49:43 -07001204
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001205 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1206 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1207 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1208 touchedWindow.pointerIds);
Jeff Browna665ca82010-09-08 11:49:43 -07001209 }
1210
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001211 // Drop the outside touch window since we will not care about them in the next iteration.
1212 mTempTouchState.removeOutsideTouchWindows();
1213
Jeff Browna665ca82010-09-08 11:49:43 -07001214Failed:
1215 // Check injection permission once and for all.
1216 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001217 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Browna665ca82010-09-08 11:49:43 -07001218 injectionPermission = INJECTION_PERMISSION_GRANTED;
1219 } else {
1220 injectionPermission = INJECTION_PERMISSION_DENIED;
1221 }
1222 }
1223
1224 // Update final pieces of touch state if the injector had permission.
1225 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001226 if (maskedAction == AMOTION_EVENT_ACTION_UP
1227 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1228 // All pointers up or canceled.
1229 mTempTouchState.reset();
1230 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1231 // First pointer went down.
1232 if (mTouchState.down) {
Jeff Browna665ca82010-09-08 11:49:43 -07001233 LOGW("Pointer down received while already down.");
Jeff Browna665ca82010-09-08 11:49:43 -07001234 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001235 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1236 // One pointer went up.
1237 if (isSplit) {
1238 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1239 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Browna665ca82010-09-08 11:49:43 -07001240
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001241 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1242 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1243 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1244 touchedWindow.pointerIds.clearBit(pointerId);
1245 if (touchedWindow.pointerIds.isEmpty()) {
1246 mTempTouchState.windows.removeAt(i);
1247 continue;
1248 }
1249 }
1250 i += 1;
1251 }
Jeff Browna665ca82010-09-08 11:49:43 -07001252 }
Jeff Browna665ca82010-09-08 11:49:43 -07001253 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001254
1255 // Save changes to touch state.
1256 mTouchState.copyFrom(mTempTouchState);
Jeff Browna665ca82010-09-08 11:49:43 -07001257 } else {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001258#if DEBUG_FOCUS
1259 LOGD("Not updating touch focus because injection was denied.");
1260#endif
Jeff Browna665ca82010-09-08 11:49:43 -07001261 }
1262
1263Unresponsive:
Jeff Brown53a415e2010-09-15 15:18:56 -07001264 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1265 updateDispatchStatisticsLocked(currentTime, entry,
1266 injectionResult, timeSpentWaitingForApplication);
Jeff Browna665ca82010-09-08 11:49:43 -07001267#if DEBUG_FOCUS
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001268 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1269 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown53a415e2010-09-15 15:18:56 -07001270 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Browna665ca82010-09-08 11:49:43 -07001271#endif
1272 return injectionResult;
1273}
1274
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001275void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1276 BitSet32 pointerIds) {
Jeff Browna665ca82010-09-08 11:49:43 -07001277 mCurrentInputTargets.push();
1278
1279 InputTarget& target = mCurrentInputTargets.editTop();
1280 target.inputChannel = window->inputChannel;
1281 target.flags = targetFlags;
Jeff Browna665ca82010-09-08 11:49:43 -07001282 target.xOffset = - window->frameLeft;
1283 target.yOffset = - window->frameTop;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001284 target.windowType = window->layoutParamsType;
1285 target.pointerIds = pointerIds;
Jeff Browna665ca82010-09-08 11:49:43 -07001286}
1287
1288void InputDispatcher::addMonitoringTargetsLocked() {
1289 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1290 mCurrentInputTargets.push();
1291
1292 InputTarget& target = mCurrentInputTargets.editTop();
1293 target.inputChannel = mMonitoringChannels[i];
1294 target.flags = 0;
Jeff Browna665ca82010-09-08 11:49:43 -07001295 target.xOffset = 0;
1296 target.yOffset = 0;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001297 target.windowType = InputWindow::TYPE_SYSTEM_OVERLAY;
Jeff Browna665ca82010-09-08 11:49:43 -07001298 }
1299}
1300
1301bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001302 const InjectionState* injectionState) {
1303 if (injectionState
1304 && injectionState->injectorUid > 0
1305 && (window == NULL || window->ownerUid != injectionState->injectorUid)) {
1306 bool result = mPolicy->checkInjectEventsPermissionNonReentrant(
1307 injectionState->injectorPid, injectionState->injectorUid);
Jeff Browna665ca82010-09-08 11:49:43 -07001308 if (! result) {
1309 if (window) {
1310 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1311 "with input channel %s owned by uid %d",
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001312 injectionState->injectorPid, injectionState->injectorUid,
1313 window->inputChannel->getName().string(),
Jeff Browna665ca82010-09-08 11:49:43 -07001314 window->ownerUid);
1315 } else {
1316 LOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001317 injectionState->injectorPid, injectionState->injectorUid);
Jeff Browna665ca82010-09-08 11:49:43 -07001318 }
1319 return false;
1320 }
1321 }
1322 return true;
1323}
1324
1325bool InputDispatcher::isWindowObscuredLocked(const InputWindow* window) {
1326 size_t numWindows = mWindows.size();
1327 for (size_t i = 0; i < numWindows; i++) {
1328 const InputWindow* other = & mWindows.itemAt(i);
1329 if (other == window) {
1330 break;
1331 }
1332 if (other->visible && window->visibleFrameIntersects(other)) {
1333 return true;
1334 }
1335 }
1336 return false;
1337}
1338
Jeff Brown53a415e2010-09-15 15:18:56 -07001339bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1340 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1341 if (connectionIndex >= 0) {
1342 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1343 return connection->outboundQueue.isEmpty();
1344 } else {
1345 return true;
1346 }
1347}
1348
1349String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1350 const InputWindow* window) {
1351 if (application) {
1352 if (window) {
1353 String8 label(application->name);
1354 label.append(" - ");
1355 label.append(window->name);
1356 return label;
1357 } else {
1358 return application->name;
1359 }
1360 } else if (window) {
1361 return window->name;
1362 } else {
1363 return String8("<unknown application or window>");
1364 }
1365}
1366
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001367bool InputDispatcher::shouldPokeUserActivityForCurrentInputTargetsLocked() {
1368 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1369 if (mCurrentInputTargets[i].windowType == InputWindow::TYPE_KEYGUARD) {
1370 return false;
1371 }
1372 }
1373 return true;
1374}
1375
1376void InputDispatcher::pokeUserActivityLocked(nsecs_t eventTime, int32_t eventType) {
Jeff Browna665ca82010-09-08 11:49:43 -07001377 CommandEntry* commandEntry = postCommandLocked(
1378 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1379 commandEntry->eventTime = eventTime;
Jeff Browna665ca82010-09-08 11:49:43 -07001380 commandEntry->userActivityEventType = eventType;
1381}
1382
Jeff Brown51d45a72010-06-17 20:52:56 -07001383void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1384 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Browne839a582010-04-22 18:58:52 -07001385 bool resumeWithAppendedMotionSample) {
1386#if DEBUG_DISPATCH_CYCLE
Jeff Brown53a415e2010-09-15 15:18:56 -07001387 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001388 "xOffset=%f, yOffset=%f, "
1389 "windowType=%d, pointerIds=0x%x, "
1390 "resumeWithAppendedMotionSample=%s",
Jeff Brown53a415e2010-09-15 15:18:56 -07001391 connection->getInputChannelName(), inputTarget->flags,
Jeff Browne839a582010-04-22 18:58:52 -07001392 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001393 inputTarget->windowType, inputTarget->pointerIds.value,
Jeff Browna665ca82010-09-08 11:49:43 -07001394 toString(resumeWithAppendedMotionSample));
Jeff Browne839a582010-04-22 18:58:52 -07001395#endif
1396
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001397 // Make sure we are never called for streaming when splitting across multiple windows.
1398 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1399 assert(! (resumeWithAppendedMotionSample && isSplit));
1400
Jeff Browne839a582010-04-22 18:58:52 -07001401 // Skip this event if the connection status is not normal.
Jeff Brown53a415e2010-09-15 15:18:56 -07001402 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Browne839a582010-04-22 18:58:52 -07001403 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Browna665ca82010-09-08 11:49:43 -07001404 LOGW("channel '%s' ~ Dropping event because the channel status is %s",
1405 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Browne839a582010-04-22 18:58:52 -07001406 return;
1407 }
1408
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001409 // Split a motion event if needed.
1410 if (isSplit) {
1411 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1412
1413 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1414 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1415 MotionEntry* splitMotionEntry = splitMotionEvent(
1416 originalMotionEntry, inputTarget->pointerIds);
1417#if DEBUG_FOCUS
1418 LOGD("channel '%s' ~ Split motion event.",
1419 connection->getInputChannelName());
1420 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1421#endif
1422 eventEntry = splitMotionEntry;
1423 }
1424 }
1425
Jeff Browne839a582010-04-22 18:58:52 -07001426 // Resume the dispatch cycle with a freshly appended motion sample.
1427 // First we check that the last dispatch entry in the outbound queue is for the same
1428 // motion event to which we appended the motion sample. If we find such a dispatch
1429 // entry, and if it is currently in progress then we try to stream the new sample.
1430 bool wasEmpty = connection->outboundQueue.isEmpty();
1431
1432 if (! wasEmpty && resumeWithAppendedMotionSample) {
1433 DispatchEntry* motionEventDispatchEntry =
1434 connection->findQueuedDispatchEntryForEvent(eventEntry);
1435 if (motionEventDispatchEntry) {
1436 // If the dispatch entry is not in progress, then we must be busy dispatching an
1437 // earlier event. Not a problem, the motion event is on the outbound queue and will
1438 // be dispatched later.
1439 if (! motionEventDispatchEntry->inProgress) {
1440#if DEBUG_BATCHING
1441 LOGD("channel '%s' ~ Not streaming because the motion event has "
1442 "not yet been dispatched. "
1443 "(Waiting for earlier events to be consumed.)",
1444 connection->getInputChannelName());
1445#endif
1446 return;
1447 }
1448
1449 // If the dispatch entry is in progress but it already has a tail of pending
1450 // motion samples, then it must mean that the shared memory buffer filled up.
1451 // Not a problem, when this dispatch cycle is finished, we will eventually start
1452 // a new dispatch cycle to process the tail and that tail includes the newly
1453 // appended motion sample.
1454 if (motionEventDispatchEntry->tailMotionSample) {
1455#if DEBUG_BATCHING
1456 LOGD("channel '%s' ~ Not streaming because no new samples can "
1457 "be appended to the motion event in this dispatch cycle. "
1458 "(Waiting for next dispatch cycle to start.)",
1459 connection->getInputChannelName());
1460#endif
1461 return;
1462 }
1463
1464 // The dispatch entry is in progress and is still potentially open for streaming.
1465 // Try to stream the new motion sample. This might fail if the consumer has already
1466 // consumed the motion event (or if the channel is broken).
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001467 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1468 MotionSample* appendedMotionSample = motionEntry->lastSample;
Jeff Browne839a582010-04-22 18:58:52 -07001469 status_t status = connection->inputPublisher.appendMotionSample(
1470 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1471 if (status == OK) {
1472#if DEBUG_BATCHING
1473 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1474 connection->getInputChannelName());
1475#endif
1476 return;
1477 }
1478
1479#if DEBUG_BATCHING
1480 if (status == NO_MEMORY) {
1481 LOGD("channel '%s' ~ Could not append motion sample to currently "
1482 "dispatched move event because the shared memory buffer is full. "
1483 "(Waiting for next dispatch cycle to start.)",
1484 connection->getInputChannelName());
1485 } else if (status == status_t(FAILED_TRANSACTION)) {
1486 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown50de30a2010-06-22 01:27:15 -07001487 "dispatched move event because the event has already been consumed. "
Jeff Browne839a582010-04-22 18:58:52 -07001488 "(Waiting for next dispatch cycle to start.)",
1489 connection->getInputChannelName());
1490 } else {
1491 LOGD("channel '%s' ~ Could not append motion sample to currently "
1492 "dispatched move event due to an error, status=%d. "
1493 "(Waiting for next dispatch cycle to start.)",
1494 connection->getInputChannelName(), status);
1495 }
1496#endif
1497 // Failed to stream. Start a new tail of pending motion samples to dispatch
1498 // in the next cycle.
1499 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1500 return;
1501 }
1502 }
1503
Jeff Browna665ca82010-09-08 11:49:43 -07001504 // Bring the input state back in line with reality in case it drifted off during an ANR.
1505 if (connection->inputState.isOutOfSync()) {
1506 mTempCancelationEvents.clear();
1507 connection->inputState.synthesizeCancelationEvents(& mAllocator, mTempCancelationEvents);
1508 connection->inputState.resetOutOfSync();
1509
1510 if (! mTempCancelationEvents.isEmpty()) {
1511 LOGI("channel '%s' ~ Generated %d cancelation events to bring channel back in sync "
1512 "with reality.",
1513 connection->getInputChannelName(), mTempCancelationEvents.size());
1514
1515 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
1516 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
1517 switch (cancelationEventEntry->type) {
1518 case EventEntry::TYPE_KEY:
1519 logOutboundKeyDetailsLocked(" ",
1520 static_cast<KeyEntry*>(cancelationEventEntry));
1521 break;
1522 case EventEntry::TYPE_MOTION:
1523 logOutboundMotionDetailsLocked(" ",
1524 static_cast<MotionEntry*>(cancelationEventEntry));
1525 break;
1526 }
1527
1528 DispatchEntry* cancelationDispatchEntry =
1529 mAllocator.obtainDispatchEntry(cancelationEventEntry,
Jeff Brown53a415e2010-09-15 15:18:56 -07001530 0, inputTarget->xOffset, inputTarget->yOffset); // increments ref
Jeff Browna665ca82010-09-08 11:49:43 -07001531 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
1532
1533 mAllocator.releaseEventEntry(cancelationEventEntry);
1534 }
1535 }
1536 }
1537
Jeff Browne839a582010-04-22 18:58:52 -07001538 // This is a new event.
1539 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Browna665ca82010-09-08 11:49:43 -07001540 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Brown53a415e2010-09-15 15:18:56 -07001541 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset);
1542 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001543 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brownf67c53e2010-07-28 15:48:59 -07001544 }
1545
Jeff Browne839a582010-04-22 18:58:52 -07001546 // Handle the case where we could not stream a new motion sample because the consumer has
1547 // already consumed the motion event (otherwise the corresponding dispatch entry would
1548 // still be in the outbound queue for this connection). We set the head motion sample
1549 // to the list starting with the newly appended motion sample.
1550 if (resumeWithAppendedMotionSample) {
1551#if DEBUG_BATCHING
1552 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1553 "that cannot be streamed because the motion event has already been consumed.",
1554 connection->getInputChannelName());
1555#endif
1556 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1557 dispatchEntry->headMotionSample = appendedMotionSample;
1558 }
1559
1560 // Enqueue the dispatch entry.
1561 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1562
1563 // If the outbound queue was previously empty, start the dispatch cycle going.
1564 if (wasEmpty) {
Jeff Brown51d45a72010-06-17 20:52:56 -07001565 activateConnectionLocked(connection.get());
Jeff Brown53a415e2010-09-15 15:18:56 -07001566 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001567 }
1568}
1569
Jeff Brown51d45a72010-06-17 20:52:56 -07001570void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown53a415e2010-09-15 15:18:56 -07001571 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001572#if DEBUG_DISPATCH_CYCLE
1573 LOGD("channel '%s' ~ startDispatchCycle",
1574 connection->getInputChannelName());
1575#endif
1576
1577 assert(connection->status == Connection::STATUS_NORMAL);
1578 assert(! connection->outboundQueue.isEmpty());
1579
Jeff Browna665ca82010-09-08 11:49:43 -07001580 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Browne839a582010-04-22 18:58:52 -07001581 assert(! dispatchEntry->inProgress);
1582
Jeff Browna665ca82010-09-08 11:49:43 -07001583 // Mark the dispatch entry as in progress.
1584 dispatchEntry->inProgress = true;
1585
1586 // Update the connection's input state.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001587 EventEntry* eventEntry = dispatchEntry->eventEntry;
1588 InputState::Consistency consistency = connection->inputState.trackEvent(eventEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001589
1590#if FILTER_INPUT_EVENTS
1591 // Filter out inconsistent sequences of input events.
1592 // The input system may drop or inject events in a way that could violate implicit
1593 // invariants on input state and potentially cause an application to crash
1594 // or think that a key or pointer is stuck down. Technically we make no guarantees
1595 // of consistency but it would be nice to improve on this where possible.
1596 // XXX: This code is a proof of concept only. Not ready for prime time.
1597 if (consistency == InputState::TOLERABLE) {
1598#if DEBUG_DISPATCH_CYCLE
1599 LOGD("channel '%s' ~ Sending an event that is inconsistent with the connection's "
1600 "current input state but that is likely to be tolerated by the application.",
1601 connection->getInputChannelName());
1602#endif
1603 } else if (consistency == InputState::BROKEN) {
1604 LOGI("channel '%s' ~ Dropping an event that is inconsistent with the connection's "
1605 "current input state and that is likely to cause the application to crash.",
1606 connection->getInputChannelName());
1607 startNextDispatchCycleLocked(currentTime, connection);
1608 return;
1609 }
1610#endif
Jeff Browne839a582010-04-22 18:58:52 -07001611
1612 // Publish the event.
1613 status_t status;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001614 switch (eventEntry->type) {
Jeff Browne839a582010-04-22 18:58:52 -07001615 case EventEntry::TYPE_KEY: {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001616 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001617
1618 // Apply target flags.
1619 int32_t action = keyEntry->action;
1620 int32_t flags = keyEntry->flags;
Jeff Browne839a582010-04-22 18:58:52 -07001621
1622 // Publish the key event.
Jeff Brown5c1ed842010-07-14 18:48:53 -07001623 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Browne839a582010-04-22 18:58:52 -07001624 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1625 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1626 keyEntry->eventTime);
1627
1628 if (status) {
1629 LOGE("channel '%s' ~ Could not publish key event, "
1630 "status=%d", connection->getInputChannelName(), status);
1631 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1632 return;
1633 }
1634 break;
1635 }
1636
1637 case EventEntry::TYPE_MOTION: {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001638 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001639
1640 // Apply target flags.
1641 int32_t action = motionEntry->action;
Jeff Brownaf30ff62010-09-01 17:01:00 -07001642 int32_t flags = motionEntry->flags;
Jeff Browne839a582010-04-22 18:58:52 -07001643 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brown5c1ed842010-07-14 18:48:53 -07001644 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Browne839a582010-04-22 18:58:52 -07001645 }
Jeff Brownaf30ff62010-09-01 17:01:00 -07001646 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1647 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1648 }
Jeff Browne839a582010-04-22 18:58:52 -07001649
1650 // If headMotionSample is non-NULL, then it points to the first new sample that we
1651 // were unable to dispatch during the previous cycle so we resume dispatching from
1652 // that point in the list of motion samples.
1653 // Otherwise, we just start from the first sample of the motion event.
1654 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1655 if (! firstMotionSample) {
1656 firstMotionSample = & motionEntry->firstSample;
1657 }
1658
Jeff Brownf26db0d2010-07-16 17:21:06 -07001659 // Set the X and Y offset depending on the input source.
1660 float xOffset, yOffset;
1661 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1662 xOffset = dispatchEntry->xOffset;
1663 yOffset = dispatchEntry->yOffset;
1664 } else {
1665 xOffset = 0.0f;
1666 yOffset = 0.0f;
1667 }
1668
Jeff Browne839a582010-04-22 18:58:52 -07001669 // Publish the motion event and the first motion sample.
1670 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brownaf30ff62010-09-01 17:01:00 -07001671 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownf26db0d2010-07-16 17:21:06 -07001672 xOffset, yOffset,
Jeff Browne839a582010-04-22 18:58:52 -07001673 motionEntry->xPrecision, motionEntry->yPrecision,
1674 motionEntry->downTime, firstMotionSample->eventTime,
1675 motionEntry->pointerCount, motionEntry->pointerIds,
1676 firstMotionSample->pointerCoords);
1677
1678 if (status) {
1679 LOGE("channel '%s' ~ Could not publish motion event, "
1680 "status=%d", connection->getInputChannelName(), status);
1681 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1682 return;
1683 }
1684
1685 // Append additional motion samples.
1686 MotionSample* nextMotionSample = firstMotionSample->next;
1687 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1688 status = connection->inputPublisher.appendMotionSample(
1689 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
1690 if (status == NO_MEMORY) {
1691#if DEBUG_DISPATCH_CYCLE
1692 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1693 "be sent in the next dispatch cycle.",
1694 connection->getInputChannelName());
1695#endif
1696 break;
1697 }
1698 if (status != OK) {
1699 LOGE("channel '%s' ~ Could not append motion sample "
1700 "for a reason other than out of memory, status=%d",
1701 connection->getInputChannelName(), status);
1702 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1703 return;
1704 }
1705 }
1706
1707 // Remember the next motion sample that we could not dispatch, in case we ran out
1708 // of space in the shared memory buffer.
1709 dispatchEntry->tailMotionSample = nextMotionSample;
1710 break;
1711 }
1712
1713 default: {
1714 assert(false);
1715 }
1716 }
1717
1718 // Send the dispatch signal.
1719 status = connection->inputPublisher.sendDispatchSignal();
1720 if (status) {
1721 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1722 connection->getInputChannelName(), status);
1723 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1724 return;
1725 }
1726
1727 // Record information about the newly started dispatch cycle.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001728 connection->lastEventTime = eventEntry->eventTime;
Jeff Browne839a582010-04-22 18:58:52 -07001729 connection->lastDispatchTime = currentTime;
1730
Jeff Browne839a582010-04-22 18:58:52 -07001731 // Notify other system components.
1732 onDispatchCycleStartedLocked(currentTime, connection);
1733}
1734
Jeff Brown51d45a72010-06-17 20:52:56 -07001735void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
1736 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001737#if DEBUG_DISPATCH_CYCLE
Jeff Brown54bc2812010-06-15 01:31:58 -07001738 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Browne839a582010-04-22 18:58:52 -07001739 "%01.1fms since dispatch",
1740 connection->getInputChannelName(),
1741 connection->getEventLatencyMillis(currentTime),
1742 connection->getDispatchLatencyMillis(currentTime));
1743#endif
1744
Jeff Brown54bc2812010-06-15 01:31:58 -07001745 if (connection->status == Connection::STATUS_BROKEN
1746 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Browne839a582010-04-22 18:58:52 -07001747 return;
1748 }
1749
Jeff Brown53a415e2010-09-15 15:18:56 -07001750 // Notify other system components.
1751 onDispatchCycleFinishedLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001752
1753 // Reset the publisher since the event has been consumed.
1754 // We do this now so that the publisher can release some of its internal resources
1755 // while waiting for the next dispatch cycle to begin.
1756 status_t status = connection->inputPublisher.reset();
1757 if (status) {
1758 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1759 connection->getInputChannelName(), status);
1760 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1761 return;
1762 }
1763
Jeff Browna665ca82010-09-08 11:49:43 -07001764 startNextDispatchCycleLocked(currentTime, connection);
1765}
1766
1767void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1768 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001769 // Start the next dispatch cycle for this connection.
1770 while (! connection->outboundQueue.isEmpty()) {
Jeff Browna665ca82010-09-08 11:49:43 -07001771 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Browne839a582010-04-22 18:58:52 -07001772 if (dispatchEntry->inProgress) {
1773 // Finish or resume current event in progress.
1774 if (dispatchEntry->tailMotionSample) {
1775 // We have a tail of undispatched motion samples.
1776 // Reuse the same DispatchEntry and start a new cycle.
1777 dispatchEntry->inProgress = false;
1778 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1779 dispatchEntry->tailMotionSample = NULL;
Jeff Brown53a415e2010-09-15 15:18:56 -07001780 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001781 return;
1782 }
1783 // Finished.
1784 connection->outboundQueue.dequeueAtHead();
Jeff Brown53a415e2010-09-15 15:18:56 -07001785 if (dispatchEntry->hasForegroundTarget()) {
1786 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownf67c53e2010-07-28 15:48:59 -07001787 }
Jeff Browne839a582010-04-22 18:58:52 -07001788 mAllocator.releaseDispatchEntry(dispatchEntry);
1789 } else {
1790 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown53a415e2010-09-15 15:18:56 -07001791 // progress event, which means we actually aborted it.
Jeff Browne839a582010-04-22 18:58:52 -07001792 // So just start the next event for this connection.
Jeff Brown53a415e2010-09-15 15:18:56 -07001793 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001794 return;
1795 }
1796 }
1797
1798 // Outbound queue is empty, deactivate the connection.
Jeff Brown51d45a72010-06-17 20:52:56 -07001799 deactivateConnectionLocked(connection.get());
Jeff Browne839a582010-04-22 18:58:52 -07001800}
1801
Jeff Brown51d45a72010-06-17 20:52:56 -07001802void InputDispatcher::abortDispatchCycleLocked(nsecs_t currentTime,
1803 const sp<Connection>& connection, bool broken) {
Jeff Browne839a582010-04-22 18:58:52 -07001804#if DEBUG_DISPATCH_CYCLE
Jeff Brown54bc2812010-06-15 01:31:58 -07001805 LOGD("channel '%s' ~ abortDispatchCycle - broken=%s",
Jeff Browna665ca82010-09-08 11:49:43 -07001806 connection->getInputChannelName(), toString(broken));
Jeff Browne839a582010-04-22 18:58:52 -07001807#endif
1808
Jeff Browna665ca82010-09-08 11:49:43 -07001809 // Input state will no longer be realistic.
1810 connection->inputState.setOutOfSync();
Jeff Browne839a582010-04-22 18:58:52 -07001811
Jeff Browna665ca82010-09-08 11:49:43 -07001812 // Clear the outbound queue.
Jeff Brown53a415e2010-09-15 15:18:56 -07001813 drainOutboundQueueLocked(connection.get());
Jeff Browne839a582010-04-22 18:58:52 -07001814
1815 // Handle the case where the connection appears to be unrecoverably broken.
Jeff Brown54bc2812010-06-15 01:31:58 -07001816 // Ignore already broken or zombie connections.
Jeff Browne839a582010-04-22 18:58:52 -07001817 if (broken) {
Jeff Brown53a415e2010-09-15 15:18:56 -07001818 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brown54bc2812010-06-15 01:31:58 -07001819 connection->status = Connection::STATUS_BROKEN;
Jeff Browne839a582010-04-22 18:58:52 -07001820
Jeff Brown54bc2812010-06-15 01:31:58 -07001821 // Notify other system components.
1822 onDispatchCycleBrokenLocked(currentTime, connection);
1823 }
Jeff Browne839a582010-04-22 18:58:52 -07001824 }
Jeff Browne839a582010-04-22 18:58:52 -07001825}
1826
Jeff Brown53a415e2010-09-15 15:18:56 -07001827void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
1828 while (! connection->outboundQueue.isEmpty()) {
1829 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
1830 if (dispatchEntry->hasForegroundTarget()) {
1831 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001832 }
1833 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001834 }
1835
Jeff Brown53a415e2010-09-15 15:18:56 -07001836 deactivateConnectionLocked(connection);
Jeff Browna665ca82010-09-08 11:49:43 -07001837}
1838
Jeff Brown59abe7e2010-09-13 23:17:30 -07001839int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Browne839a582010-04-22 18:58:52 -07001840 InputDispatcher* d = static_cast<InputDispatcher*>(data);
1841
1842 { // acquire lock
1843 AutoMutex _l(d->mLock);
1844
1845 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
1846 if (connectionIndex < 0) {
1847 LOGE("Received spurious receive callback for unknown input channel. "
1848 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001849 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001850 }
1851
Jeff Brown51d45a72010-06-17 20:52:56 -07001852 nsecs_t currentTime = now();
Jeff Browne839a582010-04-22 18:58:52 -07001853
1854 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001855 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Browne839a582010-04-22 18:58:52 -07001856 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
1857 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown51d45a72010-06-17 20:52:56 -07001858 d->abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07001859 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001860 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001861 }
1862
Jeff Brown59abe7e2010-09-13 23:17:30 -07001863 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Browne839a582010-04-22 18:58:52 -07001864 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
1865 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001866 return 1;
Jeff Browne839a582010-04-22 18:58:52 -07001867 }
1868
1869 status_t status = connection->inputPublisher.receiveFinishedSignal();
1870 if (status) {
1871 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
1872 connection->getInputChannelName(), status);
Jeff Brown51d45a72010-06-17 20:52:56 -07001873 d->abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07001874 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001875 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001876 }
1877
Jeff Brown51d45a72010-06-17 20:52:56 -07001878 d->finishDispatchCycleLocked(currentTime, connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07001879 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001880 return 1;
Jeff Browne839a582010-04-22 18:58:52 -07001881 } // release lock
1882}
1883
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001884InputDispatcher::MotionEntry*
1885InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
1886 assert(pointerIds.value != 0);
1887
1888 uint32_t splitPointerIndexMap[MAX_POINTERS];
1889 int32_t splitPointerIds[MAX_POINTERS];
1890 PointerCoords splitPointerCoords[MAX_POINTERS];
1891
1892 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
1893 uint32_t splitPointerCount = 0;
1894
1895 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
1896 originalPointerIndex++) {
1897 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
1898 if (pointerIds.hasBit(pointerId)) {
1899 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
1900 splitPointerIds[splitPointerCount] = pointerId;
1901 splitPointerCoords[splitPointerCount] =
1902 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex];
1903 splitPointerCount += 1;
1904 }
1905 }
1906 assert(splitPointerCount == pointerIds.count());
1907
1908 int32_t action = originalMotionEntry->action;
1909 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1910 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
1911 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1912 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
1913 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
1914 if (pointerIds.hasBit(pointerId)) {
1915 if (pointerIds.count() == 1) {
1916 // The first/last pointer went down/up.
1917 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
1918 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
1919 }
1920 } else {
1921 // An unrelated pointer changed.
1922 action = AMOTION_EVENT_ACTION_MOVE;
1923 }
1924 }
1925
1926 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
1927 originalMotionEntry->eventTime,
1928 originalMotionEntry->deviceId,
1929 originalMotionEntry->source,
1930 originalMotionEntry->policyFlags,
1931 action,
1932 originalMotionEntry->flags,
1933 originalMotionEntry->metaState,
1934 originalMotionEntry->edgeFlags,
1935 originalMotionEntry->xPrecision,
1936 originalMotionEntry->yPrecision,
1937 originalMotionEntry->downTime,
1938 splitPointerCount, splitPointerIds, splitPointerCoords);
1939
1940 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
1941 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
1942 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
1943 splitPointerIndex++) {
1944 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
1945 splitPointerCoords[splitPointerIndex] =
1946 originalMotionSample->pointerCoords[originalPointerIndex];
1947 }
1948
1949 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
1950 splitPointerCoords);
1951 }
1952
1953 return splitMotionEntry;
1954}
1955
Jeff Brown54bc2812010-06-15 01:31:58 -07001956void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Browne839a582010-04-22 18:58:52 -07001957#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown54bc2812010-06-15 01:31:58 -07001958 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Browne839a582010-04-22 18:58:52 -07001959#endif
1960
Jeff Browna665ca82010-09-08 11:49:43 -07001961 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07001962 { // acquire lock
1963 AutoMutex _l(mLock);
1964
Jeff Brown51d45a72010-06-17 20:52:56 -07001965 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Browna665ca82010-09-08 11:49:43 -07001966 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001967 } // release lock
1968
Jeff Browna665ca82010-09-08 11:49:43 -07001969 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07001970 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07001971 }
1972}
1973
Jeff Brown5c1ed842010-07-14 18:48:53 -07001974void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -07001975 uint32_t policyFlags, int32_t action, int32_t flags,
1976 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
1977#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown5c1ed842010-07-14 18:48:53 -07001978 LOGD("notifyKey - eventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Browne839a582010-04-22 18:58:52 -07001979 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brown5c1ed842010-07-14 18:48:53 -07001980 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Browne839a582010-04-22 18:58:52 -07001981 keyCode, scanCode, metaState, downTime);
1982#endif
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001983 if (! validateKeyEvent(action)) {
1984 return;
1985 }
Jeff Browne839a582010-04-22 18:58:52 -07001986
Jeff Browna665ca82010-09-08 11:49:43 -07001987 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07001988 { // acquire lock
1989 AutoMutex _l(mLock);
1990
Jeff Brown51d45a72010-06-17 20:52:56 -07001991 int32_t repeatCount = 0;
1992 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -07001993 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown51d45a72010-06-17 20:52:56 -07001994 metaState, repeatCount, downTime);
Jeff Browne839a582010-04-22 18:58:52 -07001995
Jeff Browna665ca82010-09-08 11:49:43 -07001996 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001997 } // release lock
1998
Jeff Browna665ca82010-09-08 11:49:43 -07001999 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07002000 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002001 }
2002}
2003
Jeff Brown5c1ed842010-07-14 18:48:53 -07002004void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002005 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Browne839a582010-04-22 18:58:52 -07002006 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2007 float xPrecision, float yPrecision, nsecs_t downTime) {
2008#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown5c1ed842010-07-14 18:48:53 -07002009 LOGD("notifyMotion - eventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, "
Jeff Brownaf30ff62010-09-01 17:01:00 -07002010 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2011 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2012 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Browne839a582010-04-22 18:58:52 -07002013 xPrecision, yPrecision, downTime);
2014 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown38a7fab2010-08-30 03:02:23 -07002015 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brownaf30ff62010-09-01 17:01:00 -07002016 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown38a7fab2010-08-30 03:02:23 -07002017 "orientation=%f",
Jeff Browne839a582010-04-22 18:58:52 -07002018 i, pointerIds[i], pointerCoords[i].x, pointerCoords[i].y,
Jeff Brown38a7fab2010-08-30 03:02:23 -07002019 pointerCoords[i].pressure, pointerCoords[i].size,
2020 pointerCoords[i].touchMajor, pointerCoords[i].touchMinor,
2021 pointerCoords[i].toolMajor, pointerCoords[i].toolMinor,
2022 pointerCoords[i].orientation);
Jeff Browne839a582010-04-22 18:58:52 -07002023 }
2024#endif
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002025 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2026 return;
2027 }
Jeff Browne839a582010-04-22 18:58:52 -07002028
Jeff Browna665ca82010-09-08 11:49:43 -07002029 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07002030 { // acquire lock
2031 AutoMutex _l(mLock);
2032
2033 // Attempt batching and streaming of move events.
Jeff Brown5c1ed842010-07-14 18:48:53 -07002034 if (action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Browne839a582010-04-22 18:58:52 -07002035 // BATCHING CASE
2036 //
2037 // Try to append a move sample to the tail of the inbound queue for this device.
2038 // Give up if we encounter a non-move motion event for this device since that
2039 // means we cannot append any new samples until a new motion event has started.
Jeff Browna665ca82010-09-08 11:49:43 -07002040 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2041 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Browne839a582010-04-22 18:58:52 -07002042 if (entry->type != EventEntry::TYPE_MOTION) {
2043 // Keep looking for motion events.
2044 continue;
2045 }
2046
2047 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
2048 if (motionEntry->deviceId != deviceId) {
2049 // Keep looking for this device.
2050 continue;
2051 }
2052
Jeff Brown5c1ed842010-07-14 18:48:53 -07002053 if (motionEntry->action != AMOTION_EVENT_ACTION_MOVE
Jeff Brown51d45a72010-06-17 20:52:56 -07002054 || motionEntry->pointerCount != pointerCount
2055 || motionEntry->isInjected()) {
Jeff Browne839a582010-04-22 18:58:52 -07002056 // Last motion event in the queue for this device is not compatible for
2057 // appending new samples. Stop here.
2058 goto NoBatchingOrStreaming;
2059 }
2060
2061 // The last motion event is a move and is compatible for appending.
Jeff Brown54bc2812010-06-15 01:31:58 -07002062 // Do the batching magic.
Jeff Brown51d45a72010-06-17 20:52:56 -07002063 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Browne839a582010-04-22 18:58:52 -07002064#if DEBUG_BATCHING
2065 LOGD("Appended motion sample onto batch for most recent "
2066 "motion event for this device in the inbound queue.");
2067#endif
Jeff Brown54bc2812010-06-15 01:31:58 -07002068 return; // done!
Jeff Browne839a582010-04-22 18:58:52 -07002069 }
2070
2071 // STREAMING CASE
2072 //
2073 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown53a415e2010-09-15 15:18:56 -07002074 // Search the outbound queue for the current foreground targets to find a dispatched
2075 // motion event that is still in progress. If found, then, appen the new sample to
2076 // that event and push it out to all current targets. The logic in
2077 // prepareDispatchCycleLocked takes care of the case where some targets may
2078 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown54bc2812010-06-15 01:31:58 -07002079 if (mCurrentInputTargetsValid) {
Jeff Brown53a415e2010-09-15 15:18:56 -07002080 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2081 const InputTarget& inputTarget = mCurrentInputTargets[i];
2082 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2083 // Skip non-foreground targets. We only want to stream if there is at
2084 // least one foreground target whose dispatch is still in progress.
2085 continue;
Jeff Browne839a582010-04-22 18:58:52 -07002086 }
Jeff Brown53a415e2010-09-15 15:18:56 -07002087
2088 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2089 if (connectionIndex < 0) {
2090 // Connection must no longer be valid.
2091 continue;
2092 }
2093
2094 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2095 if (connection->outboundQueue.isEmpty()) {
2096 // This foreground target has an empty outbound queue.
2097 continue;
2098 }
2099
2100 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2101 if (! dispatchEntry->inProgress
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002102 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2103 || dispatchEntry->isSplit()) {
2104 // No motion event is being dispatched, or it is being split across
2105 // windows in which case we cannot stream.
Jeff Brown53a415e2010-09-15 15:18:56 -07002106 continue;
2107 }
2108
2109 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2110 dispatchEntry->eventEntry);
2111 if (motionEntry->action != AMOTION_EVENT_ACTION_MOVE
2112 || motionEntry->deviceId != deviceId
2113 || motionEntry->pointerCount != pointerCount
2114 || motionEntry->isInjected()) {
2115 // The motion event is not compatible with this move.
2116 continue;
2117 }
2118
2119 // Hurray! This foreground target is currently dispatching a move event
2120 // that we can stream onto. Append the motion sample and resume dispatch.
2121 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2122#if DEBUG_BATCHING
2123 LOGD("Appended motion sample onto batch for most recently dispatched "
2124 "motion event for this device in the outbound queues. "
2125 "Attempting to stream the motion sample.");
2126#endif
2127 nsecs_t currentTime = now();
2128 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2129 true /*resumeWithAppendedMotionSample*/);
2130
2131 runCommandsLockedInterruptible();
2132 return; // done!
Jeff Browne839a582010-04-22 18:58:52 -07002133 }
2134 }
2135
2136NoBatchingOrStreaming:;
2137 }
2138
2139 // Just enqueue a new motion event.
Jeff Brown51d45a72010-06-17 20:52:56 -07002140 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002141 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown51d45a72010-06-17 20:52:56 -07002142 xPrecision, yPrecision, downTime,
2143 pointerCount, pointerIds, pointerCoords);
Jeff Browne839a582010-04-22 18:58:52 -07002144
Jeff Browna665ca82010-09-08 11:49:43 -07002145 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07002146 } // release lock
2147
Jeff Browna665ca82010-09-08 11:49:43 -07002148 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07002149 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002150 }
2151}
2152
Jeff Brown51d45a72010-06-17 20:52:56 -07002153int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brownf67c53e2010-07-28 15:48:59 -07002154 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown51d45a72010-06-17 20:52:56 -07002155#if DEBUG_INBOUND_EVENT_DETAILS
2156 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brownf67c53e2010-07-28 15:48:59 -07002157 "syncMode=%d, timeoutMillis=%d",
2158 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown51d45a72010-06-17 20:52:56 -07002159#endif
2160
2161 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2162
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002163 InjectionState* injectionState;
Jeff Browna665ca82010-09-08 11:49:43 -07002164 bool needWake;
Jeff Brown51d45a72010-06-17 20:52:56 -07002165 { // acquire lock
2166 AutoMutex _l(mLock);
2167
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002168 EventEntry* injectedEntry = createEntryFromInjectedInputEventLocked(event);
Jeff Browna665ca82010-09-08 11:49:43 -07002169 if (! injectedEntry) {
2170 return INPUT_EVENT_INJECTION_FAILED;
2171 }
2172
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002173 injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
Jeff Brownf67c53e2010-07-28 15:48:59 -07002174 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002175 injectionState->injectionIsAsync = true;
Jeff Brownf67c53e2010-07-28 15:48:59 -07002176 }
2177
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002178 injectionState->refCount += 1;
2179 injectedEntry->injectionState = injectionState;
2180
Jeff Browna665ca82010-09-08 11:49:43 -07002181 needWake = enqueueInboundEventLocked(injectedEntry);
Jeff Brown51d45a72010-06-17 20:52:56 -07002182 } // release lock
2183
Jeff Browna665ca82010-09-08 11:49:43 -07002184 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07002185 mLooper->wake();
Jeff Brown51d45a72010-06-17 20:52:56 -07002186 }
2187
2188 int32_t injectionResult;
2189 { // acquire lock
2190 AutoMutex _l(mLock);
2191
Jeff Brownf67c53e2010-07-28 15:48:59 -07002192 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2193 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2194 } else {
2195 for (;;) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002196 injectionResult = injectionState->injectionResult;
Jeff Brownf67c53e2010-07-28 15:48:59 -07002197 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2198 break;
2199 }
Jeff Brown51d45a72010-06-17 20:52:56 -07002200
Jeff Brown51d45a72010-06-17 20:52:56 -07002201 nsecs_t remainingTimeout = endTime - now();
2202 if (remainingTimeout <= 0) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07002203#if DEBUG_INJECTION
2204 LOGD("injectInputEvent - Timed out waiting for injection result "
2205 "to become available.");
2206#endif
Jeff Brown51d45a72010-06-17 20:52:56 -07002207 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2208 break;
2209 }
2210
Jeff Brownf67c53e2010-07-28 15:48:59 -07002211 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2212 }
2213
2214 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2215 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002216 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07002217#if DEBUG_INJECTION
Jeff Brown53a415e2010-09-15 15:18:56 -07002218 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002219 injectionState->pendingForegroundDispatches);
Jeff Brownf67c53e2010-07-28 15:48:59 -07002220#endif
2221 nsecs_t remainingTimeout = endTime - now();
2222 if (remainingTimeout <= 0) {
2223#if DEBUG_INJECTION
Jeff Brown53a415e2010-09-15 15:18:56 -07002224 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brownf67c53e2010-07-28 15:48:59 -07002225 "dispatches to finish.");
2226#endif
2227 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2228 break;
2229 }
2230
2231 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2232 }
Jeff Brown51d45a72010-06-17 20:52:56 -07002233 }
2234 }
2235
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002236 mAllocator.releaseInjectionState(injectionState);
Jeff Brown51d45a72010-06-17 20:52:56 -07002237 } // release lock
2238
Jeff Brownf67c53e2010-07-28 15:48:59 -07002239#if DEBUG_INJECTION
2240 LOGD("injectInputEvent - Finished with result %d. "
2241 "injectorPid=%d, injectorUid=%d",
2242 injectionResult, injectorPid, injectorUid);
2243#endif
2244
Jeff Brown51d45a72010-06-17 20:52:56 -07002245 return injectionResult;
2246}
2247
2248void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002249 InjectionState* injectionState = entry->injectionState;
2250 if (injectionState) {
Jeff Brown51d45a72010-06-17 20:52:56 -07002251#if DEBUG_INJECTION
2252 LOGD("Setting input event injection result to %d. "
2253 "injectorPid=%d, injectorUid=%d",
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002254 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown51d45a72010-06-17 20:52:56 -07002255#endif
2256
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002257 if (injectionState->injectionIsAsync) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07002258 // Log the outcome since the injector did not wait for the injection result.
2259 switch (injectionResult) {
2260 case INPUT_EVENT_INJECTION_SUCCEEDED:
2261 LOGV("Asynchronous input event injection succeeded.");
2262 break;
2263 case INPUT_EVENT_INJECTION_FAILED:
2264 LOGW("Asynchronous input event injection failed.");
2265 break;
2266 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2267 LOGW("Asynchronous input event injection permission denied.");
2268 break;
2269 case INPUT_EVENT_INJECTION_TIMED_OUT:
2270 LOGW("Asynchronous input event injection timed out.");
2271 break;
2272 }
2273 }
2274
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002275 injectionState->injectionResult = injectionResult;
Jeff Brown51d45a72010-06-17 20:52:56 -07002276 mInjectionResultAvailableCondition.broadcast();
2277 }
2278}
2279
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002280void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2281 InjectionState* injectionState = entry->injectionState;
2282 if (injectionState) {
2283 injectionState->pendingForegroundDispatches += 1;
2284 }
2285}
2286
Jeff Brown53a415e2010-09-15 15:18:56 -07002287void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002288 InjectionState* injectionState = entry->injectionState;
2289 if (injectionState) {
2290 injectionState->pendingForegroundDispatches -= 1;
Jeff Brownf67c53e2010-07-28 15:48:59 -07002291
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002292 if (injectionState->pendingForegroundDispatches == 0) {
2293 mInjectionSyncFinishedCondition.broadcast();
2294 }
Jeff Browna665ca82010-09-08 11:49:43 -07002295 }
2296}
2297
2298InputDispatcher::EventEntry* InputDispatcher::createEntryFromInjectedInputEventLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002299 const InputEvent* event) {
2300 switch (event->getType()) {
Jeff Brown5c1ed842010-07-14 18:48:53 -07002301 case AINPUT_EVENT_TYPE_KEY: {
Jeff Brown51d45a72010-06-17 20:52:56 -07002302 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002303 if (! validateKeyEvent(keyEvent->getAction())) {
Jeff Browna665ca82010-09-08 11:49:43 -07002304 return NULL;
2305 }
2306
Jeff Brownaf30ff62010-09-01 17:01:00 -07002307 uint32_t policyFlags = POLICY_FLAG_INJECTED;
Jeff Brown51d45a72010-06-17 20:52:56 -07002308
2309 KeyEntry* keyEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
Jeff Brown5c1ed842010-07-14 18:48:53 -07002310 keyEvent->getDeviceId(), keyEvent->getSource(), policyFlags,
Jeff Brown51d45a72010-06-17 20:52:56 -07002311 keyEvent->getAction(), keyEvent->getFlags(),
2312 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2313 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2314 return keyEntry;
2315 }
2316
Jeff Brown5c1ed842010-07-14 18:48:53 -07002317 case AINPUT_EVENT_TYPE_MOTION: {
Jeff Brown51d45a72010-06-17 20:52:56 -07002318 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002319 if (! validateMotionEvent(motionEvent->getAction(),
2320 motionEvent->getPointerCount(), motionEvent->getPointerIds())) {
Jeff Browna665ca82010-09-08 11:49:43 -07002321 return NULL;
2322 }
Jeff Browna665ca82010-09-08 11:49:43 -07002323
Jeff Brownaf30ff62010-09-01 17:01:00 -07002324 uint32_t policyFlags = POLICY_FLAG_INJECTED;
Jeff Brown51d45a72010-06-17 20:52:56 -07002325
2326 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2327 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2328 size_t pointerCount = motionEvent->getPointerCount();
2329
2330 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
Jeff Brown5c1ed842010-07-14 18:48:53 -07002331 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002332 motionEvent->getAction(), motionEvent->getFlags(),
2333 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
Jeff Brown51d45a72010-06-17 20:52:56 -07002334 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2335 motionEvent->getDownTime(), uint32_t(pointerCount),
2336 motionEvent->getPointerIds(), samplePointerCoords);
2337 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2338 sampleEventTimes += 1;
2339 samplePointerCoords += pointerCount;
2340 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2341 }
2342 return motionEntry;
2343 }
2344
2345 default:
2346 assert(false);
2347 return NULL;
2348 }
2349}
2350
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002351const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2352 for (size_t i = 0; i < mWindows.size(); i++) {
2353 const InputWindow* window = & mWindows[i];
2354 if (window->inputChannel == inputChannel) {
2355 return window;
2356 }
2357 }
2358 return NULL;
2359}
2360
Jeff Browna665ca82010-09-08 11:49:43 -07002361void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2362#if DEBUG_FOCUS
2363 LOGD("setInputWindows");
2364#endif
2365 { // acquire lock
2366 AutoMutex _l(mLock);
2367
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002368 // Clear old window pointers.
Jeff Brown405a1d32010-09-16 12:31:46 -07002369 mFocusedWindow = NULL;
Jeff Browna665ca82010-09-08 11:49:43 -07002370 mWindows.clear();
Jeff Brown405a1d32010-09-16 12:31:46 -07002371
2372 // Loop over new windows and rebuild the necessary window pointers for
2373 // tracking focus and touch.
Jeff Browna665ca82010-09-08 11:49:43 -07002374 mWindows.appendVector(inputWindows);
2375
2376 size_t numWindows = mWindows.size();
2377 for (size_t i = 0; i < numWindows; i++) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002378 const InputWindow* window = & mWindows.itemAt(i);
Jeff Browna665ca82010-09-08 11:49:43 -07002379 if (window->hasFocus) {
2380 mFocusedWindow = window;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002381 break;
Jeff Browna665ca82010-09-08 11:49:43 -07002382 }
2383 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002384
2385 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2386 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2387 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2388 if (window) {
2389 touchedWindow.window = window;
2390 i += 1;
2391 } else {
2392 mTouchState.windows.removeAt(i);
2393 }
2394 }
Jeff Browna665ca82010-09-08 11:49:43 -07002395
Jeff Browna665ca82010-09-08 11:49:43 -07002396#if DEBUG_FOCUS
2397 logDispatchStateLocked();
2398#endif
2399 } // release lock
2400
2401 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002402 mLooper->wake();
Jeff Browna665ca82010-09-08 11:49:43 -07002403}
2404
2405void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2406#if DEBUG_FOCUS
2407 LOGD("setFocusedApplication");
2408#endif
2409 { // acquire lock
2410 AutoMutex _l(mLock);
2411
2412 releaseFocusedApplicationLocked();
2413
2414 if (inputApplication) {
2415 mFocusedApplicationStorage = *inputApplication;
2416 mFocusedApplication = & mFocusedApplicationStorage;
2417 }
2418
2419#if DEBUG_FOCUS
2420 logDispatchStateLocked();
2421#endif
2422 } // release lock
2423
2424 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002425 mLooper->wake();
Jeff Browna665ca82010-09-08 11:49:43 -07002426}
2427
2428void InputDispatcher::releaseFocusedApplicationLocked() {
2429 if (mFocusedApplication) {
2430 mFocusedApplication = NULL;
2431 mFocusedApplicationStorage.handle.clear();
2432 }
2433}
2434
2435void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2436#if DEBUG_FOCUS
2437 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2438#endif
2439
2440 bool changed;
2441 { // acquire lock
2442 AutoMutex _l(mLock);
2443
2444 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2445 if (mDispatchFrozen && ! frozen) {
2446 resetANRTimeoutsLocked();
2447 }
2448
2449 mDispatchEnabled = enabled;
2450 mDispatchFrozen = frozen;
2451 changed = true;
2452 } else {
2453 changed = false;
2454 }
2455
2456#if DEBUG_FOCUS
2457 logDispatchStateLocked();
2458#endif
2459 } // release lock
2460
2461 if (changed) {
2462 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002463 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002464 }
2465}
2466
Jeff Browna665ca82010-09-08 11:49:43 -07002467void InputDispatcher::logDispatchStateLocked() {
2468 String8 dump;
2469 dumpDispatchStateLocked(dump);
Jeff Brown405a1d32010-09-16 12:31:46 -07002470
2471 char* text = dump.lockBuffer(dump.size());
2472 char* start = text;
2473 while (*start != '\0') {
2474 char* end = strchr(start, '\n');
2475 if (*end == '\n') {
2476 *(end++) = '\0';
2477 }
2478 LOGD("%s", start);
2479 start = end;
2480 }
Jeff Browna665ca82010-09-08 11:49:43 -07002481}
2482
2483void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
2484 dump.appendFormat(" dispatchEnabled: %d\n", mDispatchEnabled);
2485 dump.appendFormat(" dispatchFrozen: %d\n", mDispatchFrozen);
2486
2487 if (mFocusedApplication) {
2488 dump.appendFormat(" focusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
2489 mFocusedApplication->name.string(),
2490 mFocusedApplication->dispatchingTimeout / 1000000.0);
2491 } else {
2492 dump.append(" focusedApplication: <null>\n");
2493 }
Jeff Brown405a1d32010-09-16 12:31:46 -07002494 dump.appendFormat(" focusedWindow: name='%s'\n",
2495 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002496 dump.appendFormat(" touchState: down=%s, split=%s\n", toString(mTouchState.down),
2497 toString(mTouchState.split));
2498 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2499 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2500 dump.appendFormat(" touchedWindow[%d]: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
2501 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
2502 touchedWindow.targetFlags);
Jeff Browna665ca82010-09-08 11:49:43 -07002503 }
2504 for (size_t i = 0; i < mWindows.size(); i++) {
Jeff Brown405a1d32010-09-16 12:31:46 -07002505 dump.appendFormat(" windows[%d]: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
2506 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Jeff Browna665ca82010-09-08 11:49:43 -07002507 "frame=[%d,%d][%d,%d], "
2508 "visibleFrame=[%d,%d][%d,%d], "
2509 "touchableArea=[%d,%d][%d,%d], "
2510 "ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brown405a1d32010-09-16 12:31:46 -07002511 i, mWindows[i].name.string(),
Jeff Browna665ca82010-09-08 11:49:43 -07002512 toString(mWindows[i].paused),
2513 toString(mWindows[i].hasFocus),
2514 toString(mWindows[i].hasWallpaper),
2515 toString(mWindows[i].visible),
Jeff Brown405a1d32010-09-16 12:31:46 -07002516 toString(mWindows[i].canReceiveKeys),
Jeff Browna665ca82010-09-08 11:49:43 -07002517 mWindows[i].layoutParamsFlags, mWindows[i].layoutParamsType,
Jeff Brown405a1d32010-09-16 12:31:46 -07002518 mWindows[i].layer,
Jeff Browna665ca82010-09-08 11:49:43 -07002519 mWindows[i].frameLeft, mWindows[i].frameTop,
2520 mWindows[i].frameRight, mWindows[i].frameBottom,
2521 mWindows[i].visibleFrameLeft, mWindows[i].visibleFrameTop,
2522 mWindows[i].visibleFrameRight, mWindows[i].visibleFrameBottom,
2523 mWindows[i].touchableAreaLeft, mWindows[i].touchableAreaTop,
2524 mWindows[i].touchableAreaRight, mWindows[i].touchableAreaBottom,
2525 mWindows[i].ownerPid, mWindows[i].ownerUid,
2526 mWindows[i].dispatchingTimeout / 1000000.0);
2527 }
2528
2529 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2530 const sp<InputChannel>& channel = mMonitoringChannels[i];
2531 dump.appendFormat(" monitoringChannel[%d]: '%s'\n",
2532 i, channel->getName().string());
2533 }
2534
Jeff Brown53a415e2010-09-15 15:18:56 -07002535 dump.appendFormat(" inboundQueue: length=%u", mInboundQueue.count());
2536
Jeff Browna665ca82010-09-08 11:49:43 -07002537 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2538 const Connection* connection = mActiveConnections[i];
Jeff Brown53a415e2010-09-15 15:18:56 -07002539 dump.appendFormat(" activeConnection[%d]: '%s', status=%s, outboundQueueLength=%u"
Jeff Browna665ca82010-09-08 11:49:43 -07002540 "inputState.isNeutral=%s, inputState.isOutOfSync=%s\n",
2541 i, connection->getInputChannelName(), connection->getStatusLabel(),
Jeff Brown53a415e2010-09-15 15:18:56 -07002542 connection->outboundQueue.count(),
Jeff Browna665ca82010-09-08 11:49:43 -07002543 toString(connection->inputState.isNeutral()),
2544 toString(connection->inputState.isOutOfSync()));
2545 }
2546
2547 if (isAppSwitchPendingLocked()) {
2548 dump.appendFormat(" appSwitch: pending, due in %01.1fms\n",
2549 (mAppSwitchDueTime - now()) / 1000000.0);
2550 } else {
2551 dump.append(" appSwitch: not pending\n");
2552 }
2553}
2554
2555status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) {
Jeff Brown54bc2812010-06-15 01:31:58 -07002556#if DEBUG_REGISTRATION
Jeff Browna665ca82010-09-08 11:49:43 -07002557 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
2558 toString(monitor));
Jeff Brown54bc2812010-06-15 01:31:58 -07002559#endif
2560
Jeff Browne839a582010-04-22 18:58:52 -07002561 { // acquire lock
2562 AutoMutex _l(mLock);
2563
Jeff Brown53a415e2010-09-15 15:18:56 -07002564 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Browne839a582010-04-22 18:58:52 -07002565 LOGW("Attempted to register already registered input channel '%s'",
2566 inputChannel->getName().string());
2567 return BAD_VALUE;
2568 }
2569
2570 sp<Connection> connection = new Connection(inputChannel);
2571 status_t status = connection->initialize();
2572 if (status) {
2573 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
2574 inputChannel->getName().string(), status);
2575 return status;
2576 }
2577
Jeff Brown0cacb872010-08-17 15:59:26 -07002578 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Browne839a582010-04-22 18:58:52 -07002579 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07002580
Jeff Browna665ca82010-09-08 11:49:43 -07002581 if (monitor) {
2582 mMonitoringChannels.push(inputChannel);
2583 }
2584
Jeff Brown59abe7e2010-09-13 23:17:30 -07002585 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown0cacb872010-08-17 15:59:26 -07002586
Jeff Brown54bc2812010-06-15 01:31:58 -07002587 runCommandsLockedInterruptible();
Jeff Browne839a582010-04-22 18:58:52 -07002588 } // release lock
Jeff Browne839a582010-04-22 18:58:52 -07002589 return OK;
2590}
2591
2592status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown54bc2812010-06-15 01:31:58 -07002593#if DEBUG_REGISTRATION
Jeff Brown50de30a2010-06-22 01:27:15 -07002594 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown54bc2812010-06-15 01:31:58 -07002595#endif
2596
Jeff Browne839a582010-04-22 18:58:52 -07002597 { // acquire lock
2598 AutoMutex _l(mLock);
2599
Jeff Brown53a415e2010-09-15 15:18:56 -07002600 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Browne839a582010-04-22 18:58:52 -07002601 if (connectionIndex < 0) {
2602 LOGW("Attempted to unregister already unregistered input channel '%s'",
2603 inputChannel->getName().string());
2604 return BAD_VALUE;
2605 }
2606
2607 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2608 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
2609
2610 connection->status = Connection::STATUS_ZOMBIE;
2611
Jeff Browna665ca82010-09-08 11:49:43 -07002612 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2613 if (mMonitoringChannels[i] == inputChannel) {
2614 mMonitoringChannels.removeAt(i);
2615 break;
2616 }
2617 }
2618
Jeff Brown59abe7e2010-09-13 23:17:30 -07002619 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown0cacb872010-08-17 15:59:26 -07002620
Jeff Brown51d45a72010-06-17 20:52:56 -07002621 nsecs_t currentTime = now();
2622 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07002623
2624 runCommandsLockedInterruptible();
Jeff Browne839a582010-04-22 18:58:52 -07002625 } // release lock
2626
Jeff Browne839a582010-04-22 18:58:52 -07002627 // Wake the poll loop because removing the connection may have changed the current
2628 // synchronization state.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002629 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002630 return OK;
2631}
2632
Jeff Brown53a415e2010-09-15 15:18:56 -07002633ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown0cacb872010-08-17 15:59:26 -07002634 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
2635 if (connectionIndex >= 0) {
2636 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2637 if (connection->inputChannel.get() == inputChannel.get()) {
2638 return connectionIndex;
2639 }
2640 }
2641
2642 return -1;
2643}
2644
Jeff Browne839a582010-04-22 18:58:52 -07002645void InputDispatcher::activateConnectionLocked(Connection* connection) {
2646 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2647 if (mActiveConnections.itemAt(i) == connection) {
2648 return;
2649 }
2650 }
2651 mActiveConnections.add(connection);
2652}
2653
2654void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
2655 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2656 if (mActiveConnections.itemAt(i) == connection) {
2657 mActiveConnections.removeAt(i);
2658 return;
2659 }
2660 }
2661}
2662
Jeff Brown54bc2812010-06-15 01:31:58 -07002663void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002664 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002665}
2666
Jeff Brown54bc2812010-06-15 01:31:58 -07002667void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002668 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002669}
2670
Jeff Brown54bc2812010-06-15 01:31:58 -07002671void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002672 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002673 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
2674 connection->getInputChannelName());
2675
Jeff Brown54bc2812010-06-15 01:31:58 -07002676 CommandEntry* commandEntry = postCommandLocked(
2677 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown51d45a72010-06-17 20:52:56 -07002678 commandEntry->connection = connection;
Jeff Browne839a582010-04-22 18:58:52 -07002679}
2680
Jeff Brown53a415e2010-09-15 15:18:56 -07002681void InputDispatcher::onANRLocked(
2682 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
2683 nsecs_t eventTime, nsecs_t waitStartTime) {
2684 LOGI("Application is not responding: %s. "
2685 "%01.1fms since event, %01.1fms since wait started",
2686 getApplicationWindowLabelLocked(application, window).string(),
2687 (currentTime - eventTime) / 1000000.0,
2688 (currentTime - waitStartTime) / 1000000.0);
2689
2690 CommandEntry* commandEntry = postCommandLocked(
2691 & InputDispatcher::doNotifyANRLockedInterruptible);
2692 if (application) {
2693 commandEntry->inputApplicationHandle = application->handle;
2694 }
2695 if (window) {
2696 commandEntry->inputChannel = window->inputChannel;
2697 }
2698}
2699
Jeff Browna665ca82010-09-08 11:49:43 -07002700void InputDispatcher::doNotifyConfigurationChangedInterruptible(
2701 CommandEntry* commandEntry) {
2702 mLock.unlock();
2703
2704 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
2705
2706 mLock.lock();
2707}
2708
Jeff Brown54bc2812010-06-15 01:31:58 -07002709void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
2710 CommandEntry* commandEntry) {
Jeff Brown51d45a72010-06-17 20:52:56 -07002711 sp<Connection> connection = commandEntry->connection;
Jeff Brown54bc2812010-06-15 01:31:58 -07002712
Jeff Brown51d45a72010-06-17 20:52:56 -07002713 if (connection->status != Connection::STATUS_ZOMBIE) {
2714 mLock.unlock();
Jeff Brown54bc2812010-06-15 01:31:58 -07002715
Jeff Brown51d45a72010-06-17 20:52:56 -07002716 mPolicy->notifyInputChannelBroken(connection->inputChannel);
2717
2718 mLock.lock();
2719 }
Jeff Brown54bc2812010-06-15 01:31:58 -07002720}
2721
Jeff Brown53a415e2010-09-15 15:18:56 -07002722void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown54bc2812010-06-15 01:31:58 -07002723 CommandEntry* commandEntry) {
Jeff Brown53a415e2010-09-15 15:18:56 -07002724 mLock.unlock();
Jeff Brown54bc2812010-06-15 01:31:58 -07002725
Jeff Brown53a415e2010-09-15 15:18:56 -07002726 nsecs_t newTimeout = mPolicy->notifyANR(
2727 commandEntry->inputApplicationHandle, commandEntry->inputChannel);
Jeff Brown54bc2812010-06-15 01:31:58 -07002728
Jeff Brown53a415e2010-09-15 15:18:56 -07002729 mLock.lock();
Jeff Brown51d45a72010-06-17 20:52:56 -07002730
Jeff Brown53a415e2010-09-15 15:18:56 -07002731 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown54bc2812010-06-15 01:31:58 -07002732}
2733
Jeff Browna665ca82010-09-08 11:49:43 -07002734void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
2735 CommandEntry* commandEntry) {
2736 KeyEntry* entry = commandEntry->keyEntry;
2737 mReusableKeyEvent.initialize(entry->deviceId, entry->source, entry->action, entry->flags,
2738 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
2739 entry->downTime, entry->eventTime);
2740
2741 mLock.unlock();
2742
2743 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputChannel,
2744 & mReusableKeyEvent, entry->policyFlags);
2745
2746 mLock.lock();
2747
2748 entry->interceptKeyResult = consumed
2749 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
2750 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
2751 mAllocator.releaseKeyEntry(entry);
2752}
2753
2754void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
2755 mLock.unlock();
2756
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002757 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Browna665ca82010-09-08 11:49:43 -07002758
2759 mLock.lock();
2760}
2761
Jeff Brown53a415e2010-09-15 15:18:56 -07002762void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
2763 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
2764 // TODO Write some statistics about how long we spend waiting.
Jeff Browna665ca82010-09-08 11:49:43 -07002765}
2766
2767void InputDispatcher::dump(String8& dump) {
2768 dumpDispatchStateLocked(dump);
2769}
2770
Jeff Brown54bc2812010-06-15 01:31:58 -07002771
Jeff Brown53a415e2010-09-15 15:18:56 -07002772// --- InputDispatcher::Queue ---
2773
2774template <typename T>
2775uint32_t InputDispatcher::Queue<T>::count() const {
2776 uint32_t result = 0;
2777 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
2778 result += 1;
2779 }
2780 return result;
2781}
2782
2783
Jeff Browne839a582010-04-22 18:58:52 -07002784// --- InputDispatcher::Allocator ---
2785
2786InputDispatcher::Allocator::Allocator() {
2787}
2788
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002789InputDispatcher::InjectionState*
2790InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
2791 InjectionState* injectionState = mInjectionStatePool.alloc();
2792 injectionState->refCount = 1;
2793 injectionState->injectorPid = injectorPid;
2794 injectionState->injectorUid = injectorUid;
2795 injectionState->injectionIsAsync = false;
2796 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
2797 injectionState->pendingForegroundDispatches = 0;
2798 return injectionState;
2799}
2800
Jeff Brown51d45a72010-06-17 20:52:56 -07002801void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
2802 nsecs_t eventTime) {
2803 entry->type = type;
2804 entry->refCount = 1;
2805 entry->dispatchInProgress = false;
Christopher Tated974e002010-06-23 16:50:30 -07002806 entry->eventTime = eventTime;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002807 entry->injectionState = NULL;
2808}
2809
2810void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
2811 if (entry->injectionState) {
2812 releaseInjectionState(entry->injectionState);
2813 entry->injectionState = NULL;
2814 }
Jeff Brown51d45a72010-06-17 20:52:56 -07002815}
2816
Jeff Browne839a582010-04-22 18:58:52 -07002817InputDispatcher::ConfigurationChangedEntry*
Jeff Brown51d45a72010-06-17 20:52:56 -07002818InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Browne839a582010-04-22 18:58:52 -07002819 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002820 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime);
Jeff Browne839a582010-04-22 18:58:52 -07002821 return entry;
2822}
2823
Jeff Brown51d45a72010-06-17 20:52:56 -07002824InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -07002825 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown51d45a72010-06-17 20:52:56 -07002826 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
2827 int32_t repeatCount, nsecs_t downTime) {
Jeff Browne839a582010-04-22 18:58:52 -07002828 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002829 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime);
2830
2831 entry->deviceId = deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -07002832 entry->source = source;
Jeff Brown51d45a72010-06-17 20:52:56 -07002833 entry->policyFlags = policyFlags;
2834 entry->action = action;
2835 entry->flags = flags;
2836 entry->keyCode = keyCode;
2837 entry->scanCode = scanCode;
2838 entry->metaState = metaState;
2839 entry->repeatCount = repeatCount;
2840 entry->downTime = downTime;
Jeff Browna665ca82010-09-08 11:49:43 -07002841 entry->syntheticRepeat = false;
2842 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Browne839a582010-04-22 18:58:52 -07002843 return entry;
2844}
2845
Jeff Brown51d45a72010-06-17 20:52:56 -07002846InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002847 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown51d45a72010-06-17 20:52:56 -07002848 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
2849 nsecs_t downTime, uint32_t pointerCount,
2850 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Browne839a582010-04-22 18:58:52 -07002851 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002852 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime);
2853
2854 entry->eventTime = eventTime;
2855 entry->deviceId = deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -07002856 entry->source = source;
Jeff Brown51d45a72010-06-17 20:52:56 -07002857 entry->policyFlags = policyFlags;
2858 entry->action = action;
Jeff Brownaf30ff62010-09-01 17:01:00 -07002859 entry->flags = flags;
Jeff Brown51d45a72010-06-17 20:52:56 -07002860 entry->metaState = metaState;
2861 entry->edgeFlags = edgeFlags;
2862 entry->xPrecision = xPrecision;
2863 entry->yPrecision = yPrecision;
2864 entry->downTime = downTime;
2865 entry->pointerCount = pointerCount;
2866 entry->firstSample.eventTime = eventTime;
Jeff Browne839a582010-04-22 18:58:52 -07002867 entry->firstSample.next = NULL;
Jeff Brown51d45a72010-06-17 20:52:56 -07002868 entry->lastSample = & entry->firstSample;
2869 for (uint32_t i = 0; i < pointerCount; i++) {
2870 entry->pointerIds[i] = pointerIds[i];
2871 entry->firstSample.pointerCoords[i] = pointerCoords[i];
2872 }
Jeff Browne839a582010-04-22 18:58:52 -07002873 return entry;
2874}
2875
2876InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Browna665ca82010-09-08 11:49:43 -07002877 EventEntry* eventEntry,
Jeff Brown53a415e2010-09-15 15:18:56 -07002878 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Browne839a582010-04-22 18:58:52 -07002879 DispatchEntry* entry = mDispatchEntryPool.alloc();
2880 entry->eventEntry = eventEntry;
2881 eventEntry->refCount += 1;
Jeff Browna665ca82010-09-08 11:49:43 -07002882 entry->targetFlags = targetFlags;
2883 entry->xOffset = xOffset;
2884 entry->yOffset = yOffset;
Jeff Browna665ca82010-09-08 11:49:43 -07002885 entry->inProgress = false;
2886 entry->headMotionSample = NULL;
2887 entry->tailMotionSample = NULL;
Jeff Browne839a582010-04-22 18:58:52 -07002888 return entry;
2889}
2890
Jeff Brown54bc2812010-06-15 01:31:58 -07002891InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
2892 CommandEntry* entry = mCommandEntryPool.alloc();
2893 entry->command = command;
2894 return entry;
2895}
2896
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002897void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
2898 injectionState->refCount -= 1;
2899 if (injectionState->refCount == 0) {
2900 mInjectionStatePool.free(injectionState);
2901 } else {
2902 assert(injectionState->refCount > 0);
2903 }
2904}
2905
Jeff Browne839a582010-04-22 18:58:52 -07002906void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
2907 switch (entry->type) {
2908 case EventEntry::TYPE_CONFIGURATION_CHANGED:
2909 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
2910 break;
2911 case EventEntry::TYPE_KEY:
2912 releaseKeyEntry(static_cast<KeyEntry*>(entry));
2913 break;
2914 case EventEntry::TYPE_MOTION:
2915 releaseMotionEntry(static_cast<MotionEntry*>(entry));
2916 break;
2917 default:
2918 assert(false);
2919 break;
2920 }
2921}
2922
2923void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
2924 ConfigurationChangedEntry* entry) {
2925 entry->refCount -= 1;
2926 if (entry->refCount == 0) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002927 releaseEventEntryInjectionState(entry);
Jeff Browne839a582010-04-22 18:58:52 -07002928 mConfigurationChangeEntryPool.free(entry);
2929 } else {
2930 assert(entry->refCount > 0);
2931 }
2932}
2933
2934void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
2935 entry->refCount -= 1;
2936 if (entry->refCount == 0) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002937 releaseEventEntryInjectionState(entry);
Jeff Browne839a582010-04-22 18:58:52 -07002938 mKeyEntryPool.free(entry);
2939 } else {
2940 assert(entry->refCount > 0);
2941 }
2942}
2943
2944void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
2945 entry->refCount -= 1;
2946 if (entry->refCount == 0) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002947 releaseEventEntryInjectionState(entry);
Jeff Brown54bc2812010-06-15 01:31:58 -07002948 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
2949 MotionSample* next = sample->next;
2950 mMotionSamplePool.free(sample);
2951 sample = next;
2952 }
Jeff Browne839a582010-04-22 18:58:52 -07002953 mMotionEntryPool.free(entry);
2954 } else {
2955 assert(entry->refCount > 0);
2956 }
2957}
2958
2959void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
2960 releaseEventEntry(entry->eventEntry);
2961 mDispatchEntryPool.free(entry);
2962}
2963
Jeff Brown54bc2812010-06-15 01:31:58 -07002964void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
2965 mCommandEntryPool.free(entry);
2966}
2967
Jeff Browne839a582010-04-22 18:58:52 -07002968void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown51d45a72010-06-17 20:52:56 -07002969 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Browne839a582010-04-22 18:58:52 -07002970 MotionSample* sample = mMotionSamplePool.alloc();
2971 sample->eventTime = eventTime;
Jeff Brown51d45a72010-06-17 20:52:56 -07002972 uint32_t pointerCount = motionEntry->pointerCount;
2973 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Browne839a582010-04-22 18:58:52 -07002974 sample->pointerCoords[i] = pointerCoords[i];
2975 }
2976
2977 sample->next = NULL;
2978 motionEntry->lastSample->next = sample;
2979 motionEntry->lastSample = sample;
2980}
2981
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002982void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
2983 releaseEventEntryInjectionState(keyEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07002984
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002985 keyEntry->dispatchInProgress = false;
2986 keyEntry->syntheticRepeat = false;
2987 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Browna665ca82010-09-08 11:49:43 -07002988}
2989
2990
Jeff Brown542412c2010-08-18 15:51:08 -07002991// --- InputDispatcher::MotionEntry ---
2992
2993uint32_t InputDispatcher::MotionEntry::countSamples() const {
2994 uint32_t count = 1;
2995 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
2996 count += 1;
2997 }
2998 return count;
2999}
3000
Jeff Browna665ca82010-09-08 11:49:43 -07003001
3002// --- InputDispatcher::InputState ---
3003
3004InputDispatcher::InputState::InputState() :
3005 mIsOutOfSync(false) {
3006}
3007
3008InputDispatcher::InputState::~InputState() {
3009}
3010
3011bool InputDispatcher::InputState::isNeutral() const {
3012 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3013}
3014
3015bool InputDispatcher::InputState::isOutOfSync() const {
3016 return mIsOutOfSync;
3017}
3018
3019void InputDispatcher::InputState::setOutOfSync() {
3020 if (! isNeutral()) {
3021 mIsOutOfSync = true;
3022 }
3023}
3024
3025void InputDispatcher::InputState::resetOutOfSync() {
3026 mIsOutOfSync = false;
3027}
3028
3029InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackEvent(
3030 const EventEntry* entry) {
3031 switch (entry->type) {
3032 case EventEntry::TYPE_KEY:
3033 return trackKey(static_cast<const KeyEntry*>(entry));
3034
3035 case EventEntry::TYPE_MOTION:
3036 return trackMotion(static_cast<const MotionEntry*>(entry));
3037
3038 default:
3039 return CONSISTENT;
3040 }
3041}
3042
3043InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackKey(
3044 const KeyEntry* entry) {
3045 int32_t action = entry->action;
3046 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3047 KeyMemento& memento = mKeyMementos.editItemAt(i);
3048 if (memento.deviceId == entry->deviceId
3049 && memento.source == entry->source
3050 && memento.keyCode == entry->keyCode
3051 && memento.scanCode == entry->scanCode) {
3052 switch (action) {
3053 case AKEY_EVENT_ACTION_UP:
3054 mKeyMementos.removeAt(i);
3055 if (isNeutral()) {
3056 mIsOutOfSync = false;
3057 }
3058 return CONSISTENT;
3059
3060 case AKEY_EVENT_ACTION_DOWN:
3061 return TOLERABLE;
3062
3063 default:
3064 return BROKEN;
3065 }
3066 }
3067 }
3068
3069 switch (action) {
3070 case AKEY_EVENT_ACTION_DOWN: {
3071 mKeyMementos.push();
3072 KeyMemento& memento = mKeyMementos.editTop();
3073 memento.deviceId = entry->deviceId;
3074 memento.source = entry->source;
3075 memento.keyCode = entry->keyCode;
3076 memento.scanCode = entry->scanCode;
3077 memento.downTime = entry->downTime;
3078 return CONSISTENT;
3079 }
3080
3081 default:
3082 return BROKEN;
3083 }
3084}
3085
3086InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackMotion(
3087 const MotionEntry* entry) {
3088 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3089 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3090 MotionMemento& memento = mMotionMementos.editItemAt(i);
3091 if (memento.deviceId == entry->deviceId
3092 && memento.source == entry->source) {
3093 switch (action) {
3094 case AMOTION_EVENT_ACTION_UP:
3095 case AMOTION_EVENT_ACTION_CANCEL:
3096 mMotionMementos.removeAt(i);
3097 if (isNeutral()) {
3098 mIsOutOfSync = false;
3099 }
3100 return CONSISTENT;
3101
3102 case AMOTION_EVENT_ACTION_DOWN:
3103 return TOLERABLE;
3104
3105 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3106 if (entry->pointerCount == memento.pointerCount + 1) {
3107 memento.setPointers(entry);
3108 return CONSISTENT;
3109 }
3110 return BROKEN;
3111
3112 case AMOTION_EVENT_ACTION_POINTER_UP:
3113 if (entry->pointerCount == memento.pointerCount - 1) {
3114 memento.setPointers(entry);
3115 return CONSISTENT;
3116 }
3117 return BROKEN;
3118
3119 case AMOTION_EVENT_ACTION_MOVE:
3120 if (entry->pointerCount == memento.pointerCount) {
3121 return CONSISTENT;
3122 }
3123 return BROKEN;
3124
3125 default:
3126 return BROKEN;
3127 }
3128 }
3129 }
3130
3131 switch (action) {
3132 case AMOTION_EVENT_ACTION_DOWN: {
3133 mMotionMementos.push();
3134 MotionMemento& memento = mMotionMementos.editTop();
3135 memento.deviceId = entry->deviceId;
3136 memento.source = entry->source;
3137 memento.xPrecision = entry->xPrecision;
3138 memento.yPrecision = entry->yPrecision;
3139 memento.downTime = entry->downTime;
3140 memento.setPointers(entry);
3141 return CONSISTENT;
3142 }
3143
3144 default:
3145 return BROKEN;
3146 }
3147}
3148
3149void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3150 pointerCount = entry->pointerCount;
3151 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3152 pointerIds[i] = entry->pointerIds[i];
3153 pointerCoords[i] = entry->lastSample->pointerCoords[i];
3154 }
3155}
3156
3157void InputDispatcher::InputState::synthesizeCancelationEvents(
3158 Allocator* allocator, Vector<EventEntry*>& outEvents) const {
3159 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3160 const KeyMemento& memento = mKeyMementos.itemAt(i);
3161 outEvents.push(allocator->obtainKeyEntry(now(),
3162 memento.deviceId, memento.source, 0,
3163 AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_CANCELED,
3164 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3165 }
3166
3167 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3168 const MotionMemento& memento = mMotionMementos.itemAt(i);
3169 outEvents.push(allocator->obtainMotionEntry(now(),
3170 memento.deviceId, memento.source, 0,
3171 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3172 memento.xPrecision, memento.yPrecision, memento.downTime,
3173 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3174 }
3175}
3176
3177void InputDispatcher::InputState::clear() {
3178 mKeyMementos.clear();
3179 mMotionMementos.clear();
3180 mIsOutOfSync = false;
3181}
3182
3183
Jeff Browne839a582010-04-22 18:58:52 -07003184// --- InputDispatcher::Connection ---
3185
3186InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel) :
3187 status(STATUS_NORMAL), inputChannel(inputChannel), inputPublisher(inputChannel),
Jeff Brown53a415e2010-09-15 15:18:56 -07003188 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Browne839a582010-04-22 18:58:52 -07003189}
3190
3191InputDispatcher::Connection::~Connection() {
3192}
3193
3194status_t InputDispatcher::Connection::initialize() {
3195 return inputPublisher.initialize();
3196}
3197
Jeff Brown54bc2812010-06-15 01:31:58 -07003198const char* InputDispatcher::Connection::getStatusLabel() const {
3199 switch (status) {
3200 case STATUS_NORMAL:
3201 return "NORMAL";
3202
3203 case STATUS_BROKEN:
3204 return "BROKEN";
3205
Jeff Brown54bc2812010-06-15 01:31:58 -07003206 case STATUS_ZOMBIE:
3207 return "ZOMBIE";
3208
3209 default:
3210 return "UNKNOWN";
3211 }
3212}
3213
Jeff Browne839a582010-04-22 18:58:52 -07003214InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3215 const EventEntry* eventEntry) const {
Jeff Browna665ca82010-09-08 11:49:43 -07003216 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3217 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Browne839a582010-04-22 18:58:52 -07003218 if (dispatchEntry->eventEntry == eventEntry) {
3219 return dispatchEntry;
3220 }
3221 }
3222 return NULL;
3223}
3224
Jeff Browna665ca82010-09-08 11:49:43 -07003225
Jeff Brown54bc2812010-06-15 01:31:58 -07003226// --- InputDispatcher::CommandEntry ---
3227
Jeff Browna665ca82010-09-08 11:49:43 -07003228InputDispatcher::CommandEntry::CommandEntry() :
3229 keyEntry(NULL) {
Jeff Brown54bc2812010-06-15 01:31:58 -07003230}
3231
3232InputDispatcher::CommandEntry::~CommandEntry() {
3233}
3234
Jeff Browne839a582010-04-22 18:58:52 -07003235
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07003236// --- InputDispatcher::TouchState ---
3237
3238InputDispatcher::TouchState::TouchState() :
3239 down(false), split(false) {
3240}
3241
3242InputDispatcher::TouchState::~TouchState() {
3243}
3244
3245void InputDispatcher::TouchState::reset() {
3246 down = false;
3247 split = false;
3248 windows.clear();
3249}
3250
3251void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
3252 down = other.down;
3253 split = other.split;
3254 windows.clear();
3255 windows.appendVector(other.windows);
3256}
3257
3258void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
3259 int32_t targetFlags, BitSet32 pointerIds) {
3260 if (targetFlags & InputTarget::FLAG_SPLIT) {
3261 split = true;
3262 }
3263
3264 for (size_t i = 0; i < windows.size(); i++) {
3265 TouchedWindow& touchedWindow = windows.editItemAt(i);
3266 if (touchedWindow.window == window) {
3267 touchedWindow.targetFlags |= targetFlags;
3268 touchedWindow.pointerIds.value |= pointerIds.value;
3269 return;
3270 }
3271 }
3272
3273 windows.push();
3274
3275 TouchedWindow& touchedWindow = windows.editTop();
3276 touchedWindow.window = window;
3277 touchedWindow.targetFlags = targetFlags;
3278 touchedWindow.pointerIds = pointerIds;
3279 touchedWindow.channel = window->inputChannel;
3280}
3281
3282void InputDispatcher::TouchState::removeOutsideTouchWindows() {
3283 for (size_t i = 0 ; i < windows.size(); ) {
3284 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
3285 windows.removeAt(i);
3286 } else {
3287 i += 1;
3288 }
3289 }
3290}
3291
3292const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
3293 for (size_t i = 0; i < windows.size(); i++) {
3294 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
3295 return windows[i].window;
3296 }
3297 }
3298 return NULL;
3299}
3300
3301
Jeff Browne839a582010-04-22 18:58:52 -07003302// --- InputDispatcherThread ---
3303
3304InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
3305 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
3306}
3307
3308InputDispatcherThread::~InputDispatcherThread() {
3309}
3310
3311bool InputDispatcherThread::threadLoop() {
3312 mDispatcher->dispatchOnce();
3313 return true;
3314}
3315
3316} // namespace android