blob: b088ee714ae5f0c6f62af565e4e6d47a6f5cd7ce [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
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -070014static constexpr bool DEBUG_CHANNEL_LIFECYCLE = false;
Jeff Brown5912f952013-07-01 19:10:31 -070015
16// Log debug messages about transport actions
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080017static constexpr bool DEBUG_TRANSPORT_ACTIONS = false;
Jeff Brown5912f952013-07-01 19:10:31 -070018
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
Michael Wright3dd60e22019-03-27 22:06:44 +000030#include <android-base/stringprintf.h>
31#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070032#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000034#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070035
Jeff Brown5912f952013-07-01 19:10:31 -070036#include <input/InputTransport.h>
37
Michael Wright3dd60e22019-03-27 22:06:44 +000038using android::base::StringPrintf;
39
Jeff Brown5912f952013-07-01 19:10:31 -070040namespace android {
41
42// Socket buffer size. The default is typically about 128KB, which is much larger than
43// we really need. So we make it smaller. It just needs to be big enough to hold
44// a few dozen large multi-finger motion events in the case where an application gets
45// behind processing touches.
46static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
47
48// Nanoseconds per milliseconds.
49static const nsecs_t NANOS_PER_MS = 1000000;
50
51// Latency added during resampling. A few milliseconds doesn't hurt much but
52// reduces the impact of mispredicted touch positions.
53static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
54
55// Minimum time difference between consecutive samples before attempting to resample.
56static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
57
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070058// Maximum time difference between consecutive samples before attempting to resample
59// by extrapolation.
60static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
61
Jeff Brown5912f952013-07-01 19:10:31 -070062// Maximum time to predict forward from the last known state, to avoid predicting too
63// far into the future. This time is further bounded by 50% of the last time delta.
64static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
65
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060066/**
67 * System property for enabling / disabling touch resampling.
68 * Resampling extrapolates / interpolates the reported touch event coordinates to better
69 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
70 * Resampling is not needed (and should be disabled) on hardware that already
71 * has touch events triggered by VSYNC.
72 * Set to "1" to enable resampling (default).
73 * Set to "0" to disable resampling.
74 * Resampling is enabled by default.
75 */
76static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
77
Jeff Brown5912f952013-07-01 19:10:31 -070078template<typename T>
79inline static T min(const T& a, const T& b) {
80 return a < b ? a : b;
81}
82
83inline static float lerp(float a, float b, float alpha) {
84 return a + alpha * (b - a);
85}
86
Siarhei Vishniakou128eab12019-05-23 10:25:59 +080087inline static bool isPointerEvent(int32_t source) {
88 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
89}
90
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080091inline static const char* toString(bool value) {
92 return value ? "true" : "false";
93}
94
Jeff Brown5912f952013-07-01 19:10:31 -070095// --- InputMessage ---
96
97bool InputMessage::isValid(size_t actualSize) const {
98 if (size() == actualSize) {
99 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700100 case Type::KEY:
101 return true;
102 case Type::MOTION:
103 return body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
104 case Type::FINISHED:
105 return true;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800106 case Type::FOCUS:
107 return true;
Jeff Brown5912f952013-07-01 19:10:31 -0700108 }
109 }
110 return false;
111}
112
113size_t InputMessage::size() const {
114 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700115 case Type::KEY:
116 return sizeof(Header) + body.key.size();
117 case Type::MOTION:
118 return sizeof(Header) + body.motion.size();
119 case Type::FINISHED:
120 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800121 case Type::FOCUS:
122 return sizeof(Header) + body.focus.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700123 }
124 return sizeof(Header);
125}
126
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800127/**
128 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
129 * memory to zero, then only copy the valid bytes on a per-field basis.
130 */
131void InputMessage::getSanitizedCopy(InputMessage* msg) const {
132 memset(msg, 0, sizeof(*msg));
133
134 // Write the header
135 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500136 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800137
138 // Write the body
139 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700140 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800141 // int32_t eventId
142 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800143 // nsecs_t eventTime
144 msg->body.key.eventTime = body.key.eventTime;
145 // int32_t deviceId
146 msg->body.key.deviceId = body.key.deviceId;
147 // int32_t source
148 msg->body.key.source = body.key.source;
149 // int32_t displayId
150 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600151 // std::array<uint8_t, 32> hmac
152 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800153 // int32_t action
154 msg->body.key.action = body.key.action;
155 // int32_t flags
156 msg->body.key.flags = body.key.flags;
157 // int32_t keyCode
158 msg->body.key.keyCode = body.key.keyCode;
159 // int32_t scanCode
160 msg->body.key.scanCode = body.key.scanCode;
161 // int32_t metaState
162 msg->body.key.metaState = body.key.metaState;
163 // int32_t repeatCount
164 msg->body.key.repeatCount = body.key.repeatCount;
165 // nsecs_t downTime
166 msg->body.key.downTime = body.key.downTime;
167 break;
168 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700169 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800170 // int32_t eventId
171 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800172 // nsecs_t eventTime
173 msg->body.motion.eventTime = body.motion.eventTime;
174 // int32_t deviceId
175 msg->body.motion.deviceId = body.motion.deviceId;
176 // int32_t source
177 msg->body.motion.source = body.motion.source;
178 // int32_t displayId
179 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600180 // std::array<uint8_t, 32> hmac
181 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800182 // int32_t action
183 msg->body.motion.action = body.motion.action;
184 // int32_t actionButton
185 msg->body.motion.actionButton = body.motion.actionButton;
186 // int32_t flags
187 msg->body.motion.flags = body.motion.flags;
188 // int32_t metaState
189 msg->body.motion.metaState = body.motion.metaState;
190 // int32_t buttonState
191 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800192 // MotionClassification classification
193 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800194 // int32_t edgeFlags
195 msg->body.motion.edgeFlags = body.motion.edgeFlags;
196 // nsecs_t downTime
197 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700198
199 msg->body.motion.dsdx = body.motion.dsdx;
200 msg->body.motion.dtdx = body.motion.dtdx;
201 msg->body.motion.dtdy = body.motion.dtdy;
202 msg->body.motion.dsdy = body.motion.dsdy;
203 msg->body.motion.tx = body.motion.tx;
204 msg->body.motion.ty = body.motion.ty;
205
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800206 // float xPrecision
207 msg->body.motion.xPrecision = body.motion.xPrecision;
208 // float yPrecision
209 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700210 // float xCursorPosition
211 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
212 // float yCursorPosition
213 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800214 // uint32_t pointerCount
215 msg->body.motion.pointerCount = body.motion.pointerCount;
216 //struct Pointer pointers[MAX_POINTERS]
217 for (size_t i = 0; i < body.motion.pointerCount; i++) {
218 // PointerProperties properties
219 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
220 msg->body.motion.pointers[i].properties.toolType =
221 body.motion.pointers[i].properties.toolType,
222 // PointerCoords coords
223 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
224 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
225 memcpy(&msg->body.motion.pointers[i].coords.values[0],
226 &body.motion.pointers[i].coords.values[0],
227 count * (sizeof(body.motion.pointers[i].coords.values[0])));
228 }
229 break;
230 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700231 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800232 msg->body.finished.handled = body.finished.handled;
233 break;
234 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800235 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800236 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800237 msg->body.focus.hasFocus = body.focus.hasFocus;
238 msg->body.focus.inTouchMode = body.focus.inTouchMode;
239 break;
240 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800241 }
242}
Jeff Brown5912f952013-07-01 19:10:31 -0700243
244// --- InputChannel ---
245
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500246std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500247 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700248 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
249 if (result != 0) {
250 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
251 strerror(errno));
252 return nullptr;
253 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500254 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500255 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700256}
257
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500258InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
259 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700260 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500261 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700262 }
Jeff Brown5912f952013-07-01 19:10:31 -0700263}
264
265InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700266 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500267 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700268 }
Robert Carr3720ed02018-08-08 16:08:27 -0700269}
270
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800271status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500272 std::unique_ptr<InputChannel>& outServerChannel,
273 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700274 int sockets[2];
275 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
276 status_t result = -errno;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500277 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d", name.c_str(), errno);
278 outServerChannel.reset();
279 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700280 return result;
281 }
282
283 int bufferSize = SOCKET_BUFFER_SIZE;
284 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
285 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
286 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
287 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
288
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700289 sp<IBinder> token = new BBinder();
290
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700291 std::string serverChannelName = name + " (server)";
292 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700293 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700294
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700295 std::string clientChannelName = name + " (client)";
296 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700297 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700298 return OK;
299}
300
301status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800302 const size_t msgLength = msg->size();
303 InputMessage cleanMsg;
304 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700305 ssize_t nWrite;
306 do {
Chris Ye0783e992020-06-02 21:34:49 -0700307 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700308 } while (nWrite == -1 && errno == EINTR);
309
310 if (nWrite < 0) {
311 int error = errno;
312#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800313 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
314 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700315#endif
316 if (error == EAGAIN || error == EWOULDBLOCK) {
317 return WOULD_BLOCK;
318 }
319 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
320 return DEAD_OBJECT;
321 }
322 return -error;
323 }
324
325 if (size_t(nWrite) != msgLength) {
326#if DEBUG_CHANNEL_MESSAGES
327 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800328 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700329#endif
330 return DEAD_OBJECT;
331 }
332
333#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800334 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700335#endif
336 return OK;
337}
338
339status_t InputChannel::receiveMessage(InputMessage* msg) {
340 ssize_t nRead;
341 do {
Chris Ye0783e992020-06-02 21:34:49 -0700342 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700343 } while (nRead == -1 && errno == EINTR);
344
345 if (nRead < 0) {
346 int error = errno;
347#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800348 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700349#endif
350 if (error == EAGAIN || error == EWOULDBLOCK) {
351 return WOULD_BLOCK;
352 }
353 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
354 return DEAD_OBJECT;
355 }
356 return -error;
357 }
358
359 if (nRead == 0) { // check for EOF
360#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800361 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700362#endif
363 return DEAD_OBJECT;
364 }
365
366 if (!msg->isValid(nRead)) {
367#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800368 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700369#endif
370 return BAD_VALUE;
371 }
372
373#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800374 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700375#endif
376 return OK;
377}
378
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500379std::unique_ptr<InputChannel> InputChannel::dup() const {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700380 android::base::unique_fd newFd(::dup(getFd()));
381 if (!newFd.ok()) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500382 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700383 strerror(errno));
Siarhei Vishniakou3d8df0e2019-09-17 14:53:07 +0100384 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
385 // If this process is out of file descriptors, then throwing that might end up exploding
386 // on the other side of a binder call, which isn't really helpful.
387 // Better to just crash here and hope that the FD leak is slow.
388 // Other failures could be client errors, so we still propagate those back to the caller.
389 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
390 getName().c_str());
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700391 return nullptr;
392 }
Chris Ye0783e992020-06-02 21:34:49 -0700393 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700394}
395
Chris Ye0783e992020-06-02 21:34:49 -0700396status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500397 if (parcel == nullptr) {
398 ALOGE("%s: Null parcel", __func__);
399 return BAD_VALUE;
400 }
401 return parcel->writeStrongBinder(mToken)
402 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700403}
404
Chris Ye0783e992020-06-02 21:34:49 -0700405status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500406 if (parcel == nullptr) {
407 ALOGE("%s: Null parcel", __func__);
408 return BAD_VALUE;
409 }
410 mToken = parcel->readStrongBinder();
411 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700412}
413
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700414sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500415 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700416}
417
Jeff Brown5912f952013-07-01 19:10:31 -0700418// --- InputPublisher ---
419
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500420InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700421
422InputPublisher::~InputPublisher() {
423}
424
Garfield Tan1c7bc862020-01-28 13:24:04 -0800425status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
426 int32_t source, int32_t displayId,
427 std::array<uint8_t, 32> hmac, int32_t action,
428 int32_t flags, int32_t keyCode, int32_t scanCode,
429 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
430 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000431 if (ATRACE_ENABLED()) {
432 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
433 mChannel->getName().c_str(), keyCode);
434 ATRACE_NAME(message.c_str());
435 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800436 if (DEBUG_TRANSPORT_ACTIONS) {
437 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
438 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
439 "downTime=%" PRId64 ", eventTime=%" PRId64,
440 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
441 metaState, repeatCount, downTime, eventTime);
442 }
Jeff Brown5912f952013-07-01 19:10:31 -0700443
444 if (!seq) {
445 ALOGE("Attempted to publish a key event with sequence number 0.");
446 return BAD_VALUE;
447 }
448
449 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700450 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500451 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800452 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700453 msg.body.key.deviceId = deviceId;
454 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100455 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700456 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700457 msg.body.key.action = action;
458 msg.body.key.flags = flags;
459 msg.body.key.keyCode = keyCode;
460 msg.body.key.scanCode = scanCode;
461 msg.body.key.metaState = metaState;
462 msg.body.key.repeatCount = repeatCount;
463 msg.body.key.downTime = downTime;
464 msg.body.key.eventTime = eventTime;
465 return mChannel->sendMessage(&msg);
466}
467
468status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800469 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600470 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
471 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700472 MotionClassification classification, const ui::Transform& transform, float xPrecision,
473 float yPrecision, float xCursorPosition, float yCursorPosition, nsecs_t downTime,
474 nsecs_t eventTime, uint32_t pointerCount, const PointerProperties* pointerProperties,
475 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000476 if (ATRACE_ENABLED()) {
477 std::string message = StringPrintf(
478 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
479 mChannel->getName().c_str(), action);
480 ATRACE_NAME(message.c_str());
481 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800482 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700483 std::string transformString;
484 transform.dump(transformString, "");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800485 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
486 "displayId=%" PRId32 ", "
487 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700488 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800489 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw9eaa22c2020-07-01 16:21:27 -0700490 "pointerCount=%" PRIu32 " transform=%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800491 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
492 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700493 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
494 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800495 }
Jeff Brown5912f952013-07-01 19:10:31 -0700496
497 if (!seq) {
498 ALOGE("Attempted to publish a motion event with sequence number 0.");
499 return BAD_VALUE;
500 }
501
502 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700503 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800504 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700505 return BAD_VALUE;
506 }
507
508 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700509 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500510 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800511 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700512 msg.body.motion.deviceId = deviceId;
513 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700514 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700515 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700516 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100517 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700518 msg.body.motion.flags = flags;
519 msg.body.motion.edgeFlags = edgeFlags;
520 msg.body.motion.metaState = metaState;
521 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800522 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700523 msg.body.motion.dsdx = transform.dsdx();
524 msg.body.motion.dtdx = transform.dtdx();
525 msg.body.motion.dtdy = transform.dtdy();
526 msg.body.motion.dsdy = transform.dsdy();
527 msg.body.motion.tx = transform.tx();
528 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700529 msg.body.motion.xPrecision = xPrecision;
530 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700531 msg.body.motion.xCursorPosition = xCursorPosition;
532 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700533 msg.body.motion.downTime = downTime;
534 msg.body.motion.eventTime = eventTime;
535 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100536 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700537 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
538 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
539 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700540
Jeff Brown5912f952013-07-01 19:10:31 -0700541 return mChannel->sendMessage(&msg);
542}
543
Garfield Tan1c7bc862020-01-28 13:24:04 -0800544status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
545 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800546 if (ATRACE_ENABLED()) {
547 std::string message =
548 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
549 mChannel->getName().c_str(), toString(hasFocus),
550 toString(inTouchMode));
551 ATRACE_NAME(message.c_str());
552 }
553
554 InputMessage msg;
555 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500556 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800557 msg.body.focus.eventId = eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800558 msg.body.focus.hasFocus = hasFocus ? 1 : 0;
559 msg.body.focus.inTouchMode = inTouchMode ? 1 : 0;
560 return mChannel->sendMessage(&msg);
561}
562
Jeff Brown5912f952013-07-01 19:10:31 -0700563status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800564 if (DEBUG_TRANSPORT_ACTIONS) {
565 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
566 }
Jeff Brown5912f952013-07-01 19:10:31 -0700567
568 InputMessage msg;
569 status_t result = mChannel->receiveMessage(&msg);
570 if (result) {
571 *outSeq = 0;
572 *outHandled = false;
573 return result;
574 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700575 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700576 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800577 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700578 return UNKNOWN_ERROR;
579 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500580 *outSeq = msg.header.seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800581 *outHandled = msg.body.finished.handled == 1;
Jeff Brown5912f952013-07-01 19:10:31 -0700582 return OK;
583}
584
585// --- InputConsumer ---
586
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500587InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
588 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700589
590InputConsumer::~InputConsumer() {
591}
592
593bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600594 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700595}
596
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800597status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
598 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800599 if (DEBUG_TRANSPORT_ACTIONS) {
600 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
601 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
602 }
Jeff Brown5912f952013-07-01 19:10:31 -0700603
604 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700605 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700606
607 // Fetch the next input message.
608 // Loop until an event can be returned or no additional events are received.
609 while (!*outEvent) {
610 if (mMsgDeferred) {
611 // mMsg contains a valid input message from the previous call to consume
612 // that has not yet been processed.
613 mMsgDeferred = false;
614 } else {
615 // Receive a fresh message.
616 status_t result = mChannel->receiveMessage(&mMsg);
617 if (result) {
618 // Consume the next batched event unless batches are being held for later.
619 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800620 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700621 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800622 if (DEBUG_TRANSPORT_ACTIONS) {
623 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
624 mChannel->getName().c_str(), *outSeq);
625 }
Jeff Brown5912f952013-07-01 19:10:31 -0700626 break;
627 }
628 }
629 return result;
630 }
631 }
632
633 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700634 case InputMessage::Type::KEY: {
635 KeyEvent* keyEvent = factory->createKeyEvent();
636 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700637
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700638 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500639 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700640 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800641 if (DEBUG_TRANSPORT_ACTIONS) {
642 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
643 mChannel->getName().c_str(), *outSeq);
644 }
Jeff Brown5912f952013-07-01 19:10:31 -0700645 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700646 }
Jeff Brown5912f952013-07-01 19:10:31 -0700647
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700648 case InputMessage::Type::MOTION: {
649 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
650 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500651 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700652 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500653 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800654 if (DEBUG_TRANSPORT_ACTIONS) {
655 ALOGD("channel '%s' consumer ~ appended to batch event",
656 mChannel->getName().c_str());
657 }
Jeff Brown5912f952013-07-01 19:10:31 -0700658 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700659 } else if (isPointerEvent(mMsg.body.motion.source) &&
660 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
661 // No need to process events that we are going to cancel anyways
662 const size_t count = batch.samples.size();
663 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500664 const InputMessage& msg = batch.samples[i];
665 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700666 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500667 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
668 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700669 } else {
670 // We cannot append to the batch in progress, so we need to consume
671 // the previous batch right now and defer the new message until later.
672 mMsgDeferred = true;
673 status_t result = consumeSamples(factory, batch, batch.samples.size(),
674 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500675 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700676 if (result) {
677 return result;
678 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800679 if (DEBUG_TRANSPORT_ACTIONS) {
680 ALOGD("channel '%s' consumer ~ consumed batch event and "
681 "deferred current event, seq=%u",
682 mChannel->getName().c_str(), *outSeq);
683 }
Jeff Brown5912f952013-07-01 19:10:31 -0700684 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700685 }
Jeff Brown5912f952013-07-01 19:10:31 -0700686 }
Jeff Brown5912f952013-07-01 19:10:31 -0700687
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800688 // Start a new batch if needed.
689 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
690 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500691 Batch batch;
692 batch.samples.push_back(mMsg);
693 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800694 if (DEBUG_TRANSPORT_ACTIONS) {
695 ALOGD("channel '%s' consumer ~ started batch event",
696 mChannel->getName().c_str());
697 }
698 break;
699 }
Jeff Brown5912f952013-07-01 19:10:31 -0700700
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800701 MotionEvent* motionEvent = factory->createMotionEvent();
702 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700703
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800704 updateTouchState(mMsg);
705 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500706 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800707 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800708
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800709 if (DEBUG_TRANSPORT_ACTIONS) {
710 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
711 mChannel->getName().c_str(), *outSeq);
712 }
713 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700714 }
Jeff Brown5912f952013-07-01 19:10:31 -0700715
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800716 case InputMessage::Type::FINISHED: {
717 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
718 "InputConsumer!");
719 break;
720 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800721
722 case InputMessage::Type::FOCUS: {
723 FocusEvent* focusEvent = factory->createFocusEvent();
724 if (!focusEvent) return NO_MEMORY;
725
726 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500727 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800728 *outEvent = focusEvent;
729 break;
730 }
Jeff Brown5912f952013-07-01 19:10:31 -0700731 }
732 }
733 return OK;
734}
735
736status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800737 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700738 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700739 for (size_t i = mBatches.size(); i > 0; ) {
740 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500741 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700742 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800743 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500744 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700745 return result;
746 }
747
Michael Wright32232172013-10-21 12:05:22 -0700748 nsecs_t sampleTime = frameTime;
749 if (mResampleTouch) {
750 sampleTime -= RESAMPLE_LATENCY;
751 }
Jeff Brown5912f952013-07-01 19:10:31 -0700752 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
753 if (split < 0) {
754 continue;
755 }
756
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800757 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700758 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500759 if (batch.samples.empty()) {
760 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700761 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700762 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500763 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700764 }
Michael Wright32232172013-10-21 12:05:22 -0700765 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700766 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
767 }
768 return result;
769 }
770
771 return WOULD_BLOCK;
772}
773
774status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800775 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700776 MotionEvent* motionEvent = factory->createMotionEvent();
777 if (! motionEvent) return NO_MEMORY;
778
779 uint32_t chain = 0;
780 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500781 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100782 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700783 if (i) {
784 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500785 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700786 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500787 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700788 addSample(motionEvent, &msg);
789 } else {
790 initializeMotionEvent(motionEvent, &msg);
791 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500792 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700793 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500794 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700795
796 *outSeq = chain;
797 *outEvent = motionEvent;
798 return OK;
799}
800
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100801void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800802 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700803 return;
804 }
805
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100806 int32_t deviceId = msg.body.motion.deviceId;
807 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700808
809 // Update the touch state history to incorporate the new input message.
810 // If the message is in the past relative to the most recently produced resampled
811 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100812 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700813 case AMOTION_EVENT_ACTION_DOWN: {
814 ssize_t index = findTouchState(deviceId, source);
815 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500816 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700817 index = mTouchStates.size() - 1;
818 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500819 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700820 touchState.initialize(deviceId, source);
821 touchState.addHistory(msg);
822 break;
823 }
824
825 case AMOTION_EVENT_ACTION_MOVE: {
826 ssize_t index = findTouchState(deviceId, source);
827 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500828 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700829 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800830 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700831 }
832 break;
833 }
834
835 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
836 ssize_t index = findTouchState(deviceId, source);
837 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500838 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100839 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700840 rewriteMessage(touchState, msg);
841 }
842 break;
843 }
844
845 case AMOTION_EVENT_ACTION_POINTER_UP: {
846 ssize_t index = findTouchState(deviceId, source);
847 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500848 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700849 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100850 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700851 }
852 break;
853 }
854
855 case AMOTION_EVENT_ACTION_SCROLL: {
856 ssize_t index = findTouchState(deviceId, source);
857 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500858 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700859 rewriteMessage(touchState, msg);
860 }
861 break;
862 }
863
864 case AMOTION_EVENT_ACTION_UP:
865 case AMOTION_EVENT_ACTION_CANCEL: {
866 ssize_t index = findTouchState(deviceId, source);
867 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500868 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700869 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500870 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700871 }
872 break;
873 }
874 }
875}
876
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800877/**
878 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
879 *
880 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
881 * is in the past relative to msg and the past two events do not contain identical coordinates),
882 * then invalidate the lastResample data for that pointer.
883 * If the two past events have identical coordinates, then lastResample data for that pointer will
884 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
885 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
886 * not equal to x0 is received.
887 */
888void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100889 nsecs_t eventTime = msg.body.motion.eventTime;
890 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
891 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700892 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100893 if (eventTime < state.lastResample.eventTime ||
894 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800895 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
896 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700897#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100898 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
899 resampleCoords.getX(), resampleCoords.getY(),
900 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700901#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800902 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
903 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
904 } else {
905 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100906 }
Jeff Brown5912f952013-07-01 19:10:31 -0700907 }
908 }
909}
910
911void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
912 const InputMessage* next) {
913 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800914 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700915 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
916 return;
917 }
918
919 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
920 if (index < 0) {
921#if DEBUG_RESAMPLING
922 ALOGD("Not resampled, no touch state for device.");
923#endif
924 return;
925 }
926
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500927 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700928 if (touchState.historySize < 1) {
929#if DEBUG_RESAMPLING
930 ALOGD("Not resampled, no history for device.");
931#endif
932 return;
933 }
934
935 // Ensure that the current sample has all of the pointers that need to be reported.
936 const History* current = touchState.getHistory(0);
937 size_t pointerCount = event->getPointerCount();
938 for (size_t i = 0; i < pointerCount; i++) {
939 uint32_t id = event->getPointerId(i);
940 if (!current->idBits.hasBit(id)) {
941#if DEBUG_RESAMPLING
942 ALOGD("Not resampled, missing id %d", id);
943#endif
944 return;
945 }
946 }
947
948 // Find the data to use for resampling.
949 const History* other;
950 History future;
951 float alpha;
952 if (next) {
953 // Interpolate between current sample and future sample.
954 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100955 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700956 other = &future;
957 nsecs_t delta = future.eventTime - current->eventTime;
958 if (delta < RESAMPLE_MIN_DELTA) {
959#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100960 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700961#endif
962 return;
963 }
964 alpha = float(sampleTime - current->eventTime) / delta;
965 } else if (touchState.historySize >= 2) {
966 // Extrapolate future sample using current sample and past sample.
967 // So other->eventTime <= current->eventTime <= sampleTime.
968 other = touchState.getHistory(1);
969 nsecs_t delta = current->eventTime - other->eventTime;
970 if (delta < RESAMPLE_MIN_DELTA) {
971#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100972 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700973#endif
974 return;
975 } else if (delta > RESAMPLE_MAX_DELTA) {
976#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100977 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700978#endif
979 return;
980 }
981 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
982 if (sampleTime > maxPredict) {
983#if DEBUG_RESAMPLING
984 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100985 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700986 sampleTime - current->eventTime, maxPredict - current->eventTime);
987#endif
988 sampleTime = maxPredict;
989 }
990 alpha = float(current->eventTime - sampleTime) / delta;
991 } else {
992#if DEBUG_RESAMPLING
993 ALOGD("Not resampled, insufficient data.");
994#endif
995 return;
996 }
997
998 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800999 History oldLastResample;
1000 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001001 touchState.lastResample.eventTime = sampleTime;
1002 touchState.lastResample.idBits.clear();
1003 for (size_t i = 0; i < pointerCount; i++) {
1004 uint32_t id = event->getPointerId(i);
1005 touchState.lastResample.idToIndex[id] = i;
1006 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001007 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1008 // We maintain the previously resampled value for this pointer (stored in
1009 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1010 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1011
1012 // We know here that the coordinates for the pointer haven't changed because we
1013 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1014 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1015 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1016 continue;
1017 }
1018
Jeff Brown5912f952013-07-01 19:10:31 -07001019 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1020 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001021 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001022 if (other->idBits.hasBit(id)
1023 && shouldResampleTool(event->getToolType(i))) {
1024 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001025 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1026 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1027 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1028 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1029#if DEBUG_RESAMPLING
1030 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1031 "other (%0.3f, %0.3f), alpha %0.3f",
1032 id, resampledCoords.getX(), resampledCoords.getY(),
1033 currentCoords.getX(), currentCoords.getY(),
1034 otherCoords.getX(), otherCoords.getY(),
1035 alpha);
1036#endif
1037 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001038#if DEBUG_RESAMPLING
1039 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1040 id, resampledCoords.getX(), resampledCoords.getY(),
1041 currentCoords.getX(), currentCoords.getY());
1042#endif
1043 }
1044 }
1045
1046 event->addSample(sampleTime, touchState.lastResample.pointers);
1047}
1048
1049bool InputConsumer::shouldResampleTool(int32_t toolType) {
1050 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1051 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1052}
1053
1054status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001055 if (DEBUG_TRANSPORT_ACTIONS) {
1056 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1057 mChannel->getName().c_str(), seq, toString(handled));
1058 }
Jeff Brown5912f952013-07-01 19:10:31 -07001059
1060 if (!seq) {
1061 ALOGE("Attempted to send a finished signal with sequence number 0.");
1062 return BAD_VALUE;
1063 }
1064
1065 // Send finished signals for the batch sequence chain first.
1066 size_t seqChainCount = mSeqChains.size();
1067 if (seqChainCount) {
1068 uint32_t currentSeq = seq;
1069 uint32_t chainSeqs[seqChainCount];
1070 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001071 for (size_t i = seqChainCount; i > 0; ) {
1072 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001073 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001074 if (seqChain.seq == currentSeq) {
1075 currentSeq = seqChain.chain;
1076 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001077 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001078 }
1079 }
1080 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001081 while (!status && chainIndex > 0) {
1082 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001083 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1084 }
1085 if (status) {
1086 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001087 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001088 SeqChain seqChain;
1089 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1090 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001091 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001092 if (!chainIndex) break;
1093 chainIndex--;
1094 }
Jeff Brown5912f952013-07-01 19:10:31 -07001095 return status;
1096 }
1097 }
1098
1099 // Send finished signal for the last message in the batch.
1100 return sendUnchainedFinishedSignal(seq, handled);
1101}
1102
1103status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1104 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001105 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001106 msg.header.seq = seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -08001107 msg.body.finished.handled = handled ? 1 : 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001108 return mChannel->sendMessage(&msg);
1109}
1110
1111bool InputConsumer::hasDeferredEvent() const {
1112 return mMsgDeferred;
1113}
1114
1115bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001116 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001117}
1118
Arthur Hungc7812be2020-02-27 22:40:27 +08001119int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001120 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001121 return AINPUT_SOURCE_CLASS_NONE;
1122 }
1123
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001124 const Batch& batch = mBatches[0];
1125 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001126 return head.body.motion.source;
1127}
1128
Jeff Brown5912f952013-07-01 19:10:31 -07001129ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1130 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001131 const Batch& batch = mBatches[i];
1132 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001133 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1134 return i;
1135 }
1136 }
1137 return -1;
1138}
1139
1140ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1141 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001142 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001143 if (touchState.deviceId == deviceId && touchState.source == source) {
1144 return i;
1145 }
1146 }
1147 return -1;
1148}
1149
1150void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001151 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001152 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1153 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1154 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1155 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001156}
1157
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001158void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001159 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus == 1,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001160 msg->body.focus.inTouchMode == 1);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001161}
1162
Jeff Brown5912f952013-07-01 19:10:31 -07001163void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001164 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001165 PointerProperties pointerProperties[pointerCount];
1166 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001167 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001168 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1169 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1170 }
1171
chaviw9eaa22c2020-07-01 16:21:27 -07001172 ui::Transform transform;
1173 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1174 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001175 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1176 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1177 msg->body.motion.actionButton, msg->body.motion.flags,
1178 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001179 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1180 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1181 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1182 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1183 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001184}
1185
1186void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001187 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001188 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001189 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001190 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1191 }
1192
1193 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1194 event->addSample(msg->body.motion.eventTime, pointerCoords);
1195}
1196
1197bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001198 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001199 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001200 if (head.body.motion.pointerCount != pointerCount
1201 || head.body.motion.action != msg->body.motion.action) {
1202 return false;
1203 }
1204 for (size_t i = 0; i < pointerCount; i++) {
1205 if (head.body.motion.pointers[i].properties
1206 != msg->body.motion.pointers[i].properties) {
1207 return false;
1208 }
1209 }
1210 return true;
1211}
1212
1213ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1214 size_t numSamples = batch.samples.size();
1215 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001216 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001217 index += 1;
1218 }
1219 return ssize_t(index) - 1;
1220}
1221
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001222std::string InputConsumer::dump() const {
1223 std::string out;
1224 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1225 out = out + "mChannel = " + mChannel->getName() + "\n";
1226 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1227 if (mMsgDeferred) {
1228 out = out + "mMsg : " + InputMessage::typeToString(mMsg.header.type) + "\n";
1229 }
1230 out += "Batches:\n";
1231 for (const Batch& batch : mBatches) {
1232 out += " Batch:\n";
1233 for (const InputMessage& msg : batch.samples) {
1234 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
1235 InputMessage::typeToString(msg.header.type));
1236 switch (msg.header.type) {
1237 case InputMessage::Type::KEY: {
1238 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1239 KeyEvent::actionToString(
1240 msg.body.key.action),
1241 msg.body.key.keyCode);
1242 break;
1243 }
1244 case InputMessage::Type::MOTION: {
1245 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1246 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1247 const float x = msg.body.motion.pointers[i].coords.getX();
1248 const float y = msg.body.motion.pointers[i].coords.getY();
1249 out += android::base::StringPrintf("\n Pointer %" PRIu32
1250 " : x=%.1f y=%.1f",
1251 i, x, y);
1252 }
1253 break;
1254 }
1255 case InputMessage::Type::FINISHED: {
1256 out += android::base::StringPrintf("handled=%s",
1257 toString(msg.body.finished.handled));
1258 break;
1259 }
1260 case InputMessage::Type::FOCUS: {
1261 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1262 toString(msg.body.focus.hasFocus),
1263 toString(msg.body.focus.inTouchMode));
1264 break;
1265 }
1266 }
1267 out += "\n";
1268 }
1269 }
1270 if (mBatches.empty()) {
1271 out += " <empty>\n";
1272 }
1273 out += "mSeqChains:\n";
1274 for (const SeqChain& chain : mSeqChains) {
1275 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1276 chain.chain);
1277 }
1278 if (mSeqChains.empty()) {
1279 out += " <empty>\n";
1280 }
1281 return out;
1282}
1283
Jeff Brown5912f952013-07-01 19:10:31 -07001284} // namespace android