blob: 85df405f98bf9f8150f1dd18d749c4f1228a6006 [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 {
Garfield Tan15601662020-09-22 15:32:38 -0700380 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700381 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700382}
383
Garfield Tan15601662020-09-22 15:32:38 -0700384void InputChannel::copyTo(InputChannel& outChannel) const {
385 outChannel.mName = getName();
386 outChannel.mFd = dupFd();
387 outChannel.mToken = getConnectionToken();
388}
389
Chris Ye0783e992020-06-02 21:34:49 -0700390status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500391 if (parcel == nullptr) {
392 ALOGE("%s: Null parcel", __func__);
393 return BAD_VALUE;
394 }
395 return parcel->writeStrongBinder(mToken)
396 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700397}
398
Chris Ye0783e992020-06-02 21:34:49 -0700399status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500400 if (parcel == nullptr) {
401 ALOGE("%s: Null parcel", __func__);
402 return BAD_VALUE;
403 }
404 mToken = parcel->readStrongBinder();
405 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700406}
407
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700408sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500409 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700410}
411
Garfield Tan15601662020-09-22 15:32:38 -0700412base::unique_fd InputChannel::dupFd() const {
413 android::base::unique_fd newFd(::dup(getFd()));
414 if (!newFd.ok()) {
415 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
416 strerror(errno));
417 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
418 // If this process is out of file descriptors, then throwing that might end up exploding
419 // on the other side of a binder call, which isn't really helpful.
420 // Better to just crash here and hope that the FD leak is slow.
421 // Other failures could be client errors, so we still propagate those back to the caller.
422 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
423 getName().c_str());
424 return {};
425 }
426 return newFd;
427}
428
Jeff Brown5912f952013-07-01 19:10:31 -0700429// --- InputPublisher ---
430
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500431InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700432
433InputPublisher::~InputPublisher() {
434}
435
Garfield Tan1c7bc862020-01-28 13:24:04 -0800436status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
437 int32_t source, int32_t displayId,
438 std::array<uint8_t, 32> hmac, int32_t action,
439 int32_t flags, int32_t keyCode, int32_t scanCode,
440 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
441 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000442 if (ATRACE_ENABLED()) {
443 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
444 mChannel->getName().c_str(), keyCode);
445 ATRACE_NAME(message.c_str());
446 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800447 if (DEBUG_TRANSPORT_ACTIONS) {
448 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
449 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
450 "downTime=%" PRId64 ", eventTime=%" PRId64,
451 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
452 metaState, repeatCount, downTime, eventTime);
453 }
Jeff Brown5912f952013-07-01 19:10:31 -0700454
455 if (!seq) {
456 ALOGE("Attempted to publish a key event with sequence number 0.");
457 return BAD_VALUE;
458 }
459
460 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700461 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500462 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800463 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700464 msg.body.key.deviceId = deviceId;
465 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100466 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700467 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700468 msg.body.key.action = action;
469 msg.body.key.flags = flags;
470 msg.body.key.keyCode = keyCode;
471 msg.body.key.scanCode = scanCode;
472 msg.body.key.metaState = metaState;
473 msg.body.key.repeatCount = repeatCount;
474 msg.body.key.downTime = downTime;
475 msg.body.key.eventTime = eventTime;
476 return mChannel->sendMessage(&msg);
477}
478
479status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800480 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600481 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
482 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700483 MotionClassification classification, const ui::Transform& transform, float xPrecision,
484 float yPrecision, float xCursorPosition, float yCursorPosition, nsecs_t downTime,
485 nsecs_t eventTime, uint32_t pointerCount, const PointerProperties* pointerProperties,
486 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000487 if (ATRACE_ENABLED()) {
488 std::string message = StringPrintf(
489 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
490 mChannel->getName().c_str(), action);
491 ATRACE_NAME(message.c_str());
492 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800493 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700494 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700495 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800496 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
497 "displayId=%" PRId32 ", "
498 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700499 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800500 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700501 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800502 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
503 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700504 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
505 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800506 }
Jeff Brown5912f952013-07-01 19:10:31 -0700507
508 if (!seq) {
509 ALOGE("Attempted to publish a motion event with sequence number 0.");
510 return BAD_VALUE;
511 }
512
513 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700514 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800515 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700516 return BAD_VALUE;
517 }
518
519 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700520 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500521 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800522 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700523 msg.body.motion.deviceId = deviceId;
524 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700525 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700526 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700527 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100528 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700529 msg.body.motion.flags = flags;
530 msg.body.motion.edgeFlags = edgeFlags;
531 msg.body.motion.metaState = metaState;
532 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800533 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700534 msg.body.motion.dsdx = transform.dsdx();
535 msg.body.motion.dtdx = transform.dtdx();
536 msg.body.motion.dtdy = transform.dtdy();
537 msg.body.motion.dsdy = transform.dsdy();
538 msg.body.motion.tx = transform.tx();
539 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700540 msg.body.motion.xPrecision = xPrecision;
541 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700542 msg.body.motion.xCursorPosition = xCursorPosition;
543 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700544 msg.body.motion.downTime = downTime;
545 msg.body.motion.eventTime = eventTime;
546 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100547 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700548 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
549 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
550 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700551
Jeff Brown5912f952013-07-01 19:10:31 -0700552 return mChannel->sendMessage(&msg);
553}
554
Garfield Tan1c7bc862020-01-28 13:24:04 -0800555status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
556 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800557 if (ATRACE_ENABLED()) {
558 std::string message =
559 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
560 mChannel->getName().c_str(), toString(hasFocus),
561 toString(inTouchMode));
562 ATRACE_NAME(message.c_str());
563 }
564
565 InputMessage msg;
566 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500567 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800568 msg.body.focus.eventId = eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800569 msg.body.focus.hasFocus = hasFocus ? 1 : 0;
570 msg.body.focus.inTouchMode = inTouchMode ? 1 : 0;
571 return mChannel->sendMessage(&msg);
572}
573
Jeff Brown5912f952013-07-01 19:10:31 -0700574status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800575 if (DEBUG_TRANSPORT_ACTIONS) {
576 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
577 }
Jeff Brown5912f952013-07-01 19:10:31 -0700578
579 InputMessage msg;
580 status_t result = mChannel->receiveMessage(&msg);
581 if (result) {
582 *outSeq = 0;
583 *outHandled = false;
584 return result;
585 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700586 if (msg.header.type != InputMessage::Type::FINISHED) {
Jeff Brown5912f952013-07-01 19:10:31 -0700587 ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800588 mChannel->getName().c_str(), msg.header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700589 return UNKNOWN_ERROR;
590 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500591 *outSeq = msg.header.seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800592 *outHandled = msg.body.finished.handled == 1;
Jeff Brown5912f952013-07-01 19:10:31 -0700593 return OK;
594}
595
596// --- InputConsumer ---
597
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500598InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
599 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700600
601InputConsumer::~InputConsumer() {
602}
603
604bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600605 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700606}
607
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800608status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
609 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800610 if (DEBUG_TRANSPORT_ACTIONS) {
611 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
612 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
613 }
Jeff Brown5912f952013-07-01 19:10:31 -0700614
615 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700616 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700617
618 // Fetch the next input message.
619 // Loop until an event can be returned or no additional events are received.
620 while (!*outEvent) {
621 if (mMsgDeferred) {
622 // mMsg contains a valid input message from the previous call to consume
623 // that has not yet been processed.
624 mMsgDeferred = false;
625 } else {
626 // Receive a fresh message.
627 status_t result = mChannel->receiveMessage(&mMsg);
628 if (result) {
629 // Consume the next batched event unless batches are being held for later.
630 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800631 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700632 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800633 if (DEBUG_TRANSPORT_ACTIONS) {
634 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
635 mChannel->getName().c_str(), *outSeq);
636 }
Jeff Brown5912f952013-07-01 19:10:31 -0700637 break;
638 }
639 }
640 return result;
641 }
642 }
643
644 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700645 case InputMessage::Type::KEY: {
646 KeyEvent* keyEvent = factory->createKeyEvent();
647 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700648
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700649 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500650 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700651 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800652 if (DEBUG_TRANSPORT_ACTIONS) {
653 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
654 mChannel->getName().c_str(), *outSeq);
655 }
Jeff Brown5912f952013-07-01 19:10:31 -0700656 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700657 }
Jeff Brown5912f952013-07-01 19:10:31 -0700658
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700659 case InputMessage::Type::MOTION: {
660 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
661 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500662 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700663 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500664 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800665 if (DEBUG_TRANSPORT_ACTIONS) {
666 ALOGD("channel '%s' consumer ~ appended to batch event",
667 mChannel->getName().c_str());
668 }
Jeff Brown5912f952013-07-01 19:10:31 -0700669 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700670 } else if (isPointerEvent(mMsg.body.motion.source) &&
671 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
672 // No need to process events that we are going to cancel anyways
673 const size_t count = batch.samples.size();
674 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500675 const InputMessage& msg = batch.samples[i];
676 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700677 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500678 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
679 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700680 } else {
681 // We cannot append to the batch in progress, so we need to consume
682 // the previous batch right now and defer the new message until later.
683 mMsgDeferred = true;
684 status_t result = consumeSamples(factory, batch, batch.samples.size(),
685 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500686 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700687 if (result) {
688 return result;
689 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800690 if (DEBUG_TRANSPORT_ACTIONS) {
691 ALOGD("channel '%s' consumer ~ consumed batch event and "
692 "deferred current event, seq=%u",
693 mChannel->getName().c_str(), *outSeq);
694 }
Jeff Brown5912f952013-07-01 19:10:31 -0700695 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700696 }
Jeff Brown5912f952013-07-01 19:10:31 -0700697 }
Jeff Brown5912f952013-07-01 19:10:31 -0700698
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800699 // Start a new batch if needed.
700 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
701 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500702 Batch batch;
703 batch.samples.push_back(mMsg);
704 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800705 if (DEBUG_TRANSPORT_ACTIONS) {
706 ALOGD("channel '%s' consumer ~ started batch event",
707 mChannel->getName().c_str());
708 }
709 break;
710 }
Jeff Brown5912f952013-07-01 19:10:31 -0700711
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800712 MotionEvent* motionEvent = factory->createMotionEvent();
713 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700714
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800715 updateTouchState(mMsg);
716 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500717 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800718 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800719
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800720 if (DEBUG_TRANSPORT_ACTIONS) {
721 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
722 mChannel->getName().c_str(), *outSeq);
723 }
724 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700725 }
Jeff Brown5912f952013-07-01 19:10:31 -0700726
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800727 case InputMessage::Type::FINISHED: {
728 LOG_ALWAYS_FATAL("Consumed a FINISHED message, which should never be seen by "
729 "InputConsumer!");
730 break;
731 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800732
733 case InputMessage::Type::FOCUS: {
734 FocusEvent* focusEvent = factory->createFocusEvent();
735 if (!focusEvent) return NO_MEMORY;
736
737 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500738 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800739 *outEvent = focusEvent;
740 break;
741 }
Jeff Brown5912f952013-07-01 19:10:31 -0700742 }
743 }
744 return OK;
745}
746
747status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800748 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700749 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700750 for (size_t i = mBatches.size(); i > 0; ) {
751 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500752 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700753 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800754 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500755 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700756 return result;
757 }
758
Michael Wright32232172013-10-21 12:05:22 -0700759 nsecs_t sampleTime = frameTime;
760 if (mResampleTouch) {
761 sampleTime -= RESAMPLE_LATENCY;
762 }
Jeff Brown5912f952013-07-01 19:10:31 -0700763 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
764 if (split < 0) {
765 continue;
766 }
767
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800768 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700769 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500770 if (batch.samples.empty()) {
771 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700772 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700773 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500774 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700775 }
Michael Wright32232172013-10-21 12:05:22 -0700776 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700777 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
778 }
779 return result;
780 }
781
782 return WOULD_BLOCK;
783}
784
785status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800786 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700787 MotionEvent* motionEvent = factory->createMotionEvent();
788 if (! motionEvent) return NO_MEMORY;
789
790 uint32_t chain = 0;
791 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500792 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100793 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700794 if (i) {
795 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500796 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700797 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500798 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700799 addSample(motionEvent, &msg);
800 } else {
801 initializeMotionEvent(motionEvent, &msg);
802 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500803 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700804 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500805 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700806
807 *outSeq = chain;
808 *outEvent = motionEvent;
809 return OK;
810}
811
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100812void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800813 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700814 return;
815 }
816
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100817 int32_t deviceId = msg.body.motion.deviceId;
818 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700819
820 // Update the touch state history to incorporate the new input message.
821 // If the message is in the past relative to the most recently produced resampled
822 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100823 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700824 case AMOTION_EVENT_ACTION_DOWN: {
825 ssize_t index = findTouchState(deviceId, source);
826 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500827 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700828 index = mTouchStates.size() - 1;
829 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500830 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700831 touchState.initialize(deviceId, source);
832 touchState.addHistory(msg);
833 break;
834 }
835
836 case AMOTION_EVENT_ACTION_MOVE: {
837 ssize_t index = findTouchState(deviceId, source);
838 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500839 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700840 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800841 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700842 }
843 break;
844 }
845
846 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
847 ssize_t index = findTouchState(deviceId, source);
848 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500849 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100850 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700851 rewriteMessage(touchState, msg);
852 }
853 break;
854 }
855
856 case AMOTION_EVENT_ACTION_POINTER_UP: {
857 ssize_t index = findTouchState(deviceId, source);
858 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500859 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700860 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100861 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700862 }
863 break;
864 }
865
866 case AMOTION_EVENT_ACTION_SCROLL: {
867 ssize_t index = findTouchState(deviceId, source);
868 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500869 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700870 rewriteMessage(touchState, msg);
871 }
872 break;
873 }
874
875 case AMOTION_EVENT_ACTION_UP:
876 case AMOTION_EVENT_ACTION_CANCEL: {
877 ssize_t index = findTouchState(deviceId, source);
878 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500879 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700880 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500881 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700882 }
883 break;
884 }
885 }
886}
887
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800888/**
889 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
890 *
891 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
892 * is in the past relative to msg and the past two events do not contain identical coordinates),
893 * then invalidate the lastResample data for that pointer.
894 * If the two past events have identical coordinates, then lastResample data for that pointer will
895 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
896 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
897 * not equal to x0 is received.
898 */
899void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100900 nsecs_t eventTime = msg.body.motion.eventTime;
901 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
902 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700903 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100904 if (eventTime < state.lastResample.eventTime ||
905 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800906 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
907 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700908#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100909 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
910 resampleCoords.getX(), resampleCoords.getY(),
911 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700912#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800913 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
914 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
915 } else {
916 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100917 }
Jeff Brown5912f952013-07-01 19:10:31 -0700918 }
919 }
920}
921
922void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
923 const InputMessage* next) {
924 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800925 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -0700926 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
927 return;
928 }
929
930 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
931 if (index < 0) {
932#if DEBUG_RESAMPLING
933 ALOGD("Not resampled, no touch state for device.");
934#endif
935 return;
936 }
937
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500938 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700939 if (touchState.historySize < 1) {
940#if DEBUG_RESAMPLING
941 ALOGD("Not resampled, no history for device.");
942#endif
943 return;
944 }
945
946 // Ensure that the current sample has all of the pointers that need to be reported.
947 const History* current = touchState.getHistory(0);
948 size_t pointerCount = event->getPointerCount();
949 for (size_t i = 0; i < pointerCount; i++) {
950 uint32_t id = event->getPointerId(i);
951 if (!current->idBits.hasBit(id)) {
952#if DEBUG_RESAMPLING
953 ALOGD("Not resampled, missing id %d", id);
954#endif
955 return;
956 }
957 }
958
959 // Find the data to use for resampling.
960 const History* other;
961 History future;
962 float alpha;
963 if (next) {
964 // Interpolate between current sample and future sample.
965 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100966 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -0700967 other = &future;
968 nsecs_t delta = future.eventTime - current->eventTime;
969 if (delta < RESAMPLE_MIN_DELTA) {
970#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100971 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700972#endif
973 return;
974 }
975 alpha = float(sampleTime - current->eventTime) / delta;
976 } else if (touchState.historySize >= 2) {
977 // Extrapolate future sample using current sample and past sample.
978 // So other->eventTime <= current->eventTime <= sampleTime.
979 other = touchState.getHistory(1);
980 nsecs_t delta = current->eventTime - other->eventTime;
981 if (delta < RESAMPLE_MIN_DELTA) {
982#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100983 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700984#endif
985 return;
986 } else if (delta > RESAMPLE_MAX_DELTA) {
987#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100988 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -0700989#endif
990 return;
991 }
992 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
993 if (sampleTime > maxPredict) {
994#if DEBUG_RESAMPLING
995 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100996 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -0700997 sampleTime - current->eventTime, maxPredict - current->eventTime);
998#endif
999 sampleTime = maxPredict;
1000 }
1001 alpha = float(current->eventTime - sampleTime) / delta;
1002 } else {
1003#if DEBUG_RESAMPLING
1004 ALOGD("Not resampled, insufficient data.");
1005#endif
1006 return;
1007 }
1008
1009 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001010 History oldLastResample;
1011 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001012 touchState.lastResample.eventTime = sampleTime;
1013 touchState.lastResample.idBits.clear();
1014 for (size_t i = 0; i < pointerCount; i++) {
1015 uint32_t id = event->getPointerId(i);
1016 touchState.lastResample.idToIndex[id] = i;
1017 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001018 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1019 // We maintain the previously resampled value for this pointer (stored in
1020 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1021 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1022
1023 // We know here that the coordinates for the pointer haven't changed because we
1024 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1025 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1026 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1027 continue;
1028 }
1029
Jeff Brown5912f952013-07-01 19:10:31 -07001030 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1031 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001032 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001033 if (other->idBits.hasBit(id)
1034 && shouldResampleTool(event->getToolType(i))) {
1035 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001036 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1037 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1038 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1039 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1040#if DEBUG_RESAMPLING
1041 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1042 "other (%0.3f, %0.3f), alpha %0.3f",
1043 id, resampledCoords.getX(), resampledCoords.getY(),
1044 currentCoords.getX(), currentCoords.getY(),
1045 otherCoords.getX(), otherCoords.getY(),
1046 alpha);
1047#endif
1048 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001049#if DEBUG_RESAMPLING
1050 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1051 id, resampledCoords.getX(), resampledCoords.getY(),
1052 currentCoords.getX(), currentCoords.getY());
1053#endif
1054 }
1055 }
1056
1057 event->addSample(sampleTime, touchState.lastResample.pointers);
1058}
1059
1060bool InputConsumer::shouldResampleTool(int32_t toolType) {
1061 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1062 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1063}
1064
1065status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001066 if (DEBUG_TRANSPORT_ACTIONS) {
1067 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1068 mChannel->getName().c_str(), seq, toString(handled));
1069 }
Jeff Brown5912f952013-07-01 19:10:31 -07001070
1071 if (!seq) {
1072 ALOGE("Attempted to send a finished signal with sequence number 0.");
1073 return BAD_VALUE;
1074 }
1075
1076 // Send finished signals for the batch sequence chain first.
1077 size_t seqChainCount = mSeqChains.size();
1078 if (seqChainCount) {
1079 uint32_t currentSeq = seq;
1080 uint32_t chainSeqs[seqChainCount];
1081 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001082 for (size_t i = seqChainCount; i > 0; ) {
1083 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001084 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001085 if (seqChain.seq == currentSeq) {
1086 currentSeq = seqChain.chain;
1087 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001088 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001089 }
1090 }
1091 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001092 while (!status && chainIndex > 0) {
1093 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001094 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1095 }
1096 if (status) {
1097 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001098 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001099 SeqChain seqChain;
1100 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1101 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001102 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001103 if (!chainIndex) break;
1104 chainIndex--;
1105 }
Jeff Brown5912f952013-07-01 19:10:31 -07001106 return status;
1107 }
1108 }
1109
1110 // Send finished signal for the last message in the batch.
1111 return sendUnchainedFinishedSignal(seq, handled);
1112}
1113
1114status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1115 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001116 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001117 msg.header.seq = seq;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -08001118 msg.body.finished.handled = handled ? 1 : 0;
Jeff Brown5912f952013-07-01 19:10:31 -07001119 return mChannel->sendMessage(&msg);
1120}
1121
1122bool InputConsumer::hasDeferredEvent() const {
1123 return mMsgDeferred;
1124}
1125
1126bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001127 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001128}
1129
Arthur Hungc7812be2020-02-27 22:40:27 +08001130int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001131 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001132 return AINPUT_SOURCE_CLASS_NONE;
1133 }
1134
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001135 const Batch& batch = mBatches[0];
1136 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001137 return head.body.motion.source;
1138}
1139
Jeff Brown5912f952013-07-01 19:10:31 -07001140ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1141 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001142 const Batch& batch = mBatches[i];
1143 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001144 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1145 return i;
1146 }
1147 }
1148 return -1;
1149}
1150
1151ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1152 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001153 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001154 if (touchState.deviceId == deviceId && touchState.source == source) {
1155 return i;
1156 }
1157 }
1158 return -1;
1159}
1160
1161void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001162 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001163 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1164 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1165 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1166 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001167}
1168
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001169void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001170 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus == 1,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001171 msg->body.focus.inTouchMode == 1);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001172}
1173
Jeff Brown5912f952013-07-01 19:10:31 -07001174void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001175 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001176 PointerProperties pointerProperties[pointerCount];
1177 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001178 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001179 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1180 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1181 }
1182
chaviw9eaa22c2020-07-01 16:21:27 -07001183 ui::Transform transform;
1184 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1185 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001186 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1187 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1188 msg->body.motion.actionButton, msg->body.motion.flags,
1189 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001190 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1191 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1192 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1193 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1194 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001195}
1196
1197void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001198 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001199 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001200 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001201 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1202 }
1203
1204 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1205 event->addSample(msg->body.motion.eventTime, pointerCoords);
1206}
1207
1208bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001209 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001210 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001211 if (head.body.motion.pointerCount != pointerCount
1212 || head.body.motion.action != msg->body.motion.action) {
1213 return false;
1214 }
1215 for (size_t i = 0; i < pointerCount; i++) {
1216 if (head.body.motion.pointers[i].properties
1217 != msg->body.motion.pointers[i].properties) {
1218 return false;
1219 }
1220 }
1221 return true;
1222}
1223
1224ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1225 size_t numSamples = batch.samples.size();
1226 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001227 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001228 index += 1;
1229 }
1230 return ssize_t(index) - 1;
1231}
1232
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001233std::string InputConsumer::dump() const {
1234 std::string out;
1235 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1236 out = out + "mChannel = " + mChannel->getName() + "\n";
1237 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1238 if (mMsgDeferred) {
1239 out = out + "mMsg : " + InputMessage::typeToString(mMsg.header.type) + "\n";
1240 }
1241 out += "Batches:\n";
1242 for (const Batch& batch : mBatches) {
1243 out += " Batch:\n";
1244 for (const InputMessage& msg : batch.samples) {
1245 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
1246 InputMessage::typeToString(msg.header.type));
1247 switch (msg.header.type) {
1248 case InputMessage::Type::KEY: {
1249 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1250 KeyEvent::actionToString(
1251 msg.body.key.action),
1252 msg.body.key.keyCode);
1253 break;
1254 }
1255 case InputMessage::Type::MOTION: {
1256 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1257 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1258 const float x = msg.body.motion.pointers[i].coords.getX();
1259 const float y = msg.body.motion.pointers[i].coords.getY();
1260 out += android::base::StringPrintf("\n Pointer %" PRIu32
1261 " : x=%.1f y=%.1f",
1262 i, x, y);
1263 }
1264 break;
1265 }
1266 case InputMessage::Type::FINISHED: {
1267 out += android::base::StringPrintf("handled=%s",
1268 toString(msg.body.finished.handled));
1269 break;
1270 }
1271 case InputMessage::Type::FOCUS: {
1272 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1273 toString(msg.body.focus.hasFocus),
1274 toString(msg.body.focus.inTouchMode));
1275 break;
1276 }
1277 }
1278 out += "\n";
1279 }
1280 }
1281 if (mBatches.empty()) {
1282 out += " <empty>\n";
1283 }
1284 out += "mSeqChains:\n";
1285 for (const SeqChain& chain : mSeqChains) {
1286 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1287 chain.chain);
1288 }
1289 if (mSeqChains.empty()) {
1290 out += " <empty>\n";
1291 }
1292 return out;
1293}
1294
Jeff Brown5912f952013-07-01 19:10:31 -07001295} // namespace android