blob: 6ef01737f9806511ee91442db886e951af9d64ee [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>
Siarhei Vishniakou7766c032021-03-02 20:32:20 +000037#include <input/NamedEnum.h>
Jeff Brown5912f952013-07-01 19:10:31 -070038
Michael Wright3dd60e22019-03-27 22:06:44 +000039using android::base::StringPrintf;
40
Jeff Brown5912f952013-07-01 19:10:31 -070041namespace android {
42
43// Socket buffer size. The default is typically about 128KB, which is much larger than
44// we really need. So we make it smaller. It just needs to be big enough to hold
45// a few dozen large multi-finger motion events in the case where an application gets
46// behind processing touches.
47static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
48
49// Nanoseconds per milliseconds.
50static const nsecs_t NANOS_PER_MS = 1000000;
51
52// Latency added during resampling. A few milliseconds doesn't hurt much but
53// reduces the impact of mispredicted touch positions.
54static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
55
56// Minimum time difference between consecutive samples before attempting to resample.
57static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
58
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -070059// Maximum time difference between consecutive samples before attempting to resample
60// by extrapolation.
61static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
62
Jeff Brown5912f952013-07-01 19:10:31 -070063// Maximum time to predict forward from the last known state, to avoid predicting too
64// far into the future. This time is further bounded by 50% of the last time delta.
65static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
66
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -060067/**
68 * System property for enabling / disabling touch resampling.
69 * Resampling extrapolates / interpolates the reported touch event coordinates to better
70 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
71 * Resampling is not needed (and should be disabled) on hardware that already
72 * has touch events triggered by VSYNC.
73 * Set to "1" to enable resampling (default).
74 * Set to "0" to disable resampling.
75 * Resampling is enabled by default.
76 */
77static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
78
Jeff Brown5912f952013-07-01 19:10:31 -070079template<typename T>
80inline static T min(const T& a, const T& b) {
81 return a < b ? a : b;
82}
83
84inline static float lerp(float a, float b, float alpha) {
85 return a + alpha * (b - a);
86}
87
Siarhei Vishniakou128eab12019-05-23 10:25:59 +080088inline static bool isPointerEvent(int32_t source) {
89 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
90}
91
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -080092inline static const char* toString(bool value) {
93 return value ? "true" : "false";
94}
95
Jeff Brown5912f952013-07-01 19:10:31 -070096// --- InputMessage ---
97
98bool InputMessage::isValid(size_t actualSize) const {
99 if (size() == actualSize) {
100 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700101 case Type::KEY:
102 return true;
103 case Type::MOTION:
104 return body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
105 case Type::FINISHED:
106 return true;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800107 case Type::FOCUS:
108 return true;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800109 case Type::CAPTURE:
110 return true;
arthurhung7632c332020-12-30 16:58:01 +0800111 case Type::DRAG:
112 return true;
Jeff Brown5912f952013-07-01 19:10:31 -0700113 }
114 }
115 return false;
116}
117
118size_t InputMessage::size() const {
119 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700120 case Type::KEY:
121 return sizeof(Header) + body.key.size();
122 case Type::MOTION:
123 return sizeof(Header) + body.motion.size();
124 case Type::FINISHED:
125 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800126 case Type::FOCUS:
127 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800128 case Type::CAPTURE:
129 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800130 case Type::DRAG:
131 return sizeof(Header) + body.drag.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700132 }
133 return sizeof(Header);
134}
135
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800136/**
137 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
138 * memory to zero, then only copy the valid bytes on a per-field basis.
139 */
140void InputMessage::getSanitizedCopy(InputMessage* msg) const {
141 memset(msg, 0, sizeof(*msg));
142
143 // Write the header
144 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500145 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800146
147 // Write the body
148 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700149 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800150 // int32_t eventId
151 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800152 // nsecs_t eventTime
153 msg->body.key.eventTime = body.key.eventTime;
154 // int32_t deviceId
155 msg->body.key.deviceId = body.key.deviceId;
156 // int32_t source
157 msg->body.key.source = body.key.source;
158 // int32_t displayId
159 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600160 // std::array<uint8_t, 32> hmac
161 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800162 // int32_t action
163 msg->body.key.action = body.key.action;
164 // int32_t flags
165 msg->body.key.flags = body.key.flags;
166 // int32_t keyCode
167 msg->body.key.keyCode = body.key.keyCode;
168 // int32_t scanCode
169 msg->body.key.scanCode = body.key.scanCode;
170 // int32_t metaState
171 msg->body.key.metaState = body.key.metaState;
172 // int32_t repeatCount
173 msg->body.key.repeatCount = body.key.repeatCount;
174 // nsecs_t downTime
175 msg->body.key.downTime = body.key.downTime;
176 break;
177 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700178 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800179 // int32_t eventId
180 msg->body.motion.eventId = body.motion.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800181 // nsecs_t eventTime
182 msg->body.motion.eventTime = body.motion.eventTime;
183 // int32_t deviceId
184 msg->body.motion.deviceId = body.motion.deviceId;
185 // int32_t source
186 msg->body.motion.source = body.motion.source;
187 // int32_t displayId
188 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600189 // std::array<uint8_t, 32> hmac
190 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800191 // int32_t action
192 msg->body.motion.action = body.motion.action;
193 // int32_t actionButton
194 msg->body.motion.actionButton = body.motion.actionButton;
195 // int32_t flags
196 msg->body.motion.flags = body.motion.flags;
197 // int32_t metaState
198 msg->body.motion.metaState = body.motion.metaState;
199 // int32_t buttonState
200 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800201 // MotionClassification classification
202 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800203 // int32_t edgeFlags
204 msg->body.motion.edgeFlags = body.motion.edgeFlags;
205 // nsecs_t downTime
206 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700207
208 msg->body.motion.dsdx = body.motion.dsdx;
209 msg->body.motion.dtdx = body.motion.dtdx;
210 msg->body.motion.dtdy = body.motion.dtdy;
211 msg->body.motion.dsdy = body.motion.dsdy;
212 msg->body.motion.tx = body.motion.tx;
213 msg->body.motion.ty = body.motion.ty;
214
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800215 // float xPrecision
216 msg->body.motion.xPrecision = body.motion.xPrecision;
217 // float yPrecision
218 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700219 // float xCursorPosition
220 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
221 // float yCursorPosition
222 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800223 // uint32_t pointerCount
224 msg->body.motion.pointerCount = body.motion.pointerCount;
225 //struct Pointer pointers[MAX_POINTERS]
226 for (size_t i = 0; i < body.motion.pointerCount; i++) {
227 // PointerProperties properties
228 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
229 msg->body.motion.pointers[i].properties.toolType =
230 body.motion.pointers[i].properties.toolType,
231 // PointerCoords coords
232 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
233 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
234 memcpy(&msg->body.motion.pointers[i].coords.values[0],
235 &body.motion.pointers[i].coords.values[0],
236 count * (sizeof(body.motion.pointers[i].coords.values[0])));
237 }
238 break;
239 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700240 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800241 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000242 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800243 break;
244 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800245 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800246 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800247 msg->body.focus.hasFocus = body.focus.hasFocus;
248 msg->body.focus.inTouchMode = body.focus.inTouchMode;
249 break;
250 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800251 case InputMessage::Type::CAPTURE: {
252 msg->body.capture.eventId = body.capture.eventId;
253 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
254 break;
255 }
arthurhung7632c332020-12-30 16:58:01 +0800256 case InputMessage::Type::DRAG: {
257 msg->body.drag.eventId = body.drag.eventId;
258 msg->body.drag.x = body.drag.x;
259 msg->body.drag.y = body.drag.y;
260 msg->body.drag.isExiting = body.drag.isExiting;
261 break;
262 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800263 }
264}
Jeff Brown5912f952013-07-01 19:10:31 -0700265
266// --- InputChannel ---
267
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500268std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500269 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700270 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
271 if (result != 0) {
272 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
273 strerror(errno));
274 return nullptr;
275 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500276 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500277 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700278}
279
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500280InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
281 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700282 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500283 ALOGD("Input channel constructed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700284 }
Jeff Brown5912f952013-07-01 19:10:31 -0700285}
286
287InputChannel::~InputChannel() {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700288 if (DEBUG_CHANNEL_LIFECYCLE) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500289 ALOGD("Input channel destroyed: name='%s', fd=%d", getName().c_str(), getFd().get());
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700290 }
Robert Carr3720ed02018-08-08 16:08:27 -0700291}
292
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800293status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500294 std::unique_ptr<InputChannel>& outServerChannel,
295 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700296 int sockets[2];
297 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
298 status_t result = -errno;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500299 ALOGE("channel '%s' ~ Could not create socket pair. errno=%d", name.c_str(), errno);
300 outServerChannel.reset();
301 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700302 return result;
303 }
304
305 int bufferSize = SOCKET_BUFFER_SIZE;
306 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
307 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
308 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
309 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
310
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700311 sp<IBinder> token = new BBinder();
312
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700313 std::string serverChannelName = name + " (server)";
314 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700315 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700316
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700317 std::string clientChannelName = name + " (client)";
318 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700319 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700320 return OK;
321}
322
323status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800324 const size_t msgLength = msg->size();
325 InputMessage cleanMsg;
326 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700327 ssize_t nWrite;
328 do {
Chris Ye0783e992020-06-02 21:34:49 -0700329 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700330 } while (nWrite == -1 && errno == EINTR);
331
332 if (nWrite < 0) {
333 int error = errno;
334#if DEBUG_CHANNEL_MESSAGES
chaviw81e2bb92019-12-18 15:03:51 -0800335 ALOGD("channel '%s' ~ error sending message of type %d, %s", mName.c_str(),
336 msg->header.type, strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700337#endif
338 if (error == EAGAIN || error == EWOULDBLOCK) {
339 return WOULD_BLOCK;
340 }
341 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
342 return DEAD_OBJECT;
343 }
344 return -error;
345 }
346
347 if (size_t(nWrite) != msgLength) {
348#if DEBUG_CHANNEL_MESSAGES
349 ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800350 mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700351#endif
352 return DEAD_OBJECT;
353 }
354
355#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800356 ALOGD("channel '%s' ~ sent message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700357#endif
358 return OK;
359}
360
361status_t InputChannel::receiveMessage(InputMessage* msg) {
362 ssize_t nRead;
363 do {
Chris Ye0783e992020-06-02 21:34:49 -0700364 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700365 } while (nRead == -1 && errno == EINTR);
366
367 if (nRead < 0) {
368 int error = errno;
369#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800370 ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700371#endif
372 if (error == EAGAIN || error == EWOULDBLOCK) {
373 return WOULD_BLOCK;
374 }
375 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
376 return DEAD_OBJECT;
377 }
378 return -error;
379 }
380
381 if (nRead == 0) { // check for EOF
382#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800383 ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700384#endif
385 return DEAD_OBJECT;
386 }
387
388 if (!msg->isValid(nRead)) {
389#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800390 ALOGD("channel '%s' ~ received invalid message", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700391#endif
392 return BAD_VALUE;
393 }
394
395#if DEBUG_CHANNEL_MESSAGES
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800396 ALOGD("channel '%s' ~ received message of type %d", mName.c_str(), msg->header.type);
Jeff Brown5912f952013-07-01 19:10:31 -0700397#endif
398 return OK;
399}
400
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500401std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700402 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700403 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700404}
405
Garfield Tan15601662020-09-22 15:32:38 -0700406void InputChannel::copyTo(InputChannel& outChannel) const {
407 outChannel.mName = getName();
408 outChannel.mFd = dupFd();
409 outChannel.mToken = getConnectionToken();
410}
411
Chris Ye0783e992020-06-02 21:34:49 -0700412status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500413 if (parcel == nullptr) {
414 ALOGE("%s: Null parcel", __func__);
415 return BAD_VALUE;
416 }
417 return parcel->writeStrongBinder(mToken)
418 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700419}
420
Chris Ye0783e992020-06-02 21:34:49 -0700421status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500422 if (parcel == nullptr) {
423 ALOGE("%s: Null parcel", __func__);
424 return BAD_VALUE;
425 }
426 mToken = parcel->readStrongBinder();
427 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700428}
429
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700430sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500431 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700432}
433
Garfield Tan15601662020-09-22 15:32:38 -0700434base::unique_fd InputChannel::dupFd() const {
435 android::base::unique_fd newFd(::dup(getFd()));
436 if (!newFd.ok()) {
437 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
438 strerror(errno));
439 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
440 // If this process is out of file descriptors, then throwing that might end up exploding
441 // on the other side of a binder call, which isn't really helpful.
442 // Better to just crash here and hope that the FD leak is slow.
443 // Other failures could be client errors, so we still propagate those back to the caller.
444 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
445 getName().c_str());
446 return {};
447 }
448 return newFd;
449}
450
Jeff Brown5912f952013-07-01 19:10:31 -0700451// --- InputPublisher ---
452
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500453InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel) : mChannel(channel) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700454
455InputPublisher::~InputPublisher() {
456}
457
Garfield Tan1c7bc862020-01-28 13:24:04 -0800458status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
459 int32_t source, int32_t displayId,
460 std::array<uint8_t, 32> hmac, int32_t action,
461 int32_t flags, int32_t keyCode, int32_t scanCode,
462 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
463 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000464 if (ATRACE_ENABLED()) {
465 std::string message = StringPrintf("publishKeyEvent(inputChannel=%s, keyCode=%" PRId32 ")",
466 mChannel->getName().c_str(), keyCode);
467 ATRACE_NAME(message.c_str());
468 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800469 if (DEBUG_TRANSPORT_ACTIONS) {
470 ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
471 "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
472 "downTime=%" PRId64 ", eventTime=%" PRId64,
473 mChannel->getName().c_str(), seq, deviceId, source, action, flags, keyCode, scanCode,
474 metaState, repeatCount, downTime, eventTime);
475 }
Jeff Brown5912f952013-07-01 19:10:31 -0700476
477 if (!seq) {
478 ALOGE("Attempted to publish a key event with sequence number 0.");
479 return BAD_VALUE;
480 }
481
482 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700483 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500484 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800485 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700486 msg.body.key.deviceId = deviceId;
487 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100488 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700489 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700490 msg.body.key.action = action;
491 msg.body.key.flags = flags;
492 msg.body.key.keyCode = keyCode;
493 msg.body.key.scanCode = scanCode;
494 msg.body.key.metaState = metaState;
495 msg.body.key.repeatCount = repeatCount;
496 msg.body.key.downTime = downTime;
497 msg.body.key.eventTime = eventTime;
498 return mChannel->sendMessage(&msg);
499}
500
501status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800502 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600503 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
504 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700505 MotionClassification classification, const ui::Transform& transform, float xPrecision,
506 float yPrecision, float xCursorPosition, float yCursorPosition, nsecs_t downTime,
507 nsecs_t eventTime, uint32_t pointerCount, const PointerProperties* pointerProperties,
508 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000509 if (ATRACE_ENABLED()) {
510 std::string message = StringPrintf(
511 "publishMotionEvent(inputChannel=%s, action=%" PRId32 ")",
512 mChannel->getName().c_str(), action);
513 ATRACE_NAME(message.c_str());
514 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800515 if (DEBUG_TRANSPORT_ACTIONS) {
chaviw9eaa22c2020-07-01 16:21:27 -0700516 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700517 transform.dump(transformString, "transform", " ");
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800518 ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
519 "displayId=%" PRId32 ", "
520 "action=0x%x, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700521 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800522 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700523 "pointerCount=%" PRIu32 " \n%s",
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800524 mChannel->getName().c_str(), seq, deviceId, source, displayId, action, actionButton,
525 flags, edgeFlags, metaState, buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700526 motionClassificationToString(classification), xPrecision, yPrecision, downTime,
527 eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800528 }
Jeff Brown5912f952013-07-01 19:10:31 -0700529
530 if (!seq) {
531 ALOGE("Attempted to publish a motion event with sequence number 0.");
532 return BAD_VALUE;
533 }
534
535 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700536 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800537 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700538 return BAD_VALUE;
539 }
540
541 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700542 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500543 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800544 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700545 msg.body.motion.deviceId = deviceId;
546 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700547 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700548 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700549 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100550 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700551 msg.body.motion.flags = flags;
552 msg.body.motion.edgeFlags = edgeFlags;
553 msg.body.motion.metaState = metaState;
554 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800555 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700556 msg.body.motion.dsdx = transform.dsdx();
557 msg.body.motion.dtdx = transform.dtdx();
558 msg.body.motion.dtdy = transform.dtdy();
559 msg.body.motion.dsdy = transform.dsdy();
560 msg.body.motion.tx = transform.tx();
561 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700562 msg.body.motion.xPrecision = xPrecision;
563 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700564 msg.body.motion.xCursorPosition = xCursorPosition;
565 msg.body.motion.yCursorPosition = yCursorPosition;
Jeff Brown5912f952013-07-01 19:10:31 -0700566 msg.body.motion.downTime = downTime;
567 msg.body.motion.eventTime = eventTime;
568 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100569 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700570 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
571 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
572 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700573
Jeff Brown5912f952013-07-01 19:10:31 -0700574 return mChannel->sendMessage(&msg);
575}
576
Garfield Tan1c7bc862020-01-28 13:24:04 -0800577status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus,
578 bool inTouchMode) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800579 if (ATRACE_ENABLED()) {
580 std::string message =
581 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s, inTouchMode=%s)",
582 mChannel->getName().c_str(), toString(hasFocus),
583 toString(inTouchMode));
584 ATRACE_NAME(message.c_str());
585 }
586
587 InputMessage msg;
588 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500589 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800590 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000591 msg.body.focus.hasFocus = hasFocus;
592 msg.body.focus.inTouchMode = inTouchMode;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800593 return mChannel->sendMessage(&msg);
594}
595
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800596status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
597 bool pointerCaptureEnabled) {
598 if (ATRACE_ENABLED()) {
599 std::string message =
600 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
601 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
602 ATRACE_NAME(message.c_str());
603 }
604
605 InputMessage msg;
606 msg.header.type = InputMessage::Type::CAPTURE;
607 msg.header.seq = seq;
608 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000609 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800610 return mChannel->sendMessage(&msg);
611}
612
arthurhung7632c332020-12-30 16:58:01 +0800613status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
614 bool isExiting) {
615 if (ATRACE_ENABLED()) {
616 std::string message =
617 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
618 mChannel->getName().c_str(), x, y, toString(isExiting));
619 ATRACE_NAME(message.c_str());
620 }
621
622 InputMessage msg;
623 msg.header.type = InputMessage::Type::DRAG;
624 msg.header.seq = seq;
625 msg.body.drag.eventId = eventId;
626 msg.body.drag.isExiting = isExiting;
627 msg.body.drag.x = x;
628 msg.body.drag.y = y;
629 return mChannel->sendMessage(&msg);
630}
631
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000632status_t InputPublisher::receiveFinishedSignal(
633 const std::function<void(uint32_t seq, bool handled, nsecs_t consumeTime)>& callback) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800634 if (DEBUG_TRANSPORT_ACTIONS) {
635 ALOGD("channel '%s' publisher ~ receiveFinishedSignal", mChannel->getName().c_str());
636 }
Jeff Brown5912f952013-07-01 19:10:31 -0700637
638 InputMessage msg;
639 status_t result = mChannel->receiveMessage(&msg);
640 if (result) {
Jeff Brown5912f952013-07-01 19:10:31 -0700641 return result;
642 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700643 if (msg.header.type != InputMessage::Type::FINISHED) {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000644 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
645 mChannel->getName().c_str(), NamedEnum::string(msg.header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700646 return UNKNOWN_ERROR;
647 }
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000648 callback(msg.header.seq, msg.body.finished.handled, msg.body.finished.consumeTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700649 return OK;
650}
651
652// --- InputConsumer ---
653
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500654InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
655 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700656
657InputConsumer::~InputConsumer() {
658}
659
660bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600661 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700662}
663
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800664status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
665 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800666 if (DEBUG_TRANSPORT_ACTIONS) {
667 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
668 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
669 }
Jeff Brown5912f952013-07-01 19:10:31 -0700670
671 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700672 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700673
674 // Fetch the next input message.
675 // Loop until an event can be returned or no additional events are received.
676 while (!*outEvent) {
677 if (mMsgDeferred) {
678 // mMsg contains a valid input message from the previous call to consume
679 // that has not yet been processed.
680 mMsgDeferred = false;
681 } else {
682 // Receive a fresh message.
683 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000684 if (result == OK) {
685 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
686 }
Jeff Brown5912f952013-07-01 19:10:31 -0700687 if (result) {
688 // Consume the next batched event unless batches are being held for later.
689 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800690 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700691 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800692 if (DEBUG_TRANSPORT_ACTIONS) {
693 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
694 mChannel->getName().c_str(), *outSeq);
695 }
Jeff Brown5912f952013-07-01 19:10:31 -0700696 break;
697 }
698 }
699 return result;
700 }
701 }
702
703 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700704 case InputMessage::Type::KEY: {
705 KeyEvent* keyEvent = factory->createKeyEvent();
706 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700707
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700708 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500709 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700710 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800711 if (DEBUG_TRANSPORT_ACTIONS) {
712 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
713 mChannel->getName().c_str(), *outSeq);
714 }
Jeff Brown5912f952013-07-01 19:10:31 -0700715 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700716 }
Jeff Brown5912f952013-07-01 19:10:31 -0700717
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700718 case InputMessage::Type::MOTION: {
719 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
720 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500721 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700722 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500723 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800724 if (DEBUG_TRANSPORT_ACTIONS) {
725 ALOGD("channel '%s' consumer ~ appended to batch event",
726 mChannel->getName().c_str());
727 }
Jeff Brown5912f952013-07-01 19:10:31 -0700728 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700729 } else if (isPointerEvent(mMsg.body.motion.source) &&
730 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
731 // No need to process events that we are going to cancel anyways
732 const size_t count = batch.samples.size();
733 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500734 const InputMessage& msg = batch.samples[i];
735 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700736 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500737 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
738 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700739 } else {
740 // We cannot append to the batch in progress, so we need to consume
741 // the previous batch right now and defer the new message until later.
742 mMsgDeferred = true;
743 status_t result = consumeSamples(factory, batch, batch.samples.size(),
744 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500745 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700746 if (result) {
747 return result;
748 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800749 if (DEBUG_TRANSPORT_ACTIONS) {
750 ALOGD("channel '%s' consumer ~ consumed batch event and "
751 "deferred current event, seq=%u",
752 mChannel->getName().c_str(), *outSeq);
753 }
Jeff Brown5912f952013-07-01 19:10:31 -0700754 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700755 }
Jeff Brown5912f952013-07-01 19:10:31 -0700756 }
Jeff Brown5912f952013-07-01 19:10:31 -0700757
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800758 // Start a new batch if needed.
759 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
760 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500761 Batch batch;
762 batch.samples.push_back(mMsg);
763 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800764 if (DEBUG_TRANSPORT_ACTIONS) {
765 ALOGD("channel '%s' consumer ~ started batch event",
766 mChannel->getName().c_str());
767 }
768 break;
769 }
Jeff Brown5912f952013-07-01 19:10:31 -0700770
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800771 MotionEvent* motionEvent = factory->createMotionEvent();
772 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700773
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800774 updateTouchState(mMsg);
775 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500776 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800777 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800778
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800779 if (DEBUG_TRANSPORT_ACTIONS) {
780 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
781 mChannel->getName().c_str(), *outSeq);
782 }
783 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700784 }
Jeff Brown5912f952013-07-01 19:10:31 -0700785
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800786 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000787 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
788 "InputConsumer!",
789 NamedEnum::string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800790 break;
791 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800792
793 case InputMessage::Type::FOCUS: {
794 FocusEvent* focusEvent = factory->createFocusEvent();
795 if (!focusEvent) return NO_MEMORY;
796
797 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500798 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800799 *outEvent = focusEvent;
800 break;
801 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800802
803 case InputMessage::Type::CAPTURE: {
804 CaptureEvent* captureEvent = factory->createCaptureEvent();
805 if (!captureEvent) return NO_MEMORY;
806
807 initializeCaptureEvent(captureEvent, &mMsg);
808 *outSeq = mMsg.header.seq;
809 *outEvent = captureEvent;
810 break;
811 }
arthurhung7632c332020-12-30 16:58:01 +0800812
813 case InputMessage::Type::DRAG: {
814 DragEvent* dragEvent = factory->createDragEvent();
815 if (!dragEvent) return NO_MEMORY;
816
817 initializeDragEvent(dragEvent, &mMsg);
818 *outSeq = mMsg.header.seq;
819 *outEvent = dragEvent;
820 break;
821 }
Jeff Brown5912f952013-07-01 19:10:31 -0700822 }
823 }
824 return OK;
825}
826
827status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800828 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700829 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700830 for (size_t i = mBatches.size(); i > 0; ) {
831 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500832 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700833 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800834 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500835 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700836 return result;
837 }
838
Michael Wright32232172013-10-21 12:05:22 -0700839 nsecs_t sampleTime = frameTime;
840 if (mResampleTouch) {
841 sampleTime -= RESAMPLE_LATENCY;
842 }
Jeff Brown5912f952013-07-01 19:10:31 -0700843 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
844 if (split < 0) {
845 continue;
846 }
847
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800848 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700849 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500850 if (batch.samples.empty()) {
851 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700852 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700853 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500854 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700855 }
Michael Wright32232172013-10-21 12:05:22 -0700856 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700857 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
858 }
859 return result;
860 }
861
862 return WOULD_BLOCK;
863}
864
865status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800866 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700867 MotionEvent* motionEvent = factory->createMotionEvent();
868 if (! motionEvent) return NO_MEMORY;
869
870 uint32_t chain = 0;
871 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500872 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100873 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700874 if (i) {
875 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500876 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700877 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500878 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700879 addSample(motionEvent, &msg);
880 } else {
881 initializeMotionEvent(motionEvent, &msg);
882 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500883 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700884 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500885 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700886
887 *outSeq = chain;
888 *outEvent = motionEvent;
889 return OK;
890}
891
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100892void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800893 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700894 return;
895 }
896
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100897 int32_t deviceId = msg.body.motion.deviceId;
898 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700899
900 // Update the touch state history to incorporate the new input message.
901 // If the message is in the past relative to the most recently produced resampled
902 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100903 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700904 case AMOTION_EVENT_ACTION_DOWN: {
905 ssize_t index = findTouchState(deviceId, source);
906 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500907 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700908 index = mTouchStates.size() - 1;
909 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500910 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700911 touchState.initialize(deviceId, source);
912 touchState.addHistory(msg);
913 break;
914 }
915
916 case AMOTION_EVENT_ACTION_MOVE: {
917 ssize_t index = findTouchState(deviceId, source);
918 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500919 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700920 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800921 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700922 }
923 break;
924 }
925
926 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
927 ssize_t index = findTouchState(deviceId, source);
928 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500929 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100930 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700931 rewriteMessage(touchState, msg);
932 }
933 break;
934 }
935
936 case AMOTION_EVENT_ACTION_POINTER_UP: {
937 ssize_t index = findTouchState(deviceId, source);
938 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500939 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700940 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100941 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700942 }
943 break;
944 }
945
946 case AMOTION_EVENT_ACTION_SCROLL: {
947 ssize_t index = findTouchState(deviceId, source);
948 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500949 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700950 rewriteMessage(touchState, msg);
951 }
952 break;
953 }
954
955 case AMOTION_EVENT_ACTION_UP:
956 case AMOTION_EVENT_ACTION_CANCEL: {
957 ssize_t index = findTouchState(deviceId, source);
958 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500959 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700960 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500961 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700962 }
963 break;
964 }
965 }
966}
967
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800968/**
969 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
970 *
971 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
972 * is in the past relative to msg and the past two events do not contain identical coordinates),
973 * then invalidate the lastResample data for that pointer.
974 * If the two past events have identical coordinates, then lastResample data for that pointer will
975 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
976 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
977 * not equal to x0 is received.
978 */
979void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100980 nsecs_t eventTime = msg.body.motion.eventTime;
981 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
982 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700983 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100984 if (eventTime < state.lastResample.eventTime ||
985 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800986 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
987 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700988#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100989 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
990 resampleCoords.getX(), resampleCoords.getY(),
991 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700992#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800993 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
994 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
995 } else {
996 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100997 }
Jeff Brown5912f952013-07-01 19:10:31 -0700998 }
999 }
1000}
1001
1002void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1003 const InputMessage* next) {
1004 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001005 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001006 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1007 return;
1008 }
1009
1010 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1011 if (index < 0) {
1012#if DEBUG_RESAMPLING
1013 ALOGD("Not resampled, no touch state for device.");
1014#endif
1015 return;
1016 }
1017
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001018 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001019 if (touchState.historySize < 1) {
1020#if DEBUG_RESAMPLING
1021 ALOGD("Not resampled, no history for device.");
1022#endif
1023 return;
1024 }
1025
1026 // Ensure that the current sample has all of the pointers that need to be reported.
1027 const History* current = touchState.getHistory(0);
1028 size_t pointerCount = event->getPointerCount();
1029 for (size_t i = 0; i < pointerCount; i++) {
1030 uint32_t id = event->getPointerId(i);
1031 if (!current->idBits.hasBit(id)) {
1032#if DEBUG_RESAMPLING
1033 ALOGD("Not resampled, missing id %d", id);
1034#endif
1035 return;
1036 }
1037 }
1038
1039 // Find the data to use for resampling.
1040 const History* other;
1041 History future;
1042 float alpha;
1043 if (next) {
1044 // Interpolate between current sample and future sample.
1045 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001046 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001047 other = &future;
1048 nsecs_t delta = future.eventTime - current->eventTime;
1049 if (delta < RESAMPLE_MIN_DELTA) {
1050#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001051 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001052#endif
1053 return;
1054 }
1055 alpha = float(sampleTime - current->eventTime) / delta;
1056 } else if (touchState.historySize >= 2) {
1057 // Extrapolate future sample using current sample and past sample.
1058 // So other->eventTime <= current->eventTime <= sampleTime.
1059 other = touchState.getHistory(1);
1060 nsecs_t delta = current->eventTime - other->eventTime;
1061 if (delta < RESAMPLE_MIN_DELTA) {
1062#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001063 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001064#endif
1065 return;
1066 } else if (delta > RESAMPLE_MAX_DELTA) {
1067#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001068 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001069#endif
1070 return;
1071 }
1072 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1073 if (sampleTime > maxPredict) {
1074#if DEBUG_RESAMPLING
1075 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001076 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001077 sampleTime - current->eventTime, maxPredict - current->eventTime);
1078#endif
1079 sampleTime = maxPredict;
1080 }
1081 alpha = float(current->eventTime - sampleTime) / delta;
1082 } else {
1083#if DEBUG_RESAMPLING
1084 ALOGD("Not resampled, insufficient data.");
1085#endif
1086 return;
1087 }
1088
1089 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001090 History oldLastResample;
1091 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001092 touchState.lastResample.eventTime = sampleTime;
1093 touchState.lastResample.idBits.clear();
1094 for (size_t i = 0; i < pointerCount; i++) {
1095 uint32_t id = event->getPointerId(i);
1096 touchState.lastResample.idToIndex[id] = i;
1097 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001098 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1099 // We maintain the previously resampled value for this pointer (stored in
1100 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1101 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1102
1103 // We know here that the coordinates for the pointer haven't changed because we
1104 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1105 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1106 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1107 continue;
1108 }
1109
Jeff Brown5912f952013-07-01 19:10:31 -07001110 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1111 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001112 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001113 if (other->idBits.hasBit(id)
1114 && shouldResampleTool(event->getToolType(i))) {
1115 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001116 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1117 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1118 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1119 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1120#if DEBUG_RESAMPLING
1121 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1122 "other (%0.3f, %0.3f), alpha %0.3f",
1123 id, resampledCoords.getX(), resampledCoords.getY(),
1124 currentCoords.getX(), currentCoords.getY(),
1125 otherCoords.getX(), otherCoords.getY(),
1126 alpha);
1127#endif
1128 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001129#if DEBUG_RESAMPLING
1130 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1131 id, resampledCoords.getX(), resampledCoords.getY(),
1132 currentCoords.getX(), currentCoords.getY());
1133#endif
1134 }
1135 }
1136
1137 event->addSample(sampleTime, touchState.lastResample.pointers);
1138}
1139
1140bool InputConsumer::shouldResampleTool(int32_t toolType) {
1141 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1142 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1143}
1144
1145status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001146 if (DEBUG_TRANSPORT_ACTIONS) {
1147 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1148 mChannel->getName().c_str(), seq, toString(handled));
1149 }
Jeff Brown5912f952013-07-01 19:10:31 -07001150
1151 if (!seq) {
1152 ALOGE("Attempted to send a finished signal with sequence number 0.");
1153 return BAD_VALUE;
1154 }
1155
1156 // Send finished signals for the batch sequence chain first.
1157 size_t seqChainCount = mSeqChains.size();
1158 if (seqChainCount) {
1159 uint32_t currentSeq = seq;
1160 uint32_t chainSeqs[seqChainCount];
1161 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001162 for (size_t i = seqChainCount; i > 0; ) {
1163 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001164 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001165 if (seqChain.seq == currentSeq) {
1166 currentSeq = seqChain.chain;
1167 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001168 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001169 }
1170 }
1171 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001172 while (!status && chainIndex > 0) {
1173 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001174 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1175 }
1176 if (status) {
1177 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001178 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001179 SeqChain seqChain;
1180 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1181 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001182 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001183 if (!chainIndex) break;
1184 chainIndex--;
1185 }
Jeff Brown5912f952013-07-01 19:10:31 -07001186 return status;
1187 }
1188 }
1189
1190 // Send finished signal for the last message in the batch.
1191 return sendUnchainedFinishedSignal(seq, handled);
1192}
1193
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001194nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1195 auto it = mConsumeTimes.find(seq);
1196 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1197 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1198 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1199 seq);
1200 return it->second;
1201}
1202
1203void InputConsumer::popConsumeTime(uint32_t seq) {
1204 mConsumeTimes.erase(seq);
1205}
1206
Jeff Brown5912f952013-07-01 19:10:31 -07001207status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1208 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001209 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001210 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001211 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001212 msg.body.finished.consumeTime = getConsumeTime(seq);
1213 status_t result = mChannel->sendMessage(&msg);
1214 if (result == OK) {
1215 // Remove the consume time if the socket write succeeded. We will not need to ack this
1216 // message anymore. If the socket write did not succeed, we will try again and will still
1217 // need consume time.
1218 popConsumeTime(seq);
1219 }
1220 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001221}
1222
1223bool InputConsumer::hasDeferredEvent() const {
1224 return mMsgDeferred;
1225}
1226
1227bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001228 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001229}
1230
Arthur Hungc7812be2020-02-27 22:40:27 +08001231int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001232 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001233 return AINPUT_SOURCE_CLASS_NONE;
1234 }
1235
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001236 const Batch& batch = mBatches[0];
1237 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001238 return head.body.motion.source;
1239}
1240
Jeff Brown5912f952013-07-01 19:10:31 -07001241ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1242 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001243 const Batch& batch = mBatches[i];
1244 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001245 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1246 return i;
1247 }
1248 }
1249 return -1;
1250}
1251
1252ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1253 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001254 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001255 if (touchState.deviceId == deviceId && touchState.source == source) {
1256 return i;
1257 }
1258 }
1259 return -1;
1260}
1261
1262void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001263 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001264 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1265 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1266 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1267 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001268}
1269
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001270void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001271 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus,
1272 msg->body.focus.inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001273}
1274
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001275void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001276 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001277}
1278
arthurhung7632c332020-12-30 16:58:01 +08001279void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1280 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1281 msg->body.drag.isExiting);
1282}
1283
Jeff Brown5912f952013-07-01 19:10:31 -07001284void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001285 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001286 PointerProperties pointerProperties[pointerCount];
1287 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001288 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001289 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1290 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1291 }
1292
chaviw9eaa22c2020-07-01 16:21:27 -07001293 ui::Transform transform;
1294 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1295 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001296 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1297 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1298 msg->body.motion.actionButton, msg->body.motion.flags,
1299 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001300 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1301 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1302 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1303 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1304 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001305}
1306
1307void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001308 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001309 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001310 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001311 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1312 }
1313
1314 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1315 event->addSample(msg->body.motion.eventTime, pointerCoords);
1316}
1317
1318bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001319 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001320 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001321 if (head.body.motion.pointerCount != pointerCount
1322 || head.body.motion.action != msg->body.motion.action) {
1323 return false;
1324 }
1325 for (size_t i = 0; i < pointerCount; i++) {
1326 if (head.body.motion.pointers[i].properties
1327 != msg->body.motion.pointers[i].properties) {
1328 return false;
1329 }
1330 }
1331 return true;
1332}
1333
1334ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1335 size_t numSamples = batch.samples.size();
1336 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001337 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001338 index += 1;
1339 }
1340 return ssize_t(index) - 1;
1341}
1342
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001343std::string InputConsumer::dump() const {
1344 std::string out;
1345 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1346 out = out + "mChannel = " + mChannel->getName() + "\n";
1347 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1348 if (mMsgDeferred) {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001349 out = out + "mMsg : " + NamedEnum::string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001350 }
1351 out += "Batches:\n";
1352 for (const Batch& batch : mBatches) {
1353 out += " Batch:\n";
1354 for (const InputMessage& msg : batch.samples) {
1355 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001356 NamedEnum::string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001357 switch (msg.header.type) {
1358 case InputMessage::Type::KEY: {
1359 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1360 KeyEvent::actionToString(
1361 msg.body.key.action),
1362 msg.body.key.keyCode);
1363 break;
1364 }
1365 case InputMessage::Type::MOTION: {
1366 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1367 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1368 const float x = msg.body.motion.pointers[i].coords.getX();
1369 const float y = msg.body.motion.pointers[i].coords.getY();
1370 out += android::base::StringPrintf("\n Pointer %" PRIu32
1371 " : x=%.1f y=%.1f",
1372 i, x, y);
1373 }
1374 break;
1375 }
1376 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001377 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1378 toString(msg.body.finished.handled),
1379 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001380 break;
1381 }
1382 case InputMessage::Type::FOCUS: {
1383 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1384 toString(msg.body.focus.hasFocus),
1385 toString(msg.body.focus.inTouchMode));
1386 break;
1387 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001388 case InputMessage::Type::CAPTURE: {
1389 out += android::base::StringPrintf("hasCapture=%s",
1390 toString(msg.body.capture
1391 .pointerCaptureEnabled));
1392 break;
1393 }
arthurhung7632c332020-12-30 16:58:01 +08001394 case InputMessage::Type::DRAG: {
1395 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1396 msg.body.drag.x, msg.body.drag.y,
1397 toString(msg.body.drag.isExiting));
1398 break;
1399 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001400 }
1401 out += "\n";
1402 }
1403 }
1404 if (mBatches.empty()) {
1405 out += " <empty>\n";
1406 }
1407 out += "mSeqChains:\n";
1408 for (const SeqChain& chain : mSeqChains) {
1409 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1410 chain.chain);
1411 }
1412 if (mSeqChains.empty()) {
1413 out += " <empty>\n";
1414 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001415 out += "mConsumeTimes:\n";
1416 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1417 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1418 consumeTime);
1419 }
1420 if (mConsumeTimes.empty()) {
1421 out += " <empty>\n";
1422 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001423 return out;
1424}
1425
Jeff Brown5912f952013-07-01 19:10:31 -07001426} // namespace android