blob: c2a3cf18162239214273611b3a332534b8e582ba [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 Vishniakoueedd0fc2021-03-12 09:50:36 +0000632android::base::Result<InputPublisher::Finished> InputPublisher::receiveFinishedSignal() {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800633 if (DEBUG_TRANSPORT_ACTIONS) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000634 ALOGD("channel '%s' publisher ~ %s", mChannel->getName().c_str(), __func__);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800635 }
Jeff Brown5912f952013-07-01 19:10:31 -0700636
637 InputMessage msg;
638 status_t result = mChannel->receiveMessage(&msg);
639 if (result) {
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000640 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700641 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700642 if (msg.header.type != InputMessage::Type::FINISHED) {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000643 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
644 mChannel->getName().c_str(), NamedEnum::string(msg.header.type).c_str());
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000645 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700646 }
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000647 return Finished{
648 .seq = msg.header.seq,
649 .handled = msg.body.finished.handled,
650 .consumeTime = msg.body.finished.consumeTime,
651 };
Jeff Brown5912f952013-07-01 19:10:31 -0700652}
653
654// --- InputConsumer ---
655
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500656InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
657 : mResampleTouch(isTouchResamplingEnabled()), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700658
659InputConsumer::~InputConsumer() {
660}
661
662bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600663 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700664}
665
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800666status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
667 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800668 if (DEBUG_TRANSPORT_ACTIONS) {
669 ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
670 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
671 }
Jeff Brown5912f952013-07-01 19:10:31 -0700672
673 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700674 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700675
676 // Fetch the next input message.
677 // Loop until an event can be returned or no additional events are received.
678 while (!*outEvent) {
679 if (mMsgDeferred) {
680 // mMsg contains a valid input message from the previous call to consume
681 // that has not yet been processed.
682 mMsgDeferred = false;
683 } else {
684 // Receive a fresh message.
685 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000686 if (result == OK) {
687 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
688 }
Jeff Brown5912f952013-07-01 19:10:31 -0700689 if (result) {
690 // Consume the next batched event unless batches are being held for later.
691 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800692 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700693 if (*outEvent) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800694 if (DEBUG_TRANSPORT_ACTIONS) {
695 ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
696 mChannel->getName().c_str(), *outSeq);
697 }
Jeff Brown5912f952013-07-01 19:10:31 -0700698 break;
699 }
700 }
701 return result;
702 }
703 }
704
705 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700706 case InputMessage::Type::KEY: {
707 KeyEvent* keyEvent = factory->createKeyEvent();
708 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700709
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700710 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500711 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700712 *outEvent = keyEvent;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800713 if (DEBUG_TRANSPORT_ACTIONS) {
714 ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
715 mChannel->getName().c_str(), *outSeq);
716 }
Jeff Brown5912f952013-07-01 19:10:31 -0700717 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700718 }
Jeff Brown5912f952013-07-01 19:10:31 -0700719
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700720 case InputMessage::Type::MOTION: {
721 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
722 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500723 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700724 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500725 batch.samples.push_back(mMsg);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800726 if (DEBUG_TRANSPORT_ACTIONS) {
727 ALOGD("channel '%s' consumer ~ appended to batch event",
728 mChannel->getName().c_str());
729 }
Jeff Brown5912f952013-07-01 19:10:31 -0700730 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700731 } else if (isPointerEvent(mMsg.body.motion.source) &&
732 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
733 // No need to process events that we are going to cancel anyways
734 const size_t count = batch.samples.size();
735 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500736 const InputMessage& msg = batch.samples[i];
737 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700738 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500739 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
740 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700741 } else {
742 // We cannot append to the batch in progress, so we need to consume
743 // the previous batch right now and defer the new message until later.
744 mMsgDeferred = true;
745 status_t result = consumeSamples(factory, batch, batch.samples.size(),
746 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500747 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700748 if (result) {
749 return result;
750 }
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800751 if (DEBUG_TRANSPORT_ACTIONS) {
752 ALOGD("channel '%s' consumer ~ consumed batch event and "
753 "deferred current event, seq=%u",
754 mChannel->getName().c_str(), *outSeq);
755 }
Jeff Brown5912f952013-07-01 19:10:31 -0700756 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700757 }
Jeff Brown5912f952013-07-01 19:10:31 -0700758 }
Jeff Brown5912f952013-07-01 19:10:31 -0700759
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800760 // Start a new batch if needed.
761 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
762 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500763 Batch batch;
764 batch.samples.push_back(mMsg);
765 mBatches.push_back(batch);
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800766 if (DEBUG_TRANSPORT_ACTIONS) {
767 ALOGD("channel '%s' consumer ~ started batch event",
768 mChannel->getName().c_str());
769 }
770 break;
771 }
Jeff Brown5912f952013-07-01 19:10:31 -0700772
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800773 MotionEvent* motionEvent = factory->createMotionEvent();
774 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700775
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800776 updateTouchState(mMsg);
777 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500778 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800779 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800780
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800781 if (DEBUG_TRANSPORT_ACTIONS) {
782 ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
783 mChannel->getName().c_str(), *outSeq);
784 }
785 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700786 }
Jeff Brown5912f952013-07-01 19:10:31 -0700787
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800788 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000789 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
790 "InputConsumer!",
791 NamedEnum::string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800792 break;
793 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800794
795 case InputMessage::Type::FOCUS: {
796 FocusEvent* focusEvent = factory->createFocusEvent();
797 if (!focusEvent) return NO_MEMORY;
798
799 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500800 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800801 *outEvent = focusEvent;
802 break;
803 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800804
805 case InputMessage::Type::CAPTURE: {
806 CaptureEvent* captureEvent = factory->createCaptureEvent();
807 if (!captureEvent) return NO_MEMORY;
808
809 initializeCaptureEvent(captureEvent, &mMsg);
810 *outSeq = mMsg.header.seq;
811 *outEvent = captureEvent;
812 break;
813 }
arthurhung7632c332020-12-30 16:58:01 +0800814
815 case InputMessage::Type::DRAG: {
816 DragEvent* dragEvent = factory->createDragEvent();
817 if (!dragEvent) return NO_MEMORY;
818
819 initializeDragEvent(dragEvent, &mMsg);
820 *outSeq = mMsg.header.seq;
821 *outEvent = dragEvent;
822 break;
823 }
Jeff Brown5912f952013-07-01 19:10:31 -0700824 }
825 }
826 return OK;
827}
828
829status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800830 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700831 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700832 for (size_t i = mBatches.size(); i > 0; ) {
833 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500834 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700835 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800836 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500837 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700838 return result;
839 }
840
Michael Wright32232172013-10-21 12:05:22 -0700841 nsecs_t sampleTime = frameTime;
842 if (mResampleTouch) {
843 sampleTime -= RESAMPLE_LATENCY;
844 }
Jeff Brown5912f952013-07-01 19:10:31 -0700845 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
846 if (split < 0) {
847 continue;
848 }
849
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800850 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700851 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500852 if (batch.samples.empty()) {
853 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -0700854 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700855 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500856 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -0700857 }
Michael Wright32232172013-10-21 12:05:22 -0700858 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -0700859 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
860 }
861 return result;
862 }
863
864 return WOULD_BLOCK;
865}
866
867status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800868 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700869 MotionEvent* motionEvent = factory->createMotionEvent();
870 if (! motionEvent) return NO_MEMORY;
871
872 uint32_t chain = 0;
873 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500874 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100875 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700876 if (i) {
877 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500878 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700879 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500880 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -0700881 addSample(motionEvent, &msg);
882 } else {
883 initializeMotionEvent(motionEvent, &msg);
884 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500885 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -0700886 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500887 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -0700888
889 *outSeq = chain;
890 *outEvent = motionEvent;
891 return OK;
892}
893
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100894void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800895 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -0700896 return;
897 }
898
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100899 int32_t deviceId = msg.body.motion.deviceId;
900 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -0700901
902 // Update the touch state history to incorporate the new input message.
903 // If the message is in the past relative to the most recently produced resampled
904 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100905 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -0700906 case AMOTION_EVENT_ACTION_DOWN: {
907 ssize_t index = findTouchState(deviceId, source);
908 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500909 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -0700910 index = mTouchStates.size() - 1;
911 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500912 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700913 touchState.initialize(deviceId, source);
914 touchState.addHistory(msg);
915 break;
916 }
917
918 case AMOTION_EVENT_ACTION_MOVE: {
919 ssize_t index = findTouchState(deviceId, source);
920 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500921 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700922 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800923 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700924 }
925 break;
926 }
927
928 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
929 ssize_t index = findTouchState(deviceId, source);
930 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500931 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100932 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700933 rewriteMessage(touchState, msg);
934 }
935 break;
936 }
937
938 case AMOTION_EVENT_ACTION_POINTER_UP: {
939 ssize_t index = findTouchState(deviceId, source);
940 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500941 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700942 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100943 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -0700944 }
945 break;
946 }
947
948 case AMOTION_EVENT_ACTION_SCROLL: {
949 ssize_t index = findTouchState(deviceId, source);
950 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500951 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700952 rewriteMessage(touchState, msg);
953 }
954 break;
955 }
956
957 case AMOTION_EVENT_ACTION_UP:
958 case AMOTION_EVENT_ACTION_CANCEL: {
959 ssize_t index = findTouchState(deviceId, source);
960 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500961 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -0700962 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500963 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -0700964 }
965 break;
966 }
967 }
968}
969
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800970/**
971 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
972 *
973 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
974 * is in the past relative to msg and the past two events do not contain identical coordinates),
975 * then invalidate the lastResample data for that pointer.
976 * If the two past events have identical coordinates, then lastResample data for that pointer will
977 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
978 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
979 * not equal to x0 is received.
980 */
981void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100982 nsecs_t eventTime = msg.body.motion.eventTime;
983 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
984 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700985 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100986 if (eventTime < state.lastResample.eventTime ||
987 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800988 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
989 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -0700990#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100991 ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
992 resampleCoords.getX(), resampleCoords.getY(),
993 msgCoords.getX(), msgCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -0700994#endif
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800995 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
996 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
997 } else {
998 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +0100999 }
Jeff Brown5912f952013-07-01 19:10:31 -07001000 }
1001 }
1002}
1003
1004void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1005 const InputMessage* next) {
1006 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001007 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001008 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1009 return;
1010 }
1011
1012 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1013 if (index < 0) {
1014#if DEBUG_RESAMPLING
1015 ALOGD("Not resampled, no touch state for device.");
1016#endif
1017 return;
1018 }
1019
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001020 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001021 if (touchState.historySize < 1) {
1022#if DEBUG_RESAMPLING
1023 ALOGD("Not resampled, no history for device.");
1024#endif
1025 return;
1026 }
1027
1028 // Ensure that the current sample has all of the pointers that need to be reported.
1029 const History* current = touchState.getHistory(0);
1030 size_t pointerCount = event->getPointerCount();
1031 for (size_t i = 0; i < pointerCount; i++) {
1032 uint32_t id = event->getPointerId(i);
1033 if (!current->idBits.hasBit(id)) {
1034#if DEBUG_RESAMPLING
1035 ALOGD("Not resampled, missing id %d", id);
1036#endif
1037 return;
1038 }
1039 }
1040
1041 // Find the data to use for resampling.
1042 const History* other;
1043 History future;
1044 float alpha;
1045 if (next) {
1046 // Interpolate between current sample and future sample.
1047 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001048 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001049 other = &future;
1050 nsecs_t delta = future.eventTime - current->eventTime;
1051 if (delta < RESAMPLE_MIN_DELTA) {
1052#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001053 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001054#endif
1055 return;
1056 }
1057 alpha = float(sampleTime - current->eventTime) / delta;
1058 } else if (touchState.historySize >= 2) {
1059 // Extrapolate future sample using current sample and past sample.
1060 // So other->eventTime <= current->eventTime <= sampleTime.
1061 other = touchState.getHistory(1);
1062 nsecs_t delta = current->eventTime - other->eventTime;
1063 if (delta < RESAMPLE_MIN_DELTA) {
1064#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001065 ALOGD("Not resampled, delta time is too small: %" PRId64 " ns.", delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001066#endif
1067 return;
1068 } else if (delta > RESAMPLE_MAX_DELTA) {
1069#if DEBUG_RESAMPLING
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001070 ALOGD("Not resampled, delta time is too large: %" PRId64 " ns.", delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001071#endif
1072 return;
1073 }
1074 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1075 if (sampleTime > maxPredict) {
1076#if DEBUG_RESAMPLING
1077 ALOGD("Sample time is too far in the future, adjusting prediction "
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001078 "from %" PRId64 " to %" PRId64 " ns.",
Jeff Brown5912f952013-07-01 19:10:31 -07001079 sampleTime - current->eventTime, maxPredict - current->eventTime);
1080#endif
1081 sampleTime = maxPredict;
1082 }
1083 alpha = float(current->eventTime - sampleTime) / delta;
1084 } else {
1085#if DEBUG_RESAMPLING
1086 ALOGD("Not resampled, insufficient data.");
1087#endif
1088 return;
1089 }
1090
1091 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001092 History oldLastResample;
1093 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001094 touchState.lastResample.eventTime = sampleTime;
1095 touchState.lastResample.idBits.clear();
1096 for (size_t i = 0; i < pointerCount; i++) {
1097 uint32_t id = event->getPointerId(i);
1098 touchState.lastResample.idToIndex[id] = i;
1099 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001100 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1101 // We maintain the previously resampled value for this pointer (stored in
1102 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1103 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1104
1105 // We know here that the coordinates for the pointer haven't changed because we
1106 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1107 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1108 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1109 continue;
1110 }
1111
Jeff Brown5912f952013-07-01 19:10:31 -07001112 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1113 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001114 resampledCoords.copyFrom(currentCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001115 if (other->idBits.hasBit(id)
1116 && shouldResampleTool(event->getToolType(i))) {
1117 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001118 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1119 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1120 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1121 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1122#if DEBUG_RESAMPLING
1123 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1124 "other (%0.3f, %0.3f), alpha %0.3f",
1125 id, resampledCoords.getX(), resampledCoords.getY(),
1126 currentCoords.getX(), currentCoords.getY(),
1127 otherCoords.getX(), otherCoords.getY(),
1128 alpha);
1129#endif
1130 } else {
Jeff Brown5912f952013-07-01 19:10:31 -07001131#if DEBUG_RESAMPLING
1132 ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
1133 id, resampledCoords.getX(), resampledCoords.getY(),
1134 currentCoords.getX(), currentCoords.getY());
1135#endif
1136 }
1137 }
1138
1139 event->addSample(sampleTime, touchState.lastResample.pointers);
1140}
1141
1142bool InputConsumer::shouldResampleTool(int32_t toolType) {
1143 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1144 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1145}
1146
1147status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08001148 if (DEBUG_TRANSPORT_ACTIONS) {
1149 ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1150 mChannel->getName().c_str(), seq, toString(handled));
1151 }
Jeff Brown5912f952013-07-01 19:10:31 -07001152
1153 if (!seq) {
1154 ALOGE("Attempted to send a finished signal with sequence number 0.");
1155 return BAD_VALUE;
1156 }
1157
1158 // Send finished signals for the batch sequence chain first.
1159 size_t seqChainCount = mSeqChains.size();
1160 if (seqChainCount) {
1161 uint32_t currentSeq = seq;
1162 uint32_t chainSeqs[seqChainCount];
1163 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001164 for (size_t i = seqChainCount; i > 0; ) {
1165 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001166 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001167 if (seqChain.seq == currentSeq) {
1168 currentSeq = seqChain.chain;
1169 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001170 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001171 }
1172 }
1173 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001174 while (!status && chainIndex > 0) {
1175 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001176 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1177 }
1178 if (status) {
1179 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001180 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001181 SeqChain seqChain;
1182 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1183 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001184 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001185 if (!chainIndex) break;
1186 chainIndex--;
1187 }
Jeff Brown5912f952013-07-01 19:10:31 -07001188 return status;
1189 }
1190 }
1191
1192 // Send finished signal for the last message in the batch.
1193 return sendUnchainedFinishedSignal(seq, handled);
1194}
1195
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001196nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1197 auto it = mConsumeTimes.find(seq);
1198 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1199 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1200 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1201 seq);
1202 return it->second;
1203}
1204
1205void InputConsumer::popConsumeTime(uint32_t seq) {
1206 mConsumeTimes.erase(seq);
1207}
1208
Jeff Brown5912f952013-07-01 19:10:31 -07001209status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1210 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001211 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001212 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001213 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001214 msg.body.finished.consumeTime = getConsumeTime(seq);
1215 status_t result = mChannel->sendMessage(&msg);
1216 if (result == OK) {
1217 // Remove the consume time if the socket write succeeded. We will not need to ack this
1218 // message anymore. If the socket write did not succeed, we will try again and will still
1219 // need consume time.
1220 popConsumeTime(seq);
1221 }
1222 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001223}
1224
1225bool InputConsumer::hasDeferredEvent() const {
1226 return mMsgDeferred;
1227}
1228
1229bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001230 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001231}
1232
Arthur Hungc7812be2020-02-27 22:40:27 +08001233int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001234 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001235 return AINPUT_SOURCE_CLASS_NONE;
1236 }
1237
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001238 const Batch& batch = mBatches[0];
1239 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001240 return head.body.motion.source;
1241}
1242
Jeff Brown5912f952013-07-01 19:10:31 -07001243ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1244 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001245 const Batch& batch = mBatches[i];
1246 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001247 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1248 return i;
1249 }
1250 }
1251 return -1;
1252}
1253
1254ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1255 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001256 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001257 if (touchState.deviceId == deviceId && touchState.source == source) {
1258 return i;
1259 }
1260 }
1261 return -1;
1262}
1263
1264void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001265 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001266 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1267 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1268 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1269 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001270}
1271
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001272void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001273 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus,
1274 msg->body.focus.inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001275}
1276
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001277void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001278 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001279}
1280
arthurhung7632c332020-12-30 16:58:01 +08001281void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1282 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1283 msg->body.drag.isExiting);
1284}
1285
Jeff Brown5912f952013-07-01 19:10:31 -07001286void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001287 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001288 PointerProperties pointerProperties[pointerCount];
1289 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001290 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001291 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1292 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1293 }
1294
chaviw9eaa22c2020-07-01 16:21:27 -07001295 ui::Transform transform;
1296 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1297 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001298 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1299 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1300 msg->body.motion.actionButton, msg->body.motion.flags,
1301 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001302 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1303 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1304 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1305 msg->body.motion.downTime, msg->body.motion.eventTime, pointerCount,
1306 pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001307}
1308
1309void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001310 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001311 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001312 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001313 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1314 }
1315
1316 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1317 event->addSample(msg->body.motion.eventTime, pointerCoords);
1318}
1319
1320bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001321 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001322 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001323 if (head.body.motion.pointerCount != pointerCount
1324 || head.body.motion.action != msg->body.motion.action) {
1325 return false;
1326 }
1327 for (size_t i = 0; i < pointerCount; i++) {
1328 if (head.body.motion.pointers[i].properties
1329 != msg->body.motion.pointers[i].properties) {
1330 return false;
1331 }
1332 }
1333 return true;
1334}
1335
1336ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1337 size_t numSamples = batch.samples.size();
1338 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001339 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001340 index += 1;
1341 }
1342 return ssize_t(index) - 1;
1343}
1344
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001345std::string InputConsumer::dump() const {
1346 std::string out;
1347 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1348 out = out + "mChannel = " + mChannel->getName() + "\n";
1349 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1350 if (mMsgDeferred) {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001351 out = out + "mMsg : " + NamedEnum::string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001352 }
1353 out += "Batches:\n";
1354 for (const Batch& batch : mBatches) {
1355 out += " Batch:\n";
1356 for (const InputMessage& msg : batch.samples) {
1357 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Siarhei Vishniakou7766c032021-03-02 20:32:20 +00001358 NamedEnum::string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001359 switch (msg.header.type) {
1360 case InputMessage::Type::KEY: {
1361 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1362 KeyEvent::actionToString(
1363 msg.body.key.action),
1364 msg.body.key.keyCode);
1365 break;
1366 }
1367 case InputMessage::Type::MOTION: {
1368 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1369 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1370 const float x = msg.body.motion.pointers[i].coords.getX();
1371 const float y = msg.body.motion.pointers[i].coords.getY();
1372 out += android::base::StringPrintf("\n Pointer %" PRIu32
1373 " : x=%.1f y=%.1f",
1374 i, x, y);
1375 }
1376 break;
1377 }
1378 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001379 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1380 toString(msg.body.finished.handled),
1381 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001382 break;
1383 }
1384 case InputMessage::Type::FOCUS: {
1385 out += android::base::StringPrintf("hasFocus=%s inTouchMode=%s",
1386 toString(msg.body.focus.hasFocus),
1387 toString(msg.body.focus.inTouchMode));
1388 break;
1389 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001390 case InputMessage::Type::CAPTURE: {
1391 out += android::base::StringPrintf("hasCapture=%s",
1392 toString(msg.body.capture
1393 .pointerCaptureEnabled));
1394 break;
1395 }
arthurhung7632c332020-12-30 16:58:01 +08001396 case InputMessage::Type::DRAG: {
1397 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1398 msg.body.drag.x, msg.body.drag.y,
1399 toString(msg.body.drag.isExiting));
1400 break;
1401 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001402 }
1403 out += "\n";
1404 }
1405 }
1406 if (mBatches.empty()) {
1407 out += " <empty>\n";
1408 }
1409 out += "mSeqChains:\n";
1410 for (const SeqChain& chain : mSeqChains) {
1411 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1412 chain.chain);
1413 }
1414 if (mSeqChains.empty()) {
1415 out += " <empty>\n";
1416 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001417 out += "mConsumeTimes:\n";
1418 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1419 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1420 consumeTime);
1421 }
1422 if (mConsumeTimes.empty()) {
1423 out += " <empty>\n";
1424 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001425 return out;
1426}
1427
Jeff Brown5912f952013-07-01 19:10:31 -07001428} // namespace android