blob: 1bbddea8db395d69cf31677f497104922e663a0f [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;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600198 // float xScale
199 msg->body.motion.xScale = body.motion.xScale;
200 // float yScale
201 msg->body.motion.yScale = body.motion.yScale;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800202 // float xOffset
203 msg->body.motion.xOffset = body.motion.xOffset;
204 // float yOffset
205 msg->body.motion.yOffset = body.motion.yOffset;
206 // 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 Vishniakouce5ab082020-07-09 17:03:21 -0500246std::shared_ptr<InputChannel> InputChannel::create(const std::string& name,
247 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
255 return std::shared_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 Vishniakouce5ab082020-07-09 17:03:21 -0500272 std::shared_ptr<InputChannel>& outServerChannel,
273 std::shared_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 Vishniakouce5ab082020-07-09 17:03:21 -0500379std::shared_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,
472 MotionClassification classification, float xScale, float yScale, float xOffset,
473 float yOffset, float xPrecision, float yPrecision, float xCursorPosition,
474 float yCursorPosition, nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
Garfield Tan00f511d2019-06-12 16:55:40 -0700475 const PointerProperties* pointerProperties, 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) {
483 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
484 "displayId=%" PRId32 ", "
485 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600486 "metaState=0x%x, buttonState=0x%x, classification=%s, xScale=%.1f, yScale=%.1f, "
487 "xOffset=%.1f, yOffset=%.1f, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800488 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
489 "pointerCount=%" PRIu32,
490 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
491 flags, edgeFlags, metaState, buttonState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600492 motionClassificationToString(classification), xScale, yScale, xOffset, yOffset,
493 xPrecision, yPrecision, downTime, eventTime, pointerCount);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800494 }
Jeff Brown5912f952013-07-01 19:10:31 -0700495
496 if (!seq) {
497 ALOGE("Attempted to publish a motion event with sequence number 0.");
498 return BAD_VALUE;
499 }
500
501 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700502 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800503 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700504 return BAD_VALUE;
505 }
506
507 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700508 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500509 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800510 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700511 msg.body.motion.deviceId = deviceId;
512 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700513 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700514 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700515 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100516 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700517 msg.body.motion.flags = flags;
518 msg.body.motion.edgeFlags = edgeFlags;
519 msg.body.motion.metaState = metaState;
520 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800521 msg.body.motion.classification = classification;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600522 msg.body.motion.xScale = xScale;
523 msg.body.motion.yScale = yScale;
Jeff Brown5912f952013-07-01 19:10:31 -0700524 msg.body.motion.xOffset = xOffset;
525 msg.body.motion.yOffset = yOffset;
526 msg.body.motion.xPrecision = xPrecision;
527 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700528 msg.body.motion.xCursorPosition = xCursorPosition;
529 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700530 msg.body.motion.downTime = downTime;
531 msg.body.motion.eventTime = eventTime;
532 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100533 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700534 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
535 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
536 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700537
Jeff Brown5912f952013-07-01 19:10:31 -0700538 return mChannel->sendMessage(&msg);
539}
540
Garfield Tan1c7bc862020-01-28 13:24:04 -0800541status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
542 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800543 if (ATRACE_ENABLED()) {
544 std::string message =
545 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
546 mChannel->getName().c_str(), toString(hasFocus),
547 toString(inTouchMode));
548 ATRACE_NAME(message.c_str());
549 }
550
551 InputMessage msg;
552 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500553 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800554 msg.body.focus.eventId = eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800555 msg.body.focus.hasFocus = hasFocus ? 1 : 0;
556 msg.body.focus.inTouchMode = inTouchMode ? 1 : 0;
557 return mChannel->sendMessage(&msg);
558}
559
Jeff Brown5912f952013-07-01 19:10:31 -0700560status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800561 if (DEBUG_TRANSPORT_ACTIONS) {
562 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
563 }
Jeff Brown5912f952013-07-01 19:10:31 -0700564
565 InputMessage msg;
566 status_t result = mChannel->receiveMessage(&msg);
567 if (result) {
568 *outSeq = 0;
569 *outHandled = false;
570 return result;
571 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700572 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700573 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800574 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700575 return UNKNOWN_ERROR;
576 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500577 *outSeq = msg.header.seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800578 *outHandled = msg.body.finished.handled == 1;
Jeff Brown5912f952013-07-01 19:10:31 -0700579 return OK;
580}
581
582// --- InputConsumer ---
583
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500584InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
585 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700586
587InputConsumer::~InputConsumer() {
588}
589
590bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600591 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700592}
593
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800594status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
595 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800596 if (DEBUG_TRANSPORT_ACTIONS) {
597 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
598 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
599 }
Jeff Brown5912f952013-07-01 19:10:31 -0700600
601 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700602 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700603
604 // Fetch the next input message.
605 // Loop until an event can be returned or no additional events are received.
606 while (!*outEvent) {
607 if (mMsgDeferred) {
608 // mMsg contains a valid input message from the previous call to consume
609 // that has not yet been processed.
610 mMsgDeferred = false;
611 } else {
612 // Receive a fresh message.
613 status_t result = mChannel->receiveMessage(&mMsg);
614 if (result) {
615 // Consume the next batched event unless batches are being held for later.
616 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800617 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700618 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800619 if (DEBUG_TRANSPORT_ACTIONS) {
620 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
621 mChannel->getName().c_str(), *outSeq);
622 }
Jeff Brown5912f952013-07-01 19:10:31 -0700623 break;
624 }
625 }
626 return result;
627 }
628 }
629
630 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700631 case InputMessage::Type::KEY: {
632 KeyEvent* keyEvent = factory->createKeyEvent();
633 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700634
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700635 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500636 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700637 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800638 if (DEBUG_TRANSPORT_ACTIONS) {
639 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
640 mChannel->getName().c_str(), *outSeq);
641 }
Jeff Brown5912f952013-07-01 19:10:31 -0700642 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700643 }
Jeff Brown5912f952013-07-01 19:10:31 -0700644
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700645 case InputMessage::Type::MOTION: {
646 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
647 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500648 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700649 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500650 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800651 if (DEBUG_TRANSPORT_ACTIONS) {
652 ALOGD("channel '%s' consumer ~ appended to batch event",
653 mChannel->getName().c_str());
654 }
Jeff Brown5912f952013-07-01 19:10:31 -0700655 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700656 } else if (isPointerEvent(mMsg.body.motion.source) &&
657 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
658 // No need to process events that we are going to cancel anyways
659 const size_t count = batch.samples.size();
660 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500661 const InputMessage& msg = batch.samples[i];
662 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700663 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500664 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
665 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700666 } else {
667 // We cannot append to the batch in progress, so we need to consume
668 // the previous batch right now and defer the new message until later.
669 mMsgDeferred = true;
670 status_t result = consumeSamples(factory, batch, batch.samples.size(),
671 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500672 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700673 if (result) {
674 return result;
675 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800676 if (DEBUG_TRANSPORT_ACTIONS) {
677 ALOGD("channel '%s' consumer ~ consumed batch event and "
678 "deferred current event, seq=%u",
679 mChannel->getName().c_str(), *outSeq);
680 }
Jeff Brown5912f952013-07-01 19:10:31 -0700681 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700682 }
Jeff Brown5912f952013-07-01 19:10:31 -0700683 }
Jeff Brown5912f952013-07-01 19:10:31 -0700684
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800685 // Start a new batch if needed.
686 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
687 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500688 Batch batch;
689 batch.samples.push_back(mMsg);
690 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800691 if (DEBUG_TRANSPORT_ACTIONS) {
692 ALOGD("channel '%s' consumer ~ started batch event",
693 mChannel->getName().c_str());
694 }
695 break;
696 }
Jeff Brown5912f952013-07-01 19:10:31 -0700697
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800698 MotionEvent* motionEvent = factory->createMotionEvent();
699 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700700
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800701 updateTouchState(mMsg);
702 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500703 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800704 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800705
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800706 if (DEBUG_TRANSPORT_ACTIONS) {
707 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
708 mChannel->getName().c_str(), *outSeq);
709 }
710 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700711 }
Jeff Brown5912f952013-07-01 19:10:31 -0700712
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800713 case InputMessage::Type::FINISHED: {
714 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
715 "InputConsumer!");
716 break;
717 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800718
719 case InputMessage::Type::FOCUS: {
720 FocusEvent* focusEvent = factory->createFocusEvent();
721 if (!focusEvent) return NO_MEMORY;
722
723 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500724 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800725 *outEvent = focusEvent;
726 break;
727 }
Jeff Brown5912f952013-07-01 19:10:31 -0700728 }
729 }
730 return OK;
731}
732
733status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800734 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700735 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700736 for (size_t i = mBatches.size(); i > 0; ) {
737 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500738 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700739 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800740 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500741 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700742 return result;
743 }
744
Michael Wright32232172013-10-21 12:05:22 -0700745 nsecs_t sampleTime = frameTime;
746 if (mResampleTouch) {
747 sampleTime -= RESAMPLE_LATENCY;
748 }
Jeff Brown5912f952013-07-01 19:10:31 -0700749 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
750 if (split < 0) {
751 continue;
752 }
753
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800754 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700755 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500756 if (batch.samples.empty()) {
757 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700758 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700759 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500760 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700761 }
Michael Wright32232172013-10-21 12:05:22 -0700762 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700763 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
764 }
765 return result;
766 }
767
768 return WOULD_BLOCK;
769}
770
771status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800772 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700773 MotionEvent* motionEvent = factory->createMotionEvent();
774 if (! motionEvent) return NO_MEMORY;
775
776 uint32_t chain = 0;
777 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500778 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100779 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700780 if (i) {
781 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500782 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700783 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500784 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700785 addSample(motionEvent, &msg);
786 } else {
787 initializeMotionEvent(motionEvent, &msg);
788 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500789 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700790 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500791 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700792
793 *outSeq = chain;
794 *outEvent = motionEvent;
795 return OK;
796}
797
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100798void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800799 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700800 return;
801 }
802
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100803 int32_t deviceId = msg.body.motion.deviceId;
804 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700805
806 // Update the touch state history to incorporate the new input message.
807 // If the message is in the past relative to the most recently produced resampled
808 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100809 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700810 case AMOTION_EVENT_ACTION_DOWN: {
811 ssize_t index = findTouchState(deviceId, source);
812 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500813 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700814 index = mTouchStates.size() - 1;
815 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500816 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700817 touchState.initialize(deviceId, source);
818 touchState.addHistory(msg);
819 break;
820 }
821
822 case AMOTION_EVENT_ACTION_MOVE: {
823 ssize_t index = findTouchState(deviceId, source);
824 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500825 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700826 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800827 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700828 }
829 break;
830 }
831
832 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
833 ssize_t index = findTouchState(deviceId, source);
834 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500835 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100836 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700837 rewriteMessage(touchState, msg);
838 }
839 break;
840 }
841
842 case AMOTION_EVENT_ACTION_POINTER_UP: {
843 ssize_t index = findTouchState(deviceId, source);
844 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500845 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700846 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100847 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700848 }
849 break;
850 }
851
852 case AMOTION_EVENT_ACTION_SCROLL: {
853 ssize_t index = findTouchState(deviceId, source);
854 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500855 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700856 rewriteMessage(touchState, msg);
857 }
858 break;
859 }
860
861 case AMOTION_EVENT_ACTION_UP:
862 case AMOTION_EVENT_ACTION_CANCEL: {
863 ssize_t index = findTouchState(deviceId, source);
864 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500865 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700866 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500867 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700868 }
869 break;
870 }
871 }
872}
873
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800874/**
875 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
876 *
877 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
878 * is in the past relative to msg and the past two events do not contain identical coordinates),
879 * then invalidate the lastResample data for that pointer.
880 * If the two past events have identical coordinates, then lastResample data for that pointer will
881 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
882 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
883 * not equal to x0 is received.
884 */
885void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100886 nsecs_t eventTime = msg.body.motion.eventTime;
887 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
888 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700889 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100890 if (eventTime < state.lastResample.eventTime ||
891 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800892 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
893 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700894#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100895 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
896 resampleCoords.getX(), resampleCoords.getY(),
897 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700898#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800899 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
900 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
901 } else {
902 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100903 }
Jeff Brown5912f952013-07-01 19:10:31 -0700904 }
905 }
906}
907
908void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
909 const InputMessage* next) {
910 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800911 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700912 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
913 return;
914 }
915
916 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
917 if (index < 0) {
918#if DEBUG_RESAMPLING
919 ALOGD("Not resampled, no touch state for device.");
920#endif
921 return;
922 }
923
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500924 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700925 if (touchState.historySize < 1) {
926#if DEBUG_RESAMPLING
927 ALOGD("Not resampled, no history for device.");
928#endif
929 return;
930 }
931
932 // Ensure that the current sample has all of the pointers that need to be reported.
933 const History* current = touchState.getHistory(0);
934 size_t pointerCount = event->getPointerCount();
935 for (size_t i = 0; i < pointerCount; i++) {
936 uint32_t id = event->getPointerId(i);
937 if (!current->idBits.hasBit(id)) {
938#if DEBUG_RESAMPLING
939 ALOGD("Not resampled, missing id %d", id);
940#endif
941 return;
942 }
943 }
944
945 // Find the data to use for resampling.
946 const History* other;
947 History future;
948 float alpha;
949 if (next) {
950 // Interpolate between current sample and future sample.
951 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100952 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700953 other = &future;
954 nsecs_t delta = future.eventTime - current->eventTime;
955 if (delta < RESAMPLE_MIN_DELTA) {
956#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100957 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700958#endif
959 return;
960 }
961 alpha = float(sampleTime - current->eventTime) / delta;
962 } else if (touchState.historySize >= 2) {
963 // Extrapolate future sample using current sample and past sample.
964 // So other->eventTime <= current->eventTime <= sampleTime.
965 other = touchState.getHistory(1);
966 nsecs_t delta = current->eventTime - other->eventTime;
967 if (delta < RESAMPLE_MIN_DELTA) {
968#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100969 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700970#endif
971 return;
972 } else if (delta > RESAMPLE_MAX_DELTA) {
973#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100974 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700975#endif
976 return;
977 }
978 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
979 if (sampleTime > maxPredict) {
980#if DEBUG_RESAMPLING
981 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100982 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700983 sampleTime - current->eventTime, maxPredict - current->eventTime);
984#endif
985 sampleTime = maxPredict;
986 }
987 alpha = float(current->eventTime - sampleTime) / delta;
988 } else {
989#if DEBUG_RESAMPLING
990 ALOGD("Not resampled, insufficient data.");
991#endif
992 return;
993 }
994
995 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800996 History oldLastResample;
997 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -0700998 touchState.lastResample.eventTime = sampleTime;
999 touchState.lastResample.idBits.clear();
1000 for (size_t i = 0; i < pointerCount; i++) {
1001 uint32_t id = event->getPointerId(i);
1002 touchState.lastResample.idToIndex[id] = i;
1003 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001004 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1005 // We maintain the previously resampled value for this pointer (stored in
1006 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1007 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1008
1009 // We know here that the coordinates for the pointer haven't changed because we
1010 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1011 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1012 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1013 continue;
1014 }
1015
Jeff Brown5912f952013-07-01 19:10:31 -07001016 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1017 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001018 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001019 if (other->idBits.hasBit(id)
1020 && shouldResampleTool(event->getToolType(i))) {
1021 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001022 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1023 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1024 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1025 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1026#if DEBUG_RESAMPLING
1027 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1028 "other (%0.3f, %0.3f), alpha %0.3f",
1029 id, resampledCoords.getX(), resampledCoords.getY(),
1030 currentCoords.getX(), currentCoords.getY(),
1031 otherCoords.getX(), otherCoords.getY(),
1032 alpha);
1033#endif
1034 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001035#if DEBUG_RESAMPLING
1036 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1037 id, resampledCoords.getX(), resampledCoords.getY(),
1038 currentCoords.getX(), currentCoords.getY());
1039#endif
1040 }
1041 }
1042
1043 event->addSample(sampleTime, touchState.lastResample.pointers);
1044}
1045
1046bool InputConsumer::shouldResampleTool(int32_t toolType) {
1047 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1048 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1049}
1050
1051status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001052 if (DEBUG_TRANSPORT_ACTIONS) {
1053 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1054 mChannel->getName().c_str(), seq, toString(handled));
1055 }
Jeff Brown5912f952013-07-01 19:10:31 -07001056
1057 if (!seq) {
1058 ALOGE("Attempted to send a finished signal with sequence number 0.");
1059 return BAD_VALUE;
1060 }
1061
1062 // Send finished signals for the batch sequence chain first.
1063 size_t seqChainCount = mSeqChains.size();
1064 if (seqChainCount) {
1065 uint32_t currentSeq = seq;
1066 uint32_t chainSeqs[seqChainCount];
1067 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001068 for (size_t i = seqChainCount; i > 0; ) {
1069 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001070 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001071 if (seqChain.seq == currentSeq) {
1072 currentSeq = seqChain.chain;
1073 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001074 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001075 }
1076 }
1077 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001078 while (!status && chainIndex > 0) {
1079 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001080 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1081 }
1082 if (status) {
1083 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001084 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001085 SeqChain seqChain;
1086 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1087 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001088 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001089 if (!chainIndex) break;
1090 chainIndex--;
1091 }
Jeff Brown5912f952013-07-01 19:10:31 -07001092 return status;
1093 }
1094 }
1095
1096 // Send finished signal for the last message in the batch.
1097 return sendUnchainedFinishedSignal(seq, handled);
1098}
1099
1100status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1101 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001102 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001103 msg.header.seq = seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -08001104 msg.body.finished.handled = handled ? 1 : 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001105 return mChannel->sendMessage(&msg);
1106}
1107
1108bool InputConsumer::hasDeferredEvent() const {
1109 return mMsgDeferred;
1110}
1111
1112bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001113 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001114}
1115
Arthur Hungc7812be2020-02-27 22:40:27 +08001116int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001117 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001118 return AINPUT_SOURCE_CLASS_NONE;
1119 }
1120
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001121 const Batch& batch = mBatches[0];
1122 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001123 return head.body.motion.source;
1124}
1125
Jeff Brown5912f952013-07-01 19:10:31 -07001126ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1127 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001128 const Batch& batch = mBatches[i];
1129 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001130 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1131 return i;
1132 }
1133 }
1134 return -1;
1135}
1136
1137ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1138 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001139 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001140 if (touchState.deviceId == deviceId && touchState.source == source) {
1141 return i;
1142 }
1143 }
1144 return -1;
1145}
1146
1147void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001148 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001149 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1150 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1151 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1152 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001153}
1154
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001155void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001156 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus == 1,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001157 msg->body.focus.inTouchMode == 1);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001158}
1159
Jeff Brown5912f952013-07-01 19:10:31 -07001160void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001161 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001162 PointerProperties pointerProperties[pointerCount];
1163 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001164 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001165 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1166 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1167 }
1168
Garfield Tan1c7bc862020-01-28 13:24:04 -08001169 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1170 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1171 msg->body.motion.actionButton, msg->body.motion.flags,
1172 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1173 msg->body.motion.buttonState, msg->body.motion.classification,
1174 msg->body.motion.xScale, msg->body.motion.yScale, msg->body.motion.xOffset,
1175 msg->body.motion.yOffset, msg->body.motion.xPrecision,
1176 msg->body.motion.yPrecision, msg->body.motion.xCursorPosition,
1177 msg->body.motion.yCursorPosition, msg->body.motion.downTime,
1178 msg->body.motion.eventTime, pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001179}
1180
1181void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001182 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001183 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001184 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001185 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1186 }
1187
1188 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1189 event->addSample(msg->body.motion.eventTime, pointerCoords);
1190}
1191
1192bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001193 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001194 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001195 if (head.body.motion.pointerCount != pointerCount
1196 || head.body.motion.action != msg->body.motion.action) {
1197 return false;
1198 }
1199 for (size_t i = 0; i < pointerCount; i++) {
1200 if (head.body.motion.pointers[i].properties
1201 != msg->body.motion.pointers[i].properties) {
1202 return false;
1203 }
1204 }
1205 return true;
1206}
1207
1208ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1209 size_t numSamples = batch.samples.size();
1210 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001211 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001212 index += 1;
1213 }
1214 return ssize_t(index) - 1;
1215}
1216
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001217std::string InputConsumer::dump() const {
1218 std::string out;
1219 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1220 out = out + "mChannel = " + mChannel->getName() + "\n";
1221 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1222 if (mMsgDeferred) {
1223 out = out + "mMsg : " + InputMessage::typeToString(mMsg.header.type) + "\n";
1224 }
1225 out += "Batches:\n";
1226 for (const Batch& batch : mBatches) {
1227 out += " Batch:\n";
1228 for (const InputMessage& msg : batch.samples) {
1229 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
1230 InputMessage::typeToString(msg.header.type));
1231 switch (msg.header.type) {
1232 case InputMessage::Type::KEY: {
1233 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1234 KeyEvent::actionToString(
1235 msg.body.key.action),
1236 msg.body.key.keyCode);
1237 break;
1238 }
1239 case InputMessage::Type::MOTION: {
1240 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1241 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1242 const float x = msg.body.motion.pointers[i].coords.getX();
1243 const float y = msg.body.motion.pointers[i].coords.getY();
1244 out += android::base::StringPrintf("\n Pointer %" PRIu32
1245 " : x=%.1f y=%.1f",
1246 i, x, y);
1247 }
1248 break;
1249 }
1250 case InputMessage::Type::FINISHED: {
1251 out += android::base::StringPrintf("handled=%s",
1252 toString(msg.body.finished.handled));
1253 break;
1254 }
1255 case InputMessage::Type::FOCUS: {
1256 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1257 toString(msg.body.focus.hasFocus),
1258 toString(msg.body.focus.inTouchMode));
1259 break;
1260 }
1261 }
1262 out += "\n";
1263 }
1264 }
1265 if (mBatches.empty()) {
1266 out += " <empty>\n";
1267 }
1268 out += "mSeqChains:\n";
1269 for (const SeqChain& chain : mSeqChains) {
1270 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1271 chain.chain);
1272 }
1273 if (mSeqChains.empty()) {
1274 out += " <empty>\n";
1275 }
1276 return out;
1277}
1278
Jeff Brown5912f952013-07-01 19:10:31 -07001279} // namespace android