blob: e93f3a4b0085d73133c7dbf948681616e03844ae [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// Provides a shared memory transport for input events.
5//
6#define LOG_TAG "InputTransport"
7
8//#define LOG_NDEBUG 0
9
10// Log debug messages about channel messages (send message, receive message)
11#define DEBUG_CHANNEL_MESSAGES 0
12
13// Log debug messages whenever InputChannel objects are created/destroyed
14#define DEBUG_CHANNEL_LIFECYCLE 0
15
16// Log debug messages about transport actions
17#define DEBUG_TRANSPORT_ACTIONS 0
18
19// Log debug messages about touch event resampling
20#define DEBUG_RESAMPLING 0
21
Jeff Brown5912f952013-07-01 19:10:31 -070022#include <errno.h>
23#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070024#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070025#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070027#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028#include <unistd.h>
29
Jeff Brown5912f952013-07-01 19:10:31 -070030#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070031#include <log/log.h>
32
Robert Carr3720ed02018-08-08 16:08:27 -070033#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070034#include <input/InputTransport.h>
35
Jeff Brown5912f952013-07-01 19:10:31 -070036namespace android {
37
38// Socket buffer size. The default is typically about 128KB, which is much larger than
39// we really need. So we make it smaller. It just needs to be big enough to hold
40// a few dozen large multi-finger motion events in the case where an application gets
41// behind processing touches.
42static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
43
44// Nanoseconds per milliseconds.
45static const nsecs_t NANOS_PER_MS = 1000000;
46
47// Latency added during resampling. A few milliseconds doesn't hurt much but
48// reduces the impact of mispredicted touch positions.
49static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
50
51// Minimum time difference between consecutive samples before attempting to resample.
52static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
53
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070054// Maximum time difference between consecutive samples before attempting to resample
55// by extrapolation.
56static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
57
Jeff Brown5912f952013-07-01 19:10:31 -070058// Maximum time to predict forward from the last known state, to avoid predicting too
59// far into the future. This time is further bounded by 50% of the last time delta.
60static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
61
62template<typename T>
63inline static T min(const T& a, const T& b) {
64 return a < b ? a : b;
65}
66
67inline static float lerp(float a, float b, float alpha) {
68 return a + alpha * (b - a);
69}
70
71// --- InputMessage ---
72
73bool InputMessage::isValid(size_t actualSize) const {
74 if (size() == actualSize) {
75 switch (header.type) {
76 case TYPE_KEY:
77 return true;
78 case TYPE_MOTION:
79 return body.motion.pointerCount > 0
80 && body.motion.pointerCount <= MAX_POINTERS;
81 case TYPE_FINISHED:
82 return true;
83 }
84 }
85 return false;
86}
87
88size_t InputMessage::size() const {
89 switch (header.type) {
90 case TYPE_KEY:
91 return sizeof(Header) + body.key.size();
92 case TYPE_MOTION:
93 return sizeof(Header) + body.motion.size();
94 case TYPE_FINISHED:
95 return sizeof(Header) + body.finished.size();
96 }
97 return sizeof(Header);
98}
99
100
101// --- InputChannel ---
102
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800103InputChannel::InputChannel(const std::string& name, int fd) :
Robert Carr3720ed02018-08-08 16:08:27 -0700104 mName(name) {
Jeff Brown5912f952013-07-01 19:10:31 -0700105#if DEBUG_CHANNEL_LIFECYCLE
106 ALOGD("Input channel constructed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800107 mName.c_str(), fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700108#endif
109
Robert Carr3720ed02018-08-08 16:08:27 -0700110 setFd(fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700111}
112
113InputChannel::~InputChannel() {
114#if DEBUG_CHANNEL_LIFECYCLE
115 ALOGD("Input channel destroyed: name='%s', fd=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800116 mName.c_str(), mFd);
Jeff Brown5912f952013-07-01 19:10:31 -0700117#endif
118
119 ::close(mFd);
120}
121
Robert Carr3720ed02018-08-08 16:08:27 -0700122void InputChannel::setFd(int fd) {
123 if (mFd > 0) {
124 ::close(mFd);
125 }
126 mFd = fd;
127 if (mFd > 0) {
128 int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
129 LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
130 "non-blocking. errno=%d", mName.c_str(), errno);
131 }
132}
133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800134status_t InputChannel::openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700135 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
136 int sockets[2];
137 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
138 status_t result = -errno;
139 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800140 name.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700141 outServerChannel.clear();
142 outClientChannel.clear();
143 return result;
144 }
145
146 int bufferSize = SOCKET_BUFFER_SIZE;
147 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
148 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
149 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
150 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800152 std::string serverChannelName = name;
153 serverChannelName += " (server)";
Jeff Brown5912f952013-07-01 19:10:31 -0700154 outServerChannel = new InputChannel(serverChannelName, sockets[0]);
155
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800156 std::string clientChannelName = name;
157 clientChannelName += " (client)";
Jeff Brown5912f952013-07-01 19:10:31 -0700158 outClientChannel = new InputChannel(clientChannelName, sockets[1]);
159 return OK;
160}
161
162status_t InputChannel::sendMessage(const InputMessage* msg) {
163 size_t msgLength = msg->size();
164 ssize_t nWrite;
165 do {
166 nWrite = ::send(mFd, msg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
167 } while (nWrite == -1 && errno == EINTR);
168
169 if (nWrite < 0) {
170 int error = errno;
171#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800172 ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.c_str(),
Jeff Brown5912f952013-07-01 19:10:31 -0700173 msg->header.type, error);
174#endif
175 if (error == EAGAIN || error == EWOULDBLOCK) {
176 return WOULD_BLOCK;
177 }
178 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
179 return DEAD_OBJECT;
180 }
181 return -error;
182 }
183
184 if (size_t(nWrite) != msgLength) {
185#if DEBUG_CHANNEL_MESSAGES
186 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800187 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700188#endif
189 return DEAD_OBJECT;
190 }
191
192#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800193 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700194#endif
195 return OK;
196}
197
198status_t InputChannel::receiveMessage(InputMessage* msg) {
199 ssize_t nRead;
200 do {
201 nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
202 } while (nRead == -1 && errno == EINTR);
203
204 if (nRead < 0) {
205 int error = errno;
206#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800207 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700208#endif
209 if (error == EAGAIN || error == EWOULDBLOCK) {
210 return WOULD_BLOCK;
211 }
212 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
213 return DEAD_OBJECT;
214 }
215 return -error;
216 }
217
218 if (nRead == 0) { // check for EOF
219#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700221#endif
222 return DEAD_OBJECT;
223 }
224
225 if (!msg->isValid(nRead)) {
226#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800227 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700228#endif
229 return BAD_VALUE;
230 }
231
232#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700234#endif
235 return OK;
236}
237
238sp<InputChannel> InputChannel::dup() const {
239 int fd = ::dup(getFd());
Yi Kong5bed83b2018-07-17 12:53:47 -0700240 return fd >= 0 ? new InputChannel(getName(), fd) : nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700241}
242
243
Robert Carr3720ed02018-08-08 16:08:27 -0700244status_t InputChannel::write(Parcel& out) const {
245 status_t s = out.writeString8(String8(getName().c_str()));
246
247 if (s != OK) {
248 return s;
249 }
Robert Carr803535b2018-08-02 16:38:15 -0700250 s = out.writeStrongBinder(mToken);
251 if (s != OK) {
252 return s;
253 }
Robert Carr3720ed02018-08-08 16:08:27 -0700254
255 s = out.writeDupFileDescriptor(getFd());
256
257 return s;
258}
259
260status_t InputChannel::read(const Parcel& from) {
261 mName = from.readString8();
Robert Carr803535b2018-08-02 16:38:15 -0700262 mToken = from.readStrongBinder();
Robert Carr3720ed02018-08-08 16:08:27 -0700263
264 int rawFd = from.readFileDescriptor();
265 setFd(::dup(rawFd));
266
267 if (mFd < 0) {
268 return BAD_VALUE;
269 }
270
271 return OK;
272}
273
Robert Carr803535b2018-08-02 16:38:15 -0700274sp<IBinder> InputChannel::getToken() const {
275 return mToken;
276}
277
278void InputChannel::setToken(const sp<IBinder>& token) {
279 if (mToken != nullptr) {
280 ALOGE("Assigning InputChannel (%s) a second handle?", mName.c_str());
281 }
282 mToken = token;
283}
284
Jeff Brown5912f952013-07-01 19:10:31 -0700285// --- InputPublisher ---
286
287InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
288 mChannel(channel) {
289}
290
291InputPublisher::~InputPublisher() {
292}
293
294status_t InputPublisher::publishKeyEvent(
295 uint32_t seq,
296 int32_t deviceId,
297 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100298 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700299 int32_t action,
300 int32_t flags,
301 int32_t keyCode,
302 int32_t scanCode,
303 int32_t metaState,
304 int32_t repeatCount,
305 nsecs_t downTime,
306 nsecs_t eventTime) {
307#if DEBUG_TRANSPORT_ACTIONS
308 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
309 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700310 "downTime=%" PRId64 ", eventTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800311 mChannel->getName().c_str(), seq,
Jeff Brown5912f952013-07-01 19:10:31 -0700312 deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
313 downTime, eventTime);
314#endif
315
316 if (!seq) {
317 ALOGE("Attempted to publish a key event with sequence number 0.");
318 return BAD_VALUE;
319 }
320
321 InputMessage msg;
322 msg.header.type = InputMessage::TYPE_KEY;
323 msg.body.key.seq = seq;
324 msg.body.key.deviceId = deviceId;
325 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100326 msg.body.key.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700327 msg.body.key.action = action;
328 msg.body.key.flags = flags;
329 msg.body.key.keyCode = keyCode;
330 msg.body.key.scanCode = scanCode;
331 msg.body.key.metaState = metaState;
332 msg.body.key.repeatCount = repeatCount;
333 msg.body.key.downTime = downTime;
334 msg.body.key.eventTime = eventTime;
335 return mChannel->sendMessage(&msg);
336}
337
338status_t InputPublisher::publishMotionEvent(
339 uint32_t seq,
340 int32_t deviceId,
341 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700342 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700343 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100344 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700345 int32_t flags,
346 int32_t edgeFlags,
347 int32_t metaState,
348 int32_t buttonState,
349 float xOffset,
350 float yOffset,
351 float xPrecision,
352 float yPrecision,
353 nsecs_t downTime,
354 nsecs_t eventTime,
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100355 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700356 const PointerProperties* pointerProperties,
357 const PointerCoords* pointerCoords) {
358#if DEBUG_TRANSPORT_ACTIONS
359 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800360 "displayId=%" PRId32 ", "
Michael Wright7b159c92015-05-14 14:48:03 +0100361 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
362 "metaState=0x%x, buttonState=0x%x, xOffset=%f, yOffset=%f, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700363 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
Michael Wright63ff3a82014-06-10 13:03:17 -0700364 "pointerCount=%" PRIu32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800365 mChannel->getName().c_str(), seq,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800366 deviceId, source, displayId, action, actionButton, flags, edgeFlags, metaState,
367 buttonState, xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime,
368 pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700369#endif
370
371 if (!seq) {
372 ALOGE("Attempted to publish a motion event with sequence number 0.");
373 return BAD_VALUE;
374 }
375
376 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700377 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800378 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700379 return BAD_VALUE;
380 }
381
382 InputMessage msg;
383 msg.header.type = InputMessage::TYPE_MOTION;
384 msg.body.motion.seq = seq;
385 msg.body.motion.deviceId = deviceId;
386 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700387 msg.body.motion.displayId = displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700388 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100389 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700390 msg.body.motion.flags = flags;
391 msg.body.motion.edgeFlags = edgeFlags;
392 msg.body.motion.metaState = metaState;
393 msg.body.motion.buttonState = buttonState;
394 msg.body.motion.xOffset = xOffset;
395 msg.body.motion.yOffset = yOffset;
396 msg.body.motion.xPrecision = xPrecision;
397 msg.body.motion.yPrecision = yPrecision;
398 msg.body.motion.downTime = downTime;
399 msg.body.motion.eventTime = eventTime;
400 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100401 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700402 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
403 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
404 }
405 return mChannel->sendMessage(&msg);
406}
407
408status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
409#if DEBUG_TRANSPORT_ACTIONS
410 ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800411 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700412#endif
413
414 InputMessage msg;
415 status_t result = mChannel->receiveMessage(&msg);
416 if (result) {
417 *outSeq = 0;
418 *outHandled = false;
419 return result;
420 }
421 if (msg.header.type != InputMessage::TYPE_FINISHED) {
422 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800423 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700424 return UNKNOWN_ERROR;
425 }
426 *outSeq = msg.body.finished.seq;
427 *outHandled = msg.body.finished.handled;
428 return OK;
429}
430
431// --- InputConsumer ---
432
433InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
434 mResampleTouch(isTouchResamplingEnabled()),
435 mChannel(channel), mMsgDeferred(false) {
436}
437
438InputConsumer::~InputConsumer() {
439}
440
441bool InputConsumer::isTouchResamplingEnabled() {
442 char value[PROPERTY_VALUE_MAX];
Yi Kong5bed83b2018-07-17 12:53:47 -0700443 int length = property_get("ro.input.noresample", value, nullptr);
Jeff Brown5912f952013-07-01 19:10:31 -0700444 if (length > 0) {
Michael Wrightad526f82013-10-10 18:54:12 -0700445 if (!strcmp("1", value)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700446 return false;
447 }
Michael Wrightad526f82013-10-10 18:54:12 -0700448 if (strcmp("0", value)) {
449 ALOGD("Unrecognized property value for 'ro.input.noresample'. "
Jeff Brown5912f952013-07-01 19:10:31 -0700450 "Use '1' or '0'.");
451 }
452 }
453 return true;
454}
455
456status_t InputConsumer::consume(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800457 bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700458#if DEBUG_TRANSPORT_ACTIONS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700459 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800460 mChannel->getName().c_str(), consumeBatches ? "true" : "false", frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700461#endif
462
463 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700464 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700465
466 // Fetch the next input message.
467 // Loop until an event can be returned or no additional events are received.
468 while (!*outEvent) {
469 if (mMsgDeferred) {
470 // mMsg contains a valid input message from the previous call to consume
471 // that has not yet been processed.
472 mMsgDeferred = false;
473 } else {
474 // Receive a fresh message.
475 status_t result = mChannel->receiveMessage(&mMsg);
476 if (result) {
477 // Consume the next batched event unless batches are being held for later.
478 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800479 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700480 if (*outEvent) {
481#if DEBUG_TRANSPORT_ACTIONS
482 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800483 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700484#endif
485 break;
486 }
487 }
488 return result;
489 }
490 }
491
492 switch (mMsg.header.type) {
493 case InputMessage::TYPE_KEY: {
494 KeyEvent* keyEvent = factory->createKeyEvent();
495 if (!keyEvent) return NO_MEMORY;
496
497 initializeKeyEvent(keyEvent, &mMsg);
498 *outSeq = mMsg.body.key.seq;
499 *outEvent = keyEvent;
500#if DEBUG_TRANSPORT_ACTIONS
501 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800502 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700503#endif
504 break;
505 }
506
gaoshange3e11a72017-08-08 16:11:31 +0800507 case InputMessage::TYPE_MOTION: {
Jeff Brown5912f952013-07-01 19:10:31 -0700508 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
509 if (batchIndex >= 0) {
510 Batch& batch = mBatches.editItemAt(batchIndex);
511 if (canAddSample(batch, &mMsg)) {
512 batch.samples.push(mMsg);
513#if DEBUG_TRANSPORT_ACTIONS
514 ALOGD("channel '%s' consumer ~ appended to batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800515 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700516#endif
517 break;
518 } else {
519 // We cannot append to the batch in progress, so we need to consume
520 // the previous batch right now and defer the new message until later.
521 mMsgDeferred = true;
522 status_t result = consumeSamples(factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800523 batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700524 mBatches.removeAt(batchIndex);
525 if (result) {
526 return result;
527 }
528#if DEBUG_TRANSPORT_ACTIONS
529 ALOGD("channel '%s' consumer ~ consumed batch event and "
530 "deferred current event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800531 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700532#endif
533 break;
534 }
535 }
536
537 // Start a new batch if needed.
538 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
539 || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
540 mBatches.push();
541 Batch& batch = mBatches.editTop();
542 batch.samples.push(mMsg);
543#if DEBUG_TRANSPORT_ACTIONS
544 ALOGD("channel '%s' consumer ~ started batch event",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800545 mChannel->getName().c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700546#endif
547 break;
548 }
549
550 MotionEvent* motionEvent = factory->createMotionEvent();
551 if (! motionEvent) return NO_MEMORY;
552
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100553 updateTouchState(mMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700554 initializeMotionEvent(motionEvent, &mMsg);
555 *outSeq = mMsg.body.motion.seq;
556 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800557
Jeff Brown5912f952013-07-01 19:10:31 -0700558#if DEBUG_TRANSPORT_ACTIONS
559 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800560 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700561#endif
562 break;
563 }
564
565 default:
566 ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800567 mChannel->getName().c_str(), mMsg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700568 return UNKNOWN_ERROR;
569 }
570 }
571 return OK;
572}
573
574status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800575 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700576 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700577 for (size_t i = mBatches.size(); i > 0; ) {
578 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700579 Batch& batch = mBatches.editItemAt(i);
Michael Wright32232172013-10-21 12:05:22 -0700580 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800581 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700582 mBatches.removeAt(i);
583 return result;
584 }
585
Michael Wright32232172013-10-21 12:05:22 -0700586 nsecs_t sampleTime = frameTime;
587 if (mResampleTouch) {
588 sampleTime -= RESAMPLE_LATENCY;
589 }
Jeff Brown5912f952013-07-01 19:10:31 -0700590 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
591 if (split < 0) {
592 continue;
593 }
594
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800595 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700596 const InputMessage* next;
597 if (batch.samples.isEmpty()) {
598 mBatches.removeAt(i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700599 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700600 } else {
601 next = &batch.samples.itemAt(0);
602 }
Michael Wright32232172013-10-21 12:05:22 -0700603 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700604 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
605 }
606 return result;
607 }
608
609 return WOULD_BLOCK;
610}
611
612status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800613 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700614 MotionEvent* motionEvent = factory->createMotionEvent();
615 if (! motionEvent) return NO_MEMORY;
616
617 uint32_t chain = 0;
618 for (size_t i = 0; i < count; i++) {
619 InputMessage& msg = batch.samples.editItemAt(i);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100620 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700621 if (i) {
622 SeqChain seqChain;
623 seqChain.seq = msg.body.motion.seq;
624 seqChain.chain = chain;
625 mSeqChains.push(seqChain);
626 addSample(motionEvent, &msg);
627 } else {
628 initializeMotionEvent(motionEvent, &msg);
629 }
630 chain = msg.body.motion.seq;
631 }
632 batch.samples.removeItemsAt(0, count);
633
634 *outSeq = chain;
635 *outEvent = motionEvent;
636 return OK;
637}
638
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100639void InputConsumer::updateTouchState(InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700640 if (!mResampleTouch ||
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100641 !(msg.body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700642 return;
643 }
644
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100645 int32_t deviceId = msg.body.motion.deviceId;
646 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700647
648 // Update the touch state history to incorporate the new input message.
649 // If the message is in the past relative to the most recently produced resampled
650 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100651 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700652 case AMOTION_EVENT_ACTION_DOWN: {
653 ssize_t index = findTouchState(deviceId, source);
654 if (index < 0) {
655 mTouchStates.push();
656 index = mTouchStates.size() - 1;
657 }
658 TouchState& touchState = mTouchStates.editItemAt(index);
659 touchState.initialize(deviceId, source);
660 touchState.addHistory(msg);
661 break;
662 }
663
664 case AMOTION_EVENT_ACTION_MOVE: {
665 ssize_t index = findTouchState(deviceId, source);
666 if (index >= 0) {
667 TouchState& touchState = mTouchStates.editItemAt(index);
668 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800669 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700670 }
671 break;
672 }
673
674 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
675 ssize_t index = findTouchState(deviceId, source);
676 if (index >= 0) {
677 TouchState& touchState = mTouchStates.editItemAt(index);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100678 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700679 rewriteMessage(touchState, msg);
680 }
681 break;
682 }
683
684 case AMOTION_EVENT_ACTION_POINTER_UP: {
685 ssize_t index = findTouchState(deviceId, source);
686 if (index >= 0) {
687 TouchState& touchState = mTouchStates.editItemAt(index);
688 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100689 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700690 }
691 break;
692 }
693
694 case AMOTION_EVENT_ACTION_SCROLL: {
695 ssize_t index = findTouchState(deviceId, source);
696 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800697 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700698 rewriteMessage(touchState, msg);
699 }
700 break;
701 }
702
703 case AMOTION_EVENT_ACTION_UP:
704 case AMOTION_EVENT_ACTION_CANCEL: {
705 ssize_t index = findTouchState(deviceId, source);
706 if (index >= 0) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800707 TouchState& touchState = mTouchStates.editItemAt(index);
Jeff Brown5912f952013-07-01 19:10:31 -0700708 rewriteMessage(touchState, msg);
709 mTouchStates.removeAt(index);
710 }
711 break;
712 }
713 }
714}
715
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800716/**
717 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
718 *
719 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
720 * is in the past relative to msg and the past two events do not contain identical coordinates),
721 * then invalidate the lastResample data for that pointer.
722 * If the two past events have identical coordinates, then lastResample data for that pointer will
723 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
724 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
725 * not equal to x0 is received.
726 */
727void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100728 nsecs_t eventTime = msg.body.motion.eventTime;
729 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
730 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700731 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100732 if (eventTime < state.lastResample.eventTime ||
733 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800734 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
735 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700736#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100737 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
738 resampleCoords.getX(), resampleCoords.getY(),
739 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700740#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800741 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
742 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
743 } else {
744 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100745 }
Jeff Brown5912f952013-07-01 19:10:31 -0700746 }
747 }
748}
749
750void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
751 const InputMessage* next) {
752 if (!mResampleTouch
753 || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
754 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
755 return;
756 }
757
758 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
759 if (index < 0) {
760#if DEBUG_RESAMPLING
761 ALOGD("Not resampled, no touch state for device.");
762#endif
763 return;
764 }
765
766 TouchState& touchState = mTouchStates.editItemAt(index);
767 if (touchState.historySize < 1) {
768#if DEBUG_RESAMPLING
769 ALOGD("Not resampled, no history for device.");
770#endif
771 return;
772 }
773
774 // Ensure that the current sample has all of the pointers that need to be reported.
775 const History* current = touchState.getHistory(0);
776 size_t pointerCount = event->getPointerCount();
777 for (size_t i = 0; i < pointerCount; i++) {
778 uint32_t id = event->getPointerId(i);
779 if (!current->idBits.hasBit(id)) {
780#if DEBUG_RESAMPLING
781 ALOGD("Not resampled, missing id %d", id);
782#endif
783 return;
784 }
785 }
786
787 // Find the data to use for resampling.
788 const History* other;
789 History future;
790 float alpha;
791 if (next) {
792 // Interpolate between current sample and future sample.
793 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100794 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700795 other = &future;
796 nsecs_t delta = future.eventTime - current->eventTime;
797 if (delta < RESAMPLE_MIN_DELTA) {
798#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100799 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700800#endif
801 return;
802 }
803 alpha = float(sampleTime - current->eventTime) / delta;
804 } else if (touchState.historySize >= 2) {
805 // Extrapolate future sample using current sample and past sample.
806 // So other->eventTime <= current->eventTime <= sampleTime.
807 other = touchState.getHistory(1);
808 nsecs_t delta = current->eventTime - other->eventTime;
809 if (delta < RESAMPLE_MIN_DELTA) {
810#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100811 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700812#endif
813 return;
814 } else if (delta > RESAMPLE_MAX_DELTA) {
815#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100816 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700817#endif
818 return;
819 }
820 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
821 if (sampleTime > maxPredict) {
822#if DEBUG_RESAMPLING
823 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100824 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700825 sampleTime - current->eventTime, maxPredict - current->eventTime);
826#endif
827 sampleTime = maxPredict;
828 }
829 alpha = float(current->eventTime - sampleTime) / delta;
830 } else {
831#if DEBUG_RESAMPLING
832 ALOGD("Not resampled, insufficient data.");
833#endif
834 return;
835 }
836
837 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800838 History oldLastResample;
839 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700840 touchState.lastResample.eventTime = sampleTime;
841 touchState.lastResample.idBits.clear();
842 for (size_t i = 0; i < pointerCount; i++) {
843 uint32_t id = event->getPointerId(i);
844 touchState.lastResample.idToIndex[id] = i;
845 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800846 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
847 // We maintain the previously resampled value for this pointer (stored in
848 // oldLastResample) when the coordinates for this pointer haven't changed since then.
849 // This way we don't introduce artificial jitter when pointers haven't actually moved.
850
851 // We know here that the coordinates for the pointer haven't changed because we
852 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
853 // lastResample in place becasue the mapping from pointer ID to index may have changed.
854 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
855 continue;
856 }
857
Jeff Brown5912f952013-07-01 19:10:31 -0700858 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
859 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800860 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700861 if (other->idBits.hasBit(id)
862 && shouldResampleTool(event->getToolType(i))) {
863 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700864 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
865 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
866 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
867 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
868#if DEBUG_RESAMPLING
869 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
870 "other (%0.3f, %0.3f), alpha %0.3f",
871 id, resampledCoords.getX(), resampledCoords.getY(),
872 currentCoords.getX(), currentCoords.getY(),
873 otherCoords.getX(), otherCoords.getY(),
874 alpha);
875#endif
876 } else {
Jeff Brown5912f952013-07-01 19:10:31 -0700877#if DEBUG_RESAMPLING
878 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
879 id, resampledCoords.getX(), resampledCoords.getY(),
880 currentCoords.getX(), currentCoords.getY());
881#endif
882 }
883 }
884
885 event->addSample(sampleTime, touchState.lastResample.pointers);
886}
887
888bool InputConsumer::shouldResampleTool(int32_t toolType) {
889 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
890 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
891}
892
893status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
894#if DEBUG_TRANSPORT_ACTIONS
895 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800896 mChannel->getName().c_str(), seq, handled ? "true" : "false");
Jeff Brown5912f952013-07-01 19:10:31 -0700897#endif
898
899 if (!seq) {
900 ALOGE("Attempted to send a finished signal with sequence number 0.");
901 return BAD_VALUE;
902 }
903
904 // Send finished signals for the batch sequence chain first.
905 size_t seqChainCount = mSeqChains.size();
906 if (seqChainCount) {
907 uint32_t currentSeq = seq;
908 uint32_t chainSeqs[seqChainCount];
909 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -0700910 for (size_t i = seqChainCount; i > 0; ) {
911 i--;
Jeff Brown5912f952013-07-01 19:10:31 -0700912 const SeqChain& seqChain = mSeqChains.itemAt(i);
913 if (seqChain.seq == currentSeq) {
914 currentSeq = seqChain.chain;
915 chainSeqs[chainIndex++] = currentSeq;
916 mSeqChains.removeAt(i);
917 }
918 }
919 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -0700920 while (!status && chainIndex > 0) {
921 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -0700922 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
923 }
924 if (status) {
925 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +0800926 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -0700927 SeqChain seqChain;
928 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
929 seqChain.chain = chainSeqs[chainIndex];
930 mSeqChains.push(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +0800931 if (!chainIndex) break;
932 chainIndex--;
933 }
Jeff Brown5912f952013-07-01 19:10:31 -0700934 return status;
935 }
936 }
937
938 // Send finished signal for the last message in the batch.
939 return sendUnchainedFinishedSignal(seq, handled);
940}
941
942status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
943 InputMessage msg;
944 msg.header.type = InputMessage::TYPE_FINISHED;
945 msg.body.finished.seq = seq;
946 msg.body.finished.handled = handled;
947 return mChannel->sendMessage(&msg);
948}
949
950bool InputConsumer::hasDeferredEvent() const {
951 return mMsgDeferred;
952}
953
954bool InputConsumer::hasPendingBatch() const {
955 return !mBatches.isEmpty();
956}
957
958ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
959 for (size_t i = 0; i < mBatches.size(); i++) {
960 const Batch& batch = mBatches.itemAt(i);
961 const InputMessage& head = batch.samples.itemAt(0);
962 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
963 return i;
964 }
965 }
966 return -1;
967}
968
969ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
970 for (size_t i = 0; i < mTouchStates.size(); i++) {
971 const TouchState& touchState = mTouchStates.itemAt(i);
972 if (touchState.deviceId == deviceId && touchState.source == source) {
973 return i;
974 }
975 }
976 return -1;
977}
978
979void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
980 event->initialize(
981 msg->body.key.deviceId,
982 msg->body.key.source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100983 msg->body.key.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700984 msg->body.key.action,
985 msg->body.key.flags,
986 msg->body.key.keyCode,
987 msg->body.key.scanCode,
988 msg->body.key.metaState,
989 msg->body.key.repeatCount,
990 msg->body.key.downTime,
991 msg->body.key.eventTime);
992}
993
994void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100995 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -0700996 PointerProperties pointerProperties[pointerCount];
997 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100998 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700999 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1000 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1001 }
1002
1003 event->initialize(
1004 msg->body.motion.deviceId,
1005 msg->body.motion.source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001006 msg->body.motion.displayId,
Jeff Brown5912f952013-07-01 19:10:31 -07001007 msg->body.motion.action,
Michael Wright7b159c92015-05-14 14:48:03 +01001008 msg->body.motion.actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -07001009 msg->body.motion.flags,
1010 msg->body.motion.edgeFlags,
1011 msg->body.motion.metaState,
1012 msg->body.motion.buttonState,
1013 msg->body.motion.xOffset,
1014 msg->body.motion.yOffset,
1015 msg->body.motion.xPrecision,
1016 msg->body.motion.yPrecision,
1017 msg->body.motion.downTime,
1018 msg->body.motion.eventTime,
1019 pointerCount,
1020 pointerProperties,
1021 pointerCoords);
1022}
1023
1024void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001025 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001026 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001027 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001028 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1029 }
1030
1031 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1032 event->addSample(msg->body.motion.eventTime, pointerCoords);
1033}
1034
1035bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1036 const InputMessage& head = batch.samples.itemAt(0);
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001037 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001038 if (head.body.motion.pointerCount != pointerCount
1039 || head.body.motion.action != msg->body.motion.action) {
1040 return false;
1041 }
1042 for (size_t i = 0; i < pointerCount; i++) {
1043 if (head.body.motion.pointers[i].properties
1044 != msg->body.motion.pointers[i].properties) {
1045 return false;
1046 }
1047 }
1048 return true;
1049}
1050
1051ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1052 size_t numSamples = batch.samples.size();
1053 size_t index = 0;
1054 while (index < numSamples
1055 && batch.samples.itemAt(index).body.motion.eventTime <= time) {
1056 index += 1;
1057 }
1058 return ssize_t(index) - 1;
1059}
1060
1061} // namespace android