blob: 9544a95fbbe91a8b5c0398db0f2559e584b7980b [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.
Jeff Brown1c322582010-09-28 13:24:41 -07001073 if (newTouchedWindow
1074 && (newTouchedWindow->layoutParamsFlags & InputWindow::FLAG_SPLIT_TOUCH)) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001075 // New window supports splitting.
1076 isSplit = true;
1077 } else if (isSplit) {
1078 // New window does not support splitting but we have already split events.
1079 // Assign the pointer to the first foreground window we find.
1080 // (May be NULL which is why we put this code block before the next check.)
1081 newTouchedWindow = mTempTouchState.getFirstForegroundWindow();
1082 }
1083 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
1084 if (isSplit) {
1085 targetFlags |= InputTarget::FLAG_SPLIT;
1086 }
1087
Jeff Browna665ca82010-09-08 11:49:43 -07001088 // If we did not find a touched window then fail.
1089 if (! newTouchedWindow) {
1090 if (mFocusedApplication) {
1091#if DEBUG_FOCUS
1092 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown53a415e2010-09-15 15:18:56 -07001093 "focused application that may eventually add a new window: %s.",
1094 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Browna665ca82010-09-08 11:49:43 -07001095#endif
1096 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1097 mFocusedApplication, NULL, nextWakeupTime);
Jeff Browna665ca82010-09-08 11:49:43 -07001098 goto Unresponsive;
1099 }
1100
1101 LOGI("Dropping event because there is no touched window or focused application.");
1102 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Browna665ca82010-09-08 11:49:43 -07001103 goto Failed;
1104 }
1105
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001106 // Update the temporary touch state.
1107 BitSet32 pointerIds;
1108 if (isSplit) {
1109 uint32_t pointerId = entry->pointerIds[pointerIndex];
1110 pointerIds.markBit(pointerId);
Jeff Browna665ca82010-09-08 11:49:43 -07001111 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001112 mTempTouchState.addOrUpdateWindow(newTouchedWindow, targetFlags, pointerIds);
Jeff Browna665ca82010-09-08 11:49:43 -07001113 } else {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001114 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
Jeff Browna665ca82010-09-08 11:49:43 -07001115
1116 // If the pointer is not currently down, then ignore the event.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001117 if (! mTempTouchState.down) {
Jeff Browna665ca82010-09-08 11:49:43 -07001118 LOGI("Dropping event because the pointer is not down.");
1119 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Browna665ca82010-09-08 11:49:43 -07001120 goto Failed;
1121 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001122 }
Jeff Browna665ca82010-09-08 11:49:43 -07001123
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001124 // Check permission to inject into all touched foreground windows and ensure there
1125 // is at least one touched foreground window.
1126 {
1127 bool haveForegroundWindow = false;
1128 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1129 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1130 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1131 haveForegroundWindow = true;
1132 if (! checkInjectionPermission(touchedWindow.window, entry->injectionState)) {
1133 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1134 injectionPermission = INJECTION_PERMISSION_DENIED;
1135 goto Failed;
1136 }
1137 }
1138 }
1139 if (! haveForegroundWindow) {
Jeff Browna665ca82010-09-08 11:49:43 -07001140#if DEBUG_INPUT_DISPATCHER_POLICY
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001141 LOGD("Dropping event because there is no touched foreground window to receive it.");
Jeff Browna665ca82010-09-08 11:49:43 -07001142#endif
1143 injectionResult = INPUT_EVENT_INJECTION_FAILED;
Jeff Browna665ca82010-09-08 11:49:43 -07001144 goto Failed;
1145 }
1146
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001147 // Permission granted to injection into all touched foreground windows.
1148 injectionPermission = INJECTION_PERMISSION_GRANTED;
1149 }
Jeff Brown53a415e2010-09-15 15:18:56 -07001150
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001151 // Ensure all touched foreground windows are ready for new input.
1152 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1153 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1154 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1155 // If the touched window is paused then keep waiting.
1156 if (touchedWindow.window->paused) {
1157#if DEBUG_INPUT_DISPATCHER_POLICY
1158 LOGD("Waiting because touched window is paused.");
Jeff Brown53a415e2010-09-15 15:18:56 -07001159#endif
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001160 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1161 NULL, touchedWindow.window, nextWakeupTime);
1162 goto Unresponsive;
1163 }
1164
1165 // If the touched window is still working on previous events then keep waiting.
1166 if (! isWindowFinishedWithPreviousInputLocked(touchedWindow.window)) {
1167#if DEBUG_FOCUS
1168 LOGD("Waiting because touched window still processing previous input.");
1169#endif
1170 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1171 NULL, touchedWindow.window, nextWakeupTime);
1172 goto Unresponsive;
1173 }
1174 }
1175 }
1176
1177 // If this is the first pointer going down and the touched window has a wallpaper
1178 // then also add the touched wallpaper windows so they are locked in for the duration
1179 // of the touch gesture.
1180 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1181 const InputWindow* foregroundWindow = mTempTouchState.getFirstForegroundWindow();
1182 if (foregroundWindow->hasWallpaper) {
1183 for (size_t i = 0; i < mWindows.size(); i++) {
1184 const InputWindow* window = & mWindows[i];
1185 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
1186 mTempTouchState.addOrUpdateWindow(window, 0, BitSet32(0));
1187 }
1188 }
1189 }
1190 }
1191
1192 // If a touched window has been obscured at any point during the touch gesture, set
1193 // the appropriate flag so we remember it for the entire gesture.
1194 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1195 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1196 if ((touchedWindow.targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) == 0) {
1197 if (isWindowObscuredLocked(touchedWindow.window)) {
1198 touchedWindow.targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1199 }
Jeff Brown53a415e2010-09-15 15:18:56 -07001200 }
Jeff Browna665ca82010-09-08 11:49:43 -07001201 }
1202
1203 // Success! Output targets.
1204 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Jeff Browna665ca82010-09-08 11:49:43 -07001205
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001206 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1207 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1208 addWindowTargetLocked(touchedWindow.window, touchedWindow.targetFlags,
1209 touchedWindow.pointerIds);
Jeff Browna665ca82010-09-08 11:49:43 -07001210 }
1211
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001212 // Drop the outside touch window since we will not care about them in the next iteration.
1213 mTempTouchState.removeOutsideTouchWindows();
1214
Jeff Browna665ca82010-09-08 11:49:43 -07001215Failed:
1216 // Check injection permission once and for all.
1217 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001218 if (checkInjectionPermission(NULL, entry->injectionState)) {
Jeff Browna665ca82010-09-08 11:49:43 -07001219 injectionPermission = INJECTION_PERMISSION_GRANTED;
1220 } else {
1221 injectionPermission = INJECTION_PERMISSION_DENIED;
1222 }
1223 }
1224
1225 // Update final pieces of touch state if the injector had permission.
1226 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001227 if (maskedAction == AMOTION_EVENT_ACTION_UP
1228 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1229 // All pointers up or canceled.
1230 mTempTouchState.reset();
1231 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1232 // First pointer went down.
1233 if (mTouchState.down) {
Jeff Browna665ca82010-09-08 11:49:43 -07001234 LOGW("Pointer down received while already down.");
Jeff Browna665ca82010-09-08 11:49:43 -07001235 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001236 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1237 // One pointer went up.
1238 if (isSplit) {
1239 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1240 uint32_t pointerId = entry->pointerIds[pointerIndex];
Jeff Browna665ca82010-09-08 11:49:43 -07001241
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001242 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1243 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1244 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1245 touchedWindow.pointerIds.clearBit(pointerId);
1246 if (touchedWindow.pointerIds.isEmpty()) {
1247 mTempTouchState.windows.removeAt(i);
1248 continue;
1249 }
1250 }
1251 i += 1;
1252 }
Jeff Browna665ca82010-09-08 11:49:43 -07001253 }
Jeff Browna665ca82010-09-08 11:49:43 -07001254 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001255
1256 // Save changes to touch state.
1257 mTouchState.copyFrom(mTempTouchState);
Jeff Browna665ca82010-09-08 11:49:43 -07001258 } else {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001259#if DEBUG_FOCUS
1260 LOGD("Not updating touch focus because injection was denied.");
1261#endif
Jeff Browna665ca82010-09-08 11:49:43 -07001262 }
1263
1264Unresponsive:
Jeff Brown53a415e2010-09-15 15:18:56 -07001265 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1266 updateDispatchStatisticsLocked(currentTime, entry,
1267 injectionResult, timeSpentWaitingForApplication);
Jeff Browna665ca82010-09-08 11:49:43 -07001268#if DEBUG_FOCUS
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001269 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1270 "timeSpentWaitingForApplication=%0.1fms",
Jeff Brown53a415e2010-09-15 15:18:56 -07001271 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Browna665ca82010-09-08 11:49:43 -07001272#endif
1273 return injectionResult;
1274}
1275
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001276void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags,
1277 BitSet32 pointerIds) {
Jeff Browna665ca82010-09-08 11:49:43 -07001278 mCurrentInputTargets.push();
1279
1280 InputTarget& target = mCurrentInputTargets.editTop();
1281 target.inputChannel = window->inputChannel;
1282 target.flags = targetFlags;
Jeff Browna665ca82010-09-08 11:49:43 -07001283 target.xOffset = - window->frameLeft;
1284 target.yOffset = - window->frameTop;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001285 target.windowType = window->layoutParamsType;
1286 target.pointerIds = pointerIds;
Jeff Browna665ca82010-09-08 11:49:43 -07001287}
1288
1289void InputDispatcher::addMonitoringTargetsLocked() {
1290 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1291 mCurrentInputTargets.push();
1292
1293 InputTarget& target = mCurrentInputTargets.editTop();
1294 target.inputChannel = mMonitoringChannels[i];
1295 target.flags = 0;
Jeff Browna665ca82010-09-08 11:49:43 -07001296 target.xOffset = 0;
1297 target.yOffset = 0;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001298 target.windowType = InputWindow::TYPE_SYSTEM_OVERLAY;
Jeff Browna665ca82010-09-08 11:49:43 -07001299 }
1300}
1301
1302bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001303 const InjectionState* injectionState) {
1304 if (injectionState
1305 && injectionState->injectorUid > 0
1306 && (window == NULL || window->ownerUid != injectionState->injectorUid)) {
1307 bool result = mPolicy->checkInjectEventsPermissionNonReentrant(
1308 injectionState->injectorPid, injectionState->injectorUid);
Jeff Browna665ca82010-09-08 11:49:43 -07001309 if (! result) {
1310 if (window) {
1311 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1312 "with input channel %s owned by uid %d",
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001313 injectionState->injectorPid, injectionState->injectorUid,
1314 window->inputChannel->getName().string(),
Jeff Browna665ca82010-09-08 11:49:43 -07001315 window->ownerUid);
1316 } else {
1317 LOGW("Permission denied: injecting event from pid %d uid %d",
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001318 injectionState->injectorPid, injectionState->injectorUid);
Jeff Browna665ca82010-09-08 11:49:43 -07001319 }
1320 return false;
1321 }
1322 }
1323 return true;
1324}
1325
1326bool InputDispatcher::isWindowObscuredLocked(const InputWindow* window) {
1327 size_t numWindows = mWindows.size();
1328 for (size_t i = 0; i < numWindows; i++) {
1329 const InputWindow* other = & mWindows.itemAt(i);
1330 if (other == window) {
1331 break;
1332 }
1333 if (other->visible && window->visibleFrameIntersects(other)) {
1334 return true;
1335 }
1336 }
1337 return false;
1338}
1339
Jeff Brown53a415e2010-09-15 15:18:56 -07001340bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1341 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1342 if (connectionIndex >= 0) {
1343 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1344 return connection->outboundQueue.isEmpty();
1345 } else {
1346 return true;
1347 }
1348}
1349
1350String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1351 const InputWindow* window) {
1352 if (application) {
1353 if (window) {
1354 String8 label(application->name);
1355 label.append(" - ");
1356 label.append(window->name);
1357 return label;
1358 } else {
1359 return application->name;
1360 }
1361 } else if (window) {
1362 return window->name;
1363 } else {
1364 return String8("<unknown application or window>");
1365 }
1366}
1367
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001368bool InputDispatcher::shouldPokeUserActivityForCurrentInputTargetsLocked() {
1369 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1370 if (mCurrentInputTargets[i].windowType == InputWindow::TYPE_KEYGUARD) {
1371 return false;
1372 }
1373 }
1374 return true;
1375}
1376
1377void InputDispatcher::pokeUserActivityLocked(nsecs_t eventTime, int32_t eventType) {
Jeff Browna665ca82010-09-08 11:49:43 -07001378 CommandEntry* commandEntry = postCommandLocked(
1379 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1380 commandEntry->eventTime = eventTime;
Jeff Browna665ca82010-09-08 11:49:43 -07001381 commandEntry->userActivityEventType = eventType;
1382}
1383
Jeff Brown51d45a72010-06-17 20:52:56 -07001384void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1385 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Browne839a582010-04-22 18:58:52 -07001386 bool resumeWithAppendedMotionSample) {
1387#if DEBUG_DISPATCH_CYCLE
Jeff Brown53a415e2010-09-15 15:18:56 -07001388 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001389 "xOffset=%f, yOffset=%f, "
1390 "windowType=%d, pointerIds=0x%x, "
1391 "resumeWithAppendedMotionSample=%s",
Jeff Brown53a415e2010-09-15 15:18:56 -07001392 connection->getInputChannelName(), inputTarget->flags,
Jeff Browne839a582010-04-22 18:58:52 -07001393 inputTarget->xOffset, inputTarget->yOffset,
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001394 inputTarget->windowType, inputTarget->pointerIds.value,
Jeff Browna665ca82010-09-08 11:49:43 -07001395 toString(resumeWithAppendedMotionSample));
Jeff Browne839a582010-04-22 18:58:52 -07001396#endif
1397
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001398 // Make sure we are never called for streaming when splitting across multiple windows.
1399 bool isSplit = inputTarget->flags & InputTarget::FLAG_SPLIT;
1400 assert(! (resumeWithAppendedMotionSample && isSplit));
1401
Jeff Browne839a582010-04-22 18:58:52 -07001402 // Skip this event if the connection status is not normal.
Jeff Brown53a415e2010-09-15 15:18:56 -07001403 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Browne839a582010-04-22 18:58:52 -07001404 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Browna665ca82010-09-08 11:49:43 -07001405 LOGW("channel '%s' ~ Dropping event because the channel status is %s",
1406 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Browne839a582010-04-22 18:58:52 -07001407 return;
1408 }
1409
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001410 // Split a motion event if needed.
1411 if (isSplit) {
1412 assert(eventEntry->type == EventEntry::TYPE_MOTION);
1413
1414 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1415 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1416 MotionEntry* splitMotionEntry = splitMotionEvent(
1417 originalMotionEntry, inputTarget->pointerIds);
1418#if DEBUG_FOCUS
1419 LOGD("channel '%s' ~ Split motion event.",
1420 connection->getInputChannelName());
1421 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1422#endif
1423 eventEntry = splitMotionEntry;
1424 }
1425 }
1426
Jeff Browne839a582010-04-22 18:58:52 -07001427 // Resume the dispatch cycle with a freshly appended motion sample.
1428 // First we check that the last dispatch entry in the outbound queue is for the same
1429 // motion event to which we appended the motion sample. If we find such a dispatch
1430 // entry, and if it is currently in progress then we try to stream the new sample.
1431 bool wasEmpty = connection->outboundQueue.isEmpty();
1432
1433 if (! wasEmpty && resumeWithAppendedMotionSample) {
1434 DispatchEntry* motionEventDispatchEntry =
1435 connection->findQueuedDispatchEntryForEvent(eventEntry);
1436 if (motionEventDispatchEntry) {
1437 // If the dispatch entry is not in progress, then we must be busy dispatching an
1438 // earlier event. Not a problem, the motion event is on the outbound queue and will
1439 // be dispatched later.
1440 if (! motionEventDispatchEntry->inProgress) {
1441#if DEBUG_BATCHING
1442 LOGD("channel '%s' ~ Not streaming because the motion event has "
1443 "not yet been dispatched. "
1444 "(Waiting for earlier events to be consumed.)",
1445 connection->getInputChannelName());
1446#endif
1447 return;
1448 }
1449
1450 // If the dispatch entry is in progress but it already has a tail of pending
1451 // motion samples, then it must mean that the shared memory buffer filled up.
1452 // Not a problem, when this dispatch cycle is finished, we will eventually start
1453 // a new dispatch cycle to process the tail and that tail includes the newly
1454 // appended motion sample.
1455 if (motionEventDispatchEntry->tailMotionSample) {
1456#if DEBUG_BATCHING
1457 LOGD("channel '%s' ~ Not streaming because no new samples can "
1458 "be appended to the motion event in this dispatch cycle. "
1459 "(Waiting for next dispatch cycle to start.)",
1460 connection->getInputChannelName());
1461#endif
1462 return;
1463 }
1464
1465 // The dispatch entry is in progress and is still potentially open for streaming.
1466 // Try to stream the new motion sample. This might fail if the consumer has already
1467 // consumed the motion event (or if the channel is broken).
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001468 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1469 MotionSample* appendedMotionSample = motionEntry->lastSample;
Jeff Browne839a582010-04-22 18:58:52 -07001470 status_t status = connection->inputPublisher.appendMotionSample(
1471 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1472 if (status == OK) {
1473#if DEBUG_BATCHING
1474 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1475 connection->getInputChannelName());
1476#endif
1477 return;
1478 }
1479
1480#if DEBUG_BATCHING
1481 if (status == NO_MEMORY) {
1482 LOGD("channel '%s' ~ Could not append motion sample to currently "
1483 "dispatched move event because the shared memory buffer is full. "
1484 "(Waiting for next dispatch cycle to start.)",
1485 connection->getInputChannelName());
1486 } else if (status == status_t(FAILED_TRANSACTION)) {
1487 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown50de30a2010-06-22 01:27:15 -07001488 "dispatched move event because the event has already been consumed. "
Jeff Browne839a582010-04-22 18:58:52 -07001489 "(Waiting for next dispatch cycle to start.)",
1490 connection->getInputChannelName());
1491 } else {
1492 LOGD("channel '%s' ~ Could not append motion sample to currently "
1493 "dispatched move event due to an error, status=%d. "
1494 "(Waiting for next dispatch cycle to start.)",
1495 connection->getInputChannelName(), status);
1496 }
1497#endif
1498 // Failed to stream. Start a new tail of pending motion samples to dispatch
1499 // in the next cycle.
1500 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1501 return;
1502 }
1503 }
1504
Jeff Browna665ca82010-09-08 11:49:43 -07001505 // Bring the input state back in line with reality in case it drifted off during an ANR.
1506 if (connection->inputState.isOutOfSync()) {
1507 mTempCancelationEvents.clear();
1508 connection->inputState.synthesizeCancelationEvents(& mAllocator, mTempCancelationEvents);
1509 connection->inputState.resetOutOfSync();
1510
1511 if (! mTempCancelationEvents.isEmpty()) {
1512 LOGI("channel '%s' ~ Generated %d cancelation events to bring channel back in sync "
1513 "with reality.",
1514 connection->getInputChannelName(), mTempCancelationEvents.size());
1515
1516 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
1517 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
1518 switch (cancelationEventEntry->type) {
1519 case EventEntry::TYPE_KEY:
1520 logOutboundKeyDetailsLocked(" ",
1521 static_cast<KeyEntry*>(cancelationEventEntry));
1522 break;
1523 case EventEntry::TYPE_MOTION:
1524 logOutboundMotionDetailsLocked(" ",
1525 static_cast<MotionEntry*>(cancelationEventEntry));
1526 break;
1527 }
1528
1529 DispatchEntry* cancelationDispatchEntry =
1530 mAllocator.obtainDispatchEntry(cancelationEventEntry,
Jeff Brown53a415e2010-09-15 15:18:56 -07001531 0, inputTarget->xOffset, inputTarget->yOffset); // increments ref
Jeff Browna665ca82010-09-08 11:49:43 -07001532 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
1533
1534 mAllocator.releaseEventEntry(cancelationEventEntry);
1535 }
1536 }
1537 }
1538
Jeff Browne839a582010-04-22 18:58:52 -07001539 // This is a new event.
1540 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Browna665ca82010-09-08 11:49:43 -07001541 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Brown53a415e2010-09-15 15:18:56 -07001542 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset);
1543 if (dispatchEntry->hasForegroundTarget()) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001544 incrementPendingForegroundDispatchesLocked(eventEntry);
Jeff Brownf67c53e2010-07-28 15:48:59 -07001545 }
1546
Jeff Browne839a582010-04-22 18:58:52 -07001547 // Handle the case where we could not stream a new motion sample because the consumer has
1548 // already consumed the motion event (otherwise the corresponding dispatch entry would
1549 // still be in the outbound queue for this connection). We set the head motion sample
1550 // to the list starting with the newly appended motion sample.
1551 if (resumeWithAppendedMotionSample) {
1552#if DEBUG_BATCHING
1553 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1554 "that cannot be streamed because the motion event has already been consumed.",
1555 connection->getInputChannelName());
1556#endif
1557 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1558 dispatchEntry->headMotionSample = appendedMotionSample;
1559 }
1560
1561 // Enqueue the dispatch entry.
1562 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1563
1564 // If the outbound queue was previously empty, start the dispatch cycle going.
1565 if (wasEmpty) {
Jeff Brown51d45a72010-06-17 20:52:56 -07001566 activateConnectionLocked(connection.get());
Jeff Brown53a415e2010-09-15 15:18:56 -07001567 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001568 }
1569}
1570
Jeff Brown51d45a72010-06-17 20:52:56 -07001571void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown53a415e2010-09-15 15:18:56 -07001572 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001573#if DEBUG_DISPATCH_CYCLE
1574 LOGD("channel '%s' ~ startDispatchCycle",
1575 connection->getInputChannelName());
1576#endif
1577
1578 assert(connection->status == Connection::STATUS_NORMAL);
1579 assert(! connection->outboundQueue.isEmpty());
1580
Jeff Browna665ca82010-09-08 11:49:43 -07001581 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Browne839a582010-04-22 18:58:52 -07001582 assert(! dispatchEntry->inProgress);
1583
Jeff Browna665ca82010-09-08 11:49:43 -07001584 // Mark the dispatch entry as in progress.
1585 dispatchEntry->inProgress = true;
1586
1587 // Update the connection's input state.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001588 EventEntry* eventEntry = dispatchEntry->eventEntry;
1589 InputState::Consistency consistency = connection->inputState.trackEvent(eventEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001590
1591#if FILTER_INPUT_EVENTS
1592 // Filter out inconsistent sequences of input events.
1593 // The input system may drop or inject events in a way that could violate implicit
1594 // invariants on input state and potentially cause an application to crash
1595 // or think that a key or pointer is stuck down. Technically we make no guarantees
1596 // of consistency but it would be nice to improve on this where possible.
1597 // XXX: This code is a proof of concept only. Not ready for prime time.
1598 if (consistency == InputState::TOLERABLE) {
1599#if DEBUG_DISPATCH_CYCLE
1600 LOGD("channel '%s' ~ Sending an event that is inconsistent with the connection's "
1601 "current input state but that is likely to be tolerated by the application.",
1602 connection->getInputChannelName());
1603#endif
1604 } else if (consistency == InputState::BROKEN) {
1605 LOGI("channel '%s' ~ Dropping an event that is inconsistent with the connection's "
1606 "current input state and that is likely to cause the application to crash.",
1607 connection->getInputChannelName());
1608 startNextDispatchCycleLocked(currentTime, connection);
1609 return;
1610 }
1611#endif
Jeff Browne839a582010-04-22 18:58:52 -07001612
1613 // Publish the event.
1614 status_t status;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001615 switch (eventEntry->type) {
Jeff Browne839a582010-04-22 18:58:52 -07001616 case EventEntry::TYPE_KEY: {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001617 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001618
1619 // Apply target flags.
1620 int32_t action = keyEntry->action;
1621 int32_t flags = keyEntry->flags;
Jeff Browne839a582010-04-22 18:58:52 -07001622
1623 // Publish the key event.
Jeff Brown5c1ed842010-07-14 18:48:53 -07001624 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Browne839a582010-04-22 18:58:52 -07001625 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1626 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1627 keyEntry->eventTime);
1628
1629 if (status) {
1630 LOGE("channel '%s' ~ Could not publish key event, "
1631 "status=%d", connection->getInputChannelName(), status);
1632 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1633 return;
1634 }
1635 break;
1636 }
1637
1638 case EventEntry::TYPE_MOTION: {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001639 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001640
1641 // Apply target flags.
1642 int32_t action = motionEntry->action;
Jeff Brownaf30ff62010-09-01 17:01:00 -07001643 int32_t flags = motionEntry->flags;
Jeff Browne839a582010-04-22 18:58:52 -07001644 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brown5c1ed842010-07-14 18:48:53 -07001645 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Browne839a582010-04-22 18:58:52 -07001646 }
Jeff Brownaf30ff62010-09-01 17:01:00 -07001647 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1648 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1649 }
Jeff Browne839a582010-04-22 18:58:52 -07001650
1651 // If headMotionSample is non-NULL, then it points to the first new sample that we
1652 // were unable to dispatch during the previous cycle so we resume dispatching from
1653 // that point in the list of motion samples.
1654 // Otherwise, we just start from the first sample of the motion event.
1655 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1656 if (! firstMotionSample) {
1657 firstMotionSample = & motionEntry->firstSample;
1658 }
1659
Jeff Brownf26db0d2010-07-16 17:21:06 -07001660 // Set the X and Y offset depending on the input source.
1661 float xOffset, yOffset;
1662 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1663 xOffset = dispatchEntry->xOffset;
1664 yOffset = dispatchEntry->yOffset;
1665 } else {
1666 xOffset = 0.0f;
1667 yOffset = 0.0f;
1668 }
1669
Jeff Browne839a582010-04-22 18:58:52 -07001670 // Publish the motion event and the first motion sample.
1671 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brownaf30ff62010-09-01 17:01:00 -07001672 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownf26db0d2010-07-16 17:21:06 -07001673 xOffset, yOffset,
Jeff Browne839a582010-04-22 18:58:52 -07001674 motionEntry->xPrecision, motionEntry->yPrecision,
1675 motionEntry->downTime, firstMotionSample->eventTime,
1676 motionEntry->pointerCount, motionEntry->pointerIds,
1677 firstMotionSample->pointerCoords);
1678
1679 if (status) {
1680 LOGE("channel '%s' ~ Could not publish motion event, "
1681 "status=%d", connection->getInputChannelName(), status);
1682 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1683 return;
1684 }
1685
1686 // Append additional motion samples.
1687 MotionSample* nextMotionSample = firstMotionSample->next;
1688 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1689 status = connection->inputPublisher.appendMotionSample(
1690 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
1691 if (status == NO_MEMORY) {
1692#if DEBUG_DISPATCH_CYCLE
1693 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1694 "be sent in the next dispatch cycle.",
1695 connection->getInputChannelName());
1696#endif
1697 break;
1698 }
1699 if (status != OK) {
1700 LOGE("channel '%s' ~ Could not append motion sample "
1701 "for a reason other than out of memory, status=%d",
1702 connection->getInputChannelName(), status);
1703 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1704 return;
1705 }
1706 }
1707
1708 // Remember the next motion sample that we could not dispatch, in case we ran out
1709 // of space in the shared memory buffer.
1710 dispatchEntry->tailMotionSample = nextMotionSample;
1711 break;
1712 }
1713
1714 default: {
1715 assert(false);
1716 }
1717 }
1718
1719 // Send the dispatch signal.
1720 status = connection->inputPublisher.sendDispatchSignal();
1721 if (status) {
1722 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1723 connection->getInputChannelName(), status);
1724 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1725 return;
1726 }
1727
1728 // Record information about the newly started dispatch cycle.
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001729 connection->lastEventTime = eventEntry->eventTime;
Jeff Browne839a582010-04-22 18:58:52 -07001730 connection->lastDispatchTime = currentTime;
1731
Jeff Browne839a582010-04-22 18:58:52 -07001732 // Notify other system components.
1733 onDispatchCycleStartedLocked(currentTime, connection);
1734}
1735
Jeff Brown51d45a72010-06-17 20:52:56 -07001736void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
1737 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001738#if DEBUG_DISPATCH_CYCLE
Jeff Brown54bc2812010-06-15 01:31:58 -07001739 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Browne839a582010-04-22 18:58:52 -07001740 "%01.1fms since dispatch",
1741 connection->getInputChannelName(),
1742 connection->getEventLatencyMillis(currentTime),
1743 connection->getDispatchLatencyMillis(currentTime));
1744#endif
1745
Jeff Brown54bc2812010-06-15 01:31:58 -07001746 if (connection->status == Connection::STATUS_BROKEN
1747 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Browne839a582010-04-22 18:58:52 -07001748 return;
1749 }
1750
Jeff Brown53a415e2010-09-15 15:18:56 -07001751 // Notify other system components.
1752 onDispatchCycleFinishedLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001753
1754 // Reset the publisher since the event has been consumed.
1755 // We do this now so that the publisher can release some of its internal resources
1756 // while waiting for the next dispatch cycle to begin.
1757 status_t status = connection->inputPublisher.reset();
1758 if (status) {
1759 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1760 connection->getInputChannelName(), status);
1761 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1762 return;
1763 }
1764
Jeff Browna665ca82010-09-08 11:49:43 -07001765 startNextDispatchCycleLocked(currentTime, connection);
1766}
1767
1768void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1769 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001770 // Start the next dispatch cycle for this connection.
1771 while (! connection->outboundQueue.isEmpty()) {
Jeff Browna665ca82010-09-08 11:49:43 -07001772 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Browne839a582010-04-22 18:58:52 -07001773 if (dispatchEntry->inProgress) {
1774 // Finish or resume current event in progress.
1775 if (dispatchEntry->tailMotionSample) {
1776 // We have a tail of undispatched motion samples.
1777 // Reuse the same DispatchEntry and start a new cycle.
1778 dispatchEntry->inProgress = false;
1779 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1780 dispatchEntry->tailMotionSample = NULL;
Jeff Brown53a415e2010-09-15 15:18:56 -07001781 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001782 return;
1783 }
1784 // Finished.
1785 connection->outboundQueue.dequeueAtHead();
Jeff Brown53a415e2010-09-15 15:18:56 -07001786 if (dispatchEntry->hasForegroundTarget()) {
1787 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownf67c53e2010-07-28 15:48:59 -07001788 }
Jeff Browne839a582010-04-22 18:58:52 -07001789 mAllocator.releaseDispatchEntry(dispatchEntry);
1790 } else {
1791 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown53a415e2010-09-15 15:18:56 -07001792 // progress event, which means we actually aborted it.
Jeff Browne839a582010-04-22 18:58:52 -07001793 // So just start the next event for this connection.
Jeff Brown53a415e2010-09-15 15:18:56 -07001794 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001795 return;
1796 }
1797 }
1798
1799 // Outbound queue is empty, deactivate the connection.
Jeff Brown51d45a72010-06-17 20:52:56 -07001800 deactivateConnectionLocked(connection.get());
Jeff Browne839a582010-04-22 18:58:52 -07001801}
1802
Jeff Brown51d45a72010-06-17 20:52:56 -07001803void InputDispatcher::abortDispatchCycleLocked(nsecs_t currentTime,
1804 const sp<Connection>& connection, bool broken) {
Jeff Browne839a582010-04-22 18:58:52 -07001805#if DEBUG_DISPATCH_CYCLE
Jeff Brown54bc2812010-06-15 01:31:58 -07001806 LOGD("channel '%s' ~ abortDispatchCycle - broken=%s",
Jeff Browna665ca82010-09-08 11:49:43 -07001807 connection->getInputChannelName(), toString(broken));
Jeff Browne839a582010-04-22 18:58:52 -07001808#endif
1809
Jeff Browna665ca82010-09-08 11:49:43 -07001810 // Input state will no longer be realistic.
1811 connection->inputState.setOutOfSync();
Jeff Browne839a582010-04-22 18:58:52 -07001812
Jeff Browna665ca82010-09-08 11:49:43 -07001813 // Clear the outbound queue.
Jeff Brown53a415e2010-09-15 15:18:56 -07001814 drainOutboundQueueLocked(connection.get());
Jeff Browne839a582010-04-22 18:58:52 -07001815
1816 // Handle the case where the connection appears to be unrecoverably broken.
Jeff Brown54bc2812010-06-15 01:31:58 -07001817 // Ignore already broken or zombie connections.
Jeff Browne839a582010-04-22 18:58:52 -07001818 if (broken) {
Jeff Brown53a415e2010-09-15 15:18:56 -07001819 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brown54bc2812010-06-15 01:31:58 -07001820 connection->status = Connection::STATUS_BROKEN;
Jeff Browne839a582010-04-22 18:58:52 -07001821
Jeff Brown54bc2812010-06-15 01:31:58 -07001822 // Notify other system components.
1823 onDispatchCycleBrokenLocked(currentTime, connection);
1824 }
Jeff Browne839a582010-04-22 18:58:52 -07001825 }
Jeff Browne839a582010-04-22 18:58:52 -07001826}
1827
Jeff Brown53a415e2010-09-15 15:18:56 -07001828void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
1829 while (! connection->outboundQueue.isEmpty()) {
1830 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
1831 if (dispatchEntry->hasForegroundTarget()) {
1832 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001833 }
1834 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001835 }
1836
Jeff Brown53a415e2010-09-15 15:18:56 -07001837 deactivateConnectionLocked(connection);
Jeff Browna665ca82010-09-08 11:49:43 -07001838}
1839
Jeff Brown59abe7e2010-09-13 23:17:30 -07001840int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Browne839a582010-04-22 18:58:52 -07001841 InputDispatcher* d = static_cast<InputDispatcher*>(data);
1842
1843 { // acquire lock
1844 AutoMutex _l(d->mLock);
1845
1846 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
1847 if (connectionIndex < 0) {
1848 LOGE("Received spurious receive callback for unknown input channel. "
1849 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001850 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001851 }
1852
Jeff Brown51d45a72010-06-17 20:52:56 -07001853 nsecs_t currentTime = now();
Jeff Browne839a582010-04-22 18:58:52 -07001854
1855 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001856 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Browne839a582010-04-22 18:58:52 -07001857 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
1858 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown51d45a72010-06-17 20:52:56 -07001859 d->abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07001860 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001861 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001862 }
1863
Jeff Brown59abe7e2010-09-13 23:17:30 -07001864 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Browne839a582010-04-22 18:58:52 -07001865 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
1866 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001867 return 1;
Jeff Browne839a582010-04-22 18:58:52 -07001868 }
1869
1870 status_t status = connection->inputPublisher.receiveFinishedSignal();
1871 if (status) {
1872 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
1873 connection->getInputChannelName(), status);
Jeff Brown51d45a72010-06-17 20:52:56 -07001874 d->abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07001875 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001876 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001877 }
1878
Jeff Brown51d45a72010-06-17 20:52:56 -07001879 d->finishDispatchCycleLocked(currentTime, connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07001880 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001881 return 1;
Jeff Browne839a582010-04-22 18:58:52 -07001882 } // release lock
1883}
1884
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001885InputDispatcher::MotionEntry*
1886InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
1887 assert(pointerIds.value != 0);
1888
1889 uint32_t splitPointerIndexMap[MAX_POINTERS];
1890 int32_t splitPointerIds[MAX_POINTERS];
1891 PointerCoords splitPointerCoords[MAX_POINTERS];
1892
1893 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
1894 uint32_t splitPointerCount = 0;
1895
1896 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
1897 originalPointerIndex++) {
1898 int32_t pointerId = uint32_t(originalMotionEntry->pointerIds[originalPointerIndex]);
1899 if (pointerIds.hasBit(pointerId)) {
1900 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
1901 splitPointerIds[splitPointerCount] = pointerId;
1902 splitPointerCoords[splitPointerCount] =
1903 originalMotionEntry->firstSample.pointerCoords[originalPointerIndex];
1904 splitPointerCount += 1;
1905 }
1906 }
1907 assert(splitPointerCount == pointerIds.count());
1908
1909 int32_t action = originalMotionEntry->action;
1910 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1911 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
1912 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1913 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
1914 int32_t pointerId = originalMotionEntry->pointerIds[originalPointerIndex];
1915 if (pointerIds.hasBit(pointerId)) {
1916 if (pointerIds.count() == 1) {
1917 // The first/last pointer went down/up.
1918 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
1919 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Jeff Brownffb16d62010-09-27 16:35:11 -07001920 } else {
1921 // A secondary pointer went down/up.
1922 uint32_t splitPointerIndex = 0;
1923 while (pointerId != splitPointerIds[splitPointerIndex]) {
1924 splitPointerIndex += 1;
1925 }
1926 action = maskedAction | (splitPointerIndex
1927 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001928 }
1929 } else {
1930 // An unrelated pointer changed.
1931 action = AMOTION_EVENT_ACTION_MOVE;
1932 }
1933 }
1934
1935 MotionEntry* splitMotionEntry = mAllocator.obtainMotionEntry(
1936 originalMotionEntry->eventTime,
1937 originalMotionEntry->deviceId,
1938 originalMotionEntry->source,
1939 originalMotionEntry->policyFlags,
1940 action,
1941 originalMotionEntry->flags,
1942 originalMotionEntry->metaState,
1943 originalMotionEntry->edgeFlags,
1944 originalMotionEntry->xPrecision,
1945 originalMotionEntry->yPrecision,
1946 originalMotionEntry->downTime,
1947 splitPointerCount, splitPointerIds, splitPointerCoords);
1948
1949 for (MotionSample* originalMotionSample = originalMotionEntry->firstSample.next;
1950 originalMotionSample != NULL; originalMotionSample = originalMotionSample->next) {
1951 for (uint32_t splitPointerIndex = 0; splitPointerIndex < splitPointerCount;
1952 splitPointerIndex++) {
1953 uint32_t originalPointerIndex = splitPointerIndexMap[splitPointerIndex];
1954 splitPointerCoords[splitPointerIndex] =
1955 originalMotionSample->pointerCoords[originalPointerIndex];
1956 }
1957
1958 mAllocator.appendMotionSample(splitMotionEntry, originalMotionSample->eventTime,
1959 splitPointerCoords);
1960 }
1961
1962 return splitMotionEntry;
1963}
1964
Jeff Brown54bc2812010-06-15 01:31:58 -07001965void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Browne839a582010-04-22 18:58:52 -07001966#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown54bc2812010-06-15 01:31:58 -07001967 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Browne839a582010-04-22 18:58:52 -07001968#endif
1969
Jeff Browna665ca82010-09-08 11:49:43 -07001970 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07001971 { // acquire lock
1972 AutoMutex _l(mLock);
1973
Jeff Brown51d45a72010-06-17 20:52:56 -07001974 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Browna665ca82010-09-08 11:49:43 -07001975 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001976 } // release lock
1977
Jeff Browna665ca82010-09-08 11:49:43 -07001978 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07001979 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07001980 }
1981}
1982
Jeff Brown5c1ed842010-07-14 18:48:53 -07001983void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -07001984 uint32_t policyFlags, int32_t action, int32_t flags,
1985 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
1986#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown5c1ed842010-07-14 18:48:53 -07001987 LOGD("notifyKey - eventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Browne839a582010-04-22 18:58:52 -07001988 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brown5c1ed842010-07-14 18:48:53 -07001989 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Browne839a582010-04-22 18:58:52 -07001990 keyCode, scanCode, metaState, downTime);
1991#endif
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07001992 if (! validateKeyEvent(action)) {
1993 return;
1994 }
Jeff Browne839a582010-04-22 18:58:52 -07001995
Jeff Browna665ca82010-09-08 11:49:43 -07001996 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07001997 { // acquire lock
1998 AutoMutex _l(mLock);
1999
Jeff Brown51d45a72010-06-17 20:52:56 -07002000 int32_t repeatCount = 0;
2001 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -07002002 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown51d45a72010-06-17 20:52:56 -07002003 metaState, repeatCount, downTime);
Jeff Browne839a582010-04-22 18:58:52 -07002004
Jeff Browna665ca82010-09-08 11:49:43 -07002005 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07002006 } // release lock
2007
Jeff Browna665ca82010-09-08 11:49:43 -07002008 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07002009 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002010 }
2011}
2012
Jeff Brown5c1ed842010-07-14 18:48:53 -07002013void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002014 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Browne839a582010-04-22 18:58:52 -07002015 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
2016 float xPrecision, float yPrecision, nsecs_t downTime) {
2017#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown5c1ed842010-07-14 18:48:53 -07002018 LOGD("notifyMotion - eventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, "
Jeff Brownaf30ff62010-09-01 17:01:00 -07002019 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
2020 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2021 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Browne839a582010-04-22 18:58:52 -07002022 xPrecision, yPrecision, downTime);
2023 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown38a7fab2010-08-30 03:02:23 -07002024 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brownaf30ff62010-09-01 17:01:00 -07002025 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown38a7fab2010-08-30 03:02:23 -07002026 "orientation=%f",
Jeff Browne839a582010-04-22 18:58:52 -07002027 i, pointerIds[i], pointerCoords[i].x, pointerCoords[i].y,
Jeff Brown38a7fab2010-08-30 03:02:23 -07002028 pointerCoords[i].pressure, pointerCoords[i].size,
2029 pointerCoords[i].touchMajor, pointerCoords[i].touchMinor,
2030 pointerCoords[i].toolMajor, pointerCoords[i].toolMinor,
2031 pointerCoords[i].orientation);
Jeff Browne839a582010-04-22 18:58:52 -07002032 }
2033#endif
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002034 if (! validateMotionEvent(action, pointerCount, pointerIds)) {
2035 return;
2036 }
Jeff Browne839a582010-04-22 18:58:52 -07002037
Jeff Browna665ca82010-09-08 11:49:43 -07002038 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07002039 { // acquire lock
2040 AutoMutex _l(mLock);
2041
2042 // Attempt batching and streaming of move events.
Jeff Brown5c1ed842010-07-14 18:48:53 -07002043 if (action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Browne839a582010-04-22 18:58:52 -07002044 // BATCHING CASE
2045 //
2046 // Try to append a move sample to the tail of the inbound queue for this device.
2047 // Give up if we encounter a non-move motion event for this device since that
2048 // means we cannot append any new samples until a new motion event has started.
Jeff Browna665ca82010-09-08 11:49:43 -07002049 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
2050 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Browne839a582010-04-22 18:58:52 -07002051 if (entry->type != EventEntry::TYPE_MOTION) {
2052 // Keep looking for motion events.
2053 continue;
2054 }
2055
2056 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
2057 if (motionEntry->deviceId != deviceId) {
2058 // Keep looking for this device.
2059 continue;
2060 }
2061
Jeff Brown5c1ed842010-07-14 18:48:53 -07002062 if (motionEntry->action != AMOTION_EVENT_ACTION_MOVE
Jeff Brown51d45a72010-06-17 20:52:56 -07002063 || motionEntry->pointerCount != pointerCount
2064 || motionEntry->isInjected()) {
Jeff Browne839a582010-04-22 18:58:52 -07002065 // Last motion event in the queue for this device is not compatible for
2066 // appending new samples. Stop here.
2067 goto NoBatchingOrStreaming;
2068 }
2069
2070 // The last motion event is a move and is compatible for appending.
Jeff Brown54bc2812010-06-15 01:31:58 -07002071 // Do the batching magic.
Jeff Brown51d45a72010-06-17 20:52:56 -07002072 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Browne839a582010-04-22 18:58:52 -07002073#if DEBUG_BATCHING
2074 LOGD("Appended motion sample onto batch for most recent "
2075 "motion event for this device in the inbound queue.");
2076#endif
Jeff Brown54bc2812010-06-15 01:31:58 -07002077 return; // done!
Jeff Browne839a582010-04-22 18:58:52 -07002078 }
2079
2080 // STREAMING CASE
2081 //
2082 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown53a415e2010-09-15 15:18:56 -07002083 // Search the outbound queue for the current foreground targets to find a dispatched
2084 // motion event that is still in progress. If found, then, appen the new sample to
2085 // that event and push it out to all current targets. The logic in
2086 // prepareDispatchCycleLocked takes care of the case where some targets may
2087 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown54bc2812010-06-15 01:31:58 -07002088 if (mCurrentInputTargetsValid) {
Jeff Brown53a415e2010-09-15 15:18:56 -07002089 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
2090 const InputTarget& inputTarget = mCurrentInputTargets[i];
2091 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
2092 // Skip non-foreground targets. We only want to stream if there is at
2093 // least one foreground target whose dispatch is still in progress.
2094 continue;
Jeff Browne839a582010-04-22 18:58:52 -07002095 }
Jeff Brown53a415e2010-09-15 15:18:56 -07002096
2097 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
2098 if (connectionIndex < 0) {
2099 // Connection must no longer be valid.
2100 continue;
2101 }
2102
2103 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2104 if (connection->outboundQueue.isEmpty()) {
2105 // This foreground target has an empty outbound queue.
2106 continue;
2107 }
2108
2109 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
2110 if (! dispatchEntry->inProgress
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002111 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION
2112 || dispatchEntry->isSplit()) {
2113 // No motion event is being dispatched, or it is being split across
2114 // windows in which case we cannot stream.
Jeff Brown53a415e2010-09-15 15:18:56 -07002115 continue;
2116 }
2117
2118 MotionEntry* motionEntry = static_cast<MotionEntry*>(
2119 dispatchEntry->eventEntry);
2120 if (motionEntry->action != AMOTION_EVENT_ACTION_MOVE
2121 || motionEntry->deviceId != deviceId
2122 || motionEntry->pointerCount != pointerCount
2123 || motionEntry->isInjected()) {
2124 // The motion event is not compatible with this move.
2125 continue;
2126 }
2127
2128 // Hurray! This foreground target is currently dispatching a move event
2129 // that we can stream onto. Append the motion sample and resume dispatch.
2130 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
2131#if DEBUG_BATCHING
2132 LOGD("Appended motion sample onto batch for most recently dispatched "
2133 "motion event for this device in the outbound queues. "
2134 "Attempting to stream the motion sample.");
2135#endif
2136 nsecs_t currentTime = now();
2137 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
2138 true /*resumeWithAppendedMotionSample*/);
2139
2140 runCommandsLockedInterruptible();
2141 return; // done!
Jeff Browne839a582010-04-22 18:58:52 -07002142 }
2143 }
2144
2145NoBatchingOrStreaming:;
2146 }
2147
2148 // Just enqueue a new motion event.
Jeff Brown51d45a72010-06-17 20:52:56 -07002149 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002150 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown51d45a72010-06-17 20:52:56 -07002151 xPrecision, yPrecision, downTime,
2152 pointerCount, pointerIds, pointerCoords);
Jeff Browne839a582010-04-22 18:58:52 -07002153
Jeff Browna665ca82010-09-08 11:49:43 -07002154 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07002155 } // release lock
2156
Jeff Browna665ca82010-09-08 11:49:43 -07002157 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07002158 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002159 }
2160}
2161
Jeff Brown51d45a72010-06-17 20:52:56 -07002162int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brownf67c53e2010-07-28 15:48:59 -07002163 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown51d45a72010-06-17 20:52:56 -07002164#if DEBUG_INBOUND_EVENT_DETAILS
2165 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brownf67c53e2010-07-28 15:48:59 -07002166 "syncMode=%d, timeoutMillis=%d",
2167 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown51d45a72010-06-17 20:52:56 -07002168#endif
2169
2170 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2171
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002172 InjectionState* injectionState;
Jeff Browna665ca82010-09-08 11:49:43 -07002173 bool needWake;
Jeff Brown51d45a72010-06-17 20:52:56 -07002174 { // acquire lock
2175 AutoMutex _l(mLock);
2176
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002177 EventEntry* injectedEntry = createEntryFromInjectedInputEventLocked(event);
Jeff Browna665ca82010-09-08 11:49:43 -07002178 if (! injectedEntry) {
2179 return INPUT_EVENT_INJECTION_FAILED;
2180 }
2181
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002182 injectionState = mAllocator.obtainInjectionState(injectorPid, injectorUid);
Jeff Brownf67c53e2010-07-28 15:48:59 -07002183 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002184 injectionState->injectionIsAsync = true;
Jeff Brownf67c53e2010-07-28 15:48:59 -07002185 }
2186
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002187 injectionState->refCount += 1;
2188 injectedEntry->injectionState = injectionState;
2189
Jeff Browna665ca82010-09-08 11:49:43 -07002190 needWake = enqueueInboundEventLocked(injectedEntry);
Jeff Brown51d45a72010-06-17 20:52:56 -07002191 } // release lock
2192
Jeff Browna665ca82010-09-08 11:49:43 -07002193 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07002194 mLooper->wake();
Jeff Brown51d45a72010-06-17 20:52:56 -07002195 }
2196
2197 int32_t injectionResult;
2198 { // acquire lock
2199 AutoMutex _l(mLock);
2200
Jeff Brownf67c53e2010-07-28 15:48:59 -07002201 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2202 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2203 } else {
2204 for (;;) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002205 injectionResult = injectionState->injectionResult;
Jeff Brownf67c53e2010-07-28 15:48:59 -07002206 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2207 break;
2208 }
Jeff Brown51d45a72010-06-17 20:52:56 -07002209
Jeff Brown51d45a72010-06-17 20:52:56 -07002210 nsecs_t remainingTimeout = endTime - now();
2211 if (remainingTimeout <= 0) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07002212#if DEBUG_INJECTION
2213 LOGD("injectInputEvent - Timed out waiting for injection result "
2214 "to become available.");
2215#endif
Jeff Brown51d45a72010-06-17 20:52:56 -07002216 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2217 break;
2218 }
2219
Jeff Brownf67c53e2010-07-28 15:48:59 -07002220 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2221 }
2222
2223 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2224 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002225 while (injectionState->pendingForegroundDispatches != 0) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07002226#if DEBUG_INJECTION
Jeff Brown53a415e2010-09-15 15:18:56 -07002227 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002228 injectionState->pendingForegroundDispatches);
Jeff Brownf67c53e2010-07-28 15:48:59 -07002229#endif
2230 nsecs_t remainingTimeout = endTime - now();
2231 if (remainingTimeout <= 0) {
2232#if DEBUG_INJECTION
Jeff Brown53a415e2010-09-15 15:18:56 -07002233 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brownf67c53e2010-07-28 15:48:59 -07002234 "dispatches to finish.");
2235#endif
2236 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2237 break;
2238 }
2239
2240 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2241 }
Jeff Brown51d45a72010-06-17 20:52:56 -07002242 }
2243 }
2244
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002245 mAllocator.releaseInjectionState(injectionState);
Jeff Brown51d45a72010-06-17 20:52:56 -07002246 } // release lock
2247
Jeff Brownf67c53e2010-07-28 15:48:59 -07002248#if DEBUG_INJECTION
2249 LOGD("injectInputEvent - Finished with result %d. "
2250 "injectorPid=%d, injectorUid=%d",
2251 injectionResult, injectorPid, injectorUid);
2252#endif
2253
Jeff Brown51d45a72010-06-17 20:52:56 -07002254 return injectionResult;
2255}
2256
2257void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002258 InjectionState* injectionState = entry->injectionState;
2259 if (injectionState) {
Jeff Brown51d45a72010-06-17 20:52:56 -07002260#if DEBUG_INJECTION
2261 LOGD("Setting input event injection result to %d. "
2262 "injectorPid=%d, injectorUid=%d",
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002263 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Jeff Brown51d45a72010-06-17 20:52:56 -07002264#endif
2265
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002266 if (injectionState->injectionIsAsync) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07002267 // Log the outcome since the injector did not wait for the injection result.
2268 switch (injectionResult) {
2269 case INPUT_EVENT_INJECTION_SUCCEEDED:
2270 LOGV("Asynchronous input event injection succeeded.");
2271 break;
2272 case INPUT_EVENT_INJECTION_FAILED:
2273 LOGW("Asynchronous input event injection failed.");
2274 break;
2275 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2276 LOGW("Asynchronous input event injection permission denied.");
2277 break;
2278 case INPUT_EVENT_INJECTION_TIMED_OUT:
2279 LOGW("Asynchronous input event injection timed out.");
2280 break;
2281 }
2282 }
2283
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002284 injectionState->injectionResult = injectionResult;
Jeff Brown51d45a72010-06-17 20:52:56 -07002285 mInjectionResultAvailableCondition.broadcast();
2286 }
2287}
2288
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002289void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2290 InjectionState* injectionState = entry->injectionState;
2291 if (injectionState) {
2292 injectionState->pendingForegroundDispatches += 1;
2293 }
2294}
2295
Jeff Brown53a415e2010-09-15 15:18:56 -07002296void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002297 InjectionState* injectionState = entry->injectionState;
2298 if (injectionState) {
2299 injectionState->pendingForegroundDispatches -= 1;
Jeff Brownf67c53e2010-07-28 15:48:59 -07002300
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002301 if (injectionState->pendingForegroundDispatches == 0) {
2302 mInjectionSyncFinishedCondition.broadcast();
2303 }
Jeff Browna665ca82010-09-08 11:49:43 -07002304 }
2305}
2306
2307InputDispatcher::EventEntry* InputDispatcher::createEntryFromInjectedInputEventLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002308 const InputEvent* event) {
2309 switch (event->getType()) {
Jeff Brown5c1ed842010-07-14 18:48:53 -07002310 case AINPUT_EVENT_TYPE_KEY: {
Jeff Brown51d45a72010-06-17 20:52:56 -07002311 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002312 if (! validateKeyEvent(keyEvent->getAction())) {
Jeff Browna665ca82010-09-08 11:49:43 -07002313 return NULL;
2314 }
2315
Jeff Brownaf30ff62010-09-01 17:01:00 -07002316 uint32_t policyFlags = POLICY_FLAG_INJECTED;
Jeff Brown51d45a72010-06-17 20:52:56 -07002317
2318 KeyEntry* keyEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
Jeff Brown5c1ed842010-07-14 18:48:53 -07002319 keyEvent->getDeviceId(), keyEvent->getSource(), policyFlags,
Jeff Brown51d45a72010-06-17 20:52:56 -07002320 keyEvent->getAction(), keyEvent->getFlags(),
2321 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2322 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2323 return keyEntry;
2324 }
2325
Jeff Brown5c1ed842010-07-14 18:48:53 -07002326 case AINPUT_EVENT_TYPE_MOTION: {
Jeff Brown51d45a72010-06-17 20:52:56 -07002327 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002328 if (! validateMotionEvent(motionEvent->getAction(),
2329 motionEvent->getPointerCount(), motionEvent->getPointerIds())) {
Jeff Browna665ca82010-09-08 11:49:43 -07002330 return NULL;
2331 }
Jeff Browna665ca82010-09-08 11:49:43 -07002332
Jeff Brownaf30ff62010-09-01 17:01:00 -07002333 uint32_t policyFlags = POLICY_FLAG_INJECTED;
Jeff Brown51d45a72010-06-17 20:52:56 -07002334
2335 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2336 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2337 size_t pointerCount = motionEvent->getPointerCount();
2338
2339 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
Jeff Brown5c1ed842010-07-14 18:48:53 -07002340 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002341 motionEvent->getAction(), motionEvent->getFlags(),
2342 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
Jeff Brown51d45a72010-06-17 20:52:56 -07002343 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2344 motionEvent->getDownTime(), uint32_t(pointerCount),
2345 motionEvent->getPointerIds(), samplePointerCoords);
2346 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2347 sampleEventTimes += 1;
2348 samplePointerCoords += pointerCount;
2349 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2350 }
2351 return motionEntry;
2352 }
2353
2354 default:
2355 assert(false);
2356 return NULL;
2357 }
2358}
2359
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002360const InputWindow* InputDispatcher::getWindowLocked(const sp<InputChannel>& inputChannel) {
2361 for (size_t i = 0; i < mWindows.size(); i++) {
2362 const InputWindow* window = & mWindows[i];
2363 if (window->inputChannel == inputChannel) {
2364 return window;
2365 }
2366 }
2367 return NULL;
2368}
2369
Jeff Browna665ca82010-09-08 11:49:43 -07002370void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2371#if DEBUG_FOCUS
2372 LOGD("setInputWindows");
2373#endif
2374 { // acquire lock
2375 AutoMutex _l(mLock);
2376
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002377 // Clear old window pointers.
Jeff Brown405a1d32010-09-16 12:31:46 -07002378 mFocusedWindow = NULL;
Jeff Browna665ca82010-09-08 11:49:43 -07002379 mWindows.clear();
Jeff Brown405a1d32010-09-16 12:31:46 -07002380
2381 // Loop over new windows and rebuild the necessary window pointers for
2382 // tracking focus and touch.
Jeff Browna665ca82010-09-08 11:49:43 -07002383 mWindows.appendVector(inputWindows);
2384
2385 size_t numWindows = mWindows.size();
2386 for (size_t i = 0; i < numWindows; i++) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002387 const InputWindow* window = & mWindows.itemAt(i);
Jeff Browna665ca82010-09-08 11:49:43 -07002388 if (window->hasFocus) {
2389 mFocusedWindow = window;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002390 break;
Jeff Browna665ca82010-09-08 11:49:43 -07002391 }
2392 }
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002393
2394 for (size_t i = 0; i < mTouchState.windows.size(); ) {
2395 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2396 const InputWindow* window = getWindowLocked(touchedWindow.channel);
2397 if (window) {
2398 touchedWindow.window = window;
2399 i += 1;
2400 } else {
2401 mTouchState.windows.removeAt(i);
2402 }
2403 }
Jeff Browna665ca82010-09-08 11:49:43 -07002404
Jeff Browna665ca82010-09-08 11:49:43 -07002405#if DEBUG_FOCUS
2406 logDispatchStateLocked();
2407#endif
2408 } // release lock
2409
2410 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002411 mLooper->wake();
Jeff Browna665ca82010-09-08 11:49:43 -07002412}
2413
2414void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2415#if DEBUG_FOCUS
2416 LOGD("setFocusedApplication");
2417#endif
2418 { // acquire lock
2419 AutoMutex _l(mLock);
2420
2421 releaseFocusedApplicationLocked();
2422
2423 if (inputApplication) {
2424 mFocusedApplicationStorage = *inputApplication;
2425 mFocusedApplication = & mFocusedApplicationStorage;
2426 }
2427
2428#if DEBUG_FOCUS
2429 logDispatchStateLocked();
2430#endif
2431 } // release lock
2432
2433 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002434 mLooper->wake();
Jeff Browna665ca82010-09-08 11:49:43 -07002435}
2436
2437void InputDispatcher::releaseFocusedApplicationLocked() {
2438 if (mFocusedApplication) {
2439 mFocusedApplication = NULL;
2440 mFocusedApplicationStorage.handle.clear();
2441 }
2442}
2443
2444void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2445#if DEBUG_FOCUS
2446 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2447#endif
2448
2449 bool changed;
2450 { // acquire lock
2451 AutoMutex _l(mLock);
2452
2453 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2454 if (mDispatchFrozen && ! frozen) {
2455 resetANRTimeoutsLocked();
2456 }
2457
2458 mDispatchEnabled = enabled;
2459 mDispatchFrozen = frozen;
2460 changed = true;
2461 } else {
2462 changed = false;
2463 }
2464
2465#if DEBUG_FOCUS
2466 logDispatchStateLocked();
2467#endif
2468 } // release lock
2469
2470 if (changed) {
2471 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002472 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002473 }
2474}
2475
Jeff Browna665ca82010-09-08 11:49:43 -07002476void InputDispatcher::logDispatchStateLocked() {
2477 String8 dump;
2478 dumpDispatchStateLocked(dump);
Jeff Brown405a1d32010-09-16 12:31:46 -07002479
2480 char* text = dump.lockBuffer(dump.size());
2481 char* start = text;
2482 while (*start != '\0') {
2483 char* end = strchr(start, '\n');
2484 if (*end == '\n') {
2485 *(end++) = '\0';
2486 }
2487 LOGD("%s", start);
2488 start = end;
2489 }
Jeff Browna665ca82010-09-08 11:49:43 -07002490}
2491
2492void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
2493 dump.appendFormat(" dispatchEnabled: %d\n", mDispatchEnabled);
2494 dump.appendFormat(" dispatchFrozen: %d\n", mDispatchFrozen);
2495
2496 if (mFocusedApplication) {
2497 dump.appendFormat(" focusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
2498 mFocusedApplication->name.string(),
2499 mFocusedApplication->dispatchingTimeout / 1000000.0);
2500 } else {
2501 dump.append(" focusedApplication: <null>\n");
2502 }
Jeff Brown405a1d32010-09-16 12:31:46 -07002503 dump.appendFormat(" focusedWindow: name='%s'\n",
2504 mFocusedWindow != NULL ? mFocusedWindow->name.string() : "<null>");
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002505 dump.appendFormat(" touchState: down=%s, split=%s\n", toString(mTouchState.down),
2506 toString(mTouchState.split));
2507 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2508 const TouchedWindow& touchedWindow = mTouchState.windows[i];
2509 dump.appendFormat(" touchedWindow[%d]: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
2510 i, touchedWindow.window->name.string(), touchedWindow.pointerIds.value,
2511 touchedWindow.targetFlags);
Jeff Browna665ca82010-09-08 11:49:43 -07002512 }
2513 for (size_t i = 0; i < mWindows.size(); i++) {
Jeff Brown405a1d32010-09-16 12:31:46 -07002514 dump.appendFormat(" windows[%d]: name='%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
2515 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Jeff Browna665ca82010-09-08 11:49:43 -07002516 "frame=[%d,%d][%d,%d], "
2517 "visibleFrame=[%d,%d][%d,%d], "
2518 "touchableArea=[%d,%d][%d,%d], "
2519 "ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Jeff Brown405a1d32010-09-16 12:31:46 -07002520 i, mWindows[i].name.string(),
Jeff Browna665ca82010-09-08 11:49:43 -07002521 toString(mWindows[i].paused),
2522 toString(mWindows[i].hasFocus),
2523 toString(mWindows[i].hasWallpaper),
2524 toString(mWindows[i].visible),
Jeff Brown405a1d32010-09-16 12:31:46 -07002525 toString(mWindows[i].canReceiveKeys),
Jeff Browna665ca82010-09-08 11:49:43 -07002526 mWindows[i].layoutParamsFlags, mWindows[i].layoutParamsType,
Jeff Brown405a1d32010-09-16 12:31:46 -07002527 mWindows[i].layer,
Jeff Browna665ca82010-09-08 11:49:43 -07002528 mWindows[i].frameLeft, mWindows[i].frameTop,
2529 mWindows[i].frameRight, mWindows[i].frameBottom,
2530 mWindows[i].visibleFrameLeft, mWindows[i].visibleFrameTop,
2531 mWindows[i].visibleFrameRight, mWindows[i].visibleFrameBottom,
2532 mWindows[i].touchableAreaLeft, mWindows[i].touchableAreaTop,
2533 mWindows[i].touchableAreaRight, mWindows[i].touchableAreaBottom,
2534 mWindows[i].ownerPid, mWindows[i].ownerUid,
2535 mWindows[i].dispatchingTimeout / 1000000.0);
2536 }
2537
2538 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2539 const sp<InputChannel>& channel = mMonitoringChannels[i];
2540 dump.appendFormat(" monitoringChannel[%d]: '%s'\n",
2541 i, channel->getName().string());
2542 }
2543
Jeff Brown53a415e2010-09-15 15:18:56 -07002544 dump.appendFormat(" inboundQueue: length=%u", mInboundQueue.count());
2545
Jeff Browna665ca82010-09-08 11:49:43 -07002546 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2547 const Connection* connection = mActiveConnections[i];
Jeff Brown53a415e2010-09-15 15:18:56 -07002548 dump.appendFormat(" activeConnection[%d]: '%s', status=%s, outboundQueueLength=%u"
Jeff Browna665ca82010-09-08 11:49:43 -07002549 "inputState.isNeutral=%s, inputState.isOutOfSync=%s\n",
2550 i, connection->getInputChannelName(), connection->getStatusLabel(),
Jeff Brown53a415e2010-09-15 15:18:56 -07002551 connection->outboundQueue.count(),
Jeff Browna665ca82010-09-08 11:49:43 -07002552 toString(connection->inputState.isNeutral()),
2553 toString(connection->inputState.isOutOfSync()));
2554 }
2555
2556 if (isAppSwitchPendingLocked()) {
2557 dump.appendFormat(" appSwitch: pending, due in %01.1fms\n",
2558 (mAppSwitchDueTime - now()) / 1000000.0);
2559 } else {
2560 dump.append(" appSwitch: not pending\n");
2561 }
2562}
2563
2564status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) {
Jeff Brown54bc2812010-06-15 01:31:58 -07002565#if DEBUG_REGISTRATION
Jeff Browna665ca82010-09-08 11:49:43 -07002566 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
2567 toString(monitor));
Jeff Brown54bc2812010-06-15 01:31:58 -07002568#endif
2569
Jeff Browne839a582010-04-22 18:58:52 -07002570 { // acquire lock
2571 AutoMutex _l(mLock);
2572
Jeff Brown53a415e2010-09-15 15:18:56 -07002573 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Browne839a582010-04-22 18:58:52 -07002574 LOGW("Attempted to register already registered input channel '%s'",
2575 inputChannel->getName().string());
2576 return BAD_VALUE;
2577 }
2578
2579 sp<Connection> connection = new Connection(inputChannel);
2580 status_t status = connection->initialize();
2581 if (status) {
2582 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
2583 inputChannel->getName().string(), status);
2584 return status;
2585 }
2586
Jeff Brown0cacb872010-08-17 15:59:26 -07002587 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Browne839a582010-04-22 18:58:52 -07002588 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07002589
Jeff Browna665ca82010-09-08 11:49:43 -07002590 if (monitor) {
2591 mMonitoringChannels.push(inputChannel);
2592 }
2593
Jeff Brown59abe7e2010-09-13 23:17:30 -07002594 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown0cacb872010-08-17 15:59:26 -07002595
Jeff Brown54bc2812010-06-15 01:31:58 -07002596 runCommandsLockedInterruptible();
Jeff Browne839a582010-04-22 18:58:52 -07002597 } // release lock
Jeff Browne839a582010-04-22 18:58:52 -07002598 return OK;
2599}
2600
2601status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown54bc2812010-06-15 01:31:58 -07002602#if DEBUG_REGISTRATION
Jeff Brown50de30a2010-06-22 01:27:15 -07002603 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown54bc2812010-06-15 01:31:58 -07002604#endif
2605
Jeff Browne839a582010-04-22 18:58:52 -07002606 { // acquire lock
2607 AutoMutex _l(mLock);
2608
Jeff Brown53a415e2010-09-15 15:18:56 -07002609 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Browne839a582010-04-22 18:58:52 -07002610 if (connectionIndex < 0) {
2611 LOGW("Attempted to unregister already unregistered input channel '%s'",
2612 inputChannel->getName().string());
2613 return BAD_VALUE;
2614 }
2615
2616 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2617 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
2618
2619 connection->status = Connection::STATUS_ZOMBIE;
2620
Jeff Browna665ca82010-09-08 11:49:43 -07002621 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2622 if (mMonitoringChannels[i] == inputChannel) {
2623 mMonitoringChannels.removeAt(i);
2624 break;
2625 }
2626 }
2627
Jeff Brown59abe7e2010-09-13 23:17:30 -07002628 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown0cacb872010-08-17 15:59:26 -07002629
Jeff Brown51d45a72010-06-17 20:52:56 -07002630 nsecs_t currentTime = now();
2631 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07002632
2633 runCommandsLockedInterruptible();
Jeff Browne839a582010-04-22 18:58:52 -07002634 } // release lock
2635
Jeff Browne839a582010-04-22 18:58:52 -07002636 // Wake the poll loop because removing the connection may have changed the current
2637 // synchronization state.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002638 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002639 return OK;
2640}
2641
Jeff Brown53a415e2010-09-15 15:18:56 -07002642ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown0cacb872010-08-17 15:59:26 -07002643 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
2644 if (connectionIndex >= 0) {
2645 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2646 if (connection->inputChannel.get() == inputChannel.get()) {
2647 return connectionIndex;
2648 }
2649 }
2650
2651 return -1;
2652}
2653
Jeff Browne839a582010-04-22 18:58:52 -07002654void InputDispatcher::activateConnectionLocked(Connection* connection) {
2655 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2656 if (mActiveConnections.itemAt(i) == connection) {
2657 return;
2658 }
2659 }
2660 mActiveConnections.add(connection);
2661}
2662
2663void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
2664 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2665 if (mActiveConnections.itemAt(i) == connection) {
2666 mActiveConnections.removeAt(i);
2667 return;
2668 }
2669 }
2670}
2671
Jeff Brown54bc2812010-06-15 01:31:58 -07002672void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002673 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002674}
2675
Jeff Brown54bc2812010-06-15 01:31:58 -07002676void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002677 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002678}
2679
Jeff Brown54bc2812010-06-15 01:31:58 -07002680void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002681 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002682 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
2683 connection->getInputChannelName());
2684
Jeff Brown54bc2812010-06-15 01:31:58 -07002685 CommandEntry* commandEntry = postCommandLocked(
2686 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown51d45a72010-06-17 20:52:56 -07002687 commandEntry->connection = connection;
Jeff Browne839a582010-04-22 18:58:52 -07002688}
2689
Jeff Brown53a415e2010-09-15 15:18:56 -07002690void InputDispatcher::onANRLocked(
2691 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
2692 nsecs_t eventTime, nsecs_t waitStartTime) {
2693 LOGI("Application is not responding: %s. "
2694 "%01.1fms since event, %01.1fms since wait started",
2695 getApplicationWindowLabelLocked(application, window).string(),
2696 (currentTime - eventTime) / 1000000.0,
2697 (currentTime - waitStartTime) / 1000000.0);
2698
2699 CommandEntry* commandEntry = postCommandLocked(
2700 & InputDispatcher::doNotifyANRLockedInterruptible);
2701 if (application) {
2702 commandEntry->inputApplicationHandle = application->handle;
2703 }
2704 if (window) {
2705 commandEntry->inputChannel = window->inputChannel;
2706 }
2707}
2708
Jeff Browna665ca82010-09-08 11:49:43 -07002709void InputDispatcher::doNotifyConfigurationChangedInterruptible(
2710 CommandEntry* commandEntry) {
2711 mLock.unlock();
2712
2713 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
2714
2715 mLock.lock();
2716}
2717
Jeff Brown54bc2812010-06-15 01:31:58 -07002718void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
2719 CommandEntry* commandEntry) {
Jeff Brown51d45a72010-06-17 20:52:56 -07002720 sp<Connection> connection = commandEntry->connection;
Jeff Brown54bc2812010-06-15 01:31:58 -07002721
Jeff Brown51d45a72010-06-17 20:52:56 -07002722 if (connection->status != Connection::STATUS_ZOMBIE) {
2723 mLock.unlock();
Jeff Brown54bc2812010-06-15 01:31:58 -07002724
Jeff Brown51d45a72010-06-17 20:52:56 -07002725 mPolicy->notifyInputChannelBroken(connection->inputChannel);
2726
2727 mLock.lock();
2728 }
Jeff Brown54bc2812010-06-15 01:31:58 -07002729}
2730
Jeff Brown53a415e2010-09-15 15:18:56 -07002731void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown54bc2812010-06-15 01:31:58 -07002732 CommandEntry* commandEntry) {
Jeff Brown53a415e2010-09-15 15:18:56 -07002733 mLock.unlock();
Jeff Brown54bc2812010-06-15 01:31:58 -07002734
Jeff Brown53a415e2010-09-15 15:18:56 -07002735 nsecs_t newTimeout = mPolicy->notifyANR(
2736 commandEntry->inputApplicationHandle, commandEntry->inputChannel);
Jeff Brown54bc2812010-06-15 01:31:58 -07002737
Jeff Brown53a415e2010-09-15 15:18:56 -07002738 mLock.lock();
Jeff Brown51d45a72010-06-17 20:52:56 -07002739
Jeff Brown53a415e2010-09-15 15:18:56 -07002740 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown54bc2812010-06-15 01:31:58 -07002741}
2742
Jeff Browna665ca82010-09-08 11:49:43 -07002743void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
2744 CommandEntry* commandEntry) {
2745 KeyEntry* entry = commandEntry->keyEntry;
2746 mReusableKeyEvent.initialize(entry->deviceId, entry->source, entry->action, entry->flags,
2747 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
2748 entry->downTime, entry->eventTime);
2749
2750 mLock.unlock();
2751
2752 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputChannel,
2753 & mReusableKeyEvent, entry->policyFlags);
2754
2755 mLock.lock();
2756
2757 entry->interceptKeyResult = consumed
2758 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
2759 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
2760 mAllocator.releaseKeyEntry(entry);
2761}
2762
2763void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
2764 mLock.unlock();
2765
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002766 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
Jeff Browna665ca82010-09-08 11:49:43 -07002767
2768 mLock.lock();
2769}
2770
Jeff Brown53a415e2010-09-15 15:18:56 -07002771void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
2772 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
2773 // TODO Write some statistics about how long we spend waiting.
Jeff Browna665ca82010-09-08 11:49:43 -07002774}
2775
2776void InputDispatcher::dump(String8& dump) {
2777 dumpDispatchStateLocked(dump);
2778}
2779
Jeff Brown54bc2812010-06-15 01:31:58 -07002780
Jeff Brown53a415e2010-09-15 15:18:56 -07002781// --- InputDispatcher::Queue ---
2782
2783template <typename T>
2784uint32_t InputDispatcher::Queue<T>::count() const {
2785 uint32_t result = 0;
2786 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
2787 result += 1;
2788 }
2789 return result;
2790}
2791
2792
Jeff Browne839a582010-04-22 18:58:52 -07002793// --- InputDispatcher::Allocator ---
2794
2795InputDispatcher::Allocator::Allocator() {
2796}
2797
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002798InputDispatcher::InjectionState*
2799InputDispatcher::Allocator::obtainInjectionState(int32_t injectorPid, int32_t injectorUid) {
2800 InjectionState* injectionState = mInjectionStatePool.alloc();
2801 injectionState->refCount = 1;
2802 injectionState->injectorPid = injectorPid;
2803 injectionState->injectorUid = injectorUid;
2804 injectionState->injectionIsAsync = false;
2805 injectionState->injectionResult = INPUT_EVENT_INJECTION_PENDING;
2806 injectionState->pendingForegroundDispatches = 0;
2807 return injectionState;
2808}
2809
Jeff Brown51d45a72010-06-17 20:52:56 -07002810void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
2811 nsecs_t eventTime) {
2812 entry->type = type;
2813 entry->refCount = 1;
2814 entry->dispatchInProgress = false;
Christopher Tated974e002010-06-23 16:50:30 -07002815 entry->eventTime = eventTime;
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002816 entry->injectionState = NULL;
2817}
2818
2819void InputDispatcher::Allocator::releaseEventEntryInjectionState(EventEntry* entry) {
2820 if (entry->injectionState) {
2821 releaseInjectionState(entry->injectionState);
2822 entry->injectionState = NULL;
2823 }
Jeff Brown51d45a72010-06-17 20:52:56 -07002824}
2825
Jeff Browne839a582010-04-22 18:58:52 -07002826InputDispatcher::ConfigurationChangedEntry*
Jeff Brown51d45a72010-06-17 20:52:56 -07002827InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Browne839a582010-04-22 18:58:52 -07002828 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002829 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime);
Jeff Browne839a582010-04-22 18:58:52 -07002830 return entry;
2831}
2832
Jeff Brown51d45a72010-06-17 20:52:56 -07002833InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -07002834 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown51d45a72010-06-17 20:52:56 -07002835 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
2836 int32_t repeatCount, nsecs_t downTime) {
Jeff Browne839a582010-04-22 18:58:52 -07002837 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002838 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime);
2839
2840 entry->deviceId = deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -07002841 entry->source = source;
Jeff Brown51d45a72010-06-17 20:52:56 -07002842 entry->policyFlags = policyFlags;
2843 entry->action = action;
2844 entry->flags = flags;
2845 entry->keyCode = keyCode;
2846 entry->scanCode = scanCode;
2847 entry->metaState = metaState;
2848 entry->repeatCount = repeatCount;
2849 entry->downTime = downTime;
Jeff Browna665ca82010-09-08 11:49:43 -07002850 entry->syntheticRepeat = false;
2851 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Browne839a582010-04-22 18:58:52 -07002852 return entry;
2853}
2854
Jeff Brown51d45a72010-06-17 20:52:56 -07002855InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002856 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown51d45a72010-06-17 20:52:56 -07002857 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
2858 nsecs_t downTime, uint32_t pointerCount,
2859 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Browne839a582010-04-22 18:58:52 -07002860 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002861 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime);
2862
2863 entry->eventTime = eventTime;
2864 entry->deviceId = deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -07002865 entry->source = source;
Jeff Brown51d45a72010-06-17 20:52:56 -07002866 entry->policyFlags = policyFlags;
2867 entry->action = action;
Jeff Brownaf30ff62010-09-01 17:01:00 -07002868 entry->flags = flags;
Jeff Brown51d45a72010-06-17 20:52:56 -07002869 entry->metaState = metaState;
2870 entry->edgeFlags = edgeFlags;
2871 entry->xPrecision = xPrecision;
2872 entry->yPrecision = yPrecision;
2873 entry->downTime = downTime;
2874 entry->pointerCount = pointerCount;
2875 entry->firstSample.eventTime = eventTime;
Jeff Browne839a582010-04-22 18:58:52 -07002876 entry->firstSample.next = NULL;
Jeff Brown51d45a72010-06-17 20:52:56 -07002877 entry->lastSample = & entry->firstSample;
2878 for (uint32_t i = 0; i < pointerCount; i++) {
2879 entry->pointerIds[i] = pointerIds[i];
2880 entry->firstSample.pointerCoords[i] = pointerCoords[i];
2881 }
Jeff Browne839a582010-04-22 18:58:52 -07002882 return entry;
2883}
2884
2885InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Browna665ca82010-09-08 11:49:43 -07002886 EventEntry* eventEntry,
Jeff Brown53a415e2010-09-15 15:18:56 -07002887 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Browne839a582010-04-22 18:58:52 -07002888 DispatchEntry* entry = mDispatchEntryPool.alloc();
2889 entry->eventEntry = eventEntry;
2890 eventEntry->refCount += 1;
Jeff Browna665ca82010-09-08 11:49:43 -07002891 entry->targetFlags = targetFlags;
2892 entry->xOffset = xOffset;
2893 entry->yOffset = yOffset;
Jeff Browna665ca82010-09-08 11:49:43 -07002894 entry->inProgress = false;
2895 entry->headMotionSample = NULL;
2896 entry->tailMotionSample = NULL;
Jeff Browne839a582010-04-22 18:58:52 -07002897 return entry;
2898}
2899
Jeff Brown54bc2812010-06-15 01:31:58 -07002900InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
2901 CommandEntry* entry = mCommandEntryPool.alloc();
2902 entry->command = command;
2903 return entry;
2904}
2905
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002906void InputDispatcher::Allocator::releaseInjectionState(InjectionState* injectionState) {
2907 injectionState->refCount -= 1;
2908 if (injectionState->refCount == 0) {
2909 mInjectionStatePool.free(injectionState);
2910 } else {
2911 assert(injectionState->refCount > 0);
2912 }
2913}
2914
Jeff Browne839a582010-04-22 18:58:52 -07002915void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
2916 switch (entry->type) {
2917 case EventEntry::TYPE_CONFIGURATION_CHANGED:
2918 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
2919 break;
2920 case EventEntry::TYPE_KEY:
2921 releaseKeyEntry(static_cast<KeyEntry*>(entry));
2922 break;
2923 case EventEntry::TYPE_MOTION:
2924 releaseMotionEntry(static_cast<MotionEntry*>(entry));
2925 break;
2926 default:
2927 assert(false);
2928 break;
2929 }
2930}
2931
2932void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
2933 ConfigurationChangedEntry* entry) {
2934 entry->refCount -= 1;
2935 if (entry->refCount == 0) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002936 releaseEventEntryInjectionState(entry);
Jeff Browne839a582010-04-22 18:58:52 -07002937 mConfigurationChangeEntryPool.free(entry);
2938 } else {
2939 assert(entry->refCount > 0);
2940 }
2941}
2942
2943void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
2944 entry->refCount -= 1;
2945 if (entry->refCount == 0) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002946 releaseEventEntryInjectionState(entry);
Jeff Browne839a582010-04-22 18:58:52 -07002947 mKeyEntryPool.free(entry);
2948 } else {
2949 assert(entry->refCount > 0);
2950 }
2951}
2952
2953void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
2954 entry->refCount -= 1;
2955 if (entry->refCount == 0) {
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002956 releaseEventEntryInjectionState(entry);
Jeff Brown54bc2812010-06-15 01:31:58 -07002957 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
2958 MotionSample* next = sample->next;
2959 mMotionSamplePool.free(sample);
2960 sample = next;
2961 }
Jeff Browne839a582010-04-22 18:58:52 -07002962 mMotionEntryPool.free(entry);
2963 } else {
2964 assert(entry->refCount > 0);
2965 }
2966}
2967
2968void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
2969 releaseEventEntry(entry->eventEntry);
2970 mDispatchEntryPool.free(entry);
2971}
2972
Jeff Brown54bc2812010-06-15 01:31:58 -07002973void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
2974 mCommandEntryPool.free(entry);
2975}
2976
Jeff Browne839a582010-04-22 18:58:52 -07002977void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown51d45a72010-06-17 20:52:56 -07002978 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Browne839a582010-04-22 18:58:52 -07002979 MotionSample* sample = mMotionSamplePool.alloc();
2980 sample->eventTime = eventTime;
Jeff Brown51d45a72010-06-17 20:52:56 -07002981 uint32_t pointerCount = motionEntry->pointerCount;
2982 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Browne839a582010-04-22 18:58:52 -07002983 sample->pointerCoords[i] = pointerCoords[i];
2984 }
2985
2986 sample->next = NULL;
2987 motionEntry->lastSample->next = sample;
2988 motionEntry->lastSample = sample;
2989}
2990
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002991void InputDispatcher::Allocator::recycleKeyEntry(KeyEntry* keyEntry) {
2992 releaseEventEntryInjectionState(keyEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07002993
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07002994 keyEntry->dispatchInProgress = false;
2995 keyEntry->syntheticRepeat = false;
2996 keyEntry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Browna665ca82010-09-08 11:49:43 -07002997}
2998
2999
Jeff Brown542412c2010-08-18 15:51:08 -07003000// --- InputDispatcher::MotionEntry ---
3001
3002uint32_t InputDispatcher::MotionEntry::countSamples() const {
3003 uint32_t count = 1;
3004 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
3005 count += 1;
3006 }
3007 return count;
3008}
3009
Jeff Browna665ca82010-09-08 11:49:43 -07003010
3011// --- InputDispatcher::InputState ---
3012
3013InputDispatcher::InputState::InputState() :
3014 mIsOutOfSync(false) {
3015}
3016
3017InputDispatcher::InputState::~InputState() {
3018}
3019
3020bool InputDispatcher::InputState::isNeutral() const {
3021 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3022}
3023
3024bool InputDispatcher::InputState::isOutOfSync() const {
3025 return mIsOutOfSync;
3026}
3027
3028void InputDispatcher::InputState::setOutOfSync() {
3029 if (! isNeutral()) {
3030 mIsOutOfSync = true;
3031 }
3032}
3033
3034void InputDispatcher::InputState::resetOutOfSync() {
3035 mIsOutOfSync = false;
3036}
3037
3038InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackEvent(
3039 const EventEntry* entry) {
3040 switch (entry->type) {
3041 case EventEntry::TYPE_KEY:
3042 return trackKey(static_cast<const KeyEntry*>(entry));
3043
3044 case EventEntry::TYPE_MOTION:
3045 return trackMotion(static_cast<const MotionEntry*>(entry));
3046
3047 default:
3048 return CONSISTENT;
3049 }
3050}
3051
3052InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackKey(
3053 const KeyEntry* entry) {
3054 int32_t action = entry->action;
3055 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3056 KeyMemento& memento = mKeyMementos.editItemAt(i);
3057 if (memento.deviceId == entry->deviceId
3058 && memento.source == entry->source
3059 && memento.keyCode == entry->keyCode
3060 && memento.scanCode == entry->scanCode) {
3061 switch (action) {
3062 case AKEY_EVENT_ACTION_UP:
3063 mKeyMementos.removeAt(i);
3064 if (isNeutral()) {
3065 mIsOutOfSync = false;
3066 }
3067 return CONSISTENT;
3068
3069 case AKEY_EVENT_ACTION_DOWN:
3070 return TOLERABLE;
3071
3072 default:
3073 return BROKEN;
3074 }
3075 }
3076 }
3077
3078 switch (action) {
3079 case AKEY_EVENT_ACTION_DOWN: {
3080 mKeyMementos.push();
3081 KeyMemento& memento = mKeyMementos.editTop();
3082 memento.deviceId = entry->deviceId;
3083 memento.source = entry->source;
3084 memento.keyCode = entry->keyCode;
3085 memento.scanCode = entry->scanCode;
3086 memento.downTime = entry->downTime;
3087 return CONSISTENT;
3088 }
3089
3090 default:
3091 return BROKEN;
3092 }
3093}
3094
3095InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackMotion(
3096 const MotionEntry* entry) {
3097 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
3098 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3099 MotionMemento& memento = mMotionMementos.editItemAt(i);
3100 if (memento.deviceId == entry->deviceId
3101 && memento.source == entry->source) {
3102 switch (action) {
3103 case AMOTION_EVENT_ACTION_UP:
3104 case AMOTION_EVENT_ACTION_CANCEL:
3105 mMotionMementos.removeAt(i);
3106 if (isNeutral()) {
3107 mIsOutOfSync = false;
3108 }
3109 return CONSISTENT;
3110
3111 case AMOTION_EVENT_ACTION_DOWN:
3112 return TOLERABLE;
3113
3114 case AMOTION_EVENT_ACTION_POINTER_DOWN:
3115 if (entry->pointerCount == memento.pointerCount + 1) {
3116 memento.setPointers(entry);
3117 return CONSISTENT;
3118 }
3119 return BROKEN;
3120
3121 case AMOTION_EVENT_ACTION_POINTER_UP:
3122 if (entry->pointerCount == memento.pointerCount - 1) {
3123 memento.setPointers(entry);
3124 return CONSISTENT;
3125 }
3126 return BROKEN;
3127
3128 case AMOTION_EVENT_ACTION_MOVE:
3129 if (entry->pointerCount == memento.pointerCount) {
3130 return CONSISTENT;
3131 }
3132 return BROKEN;
3133
3134 default:
3135 return BROKEN;
3136 }
3137 }
3138 }
3139
3140 switch (action) {
3141 case AMOTION_EVENT_ACTION_DOWN: {
3142 mMotionMementos.push();
3143 MotionMemento& memento = mMotionMementos.editTop();
3144 memento.deviceId = entry->deviceId;
3145 memento.source = entry->source;
3146 memento.xPrecision = entry->xPrecision;
3147 memento.yPrecision = entry->yPrecision;
3148 memento.downTime = entry->downTime;
3149 memento.setPointers(entry);
3150 return CONSISTENT;
3151 }
3152
3153 default:
3154 return BROKEN;
3155 }
3156}
3157
3158void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
3159 pointerCount = entry->pointerCount;
3160 for (uint32_t i = 0; i < entry->pointerCount; i++) {
3161 pointerIds[i] = entry->pointerIds[i];
3162 pointerCoords[i] = entry->lastSample->pointerCoords[i];
3163 }
3164}
3165
3166void InputDispatcher::InputState::synthesizeCancelationEvents(
3167 Allocator* allocator, Vector<EventEntry*>& outEvents) const {
3168 for (size_t i = 0; i < mKeyMementos.size(); i++) {
3169 const KeyMemento& memento = mKeyMementos.itemAt(i);
3170 outEvents.push(allocator->obtainKeyEntry(now(),
3171 memento.deviceId, memento.source, 0,
3172 AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_CANCELED,
3173 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
3174 }
3175
3176 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3177 const MotionMemento& memento = mMotionMementos.itemAt(i);
3178 outEvents.push(allocator->obtainMotionEntry(now(),
3179 memento.deviceId, memento.source, 0,
3180 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
3181 memento.xPrecision, memento.yPrecision, memento.downTime,
3182 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
3183 }
3184}
3185
3186void InputDispatcher::InputState::clear() {
3187 mKeyMementos.clear();
3188 mMotionMementos.clear();
3189 mIsOutOfSync = false;
3190}
3191
3192
Jeff Browne839a582010-04-22 18:58:52 -07003193// --- InputDispatcher::Connection ---
3194
3195InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel) :
3196 status(STATUS_NORMAL), inputChannel(inputChannel), inputPublisher(inputChannel),
Jeff Brown53a415e2010-09-15 15:18:56 -07003197 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Browne839a582010-04-22 18:58:52 -07003198}
3199
3200InputDispatcher::Connection::~Connection() {
3201}
3202
3203status_t InputDispatcher::Connection::initialize() {
3204 return inputPublisher.initialize();
3205}
3206
Jeff Brown54bc2812010-06-15 01:31:58 -07003207const char* InputDispatcher::Connection::getStatusLabel() const {
3208 switch (status) {
3209 case STATUS_NORMAL:
3210 return "NORMAL";
3211
3212 case STATUS_BROKEN:
3213 return "BROKEN";
3214
Jeff Brown54bc2812010-06-15 01:31:58 -07003215 case STATUS_ZOMBIE:
3216 return "ZOMBIE";
3217
3218 default:
3219 return "UNKNOWN";
3220 }
3221}
3222
Jeff Browne839a582010-04-22 18:58:52 -07003223InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3224 const EventEntry* eventEntry) const {
Jeff Browna665ca82010-09-08 11:49:43 -07003225 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3226 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Browne839a582010-04-22 18:58:52 -07003227 if (dispatchEntry->eventEntry == eventEntry) {
3228 return dispatchEntry;
3229 }
3230 }
3231 return NULL;
3232}
3233
Jeff Browna665ca82010-09-08 11:49:43 -07003234
Jeff Brown54bc2812010-06-15 01:31:58 -07003235// --- InputDispatcher::CommandEntry ---
3236
Jeff Browna665ca82010-09-08 11:49:43 -07003237InputDispatcher::CommandEntry::CommandEntry() :
3238 keyEntry(NULL) {
Jeff Brown54bc2812010-06-15 01:31:58 -07003239}
3240
3241InputDispatcher::CommandEntry::~CommandEntry() {
3242}
3243
Jeff Browne839a582010-04-22 18:58:52 -07003244
Jeff Brownd1b0a2b2010-09-26 22:20:12 -07003245// --- InputDispatcher::TouchState ---
3246
3247InputDispatcher::TouchState::TouchState() :
3248 down(false), split(false) {
3249}
3250
3251InputDispatcher::TouchState::~TouchState() {
3252}
3253
3254void InputDispatcher::TouchState::reset() {
3255 down = false;
3256 split = false;
3257 windows.clear();
3258}
3259
3260void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
3261 down = other.down;
3262 split = other.split;
3263 windows.clear();
3264 windows.appendVector(other.windows);
3265}
3266
3267void InputDispatcher::TouchState::addOrUpdateWindow(const InputWindow* window,
3268 int32_t targetFlags, BitSet32 pointerIds) {
3269 if (targetFlags & InputTarget::FLAG_SPLIT) {
3270 split = true;
3271 }
3272
3273 for (size_t i = 0; i < windows.size(); i++) {
3274 TouchedWindow& touchedWindow = windows.editItemAt(i);
3275 if (touchedWindow.window == window) {
3276 touchedWindow.targetFlags |= targetFlags;
3277 touchedWindow.pointerIds.value |= pointerIds.value;
3278 return;
3279 }
3280 }
3281
3282 windows.push();
3283
3284 TouchedWindow& touchedWindow = windows.editTop();
3285 touchedWindow.window = window;
3286 touchedWindow.targetFlags = targetFlags;
3287 touchedWindow.pointerIds = pointerIds;
3288 touchedWindow.channel = window->inputChannel;
3289}
3290
3291void InputDispatcher::TouchState::removeOutsideTouchWindows() {
3292 for (size_t i = 0 ; i < windows.size(); ) {
3293 if (windows[i].targetFlags & InputTarget::FLAG_OUTSIDE) {
3294 windows.removeAt(i);
3295 } else {
3296 i += 1;
3297 }
3298 }
3299}
3300
3301const InputWindow* InputDispatcher::TouchState::getFirstForegroundWindow() {
3302 for (size_t i = 0; i < windows.size(); i++) {
3303 if (windows[i].targetFlags & InputTarget::FLAG_FOREGROUND) {
3304 return windows[i].window;
3305 }
3306 }
3307 return NULL;
3308}
3309
3310
Jeff Browne839a582010-04-22 18:58:52 -07003311// --- InputDispatcherThread ---
3312
3313InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
3314 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
3315}
3316
3317InputDispatcherThread::~InputDispatcherThread() {
3318}
3319
3320bool InputDispatcherThread::threadLoop() {
3321 mDispatcher->dispatchOnce();
3322 return true;
3323}
3324
3325} // namespace android