blob: 311b2441a4bdec958dd42eaa81c679db5f275f13 [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
Jeff Brown5912f952013-07-01 19:10:31 -07008#include <errno.h>
9#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070010#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070011#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070012#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070013#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070014#include <unistd.h>
15
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000016#include <android-base/properties.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000017#include <android-base/stringprintf.h>
18#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070019#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080020#include <ftl/enum.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070021#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000022#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070023
Jeff Brown5912f952013-07-01 19:10:31 -070024#include <input/InputTransport.h>
25
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000026namespace {
27
28/**
29 * Log debug messages about channel messages (send message, receive message).
30 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
31 * (requires restart)
32 */
33const bool DEBUG_CHANNEL_MESSAGES =
34 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
35
36/**
37 * Log debug messages whenever InputChannel objects are created/destroyed.
38 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
39 * (requires restart)
40 */
41const bool DEBUG_CHANNEL_LIFECYCLE =
42 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
43
44/**
45 * Log debug messages relating to the consumer end of the transport channel.
46 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
47 */
48
49const bool DEBUG_TRANSPORT_CONSUMER =
50 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
51
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000052const bool IS_DEBUGGABLE_BUILD =
53#if defined(__ANDROID__)
54 android::base::GetBoolProperty("ro.debuggable", false);
55#else
56 true;
57#endif
58
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000059/**
60 * Log debug messages relating to the producer end of the transport channel.
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000061 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
62 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
63 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000064 */
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000065bool debugTransportPublisher() {
66 if (!IS_DEBUGGABLE_BUILD) {
67 static const bool DEBUG_TRANSPORT_PUBLISHER =
68 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
69 return DEBUG_TRANSPORT_PUBLISHER;
70 }
71 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
72}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000073
74/**
75 * Log debug messages about touch event resampling.
76 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG" (requires restart)
77 */
78const bool DEBUG_RESAMPLING =
79 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
80
81} // namespace
82
Michael Wright3dd60e22019-03-27 22:06:44 +000083using android::base::StringPrintf;
84
Jeff Brown5912f952013-07-01 19:10:31 -070085namespace android {
86
87// Socket buffer size. The default is typically about 128KB, which is much larger than
88// we really need. So we make it smaller. It just needs to be big enough to hold
89// a few dozen large multi-finger motion events in the case where an application gets
90// behind processing touches.
91static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
92
93// Nanoseconds per milliseconds.
94static const nsecs_t NANOS_PER_MS = 1000000;
95
96// Latency added during resampling. A few milliseconds doesn't hurt much but
97// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -080098const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -070099
100// Minimum time difference between consecutive samples before attempting to resample.
101static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
102
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700103// Maximum time difference between consecutive samples before attempting to resample
104// by extrapolation.
105static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
106
Jeff Brown5912f952013-07-01 19:10:31 -0700107// Maximum time to predict forward from the last known state, to avoid predicting too
108// far into the future. This time is further bounded by 50% of the last time delta.
109static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
110
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600111/**
112 * System property for enabling / disabling touch resampling.
113 * Resampling extrapolates / interpolates the reported touch event coordinates to better
114 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
115 * Resampling is not needed (and should be disabled) on hardware that already
116 * has touch events triggered by VSYNC.
117 * Set to "1" to enable resampling (default).
118 * Set to "0" to disable resampling.
119 * Resampling is enabled by default.
120 */
121static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
122
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800123/**
124 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
125 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
126 */
127static bool verifyEvents() {
128 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
129}
130
Jeff Brown5912f952013-07-01 19:10:31 -0700131template<typename T>
132inline static T min(const T& a, const T& b) {
133 return a < b ? a : b;
134}
135
136inline static float lerp(float a, float b, float alpha) {
137 return a + alpha * (b - a);
138}
139
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800140inline static bool isPointerEvent(int32_t source) {
141 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
142}
143
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800144inline static const char* toString(bool value) {
145 return value ? "true" : "false";
146}
147
Jeff Brown5912f952013-07-01 19:10:31 -0700148// --- InputMessage ---
149
150bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000151 if (size() != actualSize) {
152 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
153 return false;
154 }
155
156 switch (header.type) {
157 case Type::KEY:
158 return true;
159 case Type::MOTION: {
160 const bool valid =
161 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
162 if (!valid) {
163 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
164 }
165 return valid;
166 }
167 case Type::FINISHED:
168 case Type::FOCUS:
169 case Type::CAPTURE:
170 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700171 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000172 return true;
173 case Type::TIMELINE: {
174 const nsecs_t gpuCompletedTime =
175 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
176 const nsecs_t presentTime =
177 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
178 const bool valid = presentTime > gpuCompletedTime;
179 if (!valid) {
180 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
181 " presentTime = %" PRId64,
182 gpuCompletedTime, presentTime);
183 }
184 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700185 }
186 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000187 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700188 return false;
189}
190
191size_t InputMessage::size() const {
192 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700193 case Type::KEY:
194 return sizeof(Header) + body.key.size();
195 case Type::MOTION:
196 return sizeof(Header) + body.motion.size();
197 case Type::FINISHED:
198 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800199 case Type::FOCUS:
200 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800201 case Type::CAPTURE:
202 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800203 case Type::DRAG:
204 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000205 case Type::TIMELINE:
206 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700207 case Type::TOUCH_MODE:
208 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700209 }
210 return sizeof(Header);
211}
212
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800213/**
214 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
215 * memory to zero, then only copy the valid bytes on a per-field basis.
216 */
217void InputMessage::getSanitizedCopy(InputMessage* msg) const {
218 memset(msg, 0, sizeof(*msg));
219
220 // Write the header
221 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500222 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800223
224 // Write the body
225 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700226 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800227 // int32_t eventId
228 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800229 // nsecs_t eventTime
230 msg->body.key.eventTime = body.key.eventTime;
231 // int32_t deviceId
232 msg->body.key.deviceId = body.key.deviceId;
233 // int32_t source
234 msg->body.key.source = body.key.source;
235 // int32_t displayId
236 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600237 // std::array<uint8_t, 32> hmac
238 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800239 // int32_t action
240 msg->body.key.action = body.key.action;
241 // int32_t flags
242 msg->body.key.flags = body.key.flags;
243 // int32_t keyCode
244 msg->body.key.keyCode = body.key.keyCode;
245 // int32_t scanCode
246 msg->body.key.scanCode = body.key.scanCode;
247 // int32_t metaState
248 msg->body.key.metaState = body.key.metaState;
249 // int32_t repeatCount
250 msg->body.key.repeatCount = body.key.repeatCount;
251 // nsecs_t downTime
252 msg->body.key.downTime = body.key.downTime;
253 break;
254 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700255 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800256 // int32_t eventId
257 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700258 // uint32_t pointerCount
259 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800260 // nsecs_t eventTime
261 msg->body.motion.eventTime = body.motion.eventTime;
262 // int32_t deviceId
263 msg->body.motion.deviceId = body.motion.deviceId;
264 // int32_t source
265 msg->body.motion.source = body.motion.source;
266 // int32_t displayId
267 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600268 // std::array<uint8_t, 32> hmac
269 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800270 // int32_t action
271 msg->body.motion.action = body.motion.action;
272 // int32_t actionButton
273 msg->body.motion.actionButton = body.motion.actionButton;
274 // int32_t flags
275 msg->body.motion.flags = body.motion.flags;
276 // int32_t metaState
277 msg->body.motion.metaState = body.motion.metaState;
278 // int32_t buttonState
279 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800280 // MotionClassification classification
281 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800282 // int32_t edgeFlags
283 msg->body.motion.edgeFlags = body.motion.edgeFlags;
284 // nsecs_t downTime
285 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700286
287 msg->body.motion.dsdx = body.motion.dsdx;
288 msg->body.motion.dtdx = body.motion.dtdx;
289 msg->body.motion.dtdy = body.motion.dtdy;
290 msg->body.motion.dsdy = body.motion.dsdy;
291 msg->body.motion.tx = body.motion.tx;
292 msg->body.motion.ty = body.motion.ty;
293
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800294 // float xPrecision
295 msg->body.motion.xPrecision = body.motion.xPrecision;
296 // float yPrecision
297 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700298 // float xCursorPosition
299 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
300 // float yCursorPosition
301 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700302
303 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
304 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
305 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
306 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
307 msg->body.motion.txRaw = body.motion.txRaw;
308 msg->body.motion.tyRaw = body.motion.tyRaw;
309
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800310 //struct Pointer pointers[MAX_POINTERS]
311 for (size_t i = 0; i < body.motion.pointerCount; i++) {
312 // PointerProperties properties
313 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
314 msg->body.motion.pointers[i].properties.toolType =
315 body.motion.pointers[i].properties.toolType,
316 // PointerCoords coords
317 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
318 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
319 memcpy(&msg->body.motion.pointers[i].coords.values[0],
320 &body.motion.pointers[i].coords.values[0],
321 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800322 msg->body.motion.pointers[i].coords.isResampled =
323 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800324 }
325 break;
326 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700327 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800328 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000329 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800330 break;
331 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800332 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800333 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800334 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800335 break;
336 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800337 case InputMessage::Type::CAPTURE: {
338 msg->body.capture.eventId = body.capture.eventId;
339 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
340 break;
341 }
arthurhung7632c332020-12-30 16:58:01 +0800342 case InputMessage::Type::DRAG: {
343 msg->body.drag.eventId = body.drag.eventId;
344 msg->body.drag.x = body.drag.x;
345 msg->body.drag.y = body.drag.y;
346 msg->body.drag.isExiting = body.drag.isExiting;
347 break;
348 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000349 case InputMessage::Type::TIMELINE: {
350 msg->body.timeline.eventId = body.timeline.eventId;
351 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
352 break;
353 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700354 case InputMessage::Type::TOUCH_MODE: {
355 msg->body.touchMode.eventId = body.touchMode.eventId;
356 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
357 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800358 }
359}
Jeff Brown5912f952013-07-01 19:10:31 -0700360
361// --- InputChannel ---
362
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500363std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500364 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700365 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
366 if (result != 0) {
367 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
368 strerror(errno));
369 return nullptr;
370 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500371 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500372 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700373}
374
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500375InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
376 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000377 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
378 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700379}
380
381InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000382 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
383 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700384}
385
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800386status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500387 std::unique_ptr<InputChannel>& outServerChannel,
388 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700389 int sockets[2];
390 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
391 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000392 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
393 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500394 outServerChannel.reset();
395 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700396 return result;
397 }
398
399 int bufferSize = SOCKET_BUFFER_SIZE;
400 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
401 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
402 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
403 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
404
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700405 sp<IBinder> token = new BBinder();
406
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700407 std::string serverChannelName = name + " (server)";
408 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700409 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700410
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700411 std::string clientChannelName = name + " (client)";
412 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700413 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700414 return OK;
415}
416
417status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800418 const size_t msgLength = msg->size();
419 InputMessage cleanMsg;
420 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700421 ssize_t nWrite;
422 do {
Chris Ye0783e992020-06-02 21:34:49 -0700423 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700424 } while (nWrite == -1 && errno == EINTR);
425
426 if (nWrite < 0) {
427 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000428 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
429 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700430 if (error == EAGAIN || error == EWOULDBLOCK) {
431 return WOULD_BLOCK;
432 }
433 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
434 return DEAD_OBJECT;
435 }
436 return -error;
437 }
438
439 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000440 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
441 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
442 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700443 return DEAD_OBJECT;
444 }
445
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000446 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
447 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700448 return OK;
449}
450
451status_t InputChannel::receiveMessage(InputMessage* msg) {
452 ssize_t nRead;
453 do {
Chris Ye0783e992020-06-02 21:34:49 -0700454 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700455 } while (nRead == -1 && errno == EINTR);
456
457 if (nRead < 0) {
458 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000459 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
460 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700461 if (error == EAGAIN || error == EWOULDBLOCK) {
462 return WOULD_BLOCK;
463 }
464 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
465 return DEAD_OBJECT;
466 }
467 return -error;
468 }
469
470 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000471 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
472 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700473 return DEAD_OBJECT;
474 }
475
476 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000477 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700478 return BAD_VALUE;
479 }
480
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000481 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
482 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700483 return OK;
484}
485
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500486std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700487 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700488 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700489}
490
Garfield Tan15601662020-09-22 15:32:38 -0700491void InputChannel::copyTo(InputChannel& outChannel) const {
492 outChannel.mName = getName();
493 outChannel.mFd = dupFd();
494 outChannel.mToken = getConnectionToken();
495}
496
Chris Ye0783e992020-06-02 21:34:49 -0700497status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500498 if (parcel == nullptr) {
499 ALOGE("%s: Null parcel", __func__);
500 return BAD_VALUE;
501 }
502 return parcel->writeStrongBinder(mToken)
503 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700504}
505
Chris Ye0783e992020-06-02 21:34:49 -0700506status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500507 if (parcel == nullptr) {
508 ALOGE("%s: Null parcel", __func__);
509 return BAD_VALUE;
510 }
511 mToken = parcel->readStrongBinder();
512 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700513}
514
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700515sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500516 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700517}
518
Garfield Tan15601662020-09-22 15:32:38 -0700519base::unique_fd InputChannel::dupFd() const {
520 android::base::unique_fd newFd(::dup(getFd()));
521 if (!newFd.ok()) {
522 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
523 strerror(errno));
524 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
525 // If this process is out of file descriptors, then throwing that might end up exploding
526 // on the other side of a binder call, which isn't really helpful.
527 // Better to just crash here and hope that the FD leak is slow.
528 // Other failures could be client errors, so we still propagate those back to the caller.
529 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
530 getName().c_str());
531 return {};
532 }
533 return newFd;
534}
535
Jeff Brown5912f952013-07-01 19:10:31 -0700536// --- InputPublisher ---
537
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800538InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
539 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700540
541InputPublisher::~InputPublisher() {
542}
543
Garfield Tan1c7bc862020-01-28 13:24:04 -0800544status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
545 int32_t source, int32_t displayId,
546 std::array<uint8_t, 32> hmac, int32_t action,
547 int32_t flags, int32_t keyCode, int32_t scanCode,
548 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
549 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000550 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000551 std::string message =
552 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
553 mChannel->getName().c_str(), KeyEvent::actionToString(action),
554 KeyEvent::getLabel(keyCode));
Michael Wright3dd60e22019-03-27 22:06:44 +0000555 ATRACE_NAME(message.c_str());
556 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000557 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000558 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000559 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
560 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000561 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000562 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
563 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700564
565 if (!seq) {
566 ALOGE("Attempted to publish a key event with sequence number 0.");
567 return BAD_VALUE;
568 }
569
570 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700571 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500572 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800573 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700574 msg.body.key.deviceId = deviceId;
575 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100576 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700577 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700578 msg.body.key.action = action;
579 msg.body.key.flags = flags;
580 msg.body.key.keyCode = keyCode;
581 msg.body.key.scanCode = scanCode;
582 msg.body.key.metaState = metaState;
583 msg.body.key.repeatCount = repeatCount;
584 msg.body.key.downTime = downTime;
585 msg.body.key.eventTime = eventTime;
586 return mChannel->sendMessage(&msg);
587}
588
589status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800590 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600591 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
592 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700593 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700594 float yPrecision, float xCursorPosition, float yCursorPosition,
595 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700596 uint32_t pointerCount, const PointerProperties* pointerProperties,
597 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000598 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000599 std::string message = StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
600 mChannel->getName().c_str(),
601 MotionEvent::actionToString(action).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +0000602 ATRACE_NAME(message.c_str());
603 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800604 if (verifyEvents()) {
605 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
606 pointerCoords, flags);
607 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000608 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700609 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700610 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000611 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800612 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000613 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700614 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800615 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700616 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000617 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000618 inputEventSourceToString(source).c_str(), displayId,
619 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
620 metaState, buttonState, motionClassificationToString(classification), xPrecision,
621 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800622 }
Jeff Brown5912f952013-07-01 19:10:31 -0700623
624 if (!seq) {
625 ALOGE("Attempted to publish a motion event with sequence number 0.");
626 return BAD_VALUE;
627 }
628
629 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700630 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800631 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700632 return BAD_VALUE;
633 }
634
635 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700636 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500637 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800638 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700639 msg.body.motion.deviceId = deviceId;
640 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700641 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700642 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700643 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100644 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700645 msg.body.motion.flags = flags;
646 msg.body.motion.edgeFlags = edgeFlags;
647 msg.body.motion.metaState = metaState;
648 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800649 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700650 msg.body.motion.dsdx = transform.dsdx();
651 msg.body.motion.dtdx = transform.dtdx();
652 msg.body.motion.dtdy = transform.dtdy();
653 msg.body.motion.dsdy = transform.dsdy();
654 msg.body.motion.tx = transform.tx();
655 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700656 msg.body.motion.xPrecision = xPrecision;
657 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700658 msg.body.motion.xCursorPosition = xCursorPosition;
659 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700660 msg.body.motion.dsdxRaw = rawTransform.dsdx();
661 msg.body.motion.dtdxRaw = rawTransform.dtdx();
662 msg.body.motion.dtdyRaw = rawTransform.dtdy();
663 msg.body.motion.dsdyRaw = rawTransform.dsdy();
664 msg.body.motion.txRaw = rawTransform.tx();
665 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700666 msg.body.motion.downTime = downTime;
667 msg.body.motion.eventTime = eventTime;
668 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100669 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700670 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
671 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
672 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700673
Jeff Brown5912f952013-07-01 19:10:31 -0700674 return mChannel->sendMessage(&msg);
675}
676
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700677status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800678 if (ATRACE_ENABLED()) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700679 std::string message = StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
680 mChannel->getName().c_str(), toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800681 ATRACE_NAME(message.c_str());
682 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000683 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
684 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800685
686 InputMessage msg;
687 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500688 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800689 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000690 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800691 return mChannel->sendMessage(&msg);
692}
693
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800694status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
695 bool pointerCaptureEnabled) {
696 if (ATRACE_ENABLED()) {
697 std::string message =
698 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
699 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
700 ATRACE_NAME(message.c_str());
701 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000702 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000703 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
704 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800705
706 InputMessage msg;
707 msg.header.type = InputMessage::Type::CAPTURE;
708 msg.header.seq = seq;
709 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000710 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800711 return mChannel->sendMessage(&msg);
712}
713
arthurhung7632c332020-12-30 16:58:01 +0800714status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
715 bool isExiting) {
716 if (ATRACE_ENABLED()) {
717 std::string message =
718 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
719 mChannel->getName().c_str(), x, y, toString(isExiting));
720 ATRACE_NAME(message.c_str());
721 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000722 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000723 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
724 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800725
726 InputMessage msg;
727 msg.header.type = InputMessage::Type::DRAG;
728 msg.header.seq = seq;
729 msg.body.drag.eventId = eventId;
730 msg.body.drag.isExiting = isExiting;
731 msg.body.drag.x = x;
732 msg.body.drag.y = y;
733 return mChannel->sendMessage(&msg);
734}
735
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700736status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
737 if (ATRACE_ENABLED()) {
738 std::string message =
739 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
740 mChannel->getName().c_str(), toString(isInTouchMode));
741 ATRACE_NAME(message.c_str());
742 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000743 ALOGD_IF(debugTransportPublisher(),
744 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
745 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700746
747 InputMessage msg;
748 msg.header.type = InputMessage::Type::TOUCH_MODE;
749 msg.header.seq = seq;
750 msg.body.touchMode.eventId = eventId;
751 msg.body.touchMode.isInTouchMode = isInTouchMode;
752 return mChannel->sendMessage(&msg);
753}
754
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000755android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700756 InputMessage msg;
757 status_t result = mChannel->receiveMessage(&msg);
758 if (result) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000759 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: %s",
760 mChannel->getName().c_str(), __func__, strerror(result));
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000761 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700762 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000763 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000764 ALOGD_IF(debugTransportPublisher(),
765 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
766 mChannel->getName().c_str(), __func__, msg.header.seq,
767 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000768 return Finished{
769 .seq = msg.header.seq,
770 .handled = msg.body.finished.handled,
771 .consumeTime = msg.body.finished.consumeTime,
772 };
Jeff Brown5912f952013-07-01 19:10:31 -0700773 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000774
775 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000776 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
777 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000778 return Timeline{
779 .inputEventId = msg.body.timeline.eventId,
780 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
781 };
782 }
783
784 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800785 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000786 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700787}
788
789// --- InputConsumer ---
790
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500791InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800792 : InputConsumer(channel, isTouchResamplingEnabled()) {}
793
794InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
795 bool enableTouchResampling)
796 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700797
798InputConsumer::~InputConsumer() {
799}
800
801bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600802 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700803}
804
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800805status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
806 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000807 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
808 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
809 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700810
811 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700812 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700813
814 // Fetch the next input message.
815 // Loop until an event can be returned or no additional events are received.
816 while (!*outEvent) {
817 if (mMsgDeferred) {
818 // mMsg contains a valid input message from the previous call to consume
819 // that has not yet been processed.
820 mMsgDeferred = false;
821 } else {
822 // Receive a fresh message.
823 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000824 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800825 const auto [_, inserted] =
826 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
827 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
828 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000829 }
Jeff Brown5912f952013-07-01 19:10:31 -0700830 if (result) {
831 // Consume the next batched event unless batches are being held for later.
832 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800833 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700834 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000835 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
836 "channel '%s' consumer ~ consumed batch event, seq=%u",
837 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700838 break;
839 }
840 }
841 return result;
842 }
843 }
844
845 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700846 case InputMessage::Type::KEY: {
847 KeyEvent* keyEvent = factory->createKeyEvent();
848 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700849
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700850 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500851 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700852 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000853 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
854 "channel '%s' consumer ~ consumed key event, seq=%u",
855 mChannel->getName().c_str(), *outSeq);
856 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700857 }
Jeff Brown5912f952013-07-01 19:10:31 -0700858
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700859 case InputMessage::Type::MOTION: {
860 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
861 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500862 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700863 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500864 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000865 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
866 "channel '%s' consumer ~ appended to batch event",
867 mChannel->getName().c_str());
868 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700869 } else if (isPointerEvent(mMsg.body.motion.source) &&
870 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
871 // No need to process events that we are going to cancel anyways
872 const size_t count = batch.samples.size();
873 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500874 const InputMessage& msg = batch.samples[i];
875 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700876 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500877 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
878 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700879 } else {
880 // We cannot append to the batch in progress, so we need to consume
881 // the previous batch right now and defer the new message until later.
882 mMsgDeferred = true;
883 status_t result = consumeSamples(factory, batch, batch.samples.size(),
884 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500885 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700886 if (result) {
887 return result;
888 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000889 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
890 "channel '%s' consumer ~ consumed batch event and "
891 "deferred current event, seq=%u",
892 mChannel->getName().c_str(), *outSeq);
893 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700894 }
Jeff Brown5912f952013-07-01 19:10:31 -0700895 }
Jeff Brown5912f952013-07-01 19:10:31 -0700896
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800897 // Start a new batch if needed.
898 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
899 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500900 Batch batch;
901 batch.samples.push_back(mMsg);
902 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000903 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
904 "channel '%s' consumer ~ started batch event",
905 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800906 break;
907 }
Jeff Brown5912f952013-07-01 19:10:31 -0700908
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800909 MotionEvent* motionEvent = factory->createMotionEvent();
910 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700911
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800912 updateTouchState(mMsg);
913 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500914 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800915 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800916
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000917 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
918 "channel '%s' consumer ~ consumed motion event, seq=%u",
919 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800920 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700921 }
Jeff Brown5912f952013-07-01 19:10:31 -0700922
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000923 case InputMessage::Type::FINISHED:
924 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000925 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
926 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800927 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800928 break;
929 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800930
931 case InputMessage::Type::FOCUS: {
932 FocusEvent* focusEvent = factory->createFocusEvent();
933 if (!focusEvent) return NO_MEMORY;
934
935 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500936 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800937 *outEvent = focusEvent;
938 break;
939 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800940
941 case InputMessage::Type::CAPTURE: {
942 CaptureEvent* captureEvent = factory->createCaptureEvent();
943 if (!captureEvent) return NO_MEMORY;
944
945 initializeCaptureEvent(captureEvent, &mMsg);
946 *outSeq = mMsg.header.seq;
947 *outEvent = captureEvent;
948 break;
949 }
arthurhung7632c332020-12-30 16:58:01 +0800950
951 case InputMessage::Type::DRAG: {
952 DragEvent* dragEvent = factory->createDragEvent();
953 if (!dragEvent) return NO_MEMORY;
954
955 initializeDragEvent(dragEvent, &mMsg);
956 *outSeq = mMsg.header.seq;
957 *outEvent = dragEvent;
958 break;
959 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700960
961 case InputMessage::Type::TOUCH_MODE: {
962 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
963 if (!touchModeEvent) return NO_MEMORY;
964
965 initializeTouchModeEvent(touchModeEvent, &mMsg);
966 *outSeq = mMsg.header.seq;
967 *outEvent = touchModeEvent;
968 break;
969 }
Jeff Brown5912f952013-07-01 19:10:31 -0700970 }
971 }
972 return OK;
973}
974
975status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800976 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700977 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700978 for (size_t i = mBatches.size(); i > 0; ) {
979 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500980 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700981 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800982 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500983 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700984 return result;
985 }
986
Michael Wright32232172013-10-21 12:05:22 -0700987 nsecs_t sampleTime = frameTime;
988 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800989 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -0700990 }
Jeff Brown5912f952013-07-01 19:10:31 -0700991 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
992 if (split < 0) {
993 continue;
994 }
995
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800996 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700997 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500998 if (batch.samples.empty()) {
999 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001000 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001001 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001002 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001003 }
Michael Wright32232172013-10-21 12:05:22 -07001004 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001005 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1006 }
1007 return result;
1008 }
1009
1010 return WOULD_BLOCK;
1011}
1012
1013status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001014 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001015 MotionEvent* motionEvent = factory->createMotionEvent();
1016 if (! motionEvent) return NO_MEMORY;
1017
1018 uint32_t chain = 0;
1019 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001020 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001021 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001022 if (i) {
1023 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001024 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001025 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001026 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001027 addSample(motionEvent, &msg);
1028 } else {
1029 initializeMotionEvent(motionEvent, &msg);
1030 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001031 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001032 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001033 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001034
1035 *outSeq = chain;
1036 *outEvent = motionEvent;
1037 return OK;
1038}
1039
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001040void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001041 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001042 return;
1043 }
1044
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001045 int32_t deviceId = msg.body.motion.deviceId;
1046 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001047
1048 // Update the touch state history to incorporate the new input message.
1049 // If the message is in the past relative to the most recently produced resampled
1050 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001051 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001052 case AMOTION_EVENT_ACTION_DOWN: {
1053 ssize_t index = findTouchState(deviceId, source);
1054 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001055 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001056 index = mTouchStates.size() - 1;
1057 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001058 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001059 touchState.initialize(deviceId, source);
1060 touchState.addHistory(msg);
1061 break;
1062 }
1063
1064 case AMOTION_EVENT_ACTION_MOVE: {
1065 ssize_t index = findTouchState(deviceId, source);
1066 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001067 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001068 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001069 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001070 }
1071 break;
1072 }
1073
1074 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1075 ssize_t index = findTouchState(deviceId, source);
1076 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001077 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001078 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001079 rewriteMessage(touchState, msg);
1080 }
1081 break;
1082 }
1083
1084 case AMOTION_EVENT_ACTION_POINTER_UP: {
1085 ssize_t index = findTouchState(deviceId, source);
1086 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001087 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001088 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001089 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001090 }
1091 break;
1092 }
1093
1094 case AMOTION_EVENT_ACTION_SCROLL: {
1095 ssize_t index = findTouchState(deviceId, source);
1096 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001097 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001098 rewriteMessage(touchState, msg);
1099 }
1100 break;
1101 }
1102
1103 case AMOTION_EVENT_ACTION_UP:
1104 case AMOTION_EVENT_ACTION_CANCEL: {
1105 ssize_t index = findTouchState(deviceId, source);
1106 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001107 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001108 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001109 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001110 }
1111 break;
1112 }
1113 }
1114}
1115
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001116/**
1117 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1118 *
1119 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1120 * is in the past relative to msg and the past two events do not contain identical coordinates),
1121 * then invalidate the lastResample data for that pointer.
1122 * If the two past events have identical coordinates, then lastResample data for that pointer will
1123 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1124 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1125 * not equal to x0 is received.
1126 */
1127void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001128 nsecs_t eventTime = msg.body.motion.eventTime;
1129 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1130 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001131 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001132 if (eventTime < state.lastResample.eventTime ||
1133 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001134 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1135 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001136 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1137 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1138 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001139 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1140 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001141 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001142 } else {
1143 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001144 }
Jeff Brown5912f952013-07-01 19:10:31 -07001145 }
1146 }
1147}
1148
1149void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1150 const InputMessage* next) {
1151 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001152 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001153 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1154 return;
1155 }
1156
1157 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1158 if (index < 0) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001159 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001160 return;
1161 }
1162
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001163 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001164 if (touchState.historySize < 1) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001165 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001166 return;
1167 }
1168
1169 // Ensure that the current sample has all of the pointers that need to be reported.
1170 const History* current = touchState.getHistory(0);
1171 size_t pointerCount = event->getPointerCount();
1172 for (size_t i = 0; i < pointerCount; i++) {
1173 uint32_t id = event->getPointerId(i);
1174 if (!current->idBits.hasBit(id)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001175 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001176 return;
1177 }
1178 }
1179
1180 // Find the data to use for resampling.
1181 const History* other;
1182 History future;
1183 float alpha;
1184 if (next) {
1185 // Interpolate between current sample and future sample.
1186 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001187 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001188 other = &future;
1189 nsecs_t delta = future.eventTime - current->eventTime;
1190 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001191 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1192 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001193 return;
1194 }
1195 alpha = float(sampleTime - current->eventTime) / delta;
1196 } else if (touchState.historySize >= 2) {
1197 // Extrapolate future sample using current sample and past sample.
1198 // So other->eventTime <= current->eventTime <= sampleTime.
1199 other = touchState.getHistory(1);
1200 nsecs_t delta = current->eventTime - other->eventTime;
1201 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001202 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1203 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001204 return;
1205 } else if (delta > RESAMPLE_MAX_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001206 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too large: %" PRId64 " ns.",
1207 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001208 return;
1209 }
1210 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1211 if (sampleTime > maxPredict) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001212 ALOGD_IF(DEBUG_RESAMPLING,
1213 "Sample time is too far in the future, adjusting prediction "
1214 "from %" PRId64 " to %" PRId64 " ns.",
1215 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001216 sampleTime = maxPredict;
1217 }
1218 alpha = float(current->eventTime - sampleTime) / delta;
1219 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001220 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001221 return;
1222 }
1223
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001224 if (current->eventTime == sampleTime) {
1225 // Prevents having 2 events with identical times and coordinates.
1226 return;
1227 }
1228
Jeff Brown5912f952013-07-01 19:10:31 -07001229 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001230 History oldLastResample;
1231 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001232 touchState.lastResample.eventTime = sampleTime;
1233 touchState.lastResample.idBits.clear();
1234 for (size_t i = 0; i < pointerCount; i++) {
1235 uint32_t id = event->getPointerId(i);
1236 touchState.lastResample.idToIndex[id] = i;
1237 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001238 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1239 // We maintain the previously resampled value for this pointer (stored in
1240 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1241 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001242 // The isResampled flag isn't cleared as the values don't reflect what the device is
1243 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001244
1245 // We know here that the coordinates for the pointer haven't changed because we
1246 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1247 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1248 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1249 continue;
1250 }
1251
Jeff Brown5912f952013-07-01 19:10:31 -07001252 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1253 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001254 resampledCoords.copyFrom(currentCoords);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001255 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001256 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001257 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001258 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001259 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001260 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001261 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001262 ALOGD_IF(DEBUG_RESAMPLING,
1263 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1264 "other (%0.3f, %0.3f), alpha %0.3f",
1265 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1266 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001267 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001268 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
1269 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1270 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001271 }
1272 }
1273
1274 event->addSample(sampleTime, touchState.lastResample.pointers);
1275}
1276
1277bool InputConsumer::shouldResampleTool(int32_t toolType) {
1278 return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
1279 || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1280}
1281
1282status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001283 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1284 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1285 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001286
1287 if (!seq) {
1288 ALOGE("Attempted to send a finished signal with sequence number 0.");
1289 return BAD_VALUE;
1290 }
1291
1292 // Send finished signals for the batch sequence chain first.
1293 size_t seqChainCount = mSeqChains.size();
1294 if (seqChainCount) {
1295 uint32_t currentSeq = seq;
1296 uint32_t chainSeqs[seqChainCount];
1297 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001298 for (size_t i = seqChainCount; i > 0; ) {
1299 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001300 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001301 if (seqChain.seq == currentSeq) {
1302 currentSeq = seqChain.chain;
1303 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001304 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001305 }
1306 }
1307 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001308 while (!status && chainIndex > 0) {
1309 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001310 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1311 }
1312 if (status) {
1313 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001314 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001315 SeqChain seqChain;
1316 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1317 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001318 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001319 if (!chainIndex) break;
1320 chainIndex--;
1321 }
Jeff Brown5912f952013-07-01 19:10:31 -07001322 return status;
1323 }
1324 }
1325
1326 // Send finished signal for the last message in the batch.
1327 return sendUnchainedFinishedSignal(seq, handled);
1328}
1329
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001330status_t InputConsumer::sendTimeline(int32_t inputEventId,
1331 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001332 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1333 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1334 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1335 mChannel->getName().c_str(), inputEventId,
1336 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1337 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001338
1339 InputMessage msg;
1340 msg.header.type = InputMessage::Type::TIMELINE;
1341 msg.header.seq = 0;
1342 msg.body.timeline.eventId = inputEventId;
1343 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1344 return mChannel->sendMessage(&msg);
1345}
1346
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001347nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1348 auto it = mConsumeTimes.find(seq);
1349 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1350 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1351 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1352 seq);
1353 return it->second;
1354}
1355
1356void InputConsumer::popConsumeTime(uint32_t seq) {
1357 mConsumeTimes.erase(seq);
1358}
1359
Jeff Brown5912f952013-07-01 19:10:31 -07001360status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1361 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001362 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001363 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001364 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001365 msg.body.finished.consumeTime = getConsumeTime(seq);
1366 status_t result = mChannel->sendMessage(&msg);
1367 if (result == OK) {
1368 // Remove the consume time if the socket write succeeded. We will not need to ack this
1369 // message anymore. If the socket write did not succeed, we will try again and will still
1370 // need consume time.
1371 popConsumeTime(seq);
1372 }
1373 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001374}
1375
Jeff Brown5912f952013-07-01 19:10:31 -07001376bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001377 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001378}
1379
Arthur Hungc7812be2020-02-27 22:40:27 +08001380int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001381 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001382 return AINPUT_SOURCE_CLASS_NONE;
1383 }
1384
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001385 const Batch& batch = mBatches[0];
1386 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001387 return head.body.motion.source;
1388}
1389
Jeff Brown5912f952013-07-01 19:10:31 -07001390ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1391 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001392 const Batch& batch = mBatches[i];
1393 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001394 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1395 return i;
1396 }
1397 }
1398 return -1;
1399}
1400
1401ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1402 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001403 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001404 if (touchState.deviceId == deviceId && touchState.source == source) {
1405 return i;
1406 }
1407 }
1408 return -1;
1409}
1410
1411void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001412 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001413 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1414 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1415 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1416 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001417}
1418
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001419void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001420 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001421}
1422
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001423void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001424 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001425}
1426
arthurhung7632c332020-12-30 16:58:01 +08001427void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1428 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1429 msg->body.drag.isExiting);
1430}
1431
Jeff Brown5912f952013-07-01 19:10:31 -07001432void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001433 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001434 PointerProperties pointerProperties[pointerCount];
1435 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001436 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001437 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1438 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1439 }
1440
chaviw9eaa22c2020-07-01 16:21:27 -07001441 ui::Transform transform;
1442 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1443 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001444 ui::Transform displayTransform;
1445 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1446 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1447 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001448 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1449 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1450 msg->body.motion.actionButton, msg->body.motion.flags,
1451 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001452 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1453 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1454 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001455 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1456 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001457}
1458
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001459void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1460 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1461}
1462
Jeff Brown5912f952013-07-01 19:10:31 -07001463void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001464 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001465 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001466 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001467 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1468 }
1469
1470 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1471 event->addSample(msg->body.motion.eventTime, pointerCoords);
1472}
1473
1474bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001475 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001476 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001477 if (head.body.motion.pointerCount != pointerCount
1478 || head.body.motion.action != msg->body.motion.action) {
1479 return false;
1480 }
1481 for (size_t i = 0; i < pointerCount; i++) {
1482 if (head.body.motion.pointers[i].properties
1483 != msg->body.motion.pointers[i].properties) {
1484 return false;
1485 }
1486 }
1487 return true;
1488}
1489
1490ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1491 size_t numSamples = batch.samples.size();
1492 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001493 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001494 index += 1;
1495 }
1496 return ssize_t(index) - 1;
1497}
1498
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001499std::string InputConsumer::dump() const {
1500 std::string out;
1501 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1502 out = out + "mChannel = " + mChannel->getName() + "\n";
1503 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1504 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001505 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001506 }
1507 out += "Batches:\n";
1508 for (const Batch& batch : mBatches) {
1509 out += " Batch:\n";
1510 for (const InputMessage& msg : batch.samples) {
1511 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001512 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001513 switch (msg.header.type) {
1514 case InputMessage::Type::KEY: {
1515 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1516 KeyEvent::actionToString(
1517 msg.body.key.action),
1518 msg.body.key.keyCode);
1519 break;
1520 }
1521 case InputMessage::Type::MOTION: {
1522 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1523 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1524 const float x = msg.body.motion.pointers[i].coords.getX();
1525 const float y = msg.body.motion.pointers[i].coords.getY();
1526 out += android::base::StringPrintf("\n Pointer %" PRIu32
1527 " : x=%.1f y=%.1f",
1528 i, x, y);
1529 }
1530 break;
1531 }
1532 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001533 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1534 toString(msg.body.finished.handled),
1535 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001536 break;
1537 }
1538 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001539 out += android::base::StringPrintf("hasFocus=%s",
1540 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001541 break;
1542 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001543 case InputMessage::Type::CAPTURE: {
1544 out += android::base::StringPrintf("hasCapture=%s",
1545 toString(msg.body.capture
1546 .pointerCaptureEnabled));
1547 break;
1548 }
arthurhung7632c332020-12-30 16:58:01 +08001549 case InputMessage::Type::DRAG: {
1550 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1551 msg.body.drag.x, msg.body.drag.y,
1552 toString(msg.body.drag.isExiting));
1553 break;
1554 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001555 case InputMessage::Type::TIMELINE: {
1556 const nsecs_t gpuCompletedTime =
1557 msg.body.timeline
1558 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1559 const nsecs_t presentTime =
1560 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1561 out += android::base::StringPrintf("inputEventId=%" PRId32
1562 ", gpuCompletedTime=%" PRId64
1563 ", presentTime=%" PRId64,
1564 msg.body.timeline.eventId, gpuCompletedTime,
1565 presentTime);
1566 break;
1567 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001568 case InputMessage::Type::TOUCH_MODE: {
1569 out += android::base::StringPrintf("isInTouchMode=%s",
1570 toString(msg.body.touchMode.isInTouchMode));
1571 break;
1572 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001573 }
1574 out += "\n";
1575 }
1576 }
1577 if (mBatches.empty()) {
1578 out += " <empty>\n";
1579 }
1580 out += "mSeqChains:\n";
1581 for (const SeqChain& chain : mSeqChains) {
1582 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1583 chain.chain);
1584 }
1585 if (mSeqChains.empty()) {
1586 out += " <empty>\n";
1587 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001588 out += "mConsumeTimes:\n";
1589 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1590 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1591 consumeTime);
1592 }
1593 if (mConsumeTimes.empty()) {
1594 out += " <empty>\n";
1595 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001596 return out;
1597}
1598
Jeff Brown5912f952013-07-01 19:10:31 -07001599} // namespace android