blob: dea7936f19195b5e79454f37a2c6c91d5f9eb53c [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
72
73// --- InputWindow ---
74
75bool InputWindow::visibleFrameIntersects(const InputWindow* other) const {
76 return visibleFrameRight > other->visibleFrameLeft
77 && visibleFrameLeft < other->visibleFrameRight
78 && visibleFrameBottom > other->visibleFrameTop
79 && visibleFrameTop < other->visibleFrameBottom;
80}
81
82bool InputWindow::touchableAreaContainsPoint(int32_t x, int32_t y) const {
83 return x >= touchableAreaLeft && x <= touchableAreaRight
84 && y >= touchableAreaTop && y <= touchableAreaBottom;
85}
86
87
Jeff Browne839a582010-04-22 18:58:52 -070088// --- InputDispatcher ---
89
Jeff Brown54bc2812010-06-15 01:31:58 -070090InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
Jeff Browna665ca82010-09-08 11:49:43 -070091 mPolicy(policy),
92 mPendingEvent(NULL), mAppSwitchDueTime(LONG_LONG_MAX),
93 mDispatchEnabled(true), mDispatchFrozen(false),
94 mFocusedWindow(NULL), mTouchDown(false), mTouchedWindow(NULL),
95 mFocusedApplication(NULL),
96 mCurrentInputTargetsValid(false),
97 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Jeff Brown59abe7e2010-09-13 23:17:30 -070098 mLooper = new Looper(false);
Jeff Browne839a582010-04-22 18:58:52 -070099
Jeff Browna665ca82010-09-08 11:49:43 -0700100 mInboundQueue.headSentinel.refCount = -1;
101 mInboundQueue.headSentinel.type = EventEntry::TYPE_SENTINEL;
102 mInboundQueue.headSentinel.eventTime = LONG_LONG_MIN;
Jeff Browne839a582010-04-22 18:58:52 -0700103
Jeff Browna665ca82010-09-08 11:49:43 -0700104 mInboundQueue.tailSentinel.refCount = -1;
105 mInboundQueue.tailSentinel.type = EventEntry::TYPE_SENTINEL;
106 mInboundQueue.tailSentinel.eventTime = LONG_LONG_MAX;
Jeff Browne839a582010-04-22 18:58:52 -0700107
108 mKeyRepeatState.lastKeyEntry = NULL;
Jeff Brown54bc2812010-06-15 01:31:58 -0700109
Jeff Brown542412c2010-08-18 15:51:08 -0700110 int32_t maxEventsPerSecond = policy->getMaxEventsPerSecond();
111 mThrottleState.minTimeBetweenEvents = 1000000000LL / maxEventsPerSecond;
112 mThrottleState.lastDeviceId = -1;
113
114#if DEBUG_THROTTLING
115 mThrottleState.originalSampleCount = 0;
116 LOGD("Throttling - Max events per second = %d", maxEventsPerSecond);
117#endif
Jeff Browne839a582010-04-22 18:58:52 -0700118}
119
120InputDispatcher::~InputDispatcher() {
Jeff Browna665ca82010-09-08 11:49:43 -0700121 { // acquire lock
122 AutoMutex _l(mLock);
123
124 resetKeyRepeatLocked();
125 releasePendingEventLocked(true);
126 drainInboundQueueLocked();
127 }
Jeff Browne839a582010-04-22 18:58:52 -0700128
129 while (mConnectionsByReceiveFd.size() != 0) {
130 unregisterInputChannel(mConnectionsByReceiveFd.valueAt(0)->inputChannel);
131 }
Jeff Browne839a582010-04-22 18:58:52 -0700132}
133
134void InputDispatcher::dispatchOnce() {
Jeff Brown54bc2812010-06-15 01:31:58 -0700135 nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();
Jeff Brown61ce3982010-09-07 10:44:57 -0700136 nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();
Jeff Browne839a582010-04-22 18:58:52 -0700137
Jeff Browne839a582010-04-22 18:58:52 -0700138 nsecs_t nextWakeupTime = LONG_LONG_MAX;
139 { // acquire lock
140 AutoMutex _l(mLock);
Jeff Browna665ca82010-09-08 11:49:43 -0700141 dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);
Jeff Browne839a582010-04-22 18:58:52 -0700142
Jeff Browna665ca82010-09-08 11:49:43 -0700143 if (runCommandsLockedInterruptible()) {
144 nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Jeff Browne839a582010-04-22 18:58:52 -0700145 }
Jeff Browne839a582010-04-22 18:58:52 -0700146 } // release lock
147
Jeff Browna665ca82010-09-08 11:49:43 -0700148 // Wait for callback or timeout or wake. (make sure we round up, not down)
149 nsecs_t currentTime = now();
150 int32_t timeoutMillis;
151 if (nextWakeupTime > currentTime) {
152 uint64_t timeout = uint64_t(nextWakeupTime - currentTime);
153 timeout = (timeout + 999999LL) / 1000000LL;
154 timeoutMillis = timeout > INT_MAX ? -1 : int32_t(timeout);
155 } else {
156 timeoutMillis = 0;
157 }
158
Jeff Brown59abe7e2010-09-13 23:17:30 -0700159 mLooper->pollOnce(timeoutMillis);
Jeff Browna665ca82010-09-08 11:49:43 -0700160}
161
162void InputDispatcher::dispatchOnceInnerLocked(nsecs_t keyRepeatTimeout,
163 nsecs_t keyRepeatDelay, nsecs_t* nextWakeupTime) {
164 nsecs_t currentTime = now();
165
166 // Reset the key repeat timer whenever we disallow key events, even if the next event
167 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
168 // out of sleep.
169 if (keyRepeatTimeout < 0) {
170 resetKeyRepeatLocked();
171 }
172
173 // If dispatching is disabled, drop all events in the queue.
174 if (! mDispatchEnabled) {
175 if (mPendingEvent || ! mInboundQueue.isEmpty()) {
176 LOGI("Dropping pending events because input dispatch is disabled.");
177 releasePendingEventLocked(true);
178 drainInboundQueueLocked();
179 }
Jeff Brown54bc2812010-06-15 01:31:58 -0700180 return;
181 }
182
Jeff Browna665ca82010-09-08 11:49:43 -0700183 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
184 if (mDispatchFrozen) {
185#if DEBUG_FOCUS
186 LOGD("Dispatch frozen. Waiting some more.");
187#endif
188 return;
189 }
190
191 // Optimize latency of app switches.
192 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
193 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
194 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
195 if (mAppSwitchDueTime < *nextWakeupTime) {
196 *nextWakeupTime = mAppSwitchDueTime;
197 }
198
Jeff Browna665ca82010-09-08 11:49:43 -0700199 // Ready to start a new event.
200 // If we don't already have a pending event, go grab one.
201 if (! mPendingEvent) {
202 if (mInboundQueue.isEmpty()) {
203 if (isAppSwitchDue) {
204 // The inbound queue is empty so the app switch key we were waiting
205 // for will never arrive. Stop waiting for it.
206 resetPendingAppSwitchLocked(false);
207 isAppSwitchDue = false;
208 }
209
210 // Synthesize a key repeat if appropriate.
211 if (mKeyRepeatState.lastKeyEntry) {
212 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
213 mPendingEvent = synthesizeKeyRepeatLocked(currentTime, keyRepeatDelay);
214 } else {
215 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
216 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
217 }
218 }
219 }
220 if (! mPendingEvent) {
221 return;
222 }
223 } else {
224 // Inbound queue has at least one entry.
225 EventEntry* entry = mInboundQueue.headSentinel.next;
226
227 // Throttle the entry if it is a move event and there are no
228 // other events behind it in the queue. Due to movement batching, additional
229 // samples may be appended to this event by the time the throttling timeout
230 // expires.
231 // TODO Make this smarter and consider throttling per device independently.
232 if (entry->type == EventEntry::TYPE_MOTION) {
233 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
234 int32_t deviceId = motionEntry->deviceId;
235 uint32_t source = motionEntry->source;
236 if (! isAppSwitchDue
237 && motionEntry->next == & mInboundQueue.tailSentinel // exactly one event
238 && motionEntry->action == AMOTION_EVENT_ACTION_MOVE
239 && deviceId == mThrottleState.lastDeviceId
240 && source == mThrottleState.lastSource) {
241 nsecs_t nextTime = mThrottleState.lastEventTime
242 + mThrottleState.minTimeBetweenEvents;
243 if (currentTime < nextTime) {
244 // Throttle it!
245#if DEBUG_THROTTLING
246 LOGD("Throttling - Delaying motion event for "
247 "device 0x%x, source 0x%08x by up to %0.3fms.",
248 deviceId, source, (nextTime - currentTime) * 0.000001);
249#endif
250 if (nextTime < *nextWakeupTime) {
251 *nextWakeupTime = nextTime;
252 }
253 if (mThrottleState.originalSampleCount == 0) {
254 mThrottleState.originalSampleCount =
255 motionEntry->countSamples();
256 }
257 return;
258 }
259 }
260
261#if DEBUG_THROTTLING
262 if (mThrottleState.originalSampleCount != 0) {
263 uint32_t count = motionEntry->countSamples();
264 LOGD("Throttling - Motion event sample count grew by %d from %d to %d.",
265 count - mThrottleState.originalSampleCount,
266 mThrottleState.originalSampleCount, count);
267 mThrottleState.originalSampleCount = 0;
268 }
269#endif
270
271 mThrottleState.lastEventTime = entry->eventTime < currentTime
272 ? entry->eventTime : currentTime;
273 mThrottleState.lastDeviceId = deviceId;
274 mThrottleState.lastSource = source;
275 }
276
277 mInboundQueue.dequeue(entry);
278 mPendingEvent = entry;
279 }
280 }
281
282 // Now we have an event to dispatch.
283 assert(mPendingEvent != NULL);
284 bool wasDispatched = false;
285 bool wasDropped = false;
286 switch (mPendingEvent->type) {
287 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
288 ConfigurationChangedEntry* typedEntry =
289 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
290 wasDispatched = dispatchConfigurationChangedLocked(currentTime, typedEntry);
291 break;
292 }
293
294 case EventEntry::TYPE_KEY: {
295 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
296 if (isAppSwitchPendingLocked()) {
297 if (isAppSwitchKey(typedEntry->keyCode)) {
298 resetPendingAppSwitchLocked(true);
299 } else if (isAppSwitchDue) {
300 LOGI("Dropping key because of pending overdue app switch.");
301 wasDropped = true;
302 break;
303 }
304 }
305 wasDispatched = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
306 nextWakeupTime);
307 break;
308 }
309
310 case EventEntry::TYPE_MOTION: {
311 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
312 if (isAppSwitchDue) {
313 LOGI("Dropping motion because of pending overdue app switch.");
314 wasDropped = true;
315 break;
316 }
317 wasDispatched = dispatchMotionLocked(currentTime, typedEntry, nextWakeupTime);
318 break;
319 }
320
321 default:
322 assert(false);
323 wasDropped = true;
324 break;
325 }
326
327 if (wasDispatched || wasDropped) {
328 releasePendingEventLocked(wasDropped);
329 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
330 }
331}
332
333bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
334 bool needWake = mInboundQueue.isEmpty();
335 mInboundQueue.enqueueAtTail(entry);
336
337 switch (entry->type) {
338 case EventEntry::TYPE_KEY:
339 needWake |= detectPendingAppSwitchLocked(static_cast<KeyEntry*>(entry));
340 break;
341 }
342
343 return needWake;
344}
345
346bool InputDispatcher::isAppSwitchKey(int32_t keyCode) {
347 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
348}
349
350bool InputDispatcher::isAppSwitchPendingLocked() {
351 return mAppSwitchDueTime != LONG_LONG_MAX;
352}
353
354bool InputDispatcher::detectPendingAppSwitchLocked(KeyEntry* inboundKeyEntry) {
355 if (inboundKeyEntry->action == AKEY_EVENT_ACTION_UP
356 && ! (inboundKeyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
357 && isAppSwitchKey(inboundKeyEntry->keyCode)
358 && isEventFromReliableSourceLocked(inboundKeyEntry)) {
359#if DEBUG_APP_SWITCH
360 LOGD("App switch is pending!");
361#endif
362 mAppSwitchDueTime = inboundKeyEntry->eventTime + APP_SWITCH_TIMEOUT;
363 return true; // need wake
364 }
365 return false;
366}
367
368void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
369 mAppSwitchDueTime = LONG_LONG_MAX;
370
371#if DEBUG_APP_SWITCH
372 if (handled) {
373 LOGD("App switch has arrived.");
374 } else {
375 LOGD("App switch was abandoned.");
376 }
377#endif
Jeff Browne839a582010-04-22 18:58:52 -0700378}
379
Jeff Brown54bc2812010-06-15 01:31:58 -0700380bool InputDispatcher::runCommandsLockedInterruptible() {
381 if (mCommandQueue.isEmpty()) {
382 return false;
383 }
Jeff Browne839a582010-04-22 18:58:52 -0700384
Jeff Brown54bc2812010-06-15 01:31:58 -0700385 do {
386 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
387
388 Command command = commandEntry->command;
389 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
390
Jeff Brown51d45a72010-06-17 20:52:56 -0700391 commandEntry->connection.clear();
Jeff Brown54bc2812010-06-15 01:31:58 -0700392 mAllocator.releaseCommandEntry(commandEntry);
393 } while (! mCommandQueue.isEmpty());
394 return true;
Jeff Browne839a582010-04-22 18:58:52 -0700395}
396
Jeff Brown54bc2812010-06-15 01:31:58 -0700397InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
398 CommandEntry* commandEntry = mAllocator.obtainCommandEntry(command);
399 mCommandQueue.enqueueAtTail(commandEntry);
400 return commandEntry;
401}
402
Jeff Browna665ca82010-09-08 11:49:43 -0700403void InputDispatcher::drainInboundQueueLocked() {
404 while (! mInboundQueue.isEmpty()) {
405 EventEntry* entry = mInboundQueue.dequeueAtHead();
406 releaseInboundEventLocked(entry, true /*wasDropped*/);
Jeff Browne839a582010-04-22 18:58:52 -0700407 }
Jeff Browne839a582010-04-22 18:58:52 -0700408}
409
Jeff Browna665ca82010-09-08 11:49:43 -0700410void InputDispatcher::releasePendingEventLocked(bool wasDropped) {
411 if (mPendingEvent) {
412 releaseInboundEventLocked(mPendingEvent, wasDropped);
413 mPendingEvent = NULL;
414 }
415}
416
417void InputDispatcher::releaseInboundEventLocked(EventEntry* entry, bool wasDropped) {
418 if (wasDropped) {
419#if DEBUG_DISPATCH_CYCLE
420 LOGD("Pending event was dropped.");
421#endif
422 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
423 }
424 mAllocator.releaseEventEntry(entry);
425}
426
427bool InputDispatcher::isEventFromReliableSourceLocked(EventEntry* entry) {
428 return ! entry->isInjected()
429 || entry->injectorUid == 0
430 || mPolicy->checkInjectEventsPermissionNonReentrant(
431 entry->injectorPid, entry->injectorUid);
432}
433
434void InputDispatcher::resetKeyRepeatLocked() {
435 if (mKeyRepeatState.lastKeyEntry) {
436 mAllocator.releaseKeyEntry(mKeyRepeatState.lastKeyEntry);
437 mKeyRepeatState.lastKeyEntry = NULL;
438 }
439}
440
441InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(
Jeff Brown61ce3982010-09-07 10:44:57 -0700442 nsecs_t currentTime, nsecs_t keyRepeatDelay) {
Jeff Brown50de30a2010-06-22 01:27:15 -0700443 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
444
Jeff Brown50de30a2010-06-22 01:27:15 -0700445 // Reuse the repeated key entry if it is otherwise unreferenced.
Jeff Brown51d45a72010-06-17 20:52:56 -0700446 uint32_t policyFlags = entry->policyFlags & POLICY_FLAG_RAW_MASK;
Jeff Browne839a582010-04-22 18:58:52 -0700447 if (entry->refCount == 1) {
Jeff Browna665ca82010-09-08 11:49:43 -0700448 entry->recycle();
Jeff Brown51d45a72010-06-17 20:52:56 -0700449 entry->eventTime = currentTime;
Jeff Brown51d45a72010-06-17 20:52:56 -0700450 entry->policyFlags = policyFlags;
Jeff Browne839a582010-04-22 18:58:52 -0700451 entry->repeatCount += 1;
452 } else {
Jeff Brown51d45a72010-06-17 20:52:56 -0700453 KeyEntry* newEntry = mAllocator.obtainKeyEntry(currentTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700454 entry->deviceId, entry->source, policyFlags,
Jeff Brown51d45a72010-06-17 20:52:56 -0700455 entry->action, entry->flags, entry->keyCode, entry->scanCode,
Jeff Brownf16c26d2010-07-02 15:37:36 -0700456 entry->metaState, entry->repeatCount + 1, entry->downTime);
Jeff Browne839a582010-04-22 18:58:52 -0700457
458 mKeyRepeatState.lastKeyEntry = newEntry;
459 mAllocator.releaseKeyEntry(entry);
460
461 entry = newEntry;
462 }
Jeff Browna665ca82010-09-08 11:49:43 -0700463 entry->syntheticRepeat = true;
464
465 // Increment reference count since we keep a reference to the event in
466 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
467 entry->refCount += 1;
Jeff Browne839a582010-04-22 18:58:52 -0700468
Jeff Brownf16c26d2010-07-02 15:37:36 -0700469 if (entry->repeatCount == 1) {
Jeff Brown5c1ed842010-07-14 18:48:53 -0700470 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
Jeff Brownf16c26d2010-07-02 15:37:36 -0700471 }
472
Jeff Brown61ce3982010-09-07 10:44:57 -0700473 mKeyRepeatState.nextRepeatTime = currentTime + keyRepeatDelay;
Jeff Browna665ca82010-09-08 11:49:43 -0700474 return entry;
Jeff Browne839a582010-04-22 18:58:52 -0700475}
476
Jeff Browna665ca82010-09-08 11:49:43 -0700477bool InputDispatcher::dispatchConfigurationChangedLocked(
478 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
Jeff Browne839a582010-04-22 18:58:52 -0700479#if DEBUG_OUTBOUND_EVENT_DETAILS
Jeff Browna665ca82010-09-08 11:49:43 -0700480 LOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
481#endif
482
483 // Reset key repeating in case a keyboard device was added or removed or something.
484 resetKeyRepeatLocked();
485
486 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
487 CommandEntry* commandEntry = postCommandLocked(
488 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
489 commandEntry->eventTime = entry->eventTime;
490 return true;
491}
492
493bool InputDispatcher::dispatchKeyLocked(
494 nsecs_t currentTime, KeyEntry* entry, nsecs_t keyRepeatTimeout,
495 nsecs_t* nextWakeupTime) {
496 // Preprocessing.
497 if (! entry->dispatchInProgress) {
498 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
499
500 if (entry->repeatCount == 0
501 && entry->action == AKEY_EVENT_ACTION_DOWN
502 && ! entry->isInjected()) {
503 if (mKeyRepeatState.lastKeyEntry
504 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
505 // We have seen two identical key downs in a row which indicates that the device
506 // driver is automatically generating key repeats itself. We take note of the
507 // repeat here, but we disable our own next key repeat timer since it is clear that
508 // we will not need to synthesize key repeats ourselves.
509 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
510 resetKeyRepeatLocked();
511 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
512 } else {
513 // Not a repeat. Save key down state in case we do see a repeat later.
514 resetKeyRepeatLocked();
515 mKeyRepeatState.nextRepeatTime = entry->eventTime + keyRepeatTimeout;
516 }
517 mKeyRepeatState.lastKeyEntry = entry;
518 entry->refCount += 1;
519 } else if (! entry->syntheticRepeat) {
520 resetKeyRepeatLocked();
521 }
522
523 entry->dispatchInProgress = true;
Jeff Brown53a415e2010-09-15 15:18:56 -0700524 startFindingTargetsLocked(); // resets mCurrentInputTargetsValid
Jeff Browna665ca82010-09-08 11:49:43 -0700525 }
526
527 // Identify targets.
528 if (! mCurrentInputTargetsValid) {
529 InputWindow* window = NULL;
530 int32_t injectionResult = findFocusedWindowLocked(currentTime,
531 entry, nextWakeupTime, & window);
532 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
533 return false;
534 }
535
536 setInjectionResultLocked(entry, injectionResult);
537 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
538 return true;
539 }
540
541 addMonitoringTargetsLocked();
542 finishFindingTargetsLocked(window);
543 }
544
545 // Give the policy a chance to intercept the key.
546 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
547 CommandEntry* commandEntry = postCommandLocked(
548 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
549 commandEntry->inputChannel = mCurrentInputChannel;
550 commandEntry->keyEntry = entry;
551 entry->refCount += 1;
552 return false; // wait for the command to run
553 }
554 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
555 return true;
556 }
557
558 // Dispatch the key.
559 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
560
561 // Poke user activity.
562 pokeUserActivityLocked(entry->eventTime, mCurrentInputWindowType, POWER_MANAGER_BUTTON_EVENT);
563 return true;
564}
565
566void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
567#if DEBUG_OUTBOUND_EVENT_DETAILS
568 LOGD("%seventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, "
569 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
570 "downTime=%lld",
571 prefix,
572 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
573 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
574 entry->downTime);
575#endif
576}
577
578bool InputDispatcher::dispatchMotionLocked(
579 nsecs_t currentTime, MotionEntry* entry, nsecs_t* nextWakeupTime) {
580 // Preprocessing.
581 if (! entry->dispatchInProgress) {
582 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
583
584 entry->dispatchInProgress = true;
Jeff Brown53a415e2010-09-15 15:18:56 -0700585 startFindingTargetsLocked(); // resets mCurrentInputTargetsValid
Jeff Browna665ca82010-09-08 11:49:43 -0700586 }
587
588 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
589
590 // Identify targets.
591 if (! mCurrentInputTargetsValid) {
592 InputWindow* window = NULL;
593 int32_t injectionResult;
594 if (isPointerEvent) {
595 // Pointer event. (eg. touchscreen)
596 injectionResult = findTouchedWindowLocked(currentTime,
597 entry, nextWakeupTime, & window);
598 } else {
599 // Non touch event. (eg. trackball)
600 injectionResult = findFocusedWindowLocked(currentTime,
601 entry, nextWakeupTime, & window);
602 }
603 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
604 return false;
605 }
606
607 setInjectionResultLocked(entry, injectionResult);
608 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
609 return true;
610 }
611
612 addMonitoringTargetsLocked();
613 finishFindingTargetsLocked(window);
614 }
615
616 // Dispatch the motion.
617 dispatchEventToCurrentInputTargetsLocked(currentTime, entry, false);
618
619 // Poke user activity.
620 int32_t eventType;
621 if (isPointerEvent) {
622 switch (entry->action) {
623 case AMOTION_EVENT_ACTION_DOWN:
624 eventType = POWER_MANAGER_TOUCH_EVENT;
625 break;
626 case AMOTION_EVENT_ACTION_UP:
627 eventType = POWER_MANAGER_TOUCH_UP_EVENT;
628 break;
629 default:
630 if (entry->eventTime - entry->downTime >= EVENT_IGNORE_DURATION) {
631 eventType = POWER_MANAGER_TOUCH_EVENT;
632 } else {
633 eventType = POWER_MANAGER_LONG_TOUCH_EVENT;
634 }
635 break;
636 }
637 } else {
638 eventType = POWER_MANAGER_BUTTON_EVENT;
639 }
640 pokeUserActivityLocked(entry->eventTime, mCurrentInputWindowType, eventType);
641 return true;
642}
643
644
645void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
646#if DEBUG_OUTBOUND_EVENT_DETAILS
647 LOGD("%seventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, "
Jeff Brownaf30ff62010-09-01 17:01:00 -0700648 "action=0x%x, flags=0x%x, "
Jeff Browne839a582010-04-22 18:58:52 -0700649 "metaState=0x%x, edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Jeff Browna665ca82010-09-08 11:49:43 -0700650 prefix,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700651 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
652 entry->action, entry->flags,
Jeff Browne839a582010-04-22 18:58:52 -0700653 entry->metaState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
654 entry->downTime);
655
656 // Print the most recent sample that we have available, this may change due to batching.
657 size_t sampleCount = 1;
Jeff Browna665ca82010-09-08 11:49:43 -0700658 const MotionSample* sample = & entry->firstSample;
Jeff Browne839a582010-04-22 18:58:52 -0700659 for (; sample->next != NULL; sample = sample->next) {
660 sampleCount += 1;
661 }
662 for (uint32_t i = 0; i < entry->pointerCount; i++) {
Jeff Brown38a7fab2010-08-30 03:02:23 -0700663 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brownaf30ff62010-09-01 17:01:00 -0700664 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown38a7fab2010-08-30 03:02:23 -0700665 "orientation=%f",
Jeff Browne839a582010-04-22 18:58:52 -0700666 i, entry->pointerIds[i],
Jeff Brown38a7fab2010-08-30 03:02:23 -0700667 sample->pointerCoords[i].x, sample->pointerCoords[i].y,
668 sample->pointerCoords[i].pressure, sample->pointerCoords[i].size,
669 sample->pointerCoords[i].touchMajor, sample->pointerCoords[i].touchMinor,
670 sample->pointerCoords[i].toolMajor, sample->pointerCoords[i].toolMinor,
671 sample->pointerCoords[i].orientation);
Jeff Browne839a582010-04-22 18:58:52 -0700672 }
673
674 // Keep in mind that due to batching, it is possible for the number of samples actually
675 // dispatched to change before the application finally consumed them.
Jeff Brown5c1ed842010-07-14 18:48:53 -0700676 if (entry->action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Browne839a582010-04-22 18:58:52 -0700677 LOGD(" ... Total movement samples currently batched %d ...", sampleCount);
678 }
679#endif
Jeff Browne839a582010-04-22 18:58:52 -0700680}
681
682void InputDispatcher::dispatchEventToCurrentInputTargetsLocked(nsecs_t currentTime,
683 EventEntry* eventEntry, bool resumeWithAppendedMotionSample) {
684#if DEBUG_DISPATCH_CYCLE
Jeff Brown54bc2812010-06-15 01:31:58 -0700685 LOGD("dispatchEventToCurrentInputTargets - "
Jeff Browne839a582010-04-22 18:58:52 -0700686 "resumeWithAppendedMotionSample=%s",
Jeff Browna665ca82010-09-08 11:49:43 -0700687 toString(resumeWithAppendedMotionSample));
Jeff Browne839a582010-04-22 18:58:52 -0700688#endif
689
Jeff Brown54bc2812010-06-15 01:31:58 -0700690 assert(eventEntry->dispatchInProgress); // should already have been set to true
691
Jeff Browne839a582010-04-22 18:58:52 -0700692 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
693 const InputTarget& inputTarget = mCurrentInputTargets.itemAt(i);
694
Jeff Brown53a415e2010-09-15 15:18:56 -0700695 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
Jeff Browne839a582010-04-22 18:58:52 -0700696 if (connectionIndex >= 0) {
697 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown51d45a72010-06-17 20:52:56 -0700698 prepareDispatchCycleLocked(currentTime, connection, eventEntry, & inputTarget,
Jeff Browne839a582010-04-22 18:58:52 -0700699 resumeWithAppendedMotionSample);
700 } else {
701 LOGW("Framework requested delivery of an input event to channel '%s' but it "
702 "is not registered with the input dispatcher.",
703 inputTarget.inputChannel->getName().string());
704 }
705 }
706}
707
Jeff Browna665ca82010-09-08 11:49:43 -0700708void InputDispatcher::startFindingTargetsLocked() {
709 mCurrentInputTargetsValid = false;
710 mCurrentInputTargets.clear();
711 mCurrentInputChannel.clear();
712 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
713}
714
715void InputDispatcher::finishFindingTargetsLocked(const InputWindow* window) {
716 mCurrentInputWindowType = window->layoutParamsType;
717 mCurrentInputChannel = window->inputChannel;
718 mCurrentInputTargetsValid = true;
719}
720
721int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
722 const EventEntry* entry, const InputApplication* application, const InputWindow* window,
723 nsecs_t* nextWakeupTime) {
724 if (application == NULL && window == NULL) {
725 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
726#if DEBUG_FOCUS
727 LOGD("Waiting for system to become ready for input.");
728#endif
729 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
730 mInputTargetWaitStartTime = currentTime;
731 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
732 mInputTargetWaitTimeoutExpired = false;
733 }
734 } else {
735 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
736#if DEBUG_FOCUS
Jeff Brown53a415e2010-09-15 15:18:56 -0700737 LOGD("Waiting for application to become ready for input: %s",
738 getApplicationWindowLabelLocked(application, window).string());
Jeff Browna665ca82010-09-08 11:49:43 -0700739#endif
740 nsecs_t timeout = window ? window->dispatchingTimeout :
741 application ? application->dispatchingTimeout : DEFAULT_INPUT_DISPATCHING_TIMEOUT;
742
743 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
744 mInputTargetWaitStartTime = currentTime;
745 mInputTargetWaitTimeoutTime = currentTime + timeout;
746 mInputTargetWaitTimeoutExpired = false;
747 }
748 }
749
750 if (mInputTargetWaitTimeoutExpired) {
751 return INPUT_EVENT_INJECTION_TIMED_OUT;
752 }
753
754 if (currentTime >= mInputTargetWaitTimeoutTime) {
Jeff Brown53a415e2010-09-15 15:18:56 -0700755 onANRLocked(currentTime, application, window, entry->eventTime, mInputTargetWaitStartTime);
Jeff Browna665ca82010-09-08 11:49:43 -0700756
757 // Force poll loop to wake up immediately on next iteration once we get the
758 // ANR response back from the policy.
759 *nextWakeupTime = LONG_LONG_MIN;
760 return INPUT_EVENT_INJECTION_PENDING;
761 } else {
762 // Force poll loop to wake up when timeout is due.
763 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
764 *nextWakeupTime = mInputTargetWaitTimeoutTime;
765 }
766 return INPUT_EVENT_INJECTION_PENDING;
767 }
768}
769
Jeff Brown53a415e2010-09-15 15:18:56 -0700770void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
771 const sp<InputChannel>& inputChannel) {
Jeff Browna665ca82010-09-08 11:49:43 -0700772 if (newTimeout > 0) {
773 // Extend the timeout.
774 mInputTargetWaitTimeoutTime = now() + newTimeout;
775 } else {
776 // Give up.
777 mInputTargetWaitTimeoutExpired = true;
Jeff Brown53a415e2010-09-15 15:18:56 -0700778
779 // Input state will not be realistic. Mark it out of sync.
Jeff Brown40ad4702010-09-16 11:02:16 -0700780 if (inputChannel.get()) {
781 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
782 if (connectionIndex >= 0) {
783 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
784 connection->inputState.setOutOfSync();
785 }
Jeff Brown53a415e2010-09-15 15:18:56 -0700786 }
Jeff Browna665ca82010-09-08 11:49:43 -0700787 }
788}
789
Jeff Brown53a415e2010-09-15 15:18:56 -0700790nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
Jeff Browna665ca82010-09-08 11:49:43 -0700791 nsecs_t currentTime) {
792 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
793 return currentTime - mInputTargetWaitStartTime;
794 }
795 return 0;
796}
797
798void InputDispatcher::resetANRTimeoutsLocked() {
799#if DEBUG_FOCUS
800 LOGD("Resetting ANR timeouts.");
801#endif
802
Jeff Browna665ca82010-09-08 11:49:43 -0700803 // Reset input target wait timeout.
804 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
805}
806
807int32_t InputDispatcher::findFocusedWindowLocked(nsecs_t currentTime, const EventEntry* entry,
808 nsecs_t* nextWakeupTime, InputWindow** outWindow) {
809 *outWindow = NULL;
810 mCurrentInputTargets.clear();
811
812 int32_t injectionResult;
813
814 // If there is no currently focused window and no focused application
815 // then drop the event.
816 if (! mFocusedWindow) {
817 if (mFocusedApplication) {
818#if DEBUG_FOCUS
819 LOGD("Waiting because there is no focused window but there is a "
Jeff Brown53a415e2010-09-15 15:18:56 -0700820 "focused application that may eventually add a window: %s.",
821 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Browna665ca82010-09-08 11:49:43 -0700822#endif
823 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
824 mFocusedApplication, NULL, nextWakeupTime);
825 goto Unresponsive;
826 }
827
828 LOGI("Dropping event because there is no focused window or focused application.");
829 injectionResult = INPUT_EVENT_INJECTION_FAILED;
830 goto Failed;
831 }
832
833 // Check permissions.
834 if (! checkInjectionPermission(mFocusedWindow, entry->injectorPid, entry->injectorUid)) {
835 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
836 goto Failed;
837 }
838
839 // If the currently focused window is paused then keep waiting.
840 if (mFocusedWindow->paused) {
841#if DEBUG_FOCUS
842 LOGD("Waiting because focused window is paused.");
843#endif
844 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
845 mFocusedApplication, mFocusedWindow, nextWakeupTime);
846 goto Unresponsive;
847 }
848
Jeff Brown53a415e2010-09-15 15:18:56 -0700849 // If the currently focused window is still working on previous events then keep waiting.
850 if (! isWindowFinishedWithPreviousInputLocked(mFocusedWindow)) {
851#if DEBUG_FOCUS
852 LOGD("Waiting because focused window still processing previous input.");
853#endif
854 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
855 mFocusedApplication, mFocusedWindow, nextWakeupTime);
856 goto Unresponsive;
857 }
858
Jeff Browna665ca82010-09-08 11:49:43 -0700859 // Success! Output targets.
860 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
861 *outWindow = mFocusedWindow;
Jeff Brown53a415e2010-09-15 15:18:56 -0700862 addWindowTargetLocked(mFocusedWindow, InputTarget::FLAG_FOREGROUND);
Jeff Browna665ca82010-09-08 11:49:43 -0700863
864 // Done.
865Failed:
866Unresponsive:
Jeff Brown53a415e2010-09-15 15:18:56 -0700867 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
868 updateDispatchStatisticsLocked(currentTime, entry,
869 injectionResult, timeSpentWaitingForApplication);
Jeff Browna665ca82010-09-08 11:49:43 -0700870#if DEBUG_FOCUS
Jeff Brown53a415e2010-09-15 15:18:56 -0700871 LOGD("findFocusedWindow finished: injectionResult=%d, "
872 "timeSpendWaitingForApplication=%0.1fms",
873 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Jeff Browna665ca82010-09-08 11:49:43 -0700874#endif
875 return injectionResult;
876}
877
878int32_t InputDispatcher::findTouchedWindowLocked(nsecs_t currentTime, const MotionEntry* entry,
879 nsecs_t* nextWakeupTime, InputWindow** outWindow) {
880 enum InjectionPermission {
881 INJECTION_PERMISSION_UNKNOWN,
882 INJECTION_PERMISSION_GRANTED,
883 INJECTION_PERMISSION_DENIED
884 };
885
886 *outWindow = NULL;
887 mCurrentInputTargets.clear();
888
889 nsecs_t startTime = now();
890
891 // For security reasons, we defer updating the touch state until we are sure that
892 // event injection will be allowed.
893 //
894 // FIXME In the original code, screenWasOff could never be set to true.
895 // The reason is that the POLICY_FLAG_WOKE_HERE
896 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
897 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
898 // actually enqueued using the policyFlags that appeared in the final EV_SYN
899 // events upon which no preprocessing took place. So policyFlags was always 0.
900 // In the new native input dispatcher we're a bit more careful about event
901 // preprocessing so the touches we receive can actually have non-zero policyFlags.
902 // Unfortunately we obtain undesirable behavior.
903 //
904 // Here's what happens:
905 //
906 // When the device dims in anticipation of going to sleep, touches
907 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
908 // the device to brighten and reset the user activity timer.
909 // Touches on other windows (such as the launcher window)
910 // are dropped. Then after a moment, the device goes to sleep. Oops.
911 //
912 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
913 // instead of POLICY_FLAG_WOKE_HERE...
914 //
915 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
916
917 int32_t action = entry->action;
918
919 // Update the touch state as needed based on the properties of the touch event.
920 int32_t injectionResult;
921 InjectionPermission injectionPermission;
922 if (action == AMOTION_EVENT_ACTION_DOWN) {
923 /* Case 1: ACTION_DOWN */
924
925 InputWindow* newTouchedWindow = NULL;
926 mTempTouchedOutsideTargets.clear();
927
928 int32_t x = int32_t(entry->firstSample.pointerCoords[0].x);
929 int32_t y = int32_t(entry->firstSample.pointerCoords[0].y);
930 InputWindow* topErrorWindow = NULL;
931 bool obscured = false;
932
933 // Traverse windows from front to back to find touched window and outside targets.
934 size_t numWindows = mWindows.size();
935 for (size_t i = 0; i < numWindows; i++) {
936 InputWindow* window = & mWindows.editItemAt(i);
937 int32_t flags = window->layoutParamsFlags;
938
939 if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
940 if (! topErrorWindow) {
941 topErrorWindow = window;
942 }
943 }
944
945 if (window->visible) {
946 if (! (flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
947 bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
948 | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
949 if (isTouchModal || window->touchableAreaContainsPoint(x, y)) {
950 if (! screenWasOff || flags & InputWindow::FLAG_TOUCHABLE_WHEN_WAKING) {
951 newTouchedWindow = window;
952 obscured = isWindowObscuredLocked(window);
953 }
954 break; // found touched window, exit window loop
955 }
956 }
957
958 if (flags & InputWindow::FLAG_WATCH_OUTSIDE_TOUCH) {
959 OutsideTarget outsideTarget;
960 outsideTarget.window = window;
961 outsideTarget.obscured = isWindowObscuredLocked(window);
962 mTempTouchedOutsideTargets.push(outsideTarget);
963 }
964 }
965 }
966
967 // If there is an error window but it is not taking focus (typically because
968 // it is invisible) then wait for it. Any other focused window may in
969 // fact be in ANR state.
970 if (topErrorWindow && newTouchedWindow != topErrorWindow) {
971#if DEBUG_FOCUS
972 LOGD("Waiting because system error window is pending.");
973#endif
974 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
975 NULL, NULL, nextWakeupTime);
976 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
977 goto Unresponsive;
978 }
979
980 // If we did not find a touched window then fail.
981 if (! newTouchedWindow) {
982 if (mFocusedApplication) {
983#if DEBUG_FOCUS
984 LOGD("Waiting because there is no touched window but there is a "
Jeff Brown53a415e2010-09-15 15:18:56 -0700985 "focused application that may eventually add a new window: %s.",
986 getApplicationWindowLabelLocked(mFocusedApplication, NULL).string());
Jeff Browna665ca82010-09-08 11:49:43 -0700987#endif
988 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
989 mFocusedApplication, NULL, nextWakeupTime);
990 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
991 goto Unresponsive;
992 }
993
994 LOGI("Dropping event because there is no touched window or focused application.");
995 injectionResult = INPUT_EVENT_INJECTION_FAILED;
996 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
997 goto Failed;
998 }
999
1000 // Check permissions.
1001 if (! checkInjectionPermission(newTouchedWindow, entry->injectorPid, entry->injectorUid)) {
1002 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1003 injectionPermission = INJECTION_PERMISSION_DENIED;
1004 goto Failed;
1005 }
1006
1007 // If the touched window is paused then keep waiting.
1008 if (newTouchedWindow->paused) {
1009#if DEBUG_INPUT_DISPATCHER_POLICY
1010 LOGD("Waiting because touched window is paused.");
1011#endif
1012 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1013 NULL, newTouchedWindow, nextWakeupTime);
1014 injectionPermission = INJECTION_PERMISSION_GRANTED;
1015 goto Unresponsive;
1016 }
1017
Jeff Brown53a415e2010-09-15 15:18:56 -07001018 // If the touched window is still working on previous events then keep waiting.
1019 if (! isWindowFinishedWithPreviousInputLocked(newTouchedWindow)) {
1020#if DEBUG_FOCUS
1021 LOGD("Waiting because touched window still processing previous input.");
1022#endif
1023 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1024 NULL, newTouchedWindow, nextWakeupTime);
1025 injectionPermission = INJECTION_PERMISSION_GRANTED;
1026 goto Unresponsive;
1027 }
1028
Jeff Browna665ca82010-09-08 11:49:43 -07001029 // Success! Update the touch dispatch state for real.
1030 releaseTouchedWindowLocked();
1031
1032 mTouchedWindow = newTouchedWindow;
1033 mTouchedWindowIsObscured = obscured;
1034
1035 if (newTouchedWindow->hasWallpaper) {
1036 mTouchedWallpaperWindows.appendVector(mWallpaperWindows);
1037 }
1038 } else {
1039 /* Case 2: Everything but ACTION_DOWN */
1040
1041 // Check permissions.
1042 if (! checkInjectionPermission(mTouchedWindow, entry->injectorPid, entry->injectorUid)) {
1043 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1044 injectionPermission = INJECTION_PERMISSION_DENIED;
1045 goto Failed;
1046 }
1047
1048 // If the pointer is not currently down, then ignore the event.
1049 if (! mTouchDown) {
1050 LOGI("Dropping event because the pointer is not down.");
1051 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1052 injectionPermission = INJECTION_PERMISSION_GRANTED;
1053 goto Failed;
1054 }
1055
1056 // If there is no currently touched window then fail.
1057 if (! mTouchedWindow) {
1058#if DEBUG_INPUT_DISPATCHER_POLICY
1059 LOGD("Dropping event because there is no touched window to receive it.");
1060#endif
1061 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1062 injectionPermission = INJECTION_PERMISSION_GRANTED;
1063 goto Failed;
1064 }
1065
1066 // If the touched window is paused then keep waiting.
1067 if (mTouchedWindow->paused) {
1068#if DEBUG_INPUT_DISPATCHER_POLICY
1069 LOGD("Waiting because touched window is paused.");
1070#endif
1071 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1072 NULL, mTouchedWindow, nextWakeupTime);
1073 injectionPermission = INJECTION_PERMISSION_GRANTED;
1074 goto Unresponsive;
1075 }
Jeff Brown53a415e2010-09-15 15:18:56 -07001076
1077 // If the touched window is still working on previous events then keep waiting.
1078 if (! isWindowFinishedWithPreviousInputLocked(mTouchedWindow)) {
1079#if DEBUG_FOCUS
1080 LOGD("Waiting because touched window still processing previous input.");
1081#endif
1082 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1083 NULL, mTouchedWindow, nextWakeupTime);
1084 injectionPermission = INJECTION_PERMISSION_GRANTED;
1085 goto Unresponsive;
1086 }
Jeff Browna665ca82010-09-08 11:49:43 -07001087 }
1088
1089 // Success! Output targets.
1090 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1091 injectionPermission = INJECTION_PERMISSION_GRANTED;
1092
1093 {
1094 size_t numWallpaperWindows = mTouchedWallpaperWindows.size();
1095 for (size_t i = 0; i < numWallpaperWindows; i++) {
1096 addWindowTargetLocked(mTouchedWallpaperWindows[i],
Jeff Brown53a415e2010-09-15 15:18:56 -07001097 InputTarget::FLAG_WINDOW_IS_OBSCURED);
Jeff Browna665ca82010-09-08 11:49:43 -07001098 }
1099
1100 size_t numOutsideTargets = mTempTouchedOutsideTargets.size();
1101 for (size_t i = 0; i < numOutsideTargets; i++) {
1102 const OutsideTarget& outsideTarget = mTempTouchedOutsideTargets[i];
1103 int32_t outsideTargetFlags = InputTarget::FLAG_OUTSIDE;
1104 if (outsideTarget.obscured) {
1105 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1106 }
Jeff Brown53a415e2010-09-15 15:18:56 -07001107 addWindowTargetLocked(outsideTarget.window, outsideTargetFlags);
Jeff Browna665ca82010-09-08 11:49:43 -07001108 }
1109 mTempTouchedOutsideTargets.clear();
1110
Jeff Brown53a415e2010-09-15 15:18:56 -07001111 int32_t targetFlags = InputTarget::FLAG_FOREGROUND;
Jeff Browna665ca82010-09-08 11:49:43 -07001112 if (mTouchedWindowIsObscured) {
1113 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1114 }
Jeff Brown53a415e2010-09-15 15:18:56 -07001115 addWindowTargetLocked(mTouchedWindow, targetFlags);
Jeff Browna665ca82010-09-08 11:49:43 -07001116 *outWindow = mTouchedWindow;
1117 }
1118
1119Failed:
1120 // Check injection permission once and for all.
1121 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1122 if (checkInjectionPermission(action == AMOTION_EVENT_ACTION_DOWN ? NULL : mTouchedWindow,
1123 entry->injectorPid, entry->injectorUid)) {
1124 injectionPermission = INJECTION_PERMISSION_GRANTED;
1125 } else {
1126 injectionPermission = INJECTION_PERMISSION_DENIED;
1127 }
1128 }
1129
1130 // Update final pieces of touch state if the injector had permission.
1131 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1132 if (action == AMOTION_EVENT_ACTION_DOWN) {
1133 if (mTouchDown) {
1134 // This is weird. We got a down but we thought it was already down!
1135 LOGW("Pointer down received while already down.");
1136 } else {
1137 mTouchDown = true;
1138 }
1139
1140 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1141 // Since we failed to identify a target for this touch down, we may still
1142 // be holding on to an earlier target from a previous touch down. Release it.
1143 releaseTouchedWindowLocked();
1144 }
1145 } else if (action == AMOTION_EVENT_ACTION_UP) {
1146 mTouchDown = false;
1147 releaseTouchedWindowLocked();
1148 }
1149 } else {
1150 LOGW("Not updating touch focus because injection was denied.");
1151 }
1152
1153Unresponsive:
Jeff Brown53a415e2010-09-15 15:18:56 -07001154 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1155 updateDispatchStatisticsLocked(currentTime, entry,
1156 injectionResult, timeSpentWaitingForApplication);
Jeff Browna665ca82010-09-08 11:49:43 -07001157#if DEBUG_FOCUS
Jeff Brown53a415e2010-09-15 15:18:56 -07001158 LOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d,"
1159 "timeSpendWaitingForApplication=%0.1fms",
1160 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Jeff Browna665ca82010-09-08 11:49:43 -07001161#endif
1162 return injectionResult;
1163}
1164
1165void InputDispatcher::releaseTouchedWindowLocked() {
1166 mTouchedWindow = NULL;
1167 mTouchedWindowIsObscured = false;
1168 mTouchedWallpaperWindows.clear();
1169}
1170
Jeff Brown53a415e2010-09-15 15:18:56 -07001171void InputDispatcher::addWindowTargetLocked(const InputWindow* window, int32_t targetFlags) {
Jeff Browna665ca82010-09-08 11:49:43 -07001172 mCurrentInputTargets.push();
1173
1174 InputTarget& target = mCurrentInputTargets.editTop();
1175 target.inputChannel = window->inputChannel;
1176 target.flags = targetFlags;
Jeff Browna665ca82010-09-08 11:49:43 -07001177 target.xOffset = - window->frameLeft;
1178 target.yOffset = - window->frameTop;
1179}
1180
1181void InputDispatcher::addMonitoringTargetsLocked() {
1182 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1183 mCurrentInputTargets.push();
1184
1185 InputTarget& target = mCurrentInputTargets.editTop();
1186 target.inputChannel = mMonitoringChannels[i];
1187 target.flags = 0;
Jeff Browna665ca82010-09-08 11:49:43 -07001188 target.xOffset = 0;
1189 target.yOffset = 0;
1190 }
1191}
1192
1193bool InputDispatcher::checkInjectionPermission(const InputWindow* window,
1194 int32_t injectorPid, int32_t injectorUid) {
1195 if (injectorUid > 0 && (window == NULL || window->ownerUid != injectorUid)) {
1196 bool result = mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
1197 if (! result) {
1198 if (window) {
1199 LOGW("Permission denied: injecting event from pid %d uid %d to window "
1200 "with input channel %s owned by uid %d",
1201 injectorPid, injectorUid, window->inputChannel->getName().string(),
1202 window->ownerUid);
1203 } else {
1204 LOGW("Permission denied: injecting event from pid %d uid %d",
1205 injectorPid, injectorUid);
1206 }
1207 return false;
1208 }
1209 }
1210 return true;
1211}
1212
1213bool InputDispatcher::isWindowObscuredLocked(const InputWindow* window) {
1214 size_t numWindows = mWindows.size();
1215 for (size_t i = 0; i < numWindows; i++) {
1216 const InputWindow* other = & mWindows.itemAt(i);
1217 if (other == window) {
1218 break;
1219 }
1220 if (other->visible && window->visibleFrameIntersects(other)) {
1221 return true;
1222 }
1223 }
1224 return false;
1225}
1226
Jeff Brown53a415e2010-09-15 15:18:56 -07001227bool InputDispatcher::isWindowFinishedWithPreviousInputLocked(const InputWindow* window) {
1228 ssize_t connectionIndex = getConnectionIndexLocked(window->inputChannel);
1229 if (connectionIndex >= 0) {
1230 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1231 return connection->outboundQueue.isEmpty();
1232 } else {
1233 return true;
1234 }
1235}
1236
1237String8 InputDispatcher::getApplicationWindowLabelLocked(const InputApplication* application,
1238 const InputWindow* window) {
1239 if (application) {
1240 if (window) {
1241 String8 label(application->name);
1242 label.append(" - ");
1243 label.append(window->name);
1244 return label;
1245 } else {
1246 return application->name;
1247 }
1248 } else if (window) {
1249 return window->name;
1250 } else {
1251 return String8("<unknown application or window>");
1252 }
1253}
1254
Jeff Browna665ca82010-09-08 11:49:43 -07001255void InputDispatcher::pokeUserActivityLocked(nsecs_t eventTime,
1256 int32_t windowType, int32_t eventType) {
1257 CommandEntry* commandEntry = postCommandLocked(
1258 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1259 commandEntry->eventTime = eventTime;
1260 commandEntry->windowType = windowType;
1261 commandEntry->userActivityEventType = eventType;
1262}
1263
Jeff Brown51d45a72010-06-17 20:52:56 -07001264void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1265 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
Jeff Browne839a582010-04-22 18:58:52 -07001266 bool resumeWithAppendedMotionSample) {
1267#if DEBUG_DISPATCH_CYCLE
Jeff Brown53a415e2010-09-15 15:18:56 -07001268 LOGD("channel '%s' ~ prepareDispatchCycle - flags=%d, "
Jeff Browne839a582010-04-22 18:58:52 -07001269 "xOffset=%f, yOffset=%f, resumeWithAppendedMotionSample=%s",
Jeff Brown53a415e2010-09-15 15:18:56 -07001270 connection->getInputChannelName(), inputTarget->flags,
Jeff Browne839a582010-04-22 18:58:52 -07001271 inputTarget->xOffset, inputTarget->yOffset,
Jeff Browna665ca82010-09-08 11:49:43 -07001272 toString(resumeWithAppendedMotionSample));
Jeff Browne839a582010-04-22 18:58:52 -07001273#endif
1274
1275 // Skip this event if the connection status is not normal.
Jeff Brown53a415e2010-09-15 15:18:56 -07001276 // We don't want to enqueue additional outbound events if the connection is broken.
Jeff Browne839a582010-04-22 18:58:52 -07001277 if (connection->status != Connection::STATUS_NORMAL) {
Jeff Browna665ca82010-09-08 11:49:43 -07001278 LOGW("channel '%s' ~ Dropping event because the channel status is %s",
1279 connection->getInputChannelName(), connection->getStatusLabel());
Jeff Browne839a582010-04-22 18:58:52 -07001280 return;
1281 }
1282
1283 // Resume the dispatch cycle with a freshly appended motion sample.
1284 // First we check that the last dispatch entry in the outbound queue is for the same
1285 // motion event to which we appended the motion sample. If we find such a dispatch
1286 // entry, and if it is currently in progress then we try to stream the new sample.
1287 bool wasEmpty = connection->outboundQueue.isEmpty();
1288
1289 if (! wasEmpty && resumeWithAppendedMotionSample) {
1290 DispatchEntry* motionEventDispatchEntry =
1291 connection->findQueuedDispatchEntryForEvent(eventEntry);
1292 if (motionEventDispatchEntry) {
1293 // If the dispatch entry is not in progress, then we must be busy dispatching an
1294 // earlier event. Not a problem, the motion event is on the outbound queue and will
1295 // be dispatched later.
1296 if (! motionEventDispatchEntry->inProgress) {
1297#if DEBUG_BATCHING
1298 LOGD("channel '%s' ~ Not streaming because the motion event has "
1299 "not yet been dispatched. "
1300 "(Waiting for earlier events to be consumed.)",
1301 connection->getInputChannelName());
1302#endif
1303 return;
1304 }
1305
1306 // If the dispatch entry is in progress but it already has a tail of pending
1307 // motion samples, then it must mean that the shared memory buffer filled up.
1308 // Not a problem, when this dispatch cycle is finished, we will eventually start
1309 // a new dispatch cycle to process the tail and that tail includes the newly
1310 // appended motion sample.
1311 if (motionEventDispatchEntry->tailMotionSample) {
1312#if DEBUG_BATCHING
1313 LOGD("channel '%s' ~ Not streaming because no new samples can "
1314 "be appended to the motion event in this dispatch cycle. "
1315 "(Waiting for next dispatch cycle to start.)",
1316 connection->getInputChannelName());
1317#endif
1318 return;
1319 }
1320
1321 // The dispatch entry is in progress and is still potentially open for streaming.
1322 // Try to stream the new motion sample. This might fail if the consumer has already
1323 // consumed the motion event (or if the channel is broken).
1324 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1325 status_t status = connection->inputPublisher.appendMotionSample(
1326 appendedMotionSample->eventTime, appendedMotionSample->pointerCoords);
1327 if (status == OK) {
1328#if DEBUG_BATCHING
1329 LOGD("channel '%s' ~ Successfully streamed new motion sample.",
1330 connection->getInputChannelName());
1331#endif
1332 return;
1333 }
1334
1335#if DEBUG_BATCHING
1336 if (status == NO_MEMORY) {
1337 LOGD("channel '%s' ~ Could not append motion sample to currently "
1338 "dispatched move event because the shared memory buffer is full. "
1339 "(Waiting for next dispatch cycle to start.)",
1340 connection->getInputChannelName());
1341 } else if (status == status_t(FAILED_TRANSACTION)) {
1342 LOGD("channel '%s' ~ Could not append motion sample to currently "
Jeff Brown50de30a2010-06-22 01:27:15 -07001343 "dispatched move event because the event has already been consumed. "
Jeff Browne839a582010-04-22 18:58:52 -07001344 "(Waiting for next dispatch cycle to start.)",
1345 connection->getInputChannelName());
1346 } else {
1347 LOGD("channel '%s' ~ Could not append motion sample to currently "
1348 "dispatched move event due to an error, status=%d. "
1349 "(Waiting for next dispatch cycle to start.)",
1350 connection->getInputChannelName(), status);
1351 }
1352#endif
1353 // Failed to stream. Start a new tail of pending motion samples to dispatch
1354 // in the next cycle.
1355 motionEventDispatchEntry->tailMotionSample = appendedMotionSample;
1356 return;
1357 }
1358 }
1359
Jeff Browna665ca82010-09-08 11:49:43 -07001360 // Bring the input state back in line with reality in case it drifted off during an ANR.
1361 if (connection->inputState.isOutOfSync()) {
1362 mTempCancelationEvents.clear();
1363 connection->inputState.synthesizeCancelationEvents(& mAllocator, mTempCancelationEvents);
1364 connection->inputState.resetOutOfSync();
1365
1366 if (! mTempCancelationEvents.isEmpty()) {
1367 LOGI("channel '%s' ~ Generated %d cancelation events to bring channel back in sync "
1368 "with reality.",
1369 connection->getInputChannelName(), mTempCancelationEvents.size());
1370
1371 for (size_t i = 0; i < mTempCancelationEvents.size(); i++) {
1372 EventEntry* cancelationEventEntry = mTempCancelationEvents.itemAt(i);
1373 switch (cancelationEventEntry->type) {
1374 case EventEntry::TYPE_KEY:
1375 logOutboundKeyDetailsLocked(" ",
1376 static_cast<KeyEntry*>(cancelationEventEntry));
1377 break;
1378 case EventEntry::TYPE_MOTION:
1379 logOutboundMotionDetailsLocked(" ",
1380 static_cast<MotionEntry*>(cancelationEventEntry));
1381 break;
1382 }
1383
1384 DispatchEntry* cancelationDispatchEntry =
1385 mAllocator.obtainDispatchEntry(cancelationEventEntry,
Jeff Brown53a415e2010-09-15 15:18:56 -07001386 0, inputTarget->xOffset, inputTarget->yOffset); // increments ref
Jeff Browna665ca82010-09-08 11:49:43 -07001387 connection->outboundQueue.enqueueAtTail(cancelationDispatchEntry);
1388
1389 mAllocator.releaseEventEntry(cancelationEventEntry);
1390 }
1391 }
1392 }
1393
Jeff Browne839a582010-04-22 18:58:52 -07001394 // This is a new event.
1395 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Jeff Browna665ca82010-09-08 11:49:43 -07001396 DispatchEntry* dispatchEntry = mAllocator.obtainDispatchEntry(eventEntry, // increments ref
Jeff Brown53a415e2010-09-15 15:18:56 -07001397 inputTarget->flags, inputTarget->xOffset, inputTarget->yOffset);
1398 if (dispatchEntry->hasForegroundTarget()) {
1399 eventEntry->pendingForegroundDispatches += 1;
Jeff Brownf67c53e2010-07-28 15:48:59 -07001400 }
1401
Jeff Browne839a582010-04-22 18:58:52 -07001402 // Handle the case where we could not stream a new motion sample because the consumer has
1403 // already consumed the motion event (otherwise the corresponding dispatch entry would
1404 // still be in the outbound queue for this connection). We set the head motion sample
1405 // to the list starting with the newly appended motion sample.
1406 if (resumeWithAppendedMotionSample) {
1407#if DEBUG_BATCHING
1408 LOGD("channel '%s' ~ Preparing a new dispatch cycle for additional motion samples "
1409 "that cannot be streamed because the motion event has already been consumed.",
1410 connection->getInputChannelName());
1411#endif
1412 MotionSample* appendedMotionSample = static_cast<MotionEntry*>(eventEntry)->lastSample;
1413 dispatchEntry->headMotionSample = appendedMotionSample;
1414 }
1415
1416 // Enqueue the dispatch entry.
1417 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1418
1419 // If the outbound queue was previously empty, start the dispatch cycle going.
1420 if (wasEmpty) {
Jeff Brown51d45a72010-06-17 20:52:56 -07001421 activateConnectionLocked(connection.get());
Jeff Brown53a415e2010-09-15 15:18:56 -07001422 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001423 }
1424}
1425
Jeff Brown51d45a72010-06-17 20:52:56 -07001426void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Jeff Brown53a415e2010-09-15 15:18:56 -07001427 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001428#if DEBUG_DISPATCH_CYCLE
1429 LOGD("channel '%s' ~ startDispatchCycle",
1430 connection->getInputChannelName());
1431#endif
1432
1433 assert(connection->status == Connection::STATUS_NORMAL);
1434 assert(! connection->outboundQueue.isEmpty());
1435
Jeff Browna665ca82010-09-08 11:49:43 -07001436 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Browne839a582010-04-22 18:58:52 -07001437 assert(! dispatchEntry->inProgress);
1438
Jeff Browna665ca82010-09-08 11:49:43 -07001439 // Mark the dispatch entry as in progress.
1440 dispatchEntry->inProgress = true;
1441
1442 // Update the connection's input state.
1443 InputState::Consistency consistency = connection->inputState.trackEvent(
1444 dispatchEntry->eventEntry);
1445
1446#if FILTER_INPUT_EVENTS
1447 // Filter out inconsistent sequences of input events.
1448 // The input system may drop or inject events in a way that could violate implicit
1449 // invariants on input state and potentially cause an application to crash
1450 // or think that a key or pointer is stuck down. Technically we make no guarantees
1451 // of consistency but it would be nice to improve on this where possible.
1452 // XXX: This code is a proof of concept only. Not ready for prime time.
1453 if (consistency == InputState::TOLERABLE) {
1454#if DEBUG_DISPATCH_CYCLE
1455 LOGD("channel '%s' ~ Sending an event that is inconsistent with the connection's "
1456 "current input state but that is likely to be tolerated by the application.",
1457 connection->getInputChannelName());
1458#endif
1459 } else if (consistency == InputState::BROKEN) {
1460 LOGI("channel '%s' ~ Dropping an event that is inconsistent with the connection's "
1461 "current input state and that is likely to cause the application to crash.",
1462 connection->getInputChannelName());
1463 startNextDispatchCycleLocked(currentTime, connection);
1464 return;
1465 }
1466#endif
Jeff Browne839a582010-04-22 18:58:52 -07001467
1468 // Publish the event.
1469 status_t status;
1470 switch (dispatchEntry->eventEntry->type) {
1471 case EventEntry::TYPE_KEY: {
1472 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
1473
1474 // Apply target flags.
1475 int32_t action = keyEntry->action;
1476 int32_t flags = keyEntry->flags;
1477 if (dispatchEntry->targetFlags & InputTarget::FLAG_CANCEL) {
Jeff Brown5c1ed842010-07-14 18:48:53 -07001478 flags |= AKEY_EVENT_FLAG_CANCELED;
Jeff Browne839a582010-04-22 18:58:52 -07001479 }
1480
1481 // Publish the key event.
Jeff Brown5c1ed842010-07-14 18:48:53 -07001482 status = connection->inputPublisher.publishKeyEvent(keyEntry->deviceId, keyEntry->source,
Jeff Browne839a582010-04-22 18:58:52 -07001483 action, flags, keyEntry->keyCode, keyEntry->scanCode,
1484 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1485 keyEntry->eventTime);
1486
1487 if (status) {
1488 LOGE("channel '%s' ~ Could not publish key event, "
1489 "status=%d", connection->getInputChannelName(), status);
1490 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1491 return;
1492 }
1493 break;
1494 }
1495
1496 case EventEntry::TYPE_MOTION: {
1497 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
1498
1499 // Apply target flags.
1500 int32_t action = motionEntry->action;
Jeff Brownaf30ff62010-09-01 17:01:00 -07001501 int32_t flags = motionEntry->flags;
Jeff Browne839a582010-04-22 18:58:52 -07001502 if (dispatchEntry->targetFlags & InputTarget::FLAG_OUTSIDE) {
Jeff Brown5c1ed842010-07-14 18:48:53 -07001503 action = AMOTION_EVENT_ACTION_OUTSIDE;
Jeff Browne839a582010-04-22 18:58:52 -07001504 }
1505 if (dispatchEntry->targetFlags & InputTarget::FLAG_CANCEL) {
Jeff Brown5c1ed842010-07-14 18:48:53 -07001506 action = AMOTION_EVENT_ACTION_CANCEL;
Jeff Browne839a582010-04-22 18:58:52 -07001507 }
Jeff Brownaf30ff62010-09-01 17:01:00 -07001508 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1509 flags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1510 }
Jeff Browne839a582010-04-22 18:58:52 -07001511
1512 // If headMotionSample is non-NULL, then it points to the first new sample that we
1513 // were unable to dispatch during the previous cycle so we resume dispatching from
1514 // that point in the list of motion samples.
1515 // Otherwise, we just start from the first sample of the motion event.
1516 MotionSample* firstMotionSample = dispatchEntry->headMotionSample;
1517 if (! firstMotionSample) {
1518 firstMotionSample = & motionEntry->firstSample;
1519 }
1520
Jeff Brownf26db0d2010-07-16 17:21:06 -07001521 // Set the X and Y offset depending on the input source.
1522 float xOffset, yOffset;
1523 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
1524 xOffset = dispatchEntry->xOffset;
1525 yOffset = dispatchEntry->yOffset;
1526 } else {
1527 xOffset = 0.0f;
1528 yOffset = 0.0f;
1529 }
1530
Jeff Browne839a582010-04-22 18:58:52 -07001531 // Publish the motion event and the first motion sample.
1532 status = connection->inputPublisher.publishMotionEvent(motionEntry->deviceId,
Jeff Brownaf30ff62010-09-01 17:01:00 -07001533 motionEntry->source, action, flags, motionEntry->edgeFlags, motionEntry->metaState,
Jeff Brownf26db0d2010-07-16 17:21:06 -07001534 xOffset, yOffset,
Jeff Browne839a582010-04-22 18:58:52 -07001535 motionEntry->xPrecision, motionEntry->yPrecision,
1536 motionEntry->downTime, firstMotionSample->eventTime,
1537 motionEntry->pointerCount, motionEntry->pointerIds,
1538 firstMotionSample->pointerCoords);
1539
1540 if (status) {
1541 LOGE("channel '%s' ~ Could not publish motion event, "
1542 "status=%d", connection->getInputChannelName(), status);
1543 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1544 return;
1545 }
1546
1547 // Append additional motion samples.
1548 MotionSample* nextMotionSample = firstMotionSample->next;
1549 for (; nextMotionSample != NULL; nextMotionSample = nextMotionSample->next) {
1550 status = connection->inputPublisher.appendMotionSample(
1551 nextMotionSample->eventTime, nextMotionSample->pointerCoords);
1552 if (status == NO_MEMORY) {
1553#if DEBUG_DISPATCH_CYCLE
1554 LOGD("channel '%s' ~ Shared memory buffer full. Some motion samples will "
1555 "be sent in the next dispatch cycle.",
1556 connection->getInputChannelName());
1557#endif
1558 break;
1559 }
1560 if (status != OK) {
1561 LOGE("channel '%s' ~ Could not append motion sample "
1562 "for a reason other than out of memory, status=%d",
1563 connection->getInputChannelName(), status);
1564 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1565 return;
1566 }
1567 }
1568
1569 // Remember the next motion sample that we could not dispatch, in case we ran out
1570 // of space in the shared memory buffer.
1571 dispatchEntry->tailMotionSample = nextMotionSample;
1572 break;
1573 }
1574
1575 default: {
1576 assert(false);
1577 }
1578 }
1579
1580 // Send the dispatch signal.
1581 status = connection->inputPublisher.sendDispatchSignal();
1582 if (status) {
1583 LOGE("channel '%s' ~ Could not send dispatch signal, status=%d",
1584 connection->getInputChannelName(), status);
1585 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1586 return;
1587 }
1588
1589 // Record information about the newly started dispatch cycle.
Jeff Browne839a582010-04-22 18:58:52 -07001590 connection->lastEventTime = dispatchEntry->eventEntry->eventTime;
1591 connection->lastDispatchTime = currentTime;
1592
Jeff Browne839a582010-04-22 18:58:52 -07001593 // Notify other system components.
1594 onDispatchCycleStartedLocked(currentTime, connection);
1595}
1596
Jeff Brown51d45a72010-06-17 20:52:56 -07001597void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
1598 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001599#if DEBUG_DISPATCH_CYCLE
Jeff Brown54bc2812010-06-15 01:31:58 -07001600 LOGD("channel '%s' ~ finishDispatchCycle - %01.1fms since event, "
Jeff Browne839a582010-04-22 18:58:52 -07001601 "%01.1fms since dispatch",
1602 connection->getInputChannelName(),
1603 connection->getEventLatencyMillis(currentTime),
1604 connection->getDispatchLatencyMillis(currentTime));
1605#endif
1606
Jeff Brown54bc2812010-06-15 01:31:58 -07001607 if (connection->status == Connection::STATUS_BROKEN
1608 || connection->status == Connection::STATUS_ZOMBIE) {
Jeff Browne839a582010-04-22 18:58:52 -07001609 return;
1610 }
1611
Jeff Brown53a415e2010-09-15 15:18:56 -07001612 // Notify other system components.
1613 onDispatchCycleFinishedLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001614
1615 // Reset the publisher since the event has been consumed.
1616 // We do this now so that the publisher can release some of its internal resources
1617 // while waiting for the next dispatch cycle to begin.
1618 status_t status = connection->inputPublisher.reset();
1619 if (status) {
1620 LOGE("channel '%s' ~ Could not reset publisher, status=%d",
1621 connection->getInputChannelName(), status);
1622 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
1623 return;
1624 }
1625
Jeff Browna665ca82010-09-08 11:49:43 -07001626 startNextDispatchCycleLocked(currentTime, connection);
1627}
1628
1629void InputDispatcher::startNextDispatchCycleLocked(nsecs_t currentTime,
1630 const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07001631 // Start the next dispatch cycle for this connection.
1632 while (! connection->outboundQueue.isEmpty()) {
Jeff Browna665ca82010-09-08 11:49:43 -07001633 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
Jeff Browne839a582010-04-22 18:58:52 -07001634 if (dispatchEntry->inProgress) {
1635 // Finish or resume current event in progress.
1636 if (dispatchEntry->tailMotionSample) {
1637 // We have a tail of undispatched motion samples.
1638 // Reuse the same DispatchEntry and start a new cycle.
1639 dispatchEntry->inProgress = false;
1640 dispatchEntry->headMotionSample = dispatchEntry->tailMotionSample;
1641 dispatchEntry->tailMotionSample = NULL;
Jeff Brown53a415e2010-09-15 15:18:56 -07001642 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001643 return;
1644 }
1645 // Finished.
1646 connection->outboundQueue.dequeueAtHead();
Jeff Brown53a415e2010-09-15 15:18:56 -07001647 if (dispatchEntry->hasForegroundTarget()) {
1648 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Brownf67c53e2010-07-28 15:48:59 -07001649 }
Jeff Browne839a582010-04-22 18:58:52 -07001650 mAllocator.releaseDispatchEntry(dispatchEntry);
1651 } else {
1652 // If the head is not in progress, then we must have already dequeued the in
Jeff Brown53a415e2010-09-15 15:18:56 -07001653 // progress event, which means we actually aborted it.
Jeff Browne839a582010-04-22 18:58:52 -07001654 // So just start the next event for this connection.
Jeff Brown53a415e2010-09-15 15:18:56 -07001655 startDispatchCycleLocked(currentTime, connection);
Jeff Browne839a582010-04-22 18:58:52 -07001656 return;
1657 }
1658 }
1659
1660 // Outbound queue is empty, deactivate the connection.
Jeff Brown51d45a72010-06-17 20:52:56 -07001661 deactivateConnectionLocked(connection.get());
Jeff Browne839a582010-04-22 18:58:52 -07001662}
1663
Jeff Brown51d45a72010-06-17 20:52:56 -07001664void InputDispatcher::abortDispatchCycleLocked(nsecs_t currentTime,
1665 const sp<Connection>& connection, bool broken) {
Jeff Browne839a582010-04-22 18:58:52 -07001666#if DEBUG_DISPATCH_CYCLE
Jeff Brown54bc2812010-06-15 01:31:58 -07001667 LOGD("channel '%s' ~ abortDispatchCycle - broken=%s",
Jeff Browna665ca82010-09-08 11:49:43 -07001668 connection->getInputChannelName(), toString(broken));
Jeff Browne839a582010-04-22 18:58:52 -07001669#endif
1670
Jeff Browna665ca82010-09-08 11:49:43 -07001671 // Input state will no longer be realistic.
1672 connection->inputState.setOutOfSync();
Jeff Browne839a582010-04-22 18:58:52 -07001673
Jeff Browna665ca82010-09-08 11:49:43 -07001674 // Clear the outbound queue.
Jeff Brown53a415e2010-09-15 15:18:56 -07001675 drainOutboundQueueLocked(connection.get());
Jeff Browne839a582010-04-22 18:58:52 -07001676
1677 // Handle the case where the connection appears to be unrecoverably broken.
Jeff Brown54bc2812010-06-15 01:31:58 -07001678 // Ignore already broken or zombie connections.
Jeff Browne839a582010-04-22 18:58:52 -07001679 if (broken) {
Jeff Brown53a415e2010-09-15 15:18:56 -07001680 if (connection->status == Connection::STATUS_NORMAL) {
Jeff Brown54bc2812010-06-15 01:31:58 -07001681 connection->status = Connection::STATUS_BROKEN;
Jeff Browne839a582010-04-22 18:58:52 -07001682
Jeff Brown54bc2812010-06-15 01:31:58 -07001683 // Notify other system components.
1684 onDispatchCycleBrokenLocked(currentTime, connection);
1685 }
Jeff Browne839a582010-04-22 18:58:52 -07001686 }
Jeff Browne839a582010-04-22 18:58:52 -07001687}
1688
Jeff Brown53a415e2010-09-15 15:18:56 -07001689void InputDispatcher::drainOutboundQueueLocked(Connection* connection) {
1690 while (! connection->outboundQueue.isEmpty()) {
1691 DispatchEntry* dispatchEntry = connection->outboundQueue.dequeueAtHead();
1692 if (dispatchEntry->hasForegroundTarget()) {
1693 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001694 }
1695 mAllocator.releaseDispatchEntry(dispatchEntry);
Jeff Browna665ca82010-09-08 11:49:43 -07001696 }
1697
Jeff Brown53a415e2010-09-15 15:18:56 -07001698 deactivateConnectionLocked(connection);
Jeff Browna665ca82010-09-08 11:49:43 -07001699}
1700
Jeff Brown59abe7e2010-09-13 23:17:30 -07001701int InputDispatcher::handleReceiveCallback(int receiveFd, int events, void* data) {
Jeff Browne839a582010-04-22 18:58:52 -07001702 InputDispatcher* d = static_cast<InputDispatcher*>(data);
1703
1704 { // acquire lock
1705 AutoMutex _l(d->mLock);
1706
1707 ssize_t connectionIndex = d->mConnectionsByReceiveFd.indexOfKey(receiveFd);
1708 if (connectionIndex < 0) {
1709 LOGE("Received spurious receive callback for unknown input channel. "
1710 "fd=%d, events=0x%x", receiveFd, events);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001711 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001712 }
1713
Jeff Brown51d45a72010-06-17 20:52:56 -07001714 nsecs_t currentTime = now();
Jeff Browne839a582010-04-22 18:58:52 -07001715
1716 sp<Connection> connection = d->mConnectionsByReceiveFd.valueAt(connectionIndex);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001717 if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {
Jeff Browne839a582010-04-22 18:58:52 -07001718 LOGE("channel '%s' ~ Consumer closed input channel or an error occurred. "
1719 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown51d45a72010-06-17 20:52:56 -07001720 d->abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07001721 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001722 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001723 }
1724
Jeff Brown59abe7e2010-09-13 23:17:30 -07001725 if (! (events & ALOOPER_EVENT_INPUT)) {
Jeff Browne839a582010-04-22 18:58:52 -07001726 LOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
1727 "events=0x%x", connection->getInputChannelName(), events);
Jeff Brown59abe7e2010-09-13 23:17:30 -07001728 return 1;
Jeff Browne839a582010-04-22 18:58:52 -07001729 }
1730
1731 status_t status = connection->inputPublisher.receiveFinishedSignal();
1732 if (status) {
1733 LOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
1734 connection->getInputChannelName(), status);
Jeff Brown51d45a72010-06-17 20:52:56 -07001735 d->abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07001736 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001737 return 0; // remove the callback
Jeff Browne839a582010-04-22 18:58:52 -07001738 }
1739
Jeff Brown51d45a72010-06-17 20:52:56 -07001740 d->finishDispatchCycleLocked(currentTime, connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07001741 d->runCommandsLockedInterruptible();
Jeff Brown59abe7e2010-09-13 23:17:30 -07001742 return 1;
Jeff Browne839a582010-04-22 18:58:52 -07001743 } // release lock
1744}
1745
Jeff Brown54bc2812010-06-15 01:31:58 -07001746void InputDispatcher::notifyConfigurationChanged(nsecs_t eventTime) {
Jeff Browne839a582010-04-22 18:58:52 -07001747#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown54bc2812010-06-15 01:31:58 -07001748 LOGD("notifyConfigurationChanged - eventTime=%lld", eventTime);
Jeff Browne839a582010-04-22 18:58:52 -07001749#endif
1750
Jeff Browna665ca82010-09-08 11:49:43 -07001751 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07001752 { // acquire lock
1753 AutoMutex _l(mLock);
1754
Jeff Brown51d45a72010-06-17 20:52:56 -07001755 ConfigurationChangedEntry* newEntry = mAllocator.obtainConfigurationChangedEntry(eventTime);
Jeff Browna665ca82010-09-08 11:49:43 -07001756 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001757 } // release lock
1758
Jeff Browna665ca82010-09-08 11:49:43 -07001759 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07001760 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07001761 }
1762}
1763
Jeff Brown5c1ed842010-07-14 18:48:53 -07001764void InputDispatcher::notifyKey(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -07001765 uint32_t policyFlags, int32_t action, int32_t flags,
1766 int32_t keyCode, int32_t scanCode, int32_t metaState, nsecs_t downTime) {
1767#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown5c1ed842010-07-14 18:48:53 -07001768 LOGD("notifyKey - eventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, action=0x%x, "
Jeff Browne839a582010-04-22 18:58:52 -07001769 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
Jeff Brown5c1ed842010-07-14 18:48:53 -07001770 eventTime, deviceId, source, policyFlags, action, flags,
Jeff Browne839a582010-04-22 18:58:52 -07001771 keyCode, scanCode, metaState, downTime);
1772#endif
1773
Jeff Browna665ca82010-09-08 11:49:43 -07001774 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07001775 { // acquire lock
1776 AutoMutex _l(mLock);
1777
Jeff Brown51d45a72010-06-17 20:52:56 -07001778 int32_t repeatCount = 0;
1779 KeyEntry* newEntry = mAllocator.obtainKeyEntry(eventTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -07001780 deviceId, source, policyFlags, action, flags, keyCode, scanCode,
Jeff Brown51d45a72010-06-17 20:52:56 -07001781 metaState, repeatCount, downTime);
Jeff Browne839a582010-04-22 18:58:52 -07001782
Jeff Browna665ca82010-09-08 11:49:43 -07001783 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001784 } // release lock
1785
Jeff Browna665ca82010-09-08 11:49:43 -07001786 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07001787 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07001788 }
1789}
1790
Jeff Brown5c1ed842010-07-14 18:48:53 -07001791void InputDispatcher::notifyMotion(nsecs_t eventTime, int32_t deviceId, int32_t source,
Jeff Brownaf30ff62010-09-01 17:01:00 -07001792 uint32_t policyFlags, int32_t action, int32_t flags, int32_t metaState, int32_t edgeFlags,
Jeff Browne839a582010-04-22 18:58:52 -07001793 uint32_t pointerCount, const int32_t* pointerIds, const PointerCoords* pointerCoords,
1794 float xPrecision, float yPrecision, nsecs_t downTime) {
1795#if DEBUG_INBOUND_EVENT_DETAILS
Jeff Brown5c1ed842010-07-14 18:48:53 -07001796 LOGD("notifyMotion - eventTime=%lld, deviceId=0x%x, source=0x%x, policyFlags=0x%x, "
Jeff Brownaf30ff62010-09-01 17:01:00 -07001797 "action=0x%x, flags=0x%x, metaState=0x%x, edgeFlags=0x%x, "
1798 "xPrecision=%f, yPrecision=%f, downTime=%lld",
1799 eventTime, deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Browne839a582010-04-22 18:58:52 -07001800 xPrecision, yPrecision, downTime);
1801 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown38a7fab2010-08-30 03:02:23 -07001802 LOGD(" Pointer %d: id=%d, x=%f, y=%f, pressure=%f, size=%f, "
Jeff Brownaf30ff62010-09-01 17:01:00 -07001803 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Jeff Brown38a7fab2010-08-30 03:02:23 -07001804 "orientation=%f",
Jeff Browne839a582010-04-22 18:58:52 -07001805 i, pointerIds[i], pointerCoords[i].x, pointerCoords[i].y,
Jeff Brown38a7fab2010-08-30 03:02:23 -07001806 pointerCoords[i].pressure, pointerCoords[i].size,
1807 pointerCoords[i].touchMajor, pointerCoords[i].touchMinor,
1808 pointerCoords[i].toolMajor, pointerCoords[i].toolMinor,
1809 pointerCoords[i].orientation);
Jeff Browne839a582010-04-22 18:58:52 -07001810 }
1811#endif
1812
Jeff Browna665ca82010-09-08 11:49:43 -07001813 bool needWake;
Jeff Browne839a582010-04-22 18:58:52 -07001814 { // acquire lock
1815 AutoMutex _l(mLock);
1816
1817 // Attempt batching and streaming of move events.
Jeff Brown5c1ed842010-07-14 18:48:53 -07001818 if (action == AMOTION_EVENT_ACTION_MOVE) {
Jeff Browne839a582010-04-22 18:58:52 -07001819 // BATCHING CASE
1820 //
1821 // Try to append a move sample to the tail of the inbound queue for this device.
1822 // Give up if we encounter a non-move motion event for this device since that
1823 // means we cannot append any new samples until a new motion event has started.
Jeff Browna665ca82010-09-08 11:49:43 -07001824 for (EventEntry* entry = mInboundQueue.tailSentinel.prev;
1825 entry != & mInboundQueue.headSentinel; entry = entry->prev) {
Jeff Browne839a582010-04-22 18:58:52 -07001826 if (entry->type != EventEntry::TYPE_MOTION) {
1827 // Keep looking for motion events.
1828 continue;
1829 }
1830
1831 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
1832 if (motionEntry->deviceId != deviceId) {
1833 // Keep looking for this device.
1834 continue;
1835 }
1836
Jeff Brown5c1ed842010-07-14 18:48:53 -07001837 if (motionEntry->action != AMOTION_EVENT_ACTION_MOVE
Jeff Brown51d45a72010-06-17 20:52:56 -07001838 || motionEntry->pointerCount != pointerCount
1839 || motionEntry->isInjected()) {
Jeff Browne839a582010-04-22 18:58:52 -07001840 // Last motion event in the queue for this device is not compatible for
1841 // appending new samples. Stop here.
1842 goto NoBatchingOrStreaming;
1843 }
1844
1845 // The last motion event is a move and is compatible for appending.
Jeff Brown54bc2812010-06-15 01:31:58 -07001846 // Do the batching magic.
Jeff Brown51d45a72010-06-17 20:52:56 -07001847 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
Jeff Browne839a582010-04-22 18:58:52 -07001848#if DEBUG_BATCHING
1849 LOGD("Appended motion sample onto batch for most recent "
1850 "motion event for this device in the inbound queue.");
1851#endif
Jeff Brown54bc2812010-06-15 01:31:58 -07001852 return; // done!
Jeff Browne839a582010-04-22 18:58:52 -07001853 }
1854
1855 // STREAMING CASE
1856 //
1857 // There is no pending motion event (of any kind) for this device in the inbound queue.
Jeff Brown53a415e2010-09-15 15:18:56 -07001858 // Search the outbound queue for the current foreground targets to find a dispatched
1859 // motion event that is still in progress. If found, then, appen the new sample to
1860 // that event and push it out to all current targets. The logic in
1861 // prepareDispatchCycleLocked takes care of the case where some targets may
1862 // already have consumed the motion event by starting a new dispatch cycle if needed.
Jeff Brown54bc2812010-06-15 01:31:58 -07001863 if (mCurrentInputTargetsValid) {
Jeff Brown53a415e2010-09-15 15:18:56 -07001864 for (size_t i = 0; i < mCurrentInputTargets.size(); i++) {
1865 const InputTarget& inputTarget = mCurrentInputTargets[i];
1866 if ((inputTarget.flags & InputTarget::FLAG_FOREGROUND) == 0) {
1867 // Skip non-foreground targets. We only want to stream if there is at
1868 // least one foreground target whose dispatch is still in progress.
1869 continue;
Jeff Browne839a582010-04-22 18:58:52 -07001870 }
Jeff Brown53a415e2010-09-15 15:18:56 -07001871
1872 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1873 if (connectionIndex < 0) {
1874 // Connection must no longer be valid.
1875 continue;
1876 }
1877
1878 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
1879 if (connection->outboundQueue.isEmpty()) {
1880 // This foreground target has an empty outbound queue.
1881 continue;
1882 }
1883
1884 DispatchEntry* dispatchEntry = connection->outboundQueue.headSentinel.next;
1885 if (! dispatchEntry->inProgress
1886 || dispatchEntry->eventEntry->type != EventEntry::TYPE_MOTION) {
1887 // No motion event is being dispatched.
1888 continue;
1889 }
1890
1891 MotionEntry* motionEntry = static_cast<MotionEntry*>(
1892 dispatchEntry->eventEntry);
1893 if (motionEntry->action != AMOTION_EVENT_ACTION_MOVE
1894 || motionEntry->deviceId != deviceId
1895 || motionEntry->pointerCount != pointerCount
1896 || motionEntry->isInjected()) {
1897 // The motion event is not compatible with this move.
1898 continue;
1899 }
1900
1901 // Hurray! This foreground target is currently dispatching a move event
1902 // that we can stream onto. Append the motion sample and resume dispatch.
1903 mAllocator.appendMotionSample(motionEntry, eventTime, pointerCoords);
1904#if DEBUG_BATCHING
1905 LOGD("Appended motion sample onto batch for most recently dispatched "
1906 "motion event for this device in the outbound queues. "
1907 "Attempting to stream the motion sample.");
1908#endif
1909 nsecs_t currentTime = now();
1910 dispatchEventToCurrentInputTargetsLocked(currentTime, motionEntry,
1911 true /*resumeWithAppendedMotionSample*/);
1912
1913 runCommandsLockedInterruptible();
1914 return; // done!
Jeff Browne839a582010-04-22 18:58:52 -07001915 }
1916 }
1917
1918NoBatchingOrStreaming:;
1919 }
1920
1921 // Just enqueue a new motion event.
Jeff Brown51d45a72010-06-17 20:52:56 -07001922 MotionEntry* newEntry = mAllocator.obtainMotionEntry(eventTime,
Jeff Brownaf30ff62010-09-01 17:01:00 -07001923 deviceId, source, policyFlags, action, flags, metaState, edgeFlags,
Jeff Brown51d45a72010-06-17 20:52:56 -07001924 xPrecision, yPrecision, downTime,
1925 pointerCount, pointerIds, pointerCoords);
Jeff Browne839a582010-04-22 18:58:52 -07001926
Jeff Browna665ca82010-09-08 11:49:43 -07001927 needWake = enqueueInboundEventLocked(newEntry);
Jeff Browne839a582010-04-22 18:58:52 -07001928 } // release lock
1929
Jeff Browna665ca82010-09-08 11:49:43 -07001930 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07001931 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07001932 }
1933}
1934
Jeff Brown51d45a72010-06-17 20:52:56 -07001935int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Jeff Brownf67c53e2010-07-28 15:48:59 -07001936 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis) {
Jeff Brown51d45a72010-06-17 20:52:56 -07001937#if DEBUG_INBOUND_EVENT_DETAILS
1938 LOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Jeff Brownf67c53e2010-07-28 15:48:59 -07001939 "syncMode=%d, timeoutMillis=%d",
1940 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis);
Jeff Brown51d45a72010-06-17 20:52:56 -07001941#endif
1942
1943 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
1944
1945 EventEntry* injectedEntry;
Jeff Browna665ca82010-09-08 11:49:43 -07001946 bool needWake;
Jeff Brown51d45a72010-06-17 20:52:56 -07001947 { // acquire lock
1948 AutoMutex _l(mLock);
1949
Jeff Browna665ca82010-09-08 11:49:43 -07001950 injectedEntry = createEntryFromInjectedInputEventLocked(event);
1951 if (! injectedEntry) {
1952 return INPUT_EVENT_INJECTION_FAILED;
1953 }
1954
Jeff Brown51d45a72010-06-17 20:52:56 -07001955 injectedEntry->refCount += 1;
1956 injectedEntry->injectorPid = injectorPid;
1957 injectedEntry->injectorUid = injectorUid;
1958
Jeff Brownf67c53e2010-07-28 15:48:59 -07001959 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
1960 injectedEntry->injectionIsAsync = true;
1961 }
1962
Jeff Browna665ca82010-09-08 11:49:43 -07001963 needWake = enqueueInboundEventLocked(injectedEntry);
Jeff Brown51d45a72010-06-17 20:52:56 -07001964 } // release lock
1965
Jeff Browna665ca82010-09-08 11:49:43 -07001966 if (needWake) {
Jeff Brown59abe7e2010-09-13 23:17:30 -07001967 mLooper->wake();
Jeff Brown51d45a72010-06-17 20:52:56 -07001968 }
1969
1970 int32_t injectionResult;
1971 { // acquire lock
1972 AutoMutex _l(mLock);
1973
Jeff Brownf67c53e2010-07-28 15:48:59 -07001974 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
1975 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1976 } else {
1977 for (;;) {
1978 injectionResult = injectedEntry->injectionResult;
1979 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
1980 break;
1981 }
Jeff Brown51d45a72010-06-17 20:52:56 -07001982
Jeff Brown51d45a72010-06-17 20:52:56 -07001983 nsecs_t remainingTimeout = endTime - now();
1984 if (remainingTimeout <= 0) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07001985#if DEBUG_INJECTION
1986 LOGD("injectInputEvent - Timed out waiting for injection result "
1987 "to become available.");
1988#endif
Jeff Brown51d45a72010-06-17 20:52:56 -07001989 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
1990 break;
1991 }
1992
Jeff Brownf67c53e2010-07-28 15:48:59 -07001993 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
1994 }
1995
1996 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
1997 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Jeff Brown53a415e2010-09-15 15:18:56 -07001998 while (injectedEntry->pendingForegroundDispatches != 0) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07001999#if DEBUG_INJECTION
Jeff Brown53a415e2010-09-15 15:18:56 -07002000 LOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2001 injectedEntry->pendingForegroundDispatches);
Jeff Brownf67c53e2010-07-28 15:48:59 -07002002#endif
2003 nsecs_t remainingTimeout = endTime - now();
2004 if (remainingTimeout <= 0) {
2005#if DEBUG_INJECTION
Jeff Brown53a415e2010-09-15 15:18:56 -07002006 LOGD("injectInputEvent - Timed out waiting for pending foreground "
Jeff Brownf67c53e2010-07-28 15:48:59 -07002007 "dispatches to finish.");
2008#endif
2009 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2010 break;
2011 }
2012
2013 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2014 }
Jeff Brown51d45a72010-06-17 20:52:56 -07002015 }
2016 }
2017
2018 mAllocator.releaseEventEntry(injectedEntry);
2019 } // release lock
2020
Jeff Brownf67c53e2010-07-28 15:48:59 -07002021#if DEBUG_INJECTION
2022 LOGD("injectInputEvent - Finished with result %d. "
2023 "injectorPid=%d, injectorUid=%d",
2024 injectionResult, injectorPid, injectorUid);
2025#endif
2026
Jeff Brown51d45a72010-06-17 20:52:56 -07002027 return injectionResult;
2028}
2029
2030void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2031 if (entry->isInjected()) {
2032#if DEBUG_INJECTION
2033 LOGD("Setting input event injection result to %d. "
2034 "injectorPid=%d, injectorUid=%d",
2035 injectionResult, entry->injectorPid, entry->injectorUid);
2036#endif
2037
Jeff Brownf67c53e2010-07-28 15:48:59 -07002038 if (entry->injectionIsAsync) {
2039 // Log the outcome since the injector did not wait for the injection result.
2040 switch (injectionResult) {
2041 case INPUT_EVENT_INJECTION_SUCCEEDED:
2042 LOGV("Asynchronous input event injection succeeded.");
2043 break;
2044 case INPUT_EVENT_INJECTION_FAILED:
2045 LOGW("Asynchronous input event injection failed.");
2046 break;
2047 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2048 LOGW("Asynchronous input event injection permission denied.");
2049 break;
2050 case INPUT_EVENT_INJECTION_TIMED_OUT:
2051 LOGW("Asynchronous input event injection timed out.");
2052 break;
2053 }
2054 }
2055
Jeff Brown51d45a72010-06-17 20:52:56 -07002056 entry->injectionResult = injectionResult;
2057 mInjectionResultAvailableCondition.broadcast();
2058 }
2059}
2060
Jeff Brown53a415e2010-09-15 15:18:56 -07002061void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2062 entry->pendingForegroundDispatches -= 1;
Jeff Brownf67c53e2010-07-28 15:48:59 -07002063
Jeff Brown53a415e2010-09-15 15:18:56 -07002064 if (entry->isInjected() && entry->pendingForegroundDispatches == 0) {
Jeff Brownf67c53e2010-07-28 15:48:59 -07002065 mInjectionSyncFinishedCondition.broadcast();
2066 }
Jeff Brown51d45a72010-06-17 20:52:56 -07002067}
2068
Jeff Browna665ca82010-09-08 11:49:43 -07002069static bool isValidKeyAction(int32_t action) {
2070 switch (action) {
2071 case AKEY_EVENT_ACTION_DOWN:
2072 case AKEY_EVENT_ACTION_UP:
2073 return true;
2074 default:
2075 return false;
2076 }
2077}
2078
2079static bool isValidMotionAction(int32_t action) {
2080 switch (action & AMOTION_EVENT_ACTION_MASK) {
2081 case AMOTION_EVENT_ACTION_DOWN:
2082 case AMOTION_EVENT_ACTION_UP:
2083 case AMOTION_EVENT_ACTION_CANCEL:
2084 case AMOTION_EVENT_ACTION_MOVE:
2085 case AMOTION_EVENT_ACTION_POINTER_DOWN:
2086 case AMOTION_EVENT_ACTION_POINTER_UP:
2087 case AMOTION_EVENT_ACTION_OUTSIDE:
2088 return true;
2089 default:
2090 return false;
2091 }
2092}
2093
2094InputDispatcher::EventEntry* InputDispatcher::createEntryFromInjectedInputEventLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002095 const InputEvent* event) {
2096 switch (event->getType()) {
Jeff Brown5c1ed842010-07-14 18:48:53 -07002097 case AINPUT_EVENT_TYPE_KEY: {
Jeff Brown51d45a72010-06-17 20:52:56 -07002098 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
Jeff Browna665ca82010-09-08 11:49:43 -07002099 if (! isValidKeyAction(keyEvent->getAction())) {
2100 LOGE("Dropping injected key event since it has invalid action code 0x%x",
2101 keyEvent->getAction());
2102 return NULL;
2103 }
2104
Jeff Brownaf30ff62010-09-01 17:01:00 -07002105 uint32_t policyFlags = POLICY_FLAG_INJECTED;
Jeff Brown51d45a72010-06-17 20:52:56 -07002106
2107 KeyEntry* keyEntry = mAllocator.obtainKeyEntry(keyEvent->getEventTime(),
Jeff Brown5c1ed842010-07-14 18:48:53 -07002108 keyEvent->getDeviceId(), keyEvent->getSource(), policyFlags,
Jeff Brown51d45a72010-06-17 20:52:56 -07002109 keyEvent->getAction(), keyEvent->getFlags(),
2110 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2111 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2112 return keyEntry;
2113 }
2114
Jeff Brown5c1ed842010-07-14 18:48:53 -07002115 case AINPUT_EVENT_TYPE_MOTION: {
Jeff Brown51d45a72010-06-17 20:52:56 -07002116 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Jeff Browna665ca82010-09-08 11:49:43 -07002117 if (! isValidMotionAction(motionEvent->getAction())) {
2118 LOGE("Dropping injected motion event since it has invalid action code 0x%x.",
2119 motionEvent->getAction());
2120 return NULL;
2121 }
2122 if (motionEvent->getPointerCount() == 0
2123 || motionEvent->getPointerCount() > MAX_POINTERS) {
2124 LOGE("Dropping injected motion event since it has an invalid pointer count %d.",
2125 motionEvent->getPointerCount());
2126 }
2127
Jeff Brownaf30ff62010-09-01 17:01:00 -07002128 uint32_t policyFlags = POLICY_FLAG_INJECTED;
Jeff Brown51d45a72010-06-17 20:52:56 -07002129
2130 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2131 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2132 size_t pointerCount = motionEvent->getPointerCount();
2133
2134 MotionEntry* motionEntry = mAllocator.obtainMotionEntry(*sampleEventTimes,
Jeff Brown5c1ed842010-07-14 18:48:53 -07002135 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002136 motionEvent->getAction(), motionEvent->getFlags(),
2137 motionEvent->getMetaState(), motionEvent->getEdgeFlags(),
Jeff Brown51d45a72010-06-17 20:52:56 -07002138 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2139 motionEvent->getDownTime(), uint32_t(pointerCount),
2140 motionEvent->getPointerIds(), samplePointerCoords);
2141 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2142 sampleEventTimes += 1;
2143 samplePointerCoords += pointerCount;
2144 mAllocator.appendMotionSample(motionEntry, *sampleEventTimes, samplePointerCoords);
2145 }
2146 return motionEntry;
2147 }
2148
2149 default:
2150 assert(false);
2151 return NULL;
2152 }
2153}
2154
Jeff Browna665ca82010-09-08 11:49:43 -07002155void InputDispatcher::setInputWindows(const Vector<InputWindow>& inputWindows) {
2156#if DEBUG_FOCUS
2157 LOGD("setInputWindows");
2158#endif
2159 { // acquire lock
2160 AutoMutex _l(mLock);
2161
Jeff Brown53a415e2010-09-15 15:18:56 -07002162 sp<InputChannel> oldFocusedWindowChannel = mFocusedWindow
2163 ? mFocusedWindow->inputChannel : NULL;
2164 int32_t oldFocusedWindowLayer = mFocusedWindow ? mFocusedWindow->layer : -1;
2165
Jeff Browna665ca82010-09-08 11:49:43 -07002166 sp<InputChannel> touchedWindowChannel;
2167 if (mTouchedWindow) {
2168 touchedWindowChannel = mTouchedWindow->inputChannel;
2169 mTouchedWindow = NULL;
2170 }
2171 size_t numTouchedWallpapers = mTouchedWallpaperWindows.size();
2172 if (numTouchedWallpapers != 0) {
2173 for (size_t i = 0; i < numTouchedWallpapers; i++) {
2174 mTempTouchedWallpaperChannels.push(mTouchedWallpaperWindows[i]->inputChannel);
2175 }
2176 mTouchedWallpaperWindows.clear();
2177 }
2178
Jeff Browna665ca82010-09-08 11:49:43 -07002179 mFocusedWindow = NULL;
2180 mWallpaperWindows.clear();
2181
2182 mWindows.clear();
2183 mWindows.appendVector(inputWindows);
2184
2185 size_t numWindows = mWindows.size();
2186 for (size_t i = 0; i < numWindows; i++) {
2187 InputWindow* window = & mWindows.editItemAt(i);
2188 if (window->hasFocus) {
2189 mFocusedWindow = window;
2190 }
2191
2192 if (window->layoutParamsType == InputWindow::TYPE_WALLPAPER) {
2193 mWallpaperWindows.push(window);
2194
2195 for (size_t j = 0; j < numTouchedWallpapers; j++) {
2196 if (window->inputChannel == mTempTouchedWallpaperChannels[i]) {
2197 mTouchedWallpaperWindows.push(window);
2198 }
2199 }
2200 }
2201
2202 if (window->inputChannel == touchedWindowChannel) {
2203 mTouchedWindow = window;
2204 }
2205 }
2206
2207 mTempTouchedWallpaperChannels.clear();
2208
Jeff Brown53a415e2010-09-15 15:18:56 -07002209 bool preempt = false;
2210 if (mFocusedWindow
2211 && mFocusedWindow->inputChannel != oldFocusedWindowChannel
2212 && mFocusedWindow->canReceiveKeys) {
2213 // If the new input focus is an error window or appears above the current
2214 // input focus, drop the current touched window so that we can start
2215 // delivering events to the new input focus as soon as possible.
2216 if (mFocusedWindow->layoutParamsFlags & InputWindow::FLAG_SYSTEM_ERROR) {
2217#if DEBUG_FOCUS
2218 LOGD("Preempting: New SYSTEM_ERROR window; resetting state");
2219#endif
2220 preempt = true;
2221 } else if (oldFocusedWindowChannel.get() != NULL
2222 && mFocusedWindow->layer > oldFocusedWindowLayer) {
2223#if DEBUG_FOCUS
2224 LOGD("Preempting: Transferring focus to new window at higher layer: "
2225 "old win layer=%d, new win layer=%d",
2226 oldFocusedWindowLayer, mFocusedWindow->layer);
2227#endif
2228 preempt = true;
2229 }
2230 }
2231 if (mTouchedWindow && ! mTouchedWindow->visible) {
2232#if DEBUG_FOCUS
2233 LOGD("Preempting: Touched window became invisible.");
2234#endif
2235 preempt = true;
2236 }
2237 if (preempt) {
2238 releaseTouchedWindowLocked();
Jeff Browna665ca82010-09-08 11:49:43 -07002239 }
2240
2241#if DEBUG_FOCUS
2242 logDispatchStateLocked();
2243#endif
2244 } // release lock
2245
2246 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002247 mLooper->wake();
Jeff Browna665ca82010-09-08 11:49:43 -07002248}
2249
2250void InputDispatcher::setFocusedApplication(const InputApplication* inputApplication) {
2251#if DEBUG_FOCUS
2252 LOGD("setFocusedApplication");
2253#endif
2254 { // acquire lock
2255 AutoMutex _l(mLock);
2256
2257 releaseFocusedApplicationLocked();
2258
2259 if (inputApplication) {
2260 mFocusedApplicationStorage = *inputApplication;
2261 mFocusedApplication = & mFocusedApplicationStorage;
2262 }
2263
2264#if DEBUG_FOCUS
2265 logDispatchStateLocked();
2266#endif
2267 } // release lock
2268
2269 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002270 mLooper->wake();
Jeff Browna665ca82010-09-08 11:49:43 -07002271}
2272
2273void InputDispatcher::releaseFocusedApplicationLocked() {
2274 if (mFocusedApplication) {
2275 mFocusedApplication = NULL;
2276 mFocusedApplicationStorage.handle.clear();
2277 }
2278}
2279
2280void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2281#if DEBUG_FOCUS
2282 LOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2283#endif
2284
2285 bool changed;
2286 { // acquire lock
2287 AutoMutex _l(mLock);
2288
2289 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2290 if (mDispatchFrozen && ! frozen) {
2291 resetANRTimeoutsLocked();
2292 }
2293
2294 mDispatchEnabled = enabled;
2295 mDispatchFrozen = frozen;
2296 changed = true;
2297 } else {
2298 changed = false;
2299 }
2300
2301#if DEBUG_FOCUS
2302 logDispatchStateLocked();
2303#endif
2304 } // release lock
2305
2306 if (changed) {
2307 // Wake up poll loop since it may need to make new input dispatching choices.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002308 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002309 }
2310}
2311
Jeff Browna665ca82010-09-08 11:49:43 -07002312void InputDispatcher::logDispatchStateLocked() {
2313 String8 dump;
2314 dumpDispatchStateLocked(dump);
2315 LOGD("%s", dump.string());
2316}
2317
2318void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
2319 dump.appendFormat(" dispatchEnabled: %d\n", mDispatchEnabled);
2320 dump.appendFormat(" dispatchFrozen: %d\n", mDispatchFrozen);
2321
2322 if (mFocusedApplication) {
2323 dump.appendFormat(" focusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
2324 mFocusedApplication->name.string(),
2325 mFocusedApplication->dispatchingTimeout / 1000000.0);
2326 } else {
2327 dump.append(" focusedApplication: <null>\n");
2328 }
2329 dump.appendFormat(" focusedWindow: '%s'\n",
2330 mFocusedWindow != NULL ? mFocusedWindow->inputChannel->getName().string() : "<null>");
2331 dump.appendFormat(" touchedWindow: '%s', touchDown=%d\n",
2332 mTouchedWindow != NULL ? mTouchedWindow->inputChannel->getName().string() : "<null>",
2333 mTouchDown);
2334 for (size_t i = 0; i < mTouchedWallpaperWindows.size(); i++) {
2335 dump.appendFormat(" touchedWallpaperWindows[%d]: '%s'\n",
2336 i, mTouchedWallpaperWindows[i]->inputChannel->getName().string());
2337 }
2338 for (size_t i = 0; i < mWindows.size(); i++) {
2339 dump.appendFormat(" windows[%d]: '%s', paused=%s, hasFocus=%s, hasWallpaper=%s, "
2340 "visible=%s, flags=0x%08x, type=0x%08x, "
2341 "frame=[%d,%d][%d,%d], "
2342 "visibleFrame=[%d,%d][%d,%d], "
2343 "touchableArea=[%d,%d][%d,%d], "
2344 "ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
2345 i, mWindows[i].inputChannel->getName().string(),
2346 toString(mWindows[i].paused),
2347 toString(mWindows[i].hasFocus),
2348 toString(mWindows[i].hasWallpaper),
2349 toString(mWindows[i].visible),
2350 mWindows[i].layoutParamsFlags, mWindows[i].layoutParamsType,
2351 mWindows[i].frameLeft, mWindows[i].frameTop,
2352 mWindows[i].frameRight, mWindows[i].frameBottom,
2353 mWindows[i].visibleFrameLeft, mWindows[i].visibleFrameTop,
2354 mWindows[i].visibleFrameRight, mWindows[i].visibleFrameBottom,
2355 mWindows[i].touchableAreaLeft, mWindows[i].touchableAreaTop,
2356 mWindows[i].touchableAreaRight, mWindows[i].touchableAreaBottom,
2357 mWindows[i].ownerPid, mWindows[i].ownerUid,
2358 mWindows[i].dispatchingTimeout / 1000000.0);
2359 }
2360
2361 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2362 const sp<InputChannel>& channel = mMonitoringChannels[i];
2363 dump.appendFormat(" monitoringChannel[%d]: '%s'\n",
2364 i, channel->getName().string());
2365 }
2366
Jeff Brown53a415e2010-09-15 15:18:56 -07002367 dump.appendFormat(" inboundQueue: length=%u", mInboundQueue.count());
2368
Jeff Browna665ca82010-09-08 11:49:43 -07002369 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2370 const Connection* connection = mActiveConnections[i];
Jeff Brown53a415e2010-09-15 15:18:56 -07002371 dump.appendFormat(" activeConnection[%d]: '%s', status=%s, outboundQueueLength=%u"
Jeff Browna665ca82010-09-08 11:49:43 -07002372 "inputState.isNeutral=%s, inputState.isOutOfSync=%s\n",
2373 i, connection->getInputChannelName(), connection->getStatusLabel(),
Jeff Brown53a415e2010-09-15 15:18:56 -07002374 connection->outboundQueue.count(),
Jeff Browna665ca82010-09-08 11:49:43 -07002375 toString(connection->inputState.isNeutral()),
2376 toString(connection->inputState.isOutOfSync()));
2377 }
2378
2379 if (isAppSwitchPendingLocked()) {
2380 dump.appendFormat(" appSwitch: pending, due in %01.1fms\n",
2381 (mAppSwitchDueTime - now()) / 1000000.0);
2382 } else {
2383 dump.append(" appSwitch: not pending\n");
2384 }
2385}
2386
2387status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) {
Jeff Brown54bc2812010-06-15 01:31:58 -07002388#if DEBUG_REGISTRATION
Jeff Browna665ca82010-09-08 11:49:43 -07002389 LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
2390 toString(monitor));
Jeff Brown54bc2812010-06-15 01:31:58 -07002391#endif
2392
Jeff Browne839a582010-04-22 18:58:52 -07002393 { // acquire lock
2394 AutoMutex _l(mLock);
2395
Jeff Brown53a415e2010-09-15 15:18:56 -07002396 if (getConnectionIndexLocked(inputChannel) >= 0) {
Jeff Browne839a582010-04-22 18:58:52 -07002397 LOGW("Attempted to register already registered input channel '%s'",
2398 inputChannel->getName().string());
2399 return BAD_VALUE;
2400 }
2401
2402 sp<Connection> connection = new Connection(inputChannel);
2403 status_t status = connection->initialize();
2404 if (status) {
2405 LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
2406 inputChannel->getName().string(), status);
2407 return status;
2408 }
2409
Jeff Brown0cacb872010-08-17 15:59:26 -07002410 int32_t receiveFd = inputChannel->getReceivePipeFd();
Jeff Browne839a582010-04-22 18:58:52 -07002411 mConnectionsByReceiveFd.add(receiveFd, connection);
Jeff Brown54bc2812010-06-15 01:31:58 -07002412
Jeff Browna665ca82010-09-08 11:49:43 -07002413 if (monitor) {
2414 mMonitoringChannels.push(inputChannel);
2415 }
2416
Jeff Brown59abe7e2010-09-13 23:17:30 -07002417 mLooper->addFd(receiveFd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Jeff Brown0cacb872010-08-17 15:59:26 -07002418
Jeff Brown54bc2812010-06-15 01:31:58 -07002419 runCommandsLockedInterruptible();
Jeff Browne839a582010-04-22 18:58:52 -07002420 } // release lock
Jeff Browne839a582010-04-22 18:58:52 -07002421 return OK;
2422}
2423
2424status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
Jeff Brown54bc2812010-06-15 01:31:58 -07002425#if DEBUG_REGISTRATION
Jeff Brown50de30a2010-06-22 01:27:15 -07002426 LOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
Jeff Brown54bc2812010-06-15 01:31:58 -07002427#endif
2428
Jeff Browne839a582010-04-22 18:58:52 -07002429 { // acquire lock
2430 AutoMutex _l(mLock);
2431
Jeff Brown53a415e2010-09-15 15:18:56 -07002432 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
Jeff Browne839a582010-04-22 18:58:52 -07002433 if (connectionIndex < 0) {
2434 LOGW("Attempted to unregister already unregistered input channel '%s'",
2435 inputChannel->getName().string());
2436 return BAD_VALUE;
2437 }
2438
2439 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2440 mConnectionsByReceiveFd.removeItemsAt(connectionIndex);
2441
2442 connection->status = Connection::STATUS_ZOMBIE;
2443
Jeff Browna665ca82010-09-08 11:49:43 -07002444 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2445 if (mMonitoringChannels[i] == inputChannel) {
2446 mMonitoringChannels.removeAt(i);
2447 break;
2448 }
2449 }
2450
Jeff Brown59abe7e2010-09-13 23:17:30 -07002451 mLooper->removeFd(inputChannel->getReceivePipeFd());
Jeff Brown0cacb872010-08-17 15:59:26 -07002452
Jeff Brown51d45a72010-06-17 20:52:56 -07002453 nsecs_t currentTime = now();
2454 abortDispatchCycleLocked(currentTime, connection, true /*broken*/);
Jeff Brown54bc2812010-06-15 01:31:58 -07002455
2456 runCommandsLockedInterruptible();
Jeff Browne839a582010-04-22 18:58:52 -07002457 } // release lock
2458
Jeff Browne839a582010-04-22 18:58:52 -07002459 // Wake the poll loop because removing the connection may have changed the current
2460 // synchronization state.
Jeff Brown59abe7e2010-09-13 23:17:30 -07002461 mLooper->wake();
Jeff Browne839a582010-04-22 18:58:52 -07002462 return OK;
2463}
2464
Jeff Brown53a415e2010-09-15 15:18:56 -07002465ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Jeff Brown0cacb872010-08-17 15:59:26 -07002466 ssize_t connectionIndex = mConnectionsByReceiveFd.indexOfKey(inputChannel->getReceivePipeFd());
2467 if (connectionIndex >= 0) {
2468 sp<Connection> connection = mConnectionsByReceiveFd.valueAt(connectionIndex);
2469 if (connection->inputChannel.get() == inputChannel.get()) {
2470 return connectionIndex;
2471 }
2472 }
2473
2474 return -1;
2475}
2476
Jeff Browne839a582010-04-22 18:58:52 -07002477void InputDispatcher::activateConnectionLocked(Connection* connection) {
2478 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2479 if (mActiveConnections.itemAt(i) == connection) {
2480 return;
2481 }
2482 }
2483 mActiveConnections.add(connection);
2484}
2485
2486void InputDispatcher::deactivateConnectionLocked(Connection* connection) {
2487 for (size_t i = 0; i < mActiveConnections.size(); i++) {
2488 if (mActiveConnections.itemAt(i) == connection) {
2489 mActiveConnections.removeAt(i);
2490 return;
2491 }
2492 }
2493}
2494
Jeff Brown54bc2812010-06-15 01:31:58 -07002495void InputDispatcher::onDispatchCycleStartedLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002496 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002497}
2498
Jeff Brown54bc2812010-06-15 01:31:58 -07002499void InputDispatcher::onDispatchCycleFinishedLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002500 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002501}
2502
Jeff Brown54bc2812010-06-15 01:31:58 -07002503void InputDispatcher::onDispatchCycleBrokenLocked(
Jeff Brown51d45a72010-06-17 20:52:56 -07002504 nsecs_t currentTime, const sp<Connection>& connection) {
Jeff Browne839a582010-04-22 18:58:52 -07002505 LOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
2506 connection->getInputChannelName());
2507
Jeff Brown54bc2812010-06-15 01:31:58 -07002508 CommandEntry* commandEntry = postCommandLocked(
2509 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Jeff Brown51d45a72010-06-17 20:52:56 -07002510 commandEntry->connection = connection;
Jeff Browne839a582010-04-22 18:58:52 -07002511}
2512
Jeff Brown53a415e2010-09-15 15:18:56 -07002513void InputDispatcher::onANRLocked(
2514 nsecs_t currentTime, const InputApplication* application, const InputWindow* window,
2515 nsecs_t eventTime, nsecs_t waitStartTime) {
2516 LOGI("Application is not responding: %s. "
2517 "%01.1fms since event, %01.1fms since wait started",
2518 getApplicationWindowLabelLocked(application, window).string(),
2519 (currentTime - eventTime) / 1000000.0,
2520 (currentTime - waitStartTime) / 1000000.0);
2521
2522 CommandEntry* commandEntry = postCommandLocked(
2523 & InputDispatcher::doNotifyANRLockedInterruptible);
2524 if (application) {
2525 commandEntry->inputApplicationHandle = application->handle;
2526 }
2527 if (window) {
2528 commandEntry->inputChannel = window->inputChannel;
2529 }
2530}
2531
Jeff Browna665ca82010-09-08 11:49:43 -07002532void InputDispatcher::doNotifyConfigurationChangedInterruptible(
2533 CommandEntry* commandEntry) {
2534 mLock.unlock();
2535
2536 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
2537
2538 mLock.lock();
2539}
2540
Jeff Brown54bc2812010-06-15 01:31:58 -07002541void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
2542 CommandEntry* commandEntry) {
Jeff Brown51d45a72010-06-17 20:52:56 -07002543 sp<Connection> connection = commandEntry->connection;
Jeff Brown54bc2812010-06-15 01:31:58 -07002544
Jeff Brown51d45a72010-06-17 20:52:56 -07002545 if (connection->status != Connection::STATUS_ZOMBIE) {
2546 mLock.unlock();
Jeff Brown54bc2812010-06-15 01:31:58 -07002547
Jeff Brown51d45a72010-06-17 20:52:56 -07002548 mPolicy->notifyInputChannelBroken(connection->inputChannel);
2549
2550 mLock.lock();
2551 }
Jeff Brown54bc2812010-06-15 01:31:58 -07002552}
2553
Jeff Brown53a415e2010-09-15 15:18:56 -07002554void InputDispatcher::doNotifyANRLockedInterruptible(
Jeff Brown54bc2812010-06-15 01:31:58 -07002555 CommandEntry* commandEntry) {
Jeff Brown53a415e2010-09-15 15:18:56 -07002556 mLock.unlock();
Jeff Brown54bc2812010-06-15 01:31:58 -07002557
Jeff Brown53a415e2010-09-15 15:18:56 -07002558 nsecs_t newTimeout = mPolicy->notifyANR(
2559 commandEntry->inputApplicationHandle, commandEntry->inputChannel);
Jeff Brown54bc2812010-06-15 01:31:58 -07002560
Jeff Brown53a415e2010-09-15 15:18:56 -07002561 mLock.lock();
Jeff Brown51d45a72010-06-17 20:52:56 -07002562
Jeff Brown53a415e2010-09-15 15:18:56 -07002563 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Jeff Brown54bc2812010-06-15 01:31:58 -07002564}
2565
Jeff Browna665ca82010-09-08 11:49:43 -07002566void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
2567 CommandEntry* commandEntry) {
2568 KeyEntry* entry = commandEntry->keyEntry;
2569 mReusableKeyEvent.initialize(entry->deviceId, entry->source, entry->action, entry->flags,
2570 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
2571 entry->downTime, entry->eventTime);
2572
2573 mLock.unlock();
2574
2575 bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputChannel,
2576 & mReusableKeyEvent, entry->policyFlags);
2577
2578 mLock.lock();
2579
2580 entry->interceptKeyResult = consumed
2581 ? KeyEntry::INTERCEPT_KEY_RESULT_SKIP
2582 : KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
2583 mAllocator.releaseKeyEntry(entry);
2584}
2585
2586void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
2587 mLock.unlock();
2588
2589 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->windowType,
2590 commandEntry->userActivityEventType);
2591
2592 mLock.lock();
2593}
2594
Jeff Brown53a415e2010-09-15 15:18:56 -07002595void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
2596 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
2597 // TODO Write some statistics about how long we spend waiting.
Jeff Browna665ca82010-09-08 11:49:43 -07002598}
2599
2600void InputDispatcher::dump(String8& dump) {
2601 dumpDispatchStateLocked(dump);
2602}
2603
Jeff Brown54bc2812010-06-15 01:31:58 -07002604
Jeff Brown53a415e2010-09-15 15:18:56 -07002605// --- InputDispatcher::Queue ---
2606
2607template <typename T>
2608uint32_t InputDispatcher::Queue<T>::count() const {
2609 uint32_t result = 0;
2610 for (const T* entry = headSentinel.next; entry != & tailSentinel; entry = entry->next) {
2611 result += 1;
2612 }
2613 return result;
2614}
2615
2616
Jeff Browne839a582010-04-22 18:58:52 -07002617// --- InputDispatcher::Allocator ---
2618
2619InputDispatcher::Allocator::Allocator() {
2620}
2621
Jeff Brown51d45a72010-06-17 20:52:56 -07002622void InputDispatcher::Allocator::initializeEventEntry(EventEntry* entry, int32_t type,
2623 nsecs_t eventTime) {
2624 entry->type = type;
2625 entry->refCount = 1;
2626 entry->dispatchInProgress = false;
Christopher Tated974e002010-06-23 16:50:30 -07002627 entry->eventTime = eventTime;
Jeff Brown51d45a72010-06-17 20:52:56 -07002628 entry->injectionResult = INPUT_EVENT_INJECTION_PENDING;
Jeff Brownf67c53e2010-07-28 15:48:59 -07002629 entry->injectionIsAsync = false;
Jeff Brown51d45a72010-06-17 20:52:56 -07002630 entry->injectorPid = -1;
2631 entry->injectorUid = -1;
Jeff Brown53a415e2010-09-15 15:18:56 -07002632 entry->pendingForegroundDispatches = 0;
Jeff Brown51d45a72010-06-17 20:52:56 -07002633}
2634
Jeff Browne839a582010-04-22 18:58:52 -07002635InputDispatcher::ConfigurationChangedEntry*
Jeff Brown51d45a72010-06-17 20:52:56 -07002636InputDispatcher::Allocator::obtainConfigurationChangedEntry(nsecs_t eventTime) {
Jeff Browne839a582010-04-22 18:58:52 -07002637 ConfigurationChangedEntry* entry = mConfigurationChangeEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002638 initializeEventEntry(entry, EventEntry::TYPE_CONFIGURATION_CHANGED, eventTime);
Jeff Browne839a582010-04-22 18:58:52 -07002639 return entry;
2640}
2641
Jeff Brown51d45a72010-06-17 20:52:56 -07002642InputDispatcher::KeyEntry* InputDispatcher::Allocator::obtainKeyEntry(nsecs_t eventTime,
Jeff Brown5c1ed842010-07-14 18:48:53 -07002643 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action,
Jeff Brown51d45a72010-06-17 20:52:56 -07002644 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
2645 int32_t repeatCount, nsecs_t downTime) {
Jeff Browne839a582010-04-22 18:58:52 -07002646 KeyEntry* entry = mKeyEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002647 initializeEventEntry(entry, EventEntry::TYPE_KEY, eventTime);
2648
2649 entry->deviceId = deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -07002650 entry->source = source;
Jeff Brown51d45a72010-06-17 20:52:56 -07002651 entry->policyFlags = policyFlags;
2652 entry->action = action;
2653 entry->flags = flags;
2654 entry->keyCode = keyCode;
2655 entry->scanCode = scanCode;
2656 entry->metaState = metaState;
2657 entry->repeatCount = repeatCount;
2658 entry->downTime = downTime;
Jeff Browna665ca82010-09-08 11:49:43 -07002659 entry->syntheticRepeat = false;
2660 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
Jeff Browne839a582010-04-22 18:58:52 -07002661 return entry;
2662}
2663
Jeff Brown51d45a72010-06-17 20:52:56 -07002664InputDispatcher::MotionEntry* InputDispatcher::Allocator::obtainMotionEntry(nsecs_t eventTime,
Jeff Brownaf30ff62010-09-01 17:01:00 -07002665 int32_t deviceId, int32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
Jeff Brown51d45a72010-06-17 20:52:56 -07002666 int32_t metaState, int32_t edgeFlags, float xPrecision, float yPrecision,
2667 nsecs_t downTime, uint32_t pointerCount,
2668 const int32_t* pointerIds, const PointerCoords* pointerCoords) {
Jeff Browne839a582010-04-22 18:58:52 -07002669 MotionEntry* entry = mMotionEntryPool.alloc();
Jeff Brown51d45a72010-06-17 20:52:56 -07002670 initializeEventEntry(entry, EventEntry::TYPE_MOTION, eventTime);
2671
2672 entry->eventTime = eventTime;
2673 entry->deviceId = deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -07002674 entry->source = source;
Jeff Brown51d45a72010-06-17 20:52:56 -07002675 entry->policyFlags = policyFlags;
2676 entry->action = action;
Jeff Brownaf30ff62010-09-01 17:01:00 -07002677 entry->flags = flags;
Jeff Brown51d45a72010-06-17 20:52:56 -07002678 entry->metaState = metaState;
2679 entry->edgeFlags = edgeFlags;
2680 entry->xPrecision = xPrecision;
2681 entry->yPrecision = yPrecision;
2682 entry->downTime = downTime;
2683 entry->pointerCount = pointerCount;
2684 entry->firstSample.eventTime = eventTime;
Jeff Browne839a582010-04-22 18:58:52 -07002685 entry->firstSample.next = NULL;
Jeff Brown51d45a72010-06-17 20:52:56 -07002686 entry->lastSample = & entry->firstSample;
2687 for (uint32_t i = 0; i < pointerCount; i++) {
2688 entry->pointerIds[i] = pointerIds[i];
2689 entry->firstSample.pointerCoords[i] = pointerCoords[i];
2690 }
Jeff Browne839a582010-04-22 18:58:52 -07002691 return entry;
2692}
2693
2694InputDispatcher::DispatchEntry* InputDispatcher::Allocator::obtainDispatchEntry(
Jeff Browna665ca82010-09-08 11:49:43 -07002695 EventEntry* eventEntry,
Jeff Brown53a415e2010-09-15 15:18:56 -07002696 int32_t targetFlags, float xOffset, float yOffset) {
Jeff Browne839a582010-04-22 18:58:52 -07002697 DispatchEntry* entry = mDispatchEntryPool.alloc();
2698 entry->eventEntry = eventEntry;
2699 eventEntry->refCount += 1;
Jeff Browna665ca82010-09-08 11:49:43 -07002700 entry->targetFlags = targetFlags;
2701 entry->xOffset = xOffset;
2702 entry->yOffset = yOffset;
Jeff Browna665ca82010-09-08 11:49:43 -07002703 entry->inProgress = false;
2704 entry->headMotionSample = NULL;
2705 entry->tailMotionSample = NULL;
Jeff Browne839a582010-04-22 18:58:52 -07002706 return entry;
2707}
2708
Jeff Brown54bc2812010-06-15 01:31:58 -07002709InputDispatcher::CommandEntry* InputDispatcher::Allocator::obtainCommandEntry(Command command) {
2710 CommandEntry* entry = mCommandEntryPool.alloc();
2711 entry->command = command;
2712 return entry;
2713}
2714
Jeff Browne839a582010-04-22 18:58:52 -07002715void InputDispatcher::Allocator::releaseEventEntry(EventEntry* entry) {
2716 switch (entry->type) {
2717 case EventEntry::TYPE_CONFIGURATION_CHANGED:
2718 releaseConfigurationChangedEntry(static_cast<ConfigurationChangedEntry*>(entry));
2719 break;
2720 case EventEntry::TYPE_KEY:
2721 releaseKeyEntry(static_cast<KeyEntry*>(entry));
2722 break;
2723 case EventEntry::TYPE_MOTION:
2724 releaseMotionEntry(static_cast<MotionEntry*>(entry));
2725 break;
2726 default:
2727 assert(false);
2728 break;
2729 }
2730}
2731
2732void InputDispatcher::Allocator::releaseConfigurationChangedEntry(
2733 ConfigurationChangedEntry* entry) {
2734 entry->refCount -= 1;
2735 if (entry->refCount == 0) {
2736 mConfigurationChangeEntryPool.free(entry);
2737 } else {
2738 assert(entry->refCount > 0);
2739 }
2740}
2741
2742void InputDispatcher::Allocator::releaseKeyEntry(KeyEntry* entry) {
2743 entry->refCount -= 1;
2744 if (entry->refCount == 0) {
2745 mKeyEntryPool.free(entry);
2746 } else {
2747 assert(entry->refCount > 0);
2748 }
2749}
2750
2751void InputDispatcher::Allocator::releaseMotionEntry(MotionEntry* entry) {
2752 entry->refCount -= 1;
2753 if (entry->refCount == 0) {
Jeff Brown54bc2812010-06-15 01:31:58 -07002754 for (MotionSample* sample = entry->firstSample.next; sample != NULL; ) {
2755 MotionSample* next = sample->next;
2756 mMotionSamplePool.free(sample);
2757 sample = next;
2758 }
Jeff Browne839a582010-04-22 18:58:52 -07002759 mMotionEntryPool.free(entry);
2760 } else {
2761 assert(entry->refCount > 0);
2762 }
2763}
2764
2765void InputDispatcher::Allocator::releaseDispatchEntry(DispatchEntry* entry) {
2766 releaseEventEntry(entry->eventEntry);
2767 mDispatchEntryPool.free(entry);
2768}
2769
Jeff Brown54bc2812010-06-15 01:31:58 -07002770void InputDispatcher::Allocator::releaseCommandEntry(CommandEntry* entry) {
2771 mCommandEntryPool.free(entry);
2772}
2773
Jeff Browne839a582010-04-22 18:58:52 -07002774void InputDispatcher::Allocator::appendMotionSample(MotionEntry* motionEntry,
Jeff Brown51d45a72010-06-17 20:52:56 -07002775 nsecs_t eventTime, const PointerCoords* pointerCoords) {
Jeff Browne839a582010-04-22 18:58:52 -07002776 MotionSample* sample = mMotionSamplePool.alloc();
2777 sample->eventTime = eventTime;
Jeff Brown51d45a72010-06-17 20:52:56 -07002778 uint32_t pointerCount = motionEntry->pointerCount;
2779 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Browne839a582010-04-22 18:58:52 -07002780 sample->pointerCoords[i] = pointerCoords[i];
2781 }
2782
2783 sample->next = NULL;
2784 motionEntry->lastSample->next = sample;
2785 motionEntry->lastSample = sample;
2786}
2787
Jeff Browna665ca82010-09-08 11:49:43 -07002788
2789// --- InputDispatcher::EventEntry ---
2790
2791void InputDispatcher::EventEntry::recycle() {
2792 injectionResult = INPUT_EVENT_INJECTION_PENDING;
2793 dispatchInProgress = false;
Jeff Brown53a415e2010-09-15 15:18:56 -07002794 pendingForegroundDispatches = 0;
Jeff Browna665ca82010-09-08 11:49:43 -07002795}
2796
2797
2798// --- InputDispatcher::KeyEntry ---
2799
2800void InputDispatcher::KeyEntry::recycle() {
2801 EventEntry::recycle();
2802 syntheticRepeat = false;
2803 interceptKeyResult = INTERCEPT_KEY_RESULT_UNKNOWN;
2804}
2805
2806
Jeff Brown542412c2010-08-18 15:51:08 -07002807// --- InputDispatcher::MotionEntry ---
2808
2809uint32_t InputDispatcher::MotionEntry::countSamples() const {
2810 uint32_t count = 1;
2811 for (MotionSample* sample = firstSample.next; sample != NULL; sample = sample->next) {
2812 count += 1;
2813 }
2814 return count;
2815}
2816
Jeff Browna665ca82010-09-08 11:49:43 -07002817
2818// --- InputDispatcher::InputState ---
2819
2820InputDispatcher::InputState::InputState() :
2821 mIsOutOfSync(false) {
2822}
2823
2824InputDispatcher::InputState::~InputState() {
2825}
2826
2827bool InputDispatcher::InputState::isNeutral() const {
2828 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
2829}
2830
2831bool InputDispatcher::InputState::isOutOfSync() const {
2832 return mIsOutOfSync;
2833}
2834
2835void InputDispatcher::InputState::setOutOfSync() {
2836 if (! isNeutral()) {
2837 mIsOutOfSync = true;
2838 }
2839}
2840
2841void InputDispatcher::InputState::resetOutOfSync() {
2842 mIsOutOfSync = false;
2843}
2844
2845InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackEvent(
2846 const EventEntry* entry) {
2847 switch (entry->type) {
2848 case EventEntry::TYPE_KEY:
2849 return trackKey(static_cast<const KeyEntry*>(entry));
2850
2851 case EventEntry::TYPE_MOTION:
2852 return trackMotion(static_cast<const MotionEntry*>(entry));
2853
2854 default:
2855 return CONSISTENT;
2856 }
2857}
2858
2859InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackKey(
2860 const KeyEntry* entry) {
2861 int32_t action = entry->action;
2862 for (size_t i = 0; i < mKeyMementos.size(); i++) {
2863 KeyMemento& memento = mKeyMementos.editItemAt(i);
2864 if (memento.deviceId == entry->deviceId
2865 && memento.source == entry->source
2866 && memento.keyCode == entry->keyCode
2867 && memento.scanCode == entry->scanCode) {
2868 switch (action) {
2869 case AKEY_EVENT_ACTION_UP:
2870 mKeyMementos.removeAt(i);
2871 if (isNeutral()) {
2872 mIsOutOfSync = false;
2873 }
2874 return CONSISTENT;
2875
2876 case AKEY_EVENT_ACTION_DOWN:
2877 return TOLERABLE;
2878
2879 default:
2880 return BROKEN;
2881 }
2882 }
2883 }
2884
2885 switch (action) {
2886 case AKEY_EVENT_ACTION_DOWN: {
2887 mKeyMementos.push();
2888 KeyMemento& memento = mKeyMementos.editTop();
2889 memento.deviceId = entry->deviceId;
2890 memento.source = entry->source;
2891 memento.keyCode = entry->keyCode;
2892 memento.scanCode = entry->scanCode;
2893 memento.downTime = entry->downTime;
2894 return CONSISTENT;
2895 }
2896
2897 default:
2898 return BROKEN;
2899 }
2900}
2901
2902InputDispatcher::InputState::Consistency InputDispatcher::InputState::trackMotion(
2903 const MotionEntry* entry) {
2904 int32_t action = entry->action & AMOTION_EVENT_ACTION_MASK;
2905 for (size_t i = 0; i < mMotionMementos.size(); i++) {
2906 MotionMemento& memento = mMotionMementos.editItemAt(i);
2907 if (memento.deviceId == entry->deviceId
2908 && memento.source == entry->source) {
2909 switch (action) {
2910 case AMOTION_EVENT_ACTION_UP:
2911 case AMOTION_EVENT_ACTION_CANCEL:
2912 mMotionMementos.removeAt(i);
2913 if (isNeutral()) {
2914 mIsOutOfSync = false;
2915 }
2916 return CONSISTENT;
2917
2918 case AMOTION_EVENT_ACTION_DOWN:
2919 return TOLERABLE;
2920
2921 case AMOTION_EVENT_ACTION_POINTER_DOWN:
2922 if (entry->pointerCount == memento.pointerCount + 1) {
2923 memento.setPointers(entry);
2924 return CONSISTENT;
2925 }
2926 return BROKEN;
2927
2928 case AMOTION_EVENT_ACTION_POINTER_UP:
2929 if (entry->pointerCount == memento.pointerCount - 1) {
2930 memento.setPointers(entry);
2931 return CONSISTENT;
2932 }
2933 return BROKEN;
2934
2935 case AMOTION_EVENT_ACTION_MOVE:
2936 if (entry->pointerCount == memento.pointerCount) {
2937 return CONSISTENT;
2938 }
2939 return BROKEN;
2940
2941 default:
2942 return BROKEN;
2943 }
2944 }
2945 }
2946
2947 switch (action) {
2948 case AMOTION_EVENT_ACTION_DOWN: {
2949 mMotionMementos.push();
2950 MotionMemento& memento = mMotionMementos.editTop();
2951 memento.deviceId = entry->deviceId;
2952 memento.source = entry->source;
2953 memento.xPrecision = entry->xPrecision;
2954 memento.yPrecision = entry->yPrecision;
2955 memento.downTime = entry->downTime;
2956 memento.setPointers(entry);
2957 return CONSISTENT;
2958 }
2959
2960 default:
2961 return BROKEN;
2962 }
2963}
2964
2965void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
2966 pointerCount = entry->pointerCount;
2967 for (uint32_t i = 0; i < entry->pointerCount; i++) {
2968 pointerIds[i] = entry->pointerIds[i];
2969 pointerCoords[i] = entry->lastSample->pointerCoords[i];
2970 }
2971}
2972
2973void InputDispatcher::InputState::synthesizeCancelationEvents(
2974 Allocator* allocator, Vector<EventEntry*>& outEvents) const {
2975 for (size_t i = 0; i < mKeyMementos.size(); i++) {
2976 const KeyMemento& memento = mKeyMementos.itemAt(i);
2977 outEvents.push(allocator->obtainKeyEntry(now(),
2978 memento.deviceId, memento.source, 0,
2979 AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_CANCELED,
2980 memento.keyCode, memento.scanCode, 0, 0, memento.downTime));
2981 }
2982
2983 for (size_t i = 0; i < mMotionMementos.size(); i++) {
2984 const MotionMemento& memento = mMotionMementos.itemAt(i);
2985 outEvents.push(allocator->obtainMotionEntry(now(),
2986 memento.deviceId, memento.source, 0,
2987 AMOTION_EVENT_ACTION_CANCEL, 0, 0, 0,
2988 memento.xPrecision, memento.yPrecision, memento.downTime,
2989 memento.pointerCount, memento.pointerIds, memento.pointerCoords));
2990 }
2991}
2992
2993void InputDispatcher::InputState::clear() {
2994 mKeyMementos.clear();
2995 mMotionMementos.clear();
2996 mIsOutOfSync = false;
2997}
2998
2999
Jeff Browne839a582010-04-22 18:58:52 -07003000// --- InputDispatcher::Connection ---
3001
3002InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel) :
3003 status(STATUS_NORMAL), inputChannel(inputChannel), inputPublisher(inputChannel),
Jeff Brown53a415e2010-09-15 15:18:56 -07003004 lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
Jeff Browne839a582010-04-22 18:58:52 -07003005}
3006
3007InputDispatcher::Connection::~Connection() {
3008}
3009
3010status_t InputDispatcher::Connection::initialize() {
3011 return inputPublisher.initialize();
3012}
3013
Jeff Brown54bc2812010-06-15 01:31:58 -07003014const char* InputDispatcher::Connection::getStatusLabel() const {
3015 switch (status) {
3016 case STATUS_NORMAL:
3017 return "NORMAL";
3018
3019 case STATUS_BROKEN:
3020 return "BROKEN";
3021
Jeff Brown54bc2812010-06-15 01:31:58 -07003022 case STATUS_ZOMBIE:
3023 return "ZOMBIE";
3024
3025 default:
3026 return "UNKNOWN";
3027 }
3028}
3029
Jeff Browne839a582010-04-22 18:58:52 -07003030InputDispatcher::DispatchEntry* InputDispatcher::Connection::findQueuedDispatchEntryForEvent(
3031 const EventEntry* eventEntry) const {
Jeff Browna665ca82010-09-08 11:49:43 -07003032 for (DispatchEntry* dispatchEntry = outboundQueue.tailSentinel.prev;
3033 dispatchEntry != & outboundQueue.headSentinel; dispatchEntry = dispatchEntry->prev) {
Jeff Browne839a582010-04-22 18:58:52 -07003034 if (dispatchEntry->eventEntry == eventEntry) {
3035 return dispatchEntry;
3036 }
3037 }
3038 return NULL;
3039}
3040
Jeff Browna665ca82010-09-08 11:49:43 -07003041
Jeff Brown54bc2812010-06-15 01:31:58 -07003042// --- InputDispatcher::CommandEntry ---
3043
Jeff Browna665ca82010-09-08 11:49:43 -07003044InputDispatcher::CommandEntry::CommandEntry() :
3045 keyEntry(NULL) {
Jeff Brown54bc2812010-06-15 01:31:58 -07003046}
3047
3048InputDispatcher::CommandEntry::~CommandEntry() {
3049}
3050
Jeff Browne839a582010-04-22 18:58:52 -07003051
3052// --- InputDispatcherThread ---
3053
3054InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
3055 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
3056}
3057
3058InputDispatcherThread::~InputDispatcherThread() {
3059}
3060
3061bool InputDispatcherThread::threadLoop() {
3062 mDispatcher->dispatchOnce();
3063 return true;
3064}
3065
3066} // namespace android