blob: 4ecb6419bec0c5985e651bebab541d9b91b23c3b [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"
Zimd8402b62023-06-02 11:56:26 +01007#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown5912f952013-07-01 19:10:31 -07008
Jeff Brown5912f952013-07-01 19:10:31 -07009#include <errno.h>
10#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070011#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070012#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070013#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070014#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070015#include <unistd.h>
16
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000017#include <android-base/properties.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000018#include <android-base/stringprintf.h>
19#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070020#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080021#include <ftl/enum.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070022#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000023#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070024
Jeff Brown5912f952013-07-01 19:10:31 -070025#include <input/InputTransport.h>
26
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000027namespace {
28
29/**
30 * Log debug messages about channel messages (send message, receive message).
31 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
32 * (requires restart)
33 */
34const bool DEBUG_CHANNEL_MESSAGES =
35 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
36
37/**
38 * Log debug messages whenever InputChannel objects are created/destroyed.
39 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
40 * (requires restart)
41 */
42const bool DEBUG_CHANNEL_LIFECYCLE =
43 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
44
45/**
46 * Log debug messages relating to the consumer end of the transport channel.
47 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
48 */
49
50const bool DEBUG_TRANSPORT_CONSUMER =
51 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
52
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000053const bool IS_DEBUGGABLE_BUILD =
54#if defined(__ANDROID__)
55 android::base::GetBoolProperty("ro.debuggable", false);
56#else
57 true;
58#endif
59
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000060/**
61 * Log debug messages relating to the producer end of the transport channel.
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000062 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
63 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
64 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000065 */
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000066bool debugTransportPublisher() {
67 if (!IS_DEBUGGABLE_BUILD) {
68 static const bool DEBUG_TRANSPORT_PUBLISHER =
69 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
70 return DEBUG_TRANSPORT_PUBLISHER;
71 }
72 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
73}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000074
75/**
76 * Log debug messages about touch event resampling.
77 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG" (requires restart)
78 */
79const bool DEBUG_RESAMPLING =
80 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
81
82} // namespace
83
Michael Wright3dd60e22019-03-27 22:06:44 +000084using android::base::StringPrintf;
85
Jeff Brown5912f952013-07-01 19:10:31 -070086namespace android {
87
88// Socket buffer size. The default is typically about 128KB, which is much larger than
89// we really need. So we make it smaller. It just needs to be big enough to hold
90// a few dozen large multi-finger motion events in the case where an application gets
91// behind processing touches.
92static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
93
94// Nanoseconds per milliseconds.
95static const nsecs_t NANOS_PER_MS = 1000000;
96
97// Latency added during resampling. A few milliseconds doesn't hurt much but
98// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -080099const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -0700100
101// Minimum time difference between consecutive samples before attempting to resample.
102static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
103
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700104// Maximum time difference between consecutive samples before attempting to resample
105// by extrapolation.
106static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
107
Jeff Brown5912f952013-07-01 19:10:31 -0700108// Maximum time to predict forward from the last known state, to avoid predicting too
109// far into the future. This time is further bounded by 50% of the last time delta.
110static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
111
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600112/**
113 * System property for enabling / disabling touch resampling.
114 * Resampling extrapolates / interpolates the reported touch event coordinates to better
115 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
116 * Resampling is not needed (and should be disabled) on hardware that already
117 * has touch events triggered by VSYNC.
118 * Set to "1" to enable resampling (default).
119 * Set to "0" to disable resampling.
120 * Resampling is enabled by default.
121 */
122static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
123
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800124/**
125 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
126 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
127 */
128static bool verifyEvents() {
129 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
130}
131
Jeff Brown5912f952013-07-01 19:10:31 -0700132template<typename T>
133inline static T min(const T& a, const T& b) {
134 return a < b ? a : b;
135}
136
137inline static float lerp(float a, float b, float alpha) {
138 return a + alpha * (b - a);
139}
140
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800141inline static bool isPointerEvent(int32_t source) {
142 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
143}
144
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800145inline static const char* toString(bool value) {
146 return value ? "true" : "false";
147}
148
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700149static bool shouldResampleTool(ToolType toolType) {
150 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
151}
152
Jeff Brown5912f952013-07-01 19:10:31 -0700153// --- InputMessage ---
154
155bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000156 if (size() != actualSize) {
157 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
158 return false;
159 }
160
161 switch (header.type) {
162 case Type::KEY:
163 return true;
164 case Type::MOTION: {
165 const bool valid =
166 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
167 if (!valid) {
168 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
169 }
170 return valid;
171 }
172 case Type::FINISHED:
173 case Type::FOCUS:
174 case Type::CAPTURE:
175 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700176 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000177 return true;
178 case Type::TIMELINE: {
179 const nsecs_t gpuCompletedTime =
180 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
181 const nsecs_t presentTime =
182 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
183 const bool valid = presentTime > gpuCompletedTime;
184 if (!valid) {
185 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
186 " presentTime = %" PRId64,
187 gpuCompletedTime, presentTime);
188 }
189 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700190 }
191 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000192 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700193 return false;
194}
195
196size_t InputMessage::size() const {
197 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700198 case Type::KEY:
199 return sizeof(Header) + body.key.size();
200 case Type::MOTION:
201 return sizeof(Header) + body.motion.size();
202 case Type::FINISHED:
203 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800204 case Type::FOCUS:
205 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800206 case Type::CAPTURE:
207 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800208 case Type::DRAG:
209 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000210 case Type::TIMELINE:
211 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700212 case Type::TOUCH_MODE:
213 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700214 }
215 return sizeof(Header);
216}
217
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800218/**
219 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
220 * memory to zero, then only copy the valid bytes on a per-field basis.
221 */
222void InputMessage::getSanitizedCopy(InputMessage* msg) const {
223 memset(msg, 0, sizeof(*msg));
224
225 // Write the header
226 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500227 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800228
229 // Write the body
230 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700231 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800232 // int32_t eventId
233 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800234 // nsecs_t eventTime
235 msg->body.key.eventTime = body.key.eventTime;
236 // int32_t deviceId
237 msg->body.key.deviceId = body.key.deviceId;
238 // int32_t source
239 msg->body.key.source = body.key.source;
240 // int32_t displayId
241 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600242 // std::array<uint8_t, 32> hmac
243 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800244 // int32_t action
245 msg->body.key.action = body.key.action;
246 // int32_t flags
247 msg->body.key.flags = body.key.flags;
248 // int32_t keyCode
249 msg->body.key.keyCode = body.key.keyCode;
250 // int32_t scanCode
251 msg->body.key.scanCode = body.key.scanCode;
252 // int32_t metaState
253 msg->body.key.metaState = body.key.metaState;
254 // int32_t repeatCount
255 msg->body.key.repeatCount = body.key.repeatCount;
256 // nsecs_t downTime
257 msg->body.key.downTime = body.key.downTime;
258 break;
259 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700260 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800261 // int32_t eventId
262 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700263 // uint32_t pointerCount
264 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800265 // nsecs_t eventTime
266 msg->body.motion.eventTime = body.motion.eventTime;
267 // int32_t deviceId
268 msg->body.motion.deviceId = body.motion.deviceId;
269 // int32_t source
270 msg->body.motion.source = body.motion.source;
271 // int32_t displayId
272 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600273 // std::array<uint8_t, 32> hmac
274 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800275 // int32_t action
276 msg->body.motion.action = body.motion.action;
277 // int32_t actionButton
278 msg->body.motion.actionButton = body.motion.actionButton;
279 // int32_t flags
280 msg->body.motion.flags = body.motion.flags;
281 // int32_t metaState
282 msg->body.motion.metaState = body.motion.metaState;
283 // int32_t buttonState
284 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800285 // MotionClassification classification
286 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800287 // int32_t edgeFlags
288 msg->body.motion.edgeFlags = body.motion.edgeFlags;
289 // nsecs_t downTime
290 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700291
292 msg->body.motion.dsdx = body.motion.dsdx;
293 msg->body.motion.dtdx = body.motion.dtdx;
294 msg->body.motion.dtdy = body.motion.dtdy;
295 msg->body.motion.dsdy = body.motion.dsdy;
296 msg->body.motion.tx = body.motion.tx;
297 msg->body.motion.ty = body.motion.ty;
298
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800299 // float xPrecision
300 msg->body.motion.xPrecision = body.motion.xPrecision;
301 // float yPrecision
302 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700303 // float xCursorPosition
304 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
305 // float yCursorPosition
306 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700307
308 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
309 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
310 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
311 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
312 msg->body.motion.txRaw = body.motion.txRaw;
313 msg->body.motion.tyRaw = body.motion.tyRaw;
314
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800315 //struct Pointer pointers[MAX_POINTERS]
316 for (size_t i = 0; i < body.motion.pointerCount; i++) {
317 // PointerProperties properties
318 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
319 msg->body.motion.pointers[i].properties.toolType =
320 body.motion.pointers[i].properties.toolType,
321 // PointerCoords coords
322 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
323 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
324 memcpy(&msg->body.motion.pointers[i].coords.values[0],
325 &body.motion.pointers[i].coords.values[0],
326 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800327 msg->body.motion.pointers[i].coords.isResampled =
328 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800329 }
330 break;
331 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700332 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800333 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000334 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800335 break;
336 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800337 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800338 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800339 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800340 break;
341 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800342 case InputMessage::Type::CAPTURE: {
343 msg->body.capture.eventId = body.capture.eventId;
344 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
345 break;
346 }
arthurhung7632c332020-12-30 16:58:01 +0800347 case InputMessage::Type::DRAG: {
348 msg->body.drag.eventId = body.drag.eventId;
349 msg->body.drag.x = body.drag.x;
350 msg->body.drag.y = body.drag.y;
351 msg->body.drag.isExiting = body.drag.isExiting;
352 break;
353 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000354 case InputMessage::Type::TIMELINE: {
355 msg->body.timeline.eventId = body.timeline.eventId;
356 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
357 break;
358 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700359 case InputMessage::Type::TOUCH_MODE: {
360 msg->body.touchMode.eventId = body.touchMode.eventId;
361 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
362 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800363 }
364}
Jeff Brown5912f952013-07-01 19:10:31 -0700365
366// --- InputChannel ---
367
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500368std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500369 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700370 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
371 if (result != 0) {
372 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
373 strerror(errno));
374 return nullptr;
375 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500376 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500377 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700378}
379
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500380InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
381 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000382 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
383 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700384}
385
386InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000387 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
388 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700389}
390
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800391status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500392 std::unique_ptr<InputChannel>& outServerChannel,
393 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700394 int sockets[2];
395 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
396 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000397 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
398 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500399 outServerChannel.reset();
400 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700401 return result;
402 }
403
404 int bufferSize = SOCKET_BUFFER_SIZE;
405 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
406 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
407 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
408 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
409
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700410 sp<IBinder> token = new BBinder();
411
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700412 std::string serverChannelName = name + " (server)";
413 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700414 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700415
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700416 std::string clientChannelName = name + " (client)";
417 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700418 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700419 return OK;
420}
421
422status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800423 const size_t msgLength = msg->size();
424 InputMessage cleanMsg;
425 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700426 ssize_t nWrite;
427 do {
Chris Ye0783e992020-06-02 21:34:49 -0700428 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700429 } while (nWrite == -1 && errno == EINTR);
430
431 if (nWrite < 0) {
432 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000433 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
434 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700435 if (error == EAGAIN || error == EWOULDBLOCK) {
436 return WOULD_BLOCK;
437 }
438 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
439 return DEAD_OBJECT;
440 }
441 return -error;
442 }
443
444 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000445 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
446 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
447 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700448 return DEAD_OBJECT;
449 }
450
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000451 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
452 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100453
454 if (ATRACE_ENABLED()) {
455 std::string message =
456 StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=0x%" PRIx32 ")",
457 mName.c_str(), msg->header.seq, msg->header.type);
458 ATRACE_NAME(message.c_str());
459 }
Jeff Brown5912f952013-07-01 19:10:31 -0700460 return OK;
461}
462
463status_t InputChannel::receiveMessage(InputMessage* msg) {
464 ssize_t nRead;
465 do {
Chris Ye0783e992020-06-02 21:34:49 -0700466 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700467 } while (nRead == -1 && errno == EINTR);
468
469 if (nRead < 0) {
470 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000471 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
472 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700473 if (error == EAGAIN || error == EWOULDBLOCK) {
474 return WOULD_BLOCK;
475 }
476 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
477 return DEAD_OBJECT;
478 }
479 return -error;
480 }
481
482 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000483 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
484 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700485 return DEAD_OBJECT;
486 }
487
488 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000489 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700490 return BAD_VALUE;
491 }
492
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000493 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
494 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100495
496 if (ATRACE_ENABLED()) {
497 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
498 ", type=0x%" PRIx32 ")",
499 mName.c_str(), msg->header.seq, msg->header.type);
500 ATRACE_NAME(message.c_str());
501 }
Jeff Brown5912f952013-07-01 19:10:31 -0700502 return OK;
503}
504
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500505std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700506 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700507 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700508}
509
Garfield Tan15601662020-09-22 15:32:38 -0700510void InputChannel::copyTo(InputChannel& outChannel) const {
511 outChannel.mName = getName();
512 outChannel.mFd = dupFd();
513 outChannel.mToken = getConnectionToken();
514}
515
Chris Ye0783e992020-06-02 21:34:49 -0700516status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500517 if (parcel == nullptr) {
518 ALOGE("%s: Null parcel", __func__);
519 return BAD_VALUE;
520 }
521 return parcel->writeStrongBinder(mToken)
522 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700523}
524
Chris Ye0783e992020-06-02 21:34:49 -0700525status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500526 if (parcel == nullptr) {
527 ALOGE("%s: Null parcel", __func__);
528 return BAD_VALUE;
529 }
530 mToken = parcel->readStrongBinder();
531 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700532}
533
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700534sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500535 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700536}
537
Garfield Tan15601662020-09-22 15:32:38 -0700538base::unique_fd InputChannel::dupFd() const {
539 android::base::unique_fd newFd(::dup(getFd()));
540 if (!newFd.ok()) {
541 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
542 strerror(errno));
543 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
544 // If this process is out of file descriptors, then throwing that might end up exploding
545 // on the other side of a binder call, which isn't really helpful.
546 // Better to just crash here and hope that the FD leak is slow.
547 // Other failures could be client errors, so we still propagate those back to the caller.
548 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
549 getName().c_str());
550 return {};
551 }
552 return newFd;
553}
554
Jeff Brown5912f952013-07-01 19:10:31 -0700555// --- InputPublisher ---
556
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800557InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
558 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700559
560InputPublisher::~InputPublisher() {
561}
562
Garfield Tan1c7bc862020-01-28 13:24:04 -0800563status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
564 int32_t source, int32_t displayId,
565 std::array<uint8_t, 32> hmac, int32_t action,
566 int32_t flags, int32_t keyCode, int32_t scanCode,
567 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
568 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000569 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000570 std::string message =
571 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
572 mChannel->getName().c_str(), KeyEvent::actionToString(action),
573 KeyEvent::getLabel(keyCode));
Michael Wright3dd60e22019-03-27 22:06:44 +0000574 ATRACE_NAME(message.c_str());
575 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000576 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000577 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000578 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
579 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000580 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000581 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
582 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700583
584 if (!seq) {
585 ALOGE("Attempted to publish a key event with sequence number 0.");
586 return BAD_VALUE;
587 }
588
589 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700590 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500591 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800592 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700593 msg.body.key.deviceId = deviceId;
594 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100595 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700596 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700597 msg.body.key.action = action;
598 msg.body.key.flags = flags;
599 msg.body.key.keyCode = keyCode;
600 msg.body.key.scanCode = scanCode;
601 msg.body.key.metaState = metaState;
602 msg.body.key.repeatCount = repeatCount;
603 msg.body.key.downTime = downTime;
604 msg.body.key.eventTime = eventTime;
605 return mChannel->sendMessage(&msg);
606}
607
608status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800609 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600610 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
611 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700612 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700613 float yPrecision, float xCursorPosition, float yCursorPosition,
614 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700615 uint32_t pointerCount, const PointerProperties* pointerProperties,
616 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000617 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000618 std::string message = StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
619 mChannel->getName().c_str(),
620 MotionEvent::actionToString(action).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +0000621 ATRACE_NAME(message.c_str());
622 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800623 if (verifyEvents()) {
624 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
625 pointerCoords, flags);
626 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000627 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700628 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700629 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000630 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800631 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000632 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700633 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800634 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700635 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000636 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000637 inputEventSourceToString(source).c_str(), displayId,
638 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
639 metaState, buttonState, motionClassificationToString(classification), xPrecision,
640 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800641 }
Jeff Brown5912f952013-07-01 19:10:31 -0700642
643 if (!seq) {
644 ALOGE("Attempted to publish a motion event with sequence number 0.");
645 return BAD_VALUE;
646 }
647
648 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700649 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800650 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700651 return BAD_VALUE;
652 }
653
654 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700655 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500656 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800657 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700658 msg.body.motion.deviceId = deviceId;
659 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700660 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700661 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700662 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100663 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700664 msg.body.motion.flags = flags;
665 msg.body.motion.edgeFlags = edgeFlags;
666 msg.body.motion.metaState = metaState;
667 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800668 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700669 msg.body.motion.dsdx = transform.dsdx();
670 msg.body.motion.dtdx = transform.dtdx();
671 msg.body.motion.dtdy = transform.dtdy();
672 msg.body.motion.dsdy = transform.dsdy();
673 msg.body.motion.tx = transform.tx();
674 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700675 msg.body.motion.xPrecision = xPrecision;
676 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700677 msg.body.motion.xCursorPosition = xCursorPosition;
678 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700679 msg.body.motion.dsdxRaw = rawTransform.dsdx();
680 msg.body.motion.dtdxRaw = rawTransform.dtdx();
681 msg.body.motion.dtdyRaw = rawTransform.dtdy();
682 msg.body.motion.dsdyRaw = rawTransform.dsdy();
683 msg.body.motion.txRaw = rawTransform.tx();
684 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700685 msg.body.motion.downTime = downTime;
686 msg.body.motion.eventTime = eventTime;
687 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100688 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700689 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
690 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
691 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700692
Jeff Brown5912f952013-07-01 19:10:31 -0700693 return mChannel->sendMessage(&msg);
694}
695
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700696status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800697 if (ATRACE_ENABLED()) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700698 std::string message = StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
699 mChannel->getName().c_str(), toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800700 ATRACE_NAME(message.c_str());
701 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000702 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
703 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800704
705 InputMessage msg;
706 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500707 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800708 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000709 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800710 return mChannel->sendMessage(&msg);
711}
712
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800713status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
714 bool pointerCaptureEnabled) {
715 if (ATRACE_ENABLED()) {
716 std::string message =
717 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
718 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
719 ATRACE_NAME(message.c_str());
720 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000721 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000722 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
723 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800724
725 InputMessage msg;
726 msg.header.type = InputMessage::Type::CAPTURE;
727 msg.header.seq = seq;
728 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000729 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800730 return mChannel->sendMessage(&msg);
731}
732
arthurhung7632c332020-12-30 16:58:01 +0800733status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
734 bool isExiting) {
735 if (ATRACE_ENABLED()) {
736 std::string message =
737 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
738 mChannel->getName().c_str(), x, y, toString(isExiting));
739 ATRACE_NAME(message.c_str());
740 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000741 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000742 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
743 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800744
745 InputMessage msg;
746 msg.header.type = InputMessage::Type::DRAG;
747 msg.header.seq = seq;
748 msg.body.drag.eventId = eventId;
749 msg.body.drag.isExiting = isExiting;
750 msg.body.drag.x = x;
751 msg.body.drag.y = y;
752 return mChannel->sendMessage(&msg);
753}
754
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700755status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
756 if (ATRACE_ENABLED()) {
757 std::string message =
758 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
759 mChannel->getName().c_str(), toString(isInTouchMode));
760 ATRACE_NAME(message.c_str());
761 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000762 ALOGD_IF(debugTransportPublisher(),
763 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
764 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700765
766 InputMessage msg;
767 msg.header.type = InputMessage::Type::TOUCH_MODE;
768 msg.header.seq = seq;
769 msg.body.touchMode.eventId = eventId;
770 msg.body.touchMode.isInTouchMode = isInTouchMode;
771 return mChannel->sendMessage(&msg);
772}
773
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000774android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700775 InputMessage msg;
776 status_t result = mChannel->receiveMessage(&msg);
777 if (result) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000778 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: %s",
779 mChannel->getName().c_str(), __func__, strerror(result));
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000780 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700781 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000782 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000783 ALOGD_IF(debugTransportPublisher(),
784 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
785 mChannel->getName().c_str(), __func__, msg.header.seq,
786 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000787 return Finished{
788 .seq = msg.header.seq,
789 .handled = msg.body.finished.handled,
790 .consumeTime = msg.body.finished.consumeTime,
791 };
Jeff Brown5912f952013-07-01 19:10:31 -0700792 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000793
794 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000795 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
796 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000797 return Timeline{
798 .inputEventId = msg.body.timeline.eventId,
799 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
800 };
801 }
802
803 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800804 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000805 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700806}
807
808// --- InputConsumer ---
809
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500810InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800811 : InputConsumer(channel, isTouchResamplingEnabled()) {}
812
813InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
814 bool enableTouchResampling)
815 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700816
817InputConsumer::~InputConsumer() {
818}
819
820bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600821 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700822}
823
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800824status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
825 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000826 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
827 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
828 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700829
830 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700831 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700832
833 // Fetch the next input message.
834 // Loop until an event can be returned or no additional events are received.
835 while (!*outEvent) {
836 if (mMsgDeferred) {
837 // mMsg contains a valid input message from the previous call to consume
838 // that has not yet been processed.
839 mMsgDeferred = false;
840 } else {
841 // Receive a fresh message.
842 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000843 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800844 const auto [_, inserted] =
845 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
846 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
847 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000848 }
Jeff Brown5912f952013-07-01 19:10:31 -0700849 if (result) {
850 // Consume the next batched event unless batches are being held for later.
851 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800852 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700853 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000854 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
855 "channel '%s' consumer ~ consumed batch event, seq=%u",
856 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700857 break;
858 }
859 }
860 return result;
861 }
862 }
863
864 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700865 case InputMessage::Type::KEY: {
866 KeyEvent* keyEvent = factory->createKeyEvent();
867 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700868
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700869 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500870 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700871 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000872 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
873 "channel '%s' consumer ~ consumed key event, seq=%u",
874 mChannel->getName().c_str(), *outSeq);
875 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700876 }
Jeff Brown5912f952013-07-01 19:10:31 -0700877
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700878 case InputMessage::Type::MOTION: {
879 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
880 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500881 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700882 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500883 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000884 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
885 "channel '%s' consumer ~ appended to batch event",
886 mChannel->getName().c_str());
887 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700888 } else if (isPointerEvent(mMsg.body.motion.source) &&
889 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
890 // No need to process events that we are going to cancel anyways
891 const size_t count = batch.samples.size();
892 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500893 const InputMessage& msg = batch.samples[i];
894 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700895 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500896 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
897 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700898 } else {
899 // We cannot append to the batch in progress, so we need to consume
900 // the previous batch right now and defer the new message until later.
901 mMsgDeferred = true;
902 status_t result = consumeSamples(factory, batch, batch.samples.size(),
903 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500904 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700905 if (result) {
906 return result;
907 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000908 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
909 "channel '%s' consumer ~ consumed batch event and "
910 "deferred current event, seq=%u",
911 mChannel->getName().c_str(), *outSeq);
912 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700913 }
Jeff Brown5912f952013-07-01 19:10:31 -0700914 }
Jeff Brown5912f952013-07-01 19:10:31 -0700915
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800916 // Start a new batch if needed.
917 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
918 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500919 Batch batch;
920 batch.samples.push_back(mMsg);
921 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000922 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
923 "channel '%s' consumer ~ started batch event",
924 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800925 break;
926 }
Jeff Brown5912f952013-07-01 19:10:31 -0700927
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800928 MotionEvent* motionEvent = factory->createMotionEvent();
929 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700930
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800931 updateTouchState(mMsg);
932 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500933 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800934 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800935
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000936 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
937 "channel '%s' consumer ~ consumed motion event, seq=%u",
938 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800939 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700940 }
Jeff Brown5912f952013-07-01 19:10:31 -0700941
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000942 case InputMessage::Type::FINISHED:
943 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000944 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
945 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800946 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800947 break;
948 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800949
950 case InputMessage::Type::FOCUS: {
951 FocusEvent* focusEvent = factory->createFocusEvent();
952 if (!focusEvent) return NO_MEMORY;
953
954 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500955 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800956 *outEvent = focusEvent;
957 break;
958 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800959
960 case InputMessage::Type::CAPTURE: {
961 CaptureEvent* captureEvent = factory->createCaptureEvent();
962 if (!captureEvent) return NO_MEMORY;
963
964 initializeCaptureEvent(captureEvent, &mMsg);
965 *outSeq = mMsg.header.seq;
966 *outEvent = captureEvent;
967 break;
968 }
arthurhung7632c332020-12-30 16:58:01 +0800969
970 case InputMessage::Type::DRAG: {
971 DragEvent* dragEvent = factory->createDragEvent();
972 if (!dragEvent) return NO_MEMORY;
973
974 initializeDragEvent(dragEvent, &mMsg);
975 *outSeq = mMsg.header.seq;
976 *outEvent = dragEvent;
977 break;
978 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700979
980 case InputMessage::Type::TOUCH_MODE: {
981 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
982 if (!touchModeEvent) return NO_MEMORY;
983
984 initializeTouchModeEvent(touchModeEvent, &mMsg);
985 *outSeq = mMsg.header.seq;
986 *outEvent = touchModeEvent;
987 break;
988 }
Jeff Brown5912f952013-07-01 19:10:31 -0700989 }
990 }
991 return OK;
992}
993
994status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800995 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700996 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700997 for (size_t i = mBatches.size(); i > 0; ) {
998 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500999 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001000 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001001 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001002 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001003 return result;
1004 }
1005
Michael Wright32232172013-10-21 12:05:22 -07001006 nsecs_t sampleTime = frameTime;
1007 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001008 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001009 }
Jeff Brown5912f952013-07-01 19:10:31 -07001010 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1011 if (split < 0) {
1012 continue;
1013 }
1014
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001015 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001016 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001017 if (batch.samples.empty()) {
1018 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001019 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001020 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001021 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001022 }
Michael Wright32232172013-10-21 12:05:22 -07001023 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001024 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1025 }
1026 return result;
1027 }
1028
1029 return WOULD_BLOCK;
1030}
1031
1032status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001033 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001034 MotionEvent* motionEvent = factory->createMotionEvent();
1035 if (! motionEvent) return NO_MEMORY;
1036
1037 uint32_t chain = 0;
1038 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001039 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001040 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001041 if (i) {
1042 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001043 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001044 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001045 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001046 addSample(motionEvent, &msg);
1047 } else {
1048 initializeMotionEvent(motionEvent, &msg);
1049 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001050 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001051 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001052 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001053
1054 *outSeq = chain;
1055 *outEvent = motionEvent;
1056 return OK;
1057}
1058
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001059void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001060 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001061 return;
1062 }
1063
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001064 int32_t deviceId = msg.body.motion.deviceId;
1065 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001066
1067 // Update the touch state history to incorporate the new input message.
1068 // If the message is in the past relative to the most recently produced resampled
1069 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001070 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001071 case AMOTION_EVENT_ACTION_DOWN: {
1072 ssize_t index = findTouchState(deviceId, source);
1073 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001074 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001075 index = mTouchStates.size() - 1;
1076 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001077 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001078 touchState.initialize(deviceId, source);
1079 touchState.addHistory(msg);
1080 break;
1081 }
1082
1083 case AMOTION_EVENT_ACTION_MOVE: {
1084 ssize_t index = findTouchState(deviceId, source);
1085 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001086 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001087 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001088 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001089 }
1090 break;
1091 }
1092
1093 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1094 ssize_t index = findTouchState(deviceId, source);
1095 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001096 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001097 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001098 rewriteMessage(touchState, msg);
1099 }
1100 break;
1101 }
1102
1103 case AMOTION_EVENT_ACTION_POINTER_UP: {
1104 ssize_t index = findTouchState(deviceId, source);
1105 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001106 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001107 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001108 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001109 }
1110 break;
1111 }
1112
1113 case AMOTION_EVENT_ACTION_SCROLL: {
1114 ssize_t index = findTouchState(deviceId, source);
1115 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001116 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001117 rewriteMessage(touchState, msg);
1118 }
1119 break;
1120 }
1121
1122 case AMOTION_EVENT_ACTION_UP:
1123 case AMOTION_EVENT_ACTION_CANCEL: {
1124 ssize_t index = findTouchState(deviceId, source);
1125 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001126 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001127 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001128 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001129 }
1130 break;
1131 }
1132 }
1133}
1134
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001135/**
1136 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1137 *
1138 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1139 * is in the past relative to msg and the past two events do not contain identical coordinates),
1140 * then invalidate the lastResample data for that pointer.
1141 * If the two past events have identical coordinates, then lastResample data for that pointer will
1142 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1143 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1144 * not equal to x0 is received.
1145 */
1146void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001147 nsecs_t eventTime = msg.body.motion.eventTime;
1148 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1149 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001150 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001151 if (eventTime < state.lastResample.eventTime ||
1152 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001153 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1154 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001155 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1156 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1157 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001158 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1159 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001160 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001161 } else {
1162 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001163 }
Jeff Brown5912f952013-07-01 19:10:31 -07001164 }
1165 }
1166}
1167
1168void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1169 const InputMessage* next) {
1170 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001171 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001172 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1173 return;
1174 }
1175
1176 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1177 if (index < 0) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001178 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001179 return;
1180 }
1181
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001182 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001183 if (touchState.historySize < 1) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001184 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001185 return;
1186 }
1187
1188 // Ensure that the current sample has all of the pointers that need to be reported.
1189 const History* current = touchState.getHistory(0);
1190 size_t pointerCount = event->getPointerCount();
1191 for (size_t i = 0; i < pointerCount; i++) {
1192 uint32_t id = event->getPointerId(i);
1193 if (!current->idBits.hasBit(id)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001194 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001195 return;
1196 }
1197 }
1198
1199 // Find the data to use for resampling.
1200 const History* other;
1201 History future;
1202 float alpha;
1203 if (next) {
1204 // Interpolate between current sample and future sample.
1205 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001206 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001207 other = &future;
1208 nsecs_t delta = future.eventTime - current->eventTime;
1209 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001210 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1211 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001212 return;
1213 }
1214 alpha = float(sampleTime - current->eventTime) / delta;
1215 } else if (touchState.historySize >= 2) {
1216 // Extrapolate future sample using current sample and past sample.
1217 // So other->eventTime <= current->eventTime <= sampleTime.
1218 other = touchState.getHistory(1);
1219 nsecs_t delta = current->eventTime - other->eventTime;
1220 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001221 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1222 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001223 return;
1224 } else if (delta > RESAMPLE_MAX_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001225 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too large: %" PRId64 " ns.",
1226 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001227 return;
1228 }
1229 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1230 if (sampleTime > maxPredict) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001231 ALOGD_IF(DEBUG_RESAMPLING,
1232 "Sample time is too far in the future, adjusting prediction "
1233 "from %" PRId64 " to %" PRId64 " ns.",
1234 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001235 sampleTime = maxPredict;
1236 }
1237 alpha = float(current->eventTime - sampleTime) / delta;
1238 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001239 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001240 return;
1241 }
1242
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001243 if (current->eventTime == sampleTime) {
1244 // Prevents having 2 events with identical times and coordinates.
1245 return;
1246 }
1247
Jeff Brown5912f952013-07-01 19:10:31 -07001248 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001249 History oldLastResample;
1250 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001251 touchState.lastResample.eventTime = sampleTime;
1252 touchState.lastResample.idBits.clear();
1253 for (size_t i = 0; i < pointerCount; i++) {
1254 uint32_t id = event->getPointerId(i);
1255 touchState.lastResample.idToIndex[id] = i;
1256 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001257 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1258 // We maintain the previously resampled value for this pointer (stored in
1259 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1260 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001261 // The isResampled flag isn't cleared as the values don't reflect what the device is
1262 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001263
1264 // We know here that the coordinates for the pointer haven't changed because we
1265 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1266 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1267 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1268 continue;
1269 }
1270
Jeff Brown5912f952013-07-01 19:10:31 -07001271 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1272 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001273 resampledCoords.copyFrom(currentCoords);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001274 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001275 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001276 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001277 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001278 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001279 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001280 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001281 ALOGD_IF(DEBUG_RESAMPLING,
1282 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1283 "other (%0.3f, %0.3f), alpha %0.3f",
1284 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1285 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001286 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001287 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
1288 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1289 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001290 }
1291 }
1292
1293 event->addSample(sampleTime, touchState.lastResample.pointers);
1294}
1295
Jeff Brown5912f952013-07-01 19:10:31 -07001296status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001297 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1298 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1299 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001300
1301 if (!seq) {
1302 ALOGE("Attempted to send a finished signal with sequence number 0.");
1303 return BAD_VALUE;
1304 }
1305
1306 // Send finished signals for the batch sequence chain first.
1307 size_t seqChainCount = mSeqChains.size();
1308 if (seqChainCount) {
1309 uint32_t currentSeq = seq;
1310 uint32_t chainSeqs[seqChainCount];
1311 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001312 for (size_t i = seqChainCount; i > 0; ) {
1313 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001314 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001315 if (seqChain.seq == currentSeq) {
1316 currentSeq = seqChain.chain;
1317 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001318 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001319 }
1320 }
1321 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001322 while (!status && chainIndex > 0) {
1323 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001324 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1325 }
1326 if (status) {
1327 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001328 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001329 SeqChain seqChain;
1330 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1331 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001332 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001333 if (!chainIndex) break;
1334 chainIndex--;
1335 }
Jeff Brown5912f952013-07-01 19:10:31 -07001336 return status;
1337 }
1338 }
1339
1340 // Send finished signal for the last message in the batch.
1341 return sendUnchainedFinishedSignal(seq, handled);
1342}
1343
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001344status_t InputConsumer::sendTimeline(int32_t inputEventId,
1345 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001346 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1347 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1348 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1349 mChannel->getName().c_str(), inputEventId,
1350 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1351 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001352
1353 InputMessage msg;
1354 msg.header.type = InputMessage::Type::TIMELINE;
1355 msg.header.seq = 0;
1356 msg.body.timeline.eventId = inputEventId;
1357 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1358 return mChannel->sendMessage(&msg);
1359}
1360
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001361nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1362 auto it = mConsumeTimes.find(seq);
1363 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1364 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1365 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1366 seq);
1367 return it->second;
1368}
1369
1370void InputConsumer::popConsumeTime(uint32_t seq) {
1371 mConsumeTimes.erase(seq);
1372}
1373
Jeff Brown5912f952013-07-01 19:10:31 -07001374status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1375 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001376 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001377 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001378 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001379 msg.body.finished.consumeTime = getConsumeTime(seq);
1380 status_t result = mChannel->sendMessage(&msg);
1381 if (result == OK) {
1382 // Remove the consume time if the socket write succeeded. We will not need to ack this
1383 // message anymore. If the socket write did not succeed, we will try again and will still
1384 // need consume time.
1385 popConsumeTime(seq);
1386 }
1387 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001388}
1389
Jeff Brown5912f952013-07-01 19:10:31 -07001390bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001391 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001392}
1393
Arthur Hungc7812be2020-02-27 22:40:27 +08001394int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001395 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001396 return AINPUT_SOURCE_CLASS_NONE;
1397 }
1398
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001399 const Batch& batch = mBatches[0];
1400 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001401 return head.body.motion.source;
1402}
1403
Jeff Brown5912f952013-07-01 19:10:31 -07001404ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1405 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001406 const Batch& batch = mBatches[i];
1407 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001408 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1409 return i;
1410 }
1411 }
1412 return -1;
1413}
1414
1415ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1416 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001417 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001418 if (touchState.deviceId == deviceId && touchState.source == source) {
1419 return i;
1420 }
1421 }
1422 return -1;
1423}
1424
1425void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001426 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001427 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1428 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1429 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1430 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001431}
1432
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001433void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001434 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001435}
1436
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001437void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001438 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001439}
1440
arthurhung7632c332020-12-30 16:58:01 +08001441void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1442 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1443 msg->body.drag.isExiting);
1444}
1445
Jeff Brown5912f952013-07-01 19:10:31 -07001446void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001447 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001448 PointerProperties pointerProperties[pointerCount];
1449 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001450 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001451 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1452 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1453 }
1454
chaviw9eaa22c2020-07-01 16:21:27 -07001455 ui::Transform transform;
1456 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1457 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001458 ui::Transform displayTransform;
1459 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1460 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1461 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001462 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1463 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1464 msg->body.motion.actionButton, msg->body.motion.flags,
1465 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001466 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1467 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1468 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001469 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1470 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001471}
1472
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001473void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1474 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1475}
1476
Jeff Brown5912f952013-07-01 19:10:31 -07001477void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001478 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001479 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001480 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001481 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1482 }
1483
1484 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1485 event->addSample(msg->body.motion.eventTime, pointerCoords);
1486}
1487
1488bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001489 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001490 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001491 if (head.body.motion.pointerCount != pointerCount
1492 || head.body.motion.action != msg->body.motion.action) {
1493 return false;
1494 }
1495 for (size_t i = 0; i < pointerCount; i++) {
1496 if (head.body.motion.pointers[i].properties
1497 != msg->body.motion.pointers[i].properties) {
1498 return false;
1499 }
1500 }
1501 return true;
1502}
1503
1504ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1505 size_t numSamples = batch.samples.size();
1506 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001507 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001508 index += 1;
1509 }
1510 return ssize_t(index) - 1;
1511}
1512
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001513std::string InputConsumer::dump() const {
1514 std::string out;
1515 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1516 out = out + "mChannel = " + mChannel->getName() + "\n";
1517 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1518 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001519 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001520 }
1521 out += "Batches:\n";
1522 for (const Batch& batch : mBatches) {
1523 out += " Batch:\n";
1524 for (const InputMessage& msg : batch.samples) {
1525 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001526 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001527 switch (msg.header.type) {
1528 case InputMessage::Type::KEY: {
1529 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1530 KeyEvent::actionToString(
1531 msg.body.key.action),
1532 msg.body.key.keyCode);
1533 break;
1534 }
1535 case InputMessage::Type::MOTION: {
1536 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1537 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1538 const float x = msg.body.motion.pointers[i].coords.getX();
1539 const float y = msg.body.motion.pointers[i].coords.getY();
1540 out += android::base::StringPrintf("\n Pointer %" PRIu32
1541 " : x=%.1f y=%.1f",
1542 i, x, y);
1543 }
1544 break;
1545 }
1546 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001547 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1548 toString(msg.body.finished.handled),
1549 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001550 break;
1551 }
1552 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001553 out += android::base::StringPrintf("hasFocus=%s",
1554 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001555 break;
1556 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001557 case InputMessage::Type::CAPTURE: {
1558 out += android::base::StringPrintf("hasCapture=%s",
1559 toString(msg.body.capture
1560 .pointerCaptureEnabled));
1561 break;
1562 }
arthurhung7632c332020-12-30 16:58:01 +08001563 case InputMessage::Type::DRAG: {
1564 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1565 msg.body.drag.x, msg.body.drag.y,
1566 toString(msg.body.drag.isExiting));
1567 break;
1568 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001569 case InputMessage::Type::TIMELINE: {
1570 const nsecs_t gpuCompletedTime =
1571 msg.body.timeline
1572 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1573 const nsecs_t presentTime =
1574 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1575 out += android::base::StringPrintf("inputEventId=%" PRId32
1576 ", gpuCompletedTime=%" PRId64
1577 ", presentTime=%" PRId64,
1578 msg.body.timeline.eventId, gpuCompletedTime,
1579 presentTime);
1580 break;
1581 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001582 case InputMessage::Type::TOUCH_MODE: {
1583 out += android::base::StringPrintf("isInTouchMode=%s",
1584 toString(msg.body.touchMode.isInTouchMode));
1585 break;
1586 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001587 }
1588 out += "\n";
1589 }
1590 }
1591 if (mBatches.empty()) {
1592 out += " <empty>\n";
1593 }
1594 out += "mSeqChains:\n";
1595 for (const SeqChain& chain : mSeqChains) {
1596 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1597 chain.chain);
1598 }
1599 if (mSeqChains.empty()) {
1600 out += " <empty>\n";
1601 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001602 out += "mConsumeTimes:\n";
1603 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1604 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1605 consumeTime);
1606 }
1607 if (mConsumeTimes.empty()) {
1608 out += " <empty>\n";
1609 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001610 return out;
1611}
1612
Jeff Brown5912f952013-07-01 19:10:31 -07001613} // namespace android