blob: fd4d5f0f2d2f6ce7f001b6cb87a8a7f5f43a79fb [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
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700148static bool shouldResampleTool(ToolType toolType) {
149 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
150}
151
Jeff Brown5912f952013-07-01 19:10:31 -0700152// --- InputMessage ---
153
154bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000155 if (size() != actualSize) {
156 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
157 return false;
158 }
159
160 switch (header.type) {
161 case Type::KEY:
162 return true;
163 case Type::MOTION: {
164 const bool valid =
165 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
166 if (!valid) {
167 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
168 }
169 return valid;
170 }
171 case Type::FINISHED:
172 case Type::FOCUS:
173 case Type::CAPTURE:
174 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700175 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000176 return true;
177 case Type::TIMELINE: {
178 const nsecs_t gpuCompletedTime =
179 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
180 const nsecs_t presentTime =
181 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
182 const bool valid = presentTime > gpuCompletedTime;
183 if (!valid) {
184 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
185 " presentTime = %" PRId64,
186 gpuCompletedTime, presentTime);
187 }
188 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700189 }
190 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000191 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700192 return false;
193}
194
195size_t InputMessage::size() const {
196 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700197 case Type::KEY:
198 return sizeof(Header) + body.key.size();
199 case Type::MOTION:
200 return sizeof(Header) + body.motion.size();
201 case Type::FINISHED:
202 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800203 case Type::FOCUS:
204 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800205 case Type::CAPTURE:
206 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800207 case Type::DRAG:
208 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000209 case Type::TIMELINE:
210 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700211 case Type::TOUCH_MODE:
212 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700213 }
214 return sizeof(Header);
215}
216
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800217/**
218 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
219 * memory to zero, then only copy the valid bytes on a per-field basis.
220 */
221void InputMessage::getSanitizedCopy(InputMessage* msg) const {
222 memset(msg, 0, sizeof(*msg));
223
224 // Write the header
225 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500226 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800227
228 // Write the body
229 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700230 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800231 // int32_t eventId
232 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800233 // nsecs_t eventTime
234 msg->body.key.eventTime = body.key.eventTime;
235 // int32_t deviceId
236 msg->body.key.deviceId = body.key.deviceId;
237 // int32_t source
238 msg->body.key.source = body.key.source;
239 // int32_t displayId
240 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600241 // std::array<uint8_t, 32> hmac
242 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800243 // int32_t action
244 msg->body.key.action = body.key.action;
245 // int32_t flags
246 msg->body.key.flags = body.key.flags;
247 // int32_t keyCode
248 msg->body.key.keyCode = body.key.keyCode;
249 // int32_t scanCode
250 msg->body.key.scanCode = body.key.scanCode;
251 // int32_t metaState
252 msg->body.key.metaState = body.key.metaState;
253 // int32_t repeatCount
254 msg->body.key.repeatCount = body.key.repeatCount;
255 // nsecs_t downTime
256 msg->body.key.downTime = body.key.downTime;
257 break;
258 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700259 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800260 // int32_t eventId
261 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700262 // uint32_t pointerCount
263 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800264 // nsecs_t eventTime
265 msg->body.motion.eventTime = body.motion.eventTime;
266 // int32_t deviceId
267 msg->body.motion.deviceId = body.motion.deviceId;
268 // int32_t source
269 msg->body.motion.source = body.motion.source;
270 // int32_t displayId
271 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600272 // std::array<uint8_t, 32> hmac
273 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800274 // int32_t action
275 msg->body.motion.action = body.motion.action;
276 // int32_t actionButton
277 msg->body.motion.actionButton = body.motion.actionButton;
278 // int32_t flags
279 msg->body.motion.flags = body.motion.flags;
280 // int32_t metaState
281 msg->body.motion.metaState = body.motion.metaState;
282 // int32_t buttonState
283 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800284 // MotionClassification classification
285 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800286 // int32_t edgeFlags
287 msg->body.motion.edgeFlags = body.motion.edgeFlags;
288 // nsecs_t downTime
289 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700290
291 msg->body.motion.dsdx = body.motion.dsdx;
292 msg->body.motion.dtdx = body.motion.dtdx;
293 msg->body.motion.dtdy = body.motion.dtdy;
294 msg->body.motion.dsdy = body.motion.dsdy;
295 msg->body.motion.tx = body.motion.tx;
296 msg->body.motion.ty = body.motion.ty;
297
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800298 // float xPrecision
299 msg->body.motion.xPrecision = body.motion.xPrecision;
300 // float yPrecision
301 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700302 // float xCursorPosition
303 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
304 // float yCursorPosition
305 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700306
307 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
308 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
309 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
310 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
311 msg->body.motion.txRaw = body.motion.txRaw;
312 msg->body.motion.tyRaw = body.motion.tyRaw;
313
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800314 //struct Pointer pointers[MAX_POINTERS]
315 for (size_t i = 0; i < body.motion.pointerCount; i++) {
316 // PointerProperties properties
317 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
318 msg->body.motion.pointers[i].properties.toolType =
319 body.motion.pointers[i].properties.toolType,
320 // PointerCoords coords
321 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
322 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
323 memcpy(&msg->body.motion.pointers[i].coords.values[0],
324 &body.motion.pointers[i].coords.values[0],
325 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800326 msg->body.motion.pointers[i].coords.isResampled =
327 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800328 }
329 break;
330 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700331 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800332 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000333 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800334 break;
335 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800336 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800337 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800338 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800339 break;
340 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800341 case InputMessage::Type::CAPTURE: {
342 msg->body.capture.eventId = body.capture.eventId;
343 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
344 break;
345 }
arthurhung7632c332020-12-30 16:58:01 +0800346 case InputMessage::Type::DRAG: {
347 msg->body.drag.eventId = body.drag.eventId;
348 msg->body.drag.x = body.drag.x;
349 msg->body.drag.y = body.drag.y;
350 msg->body.drag.isExiting = body.drag.isExiting;
351 break;
352 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000353 case InputMessage::Type::TIMELINE: {
354 msg->body.timeline.eventId = body.timeline.eventId;
355 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
356 break;
357 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700358 case InputMessage::Type::TOUCH_MODE: {
359 msg->body.touchMode.eventId = body.touchMode.eventId;
360 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
361 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800362 }
363}
Jeff Brown5912f952013-07-01 19:10:31 -0700364
365// --- InputChannel ---
366
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500367std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500368 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700369 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
370 if (result != 0) {
371 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
372 strerror(errno));
373 return nullptr;
374 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500375 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500376 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700377}
378
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500379InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
380 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000381 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
382 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700383}
384
385InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000386 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
387 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700388}
389
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800390status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500391 std::unique_ptr<InputChannel>& outServerChannel,
392 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700393 int sockets[2];
394 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
395 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000396 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
397 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500398 outServerChannel.reset();
399 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700400 return result;
401 }
402
403 int bufferSize = SOCKET_BUFFER_SIZE;
404 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
405 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
406 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
407 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
408
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700409 sp<IBinder> token = new BBinder();
410
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700411 std::string serverChannelName = name + " (server)";
412 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700413 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700414
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700415 std::string clientChannelName = name + " (client)";
416 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700417 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700418 return OK;
419}
420
421status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800422 const size_t msgLength = msg->size();
423 InputMessage cleanMsg;
424 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700425 ssize_t nWrite;
426 do {
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800427 nWrite = ::send(getFd().get(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700428 } while (nWrite == -1 && errno == EINTR);
429
430 if (nWrite < 0) {
431 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000432 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
433 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700434 if (error == EAGAIN || error == EWOULDBLOCK) {
435 return WOULD_BLOCK;
436 }
437 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
438 return DEAD_OBJECT;
439 }
440 return -error;
441 }
442
443 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000444 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
445 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
446 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700447 return DEAD_OBJECT;
448 }
449
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000450 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
451 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700452 return OK;
453}
454
455status_t InputChannel::receiveMessage(InputMessage* msg) {
456 ssize_t nRead;
457 do {
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800458 nRead = ::recv(getFd().get(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700459 } while (nRead == -1 && errno == EINTR);
460
461 if (nRead < 0) {
462 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000463 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
464 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700465 if (error == EAGAIN || error == EWOULDBLOCK) {
466 return WOULD_BLOCK;
467 }
468 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
469 return DEAD_OBJECT;
470 }
471 return -error;
472 }
473
474 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000475 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
476 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700477 return DEAD_OBJECT;
478 }
479
480 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000481 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700482 return BAD_VALUE;
483 }
484
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000485 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
486 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700487 return OK;
488}
489
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500490std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700491 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700492 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700493}
494
Garfield Tan15601662020-09-22 15:32:38 -0700495void InputChannel::copyTo(InputChannel& outChannel) const {
496 outChannel.mName = getName();
497 outChannel.mFd = dupFd();
498 outChannel.mToken = getConnectionToken();
499}
500
Chris Ye0783e992020-06-02 21:34:49 -0700501status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500502 if (parcel == nullptr) {
503 ALOGE("%s: Null parcel", __func__);
504 return BAD_VALUE;
505 }
506 return parcel->writeStrongBinder(mToken)
507 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700508}
509
Chris Ye0783e992020-06-02 21:34:49 -0700510status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500511 if (parcel == nullptr) {
512 ALOGE("%s: Null parcel", __func__);
513 return BAD_VALUE;
514 }
515 mToken = parcel->readStrongBinder();
516 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700517}
518
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700519sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500520 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700521}
522
Garfield Tan15601662020-09-22 15:32:38 -0700523base::unique_fd InputChannel::dupFd() const {
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800524 base::unique_fd newFd(::dup(getFd().get()));
Garfield Tan15601662020-09-22 15:32:38 -0700525 if (!newFd.ok()) {
526 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
527 strerror(errno));
528 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
529 // If this process is out of file descriptors, then throwing that might end up exploding
530 // on the other side of a binder call, which isn't really helpful.
531 // Better to just crash here and hope that the FD leak is slow.
532 // Other failures could be client errors, so we still propagate those back to the caller.
533 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
534 getName().c_str());
535 return {};
536 }
537 return newFd;
538}
539
Jeff Brown5912f952013-07-01 19:10:31 -0700540// --- InputPublisher ---
541
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800542InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
543 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700544
545InputPublisher::~InputPublisher() {
546}
547
Garfield Tan1c7bc862020-01-28 13:24:04 -0800548status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
549 int32_t source, int32_t displayId,
550 std::array<uint8_t, 32> hmac, int32_t action,
551 int32_t flags, int32_t keyCode, int32_t scanCode,
552 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
553 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000554 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000555 std::string message =
556 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
557 mChannel->getName().c_str(), KeyEvent::actionToString(action),
558 KeyEvent::getLabel(keyCode));
Michael Wright3dd60e22019-03-27 22:06:44 +0000559 ATRACE_NAME(message.c_str());
560 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000561 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000562 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000563 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
564 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000565 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000566 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
567 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700568
569 if (!seq) {
570 ALOGE("Attempted to publish a key event with sequence number 0.");
571 return BAD_VALUE;
572 }
573
574 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700575 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500576 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800577 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700578 msg.body.key.deviceId = deviceId;
579 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100580 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700581 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700582 msg.body.key.action = action;
583 msg.body.key.flags = flags;
584 msg.body.key.keyCode = keyCode;
585 msg.body.key.scanCode = scanCode;
586 msg.body.key.metaState = metaState;
587 msg.body.key.repeatCount = repeatCount;
588 msg.body.key.downTime = downTime;
589 msg.body.key.eventTime = eventTime;
590 return mChannel->sendMessage(&msg);
591}
592
593status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800594 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600595 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
596 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700597 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700598 float yPrecision, float xCursorPosition, float yCursorPosition,
599 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700600 uint32_t pointerCount, const PointerProperties* pointerProperties,
601 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000602 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000603 std::string message = StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
604 mChannel->getName().c_str(),
605 MotionEvent::actionToString(action).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +0000606 ATRACE_NAME(message.c_str());
607 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800608 if (verifyEvents()) {
609 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
610 pointerCoords, flags);
611 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000612 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700613 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700614 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000615 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800616 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000617 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700618 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800619 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700620 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000621 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000622 inputEventSourceToString(source).c_str(), displayId,
623 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
624 metaState, buttonState, motionClassificationToString(classification), xPrecision,
625 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800626 }
Jeff Brown5912f952013-07-01 19:10:31 -0700627
628 if (!seq) {
629 ALOGE("Attempted to publish a motion event with sequence number 0.");
630 return BAD_VALUE;
631 }
632
633 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700634 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800635 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700636 return BAD_VALUE;
637 }
638
639 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700640 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500641 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800642 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700643 msg.body.motion.deviceId = deviceId;
644 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700645 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700646 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700647 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100648 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700649 msg.body.motion.flags = flags;
650 msg.body.motion.edgeFlags = edgeFlags;
651 msg.body.motion.metaState = metaState;
652 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800653 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700654 msg.body.motion.dsdx = transform.dsdx();
655 msg.body.motion.dtdx = transform.dtdx();
656 msg.body.motion.dtdy = transform.dtdy();
657 msg.body.motion.dsdy = transform.dsdy();
658 msg.body.motion.tx = transform.tx();
659 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700660 msg.body.motion.xPrecision = xPrecision;
661 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700662 msg.body.motion.xCursorPosition = xCursorPosition;
663 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700664 msg.body.motion.dsdxRaw = rawTransform.dsdx();
665 msg.body.motion.dtdxRaw = rawTransform.dtdx();
666 msg.body.motion.dtdyRaw = rawTransform.dtdy();
667 msg.body.motion.dsdyRaw = rawTransform.dsdy();
668 msg.body.motion.txRaw = rawTransform.tx();
669 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700670 msg.body.motion.downTime = downTime;
671 msg.body.motion.eventTime = eventTime;
672 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100673 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700674 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
675 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
676 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700677
Jeff Brown5912f952013-07-01 19:10:31 -0700678 return mChannel->sendMessage(&msg);
679}
680
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700681status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800682 if (ATRACE_ENABLED()) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700683 std::string message = StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
684 mChannel->getName().c_str(), toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800685 ATRACE_NAME(message.c_str());
686 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000687 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
688 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800689
690 InputMessage msg;
691 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500692 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800693 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000694 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800695 return mChannel->sendMessage(&msg);
696}
697
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800698status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
699 bool pointerCaptureEnabled) {
700 if (ATRACE_ENABLED()) {
701 std::string message =
702 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
703 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
704 ATRACE_NAME(message.c_str());
705 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000706 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000707 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
708 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800709
710 InputMessage msg;
711 msg.header.type = InputMessage::Type::CAPTURE;
712 msg.header.seq = seq;
713 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000714 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800715 return mChannel->sendMessage(&msg);
716}
717
arthurhung7632c332020-12-30 16:58:01 +0800718status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
719 bool isExiting) {
720 if (ATRACE_ENABLED()) {
721 std::string message =
722 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
723 mChannel->getName().c_str(), x, y, toString(isExiting));
724 ATRACE_NAME(message.c_str());
725 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000726 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000727 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
728 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800729
730 InputMessage msg;
731 msg.header.type = InputMessage::Type::DRAG;
732 msg.header.seq = seq;
733 msg.body.drag.eventId = eventId;
734 msg.body.drag.isExiting = isExiting;
735 msg.body.drag.x = x;
736 msg.body.drag.y = y;
737 return mChannel->sendMessage(&msg);
738}
739
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700740status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
741 if (ATRACE_ENABLED()) {
742 std::string message =
743 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
744 mChannel->getName().c_str(), toString(isInTouchMode));
745 ATRACE_NAME(message.c_str());
746 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000747 ALOGD_IF(debugTransportPublisher(),
748 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
749 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700750
751 InputMessage msg;
752 msg.header.type = InputMessage::Type::TOUCH_MODE;
753 msg.header.seq = seq;
754 msg.body.touchMode.eventId = eventId;
755 msg.body.touchMode.isInTouchMode = isInTouchMode;
756 return mChannel->sendMessage(&msg);
757}
758
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000759android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700760 InputMessage msg;
761 status_t result = mChannel->receiveMessage(&msg);
762 if (result) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000763 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: %s",
764 mChannel->getName().c_str(), __func__, strerror(result));
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000765 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700766 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000767 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000768 ALOGD_IF(debugTransportPublisher(),
769 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
770 mChannel->getName().c_str(), __func__, msg.header.seq,
771 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000772 return Finished{
773 .seq = msg.header.seq,
774 .handled = msg.body.finished.handled,
775 .consumeTime = msg.body.finished.consumeTime,
776 };
Jeff Brown5912f952013-07-01 19:10:31 -0700777 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000778
779 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000780 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
781 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000782 return Timeline{
783 .inputEventId = msg.body.timeline.eventId,
784 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
785 };
786 }
787
788 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800789 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000790 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700791}
792
793// --- InputConsumer ---
794
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500795InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800796 : InputConsumer(channel, isTouchResamplingEnabled()) {}
797
798InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
799 bool enableTouchResampling)
800 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700801
802InputConsumer::~InputConsumer() {
803}
804
805bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600806 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700807}
808
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800809status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
810 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000811 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
812 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
813 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700814
815 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700816 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700817
818 // Fetch the next input message.
819 // Loop until an event can be returned or no additional events are received.
820 while (!*outEvent) {
821 if (mMsgDeferred) {
822 // mMsg contains a valid input message from the previous call to consume
823 // that has not yet been processed.
824 mMsgDeferred = false;
825 } else {
826 // Receive a fresh message.
827 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000828 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800829 const auto [_, inserted] =
830 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
831 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
832 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000833 }
Jeff Brown5912f952013-07-01 19:10:31 -0700834 if (result) {
835 // Consume the next batched event unless batches are being held for later.
836 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800837 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700838 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000839 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
840 "channel '%s' consumer ~ consumed batch event, seq=%u",
841 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700842 break;
843 }
844 }
845 return result;
846 }
847 }
848
849 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700850 case InputMessage::Type::KEY: {
851 KeyEvent* keyEvent = factory->createKeyEvent();
852 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700853
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700854 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500855 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700856 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000857 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
858 "channel '%s' consumer ~ consumed key event, seq=%u",
859 mChannel->getName().c_str(), *outSeq);
860 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700861 }
Jeff Brown5912f952013-07-01 19:10:31 -0700862
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700863 case InputMessage::Type::MOTION: {
864 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
865 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500866 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700867 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500868 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000869 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
870 "channel '%s' consumer ~ appended to batch event",
871 mChannel->getName().c_str());
872 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700873 } else if (isPointerEvent(mMsg.body.motion.source) &&
874 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
875 // No need to process events that we are going to cancel anyways
876 const size_t count = batch.samples.size();
877 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500878 const InputMessage& msg = batch.samples[i];
879 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700880 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500881 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
882 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700883 } else {
884 // We cannot append to the batch in progress, so we need to consume
885 // the previous batch right now and defer the new message until later.
886 mMsgDeferred = true;
887 status_t result = consumeSamples(factory, batch, batch.samples.size(),
888 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500889 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700890 if (result) {
891 return result;
892 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000893 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
894 "channel '%s' consumer ~ consumed batch event and "
895 "deferred current event, seq=%u",
896 mChannel->getName().c_str(), *outSeq);
897 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700898 }
Jeff Brown5912f952013-07-01 19:10:31 -0700899 }
Jeff Brown5912f952013-07-01 19:10:31 -0700900
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800901 // Start a new batch if needed.
902 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
903 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500904 Batch batch;
905 batch.samples.push_back(mMsg);
906 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000907 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
908 "channel '%s' consumer ~ started batch event",
909 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800910 break;
911 }
Jeff Brown5912f952013-07-01 19:10:31 -0700912
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800913 MotionEvent* motionEvent = factory->createMotionEvent();
914 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700915
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800916 updateTouchState(mMsg);
917 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500918 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800919 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800920
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000921 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
922 "channel '%s' consumer ~ consumed motion event, seq=%u",
923 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800924 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700925 }
Jeff Brown5912f952013-07-01 19:10:31 -0700926
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000927 case InputMessage::Type::FINISHED:
928 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000929 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
930 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800931 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800932 break;
933 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800934
935 case InputMessage::Type::FOCUS: {
936 FocusEvent* focusEvent = factory->createFocusEvent();
937 if (!focusEvent) return NO_MEMORY;
938
939 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500940 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800941 *outEvent = focusEvent;
942 break;
943 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800944
945 case InputMessage::Type::CAPTURE: {
946 CaptureEvent* captureEvent = factory->createCaptureEvent();
947 if (!captureEvent) return NO_MEMORY;
948
949 initializeCaptureEvent(captureEvent, &mMsg);
950 *outSeq = mMsg.header.seq;
951 *outEvent = captureEvent;
952 break;
953 }
arthurhung7632c332020-12-30 16:58:01 +0800954
955 case InputMessage::Type::DRAG: {
956 DragEvent* dragEvent = factory->createDragEvent();
957 if (!dragEvent) return NO_MEMORY;
958
959 initializeDragEvent(dragEvent, &mMsg);
960 *outSeq = mMsg.header.seq;
961 *outEvent = dragEvent;
962 break;
963 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700964
965 case InputMessage::Type::TOUCH_MODE: {
966 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
967 if (!touchModeEvent) return NO_MEMORY;
968
969 initializeTouchModeEvent(touchModeEvent, &mMsg);
970 *outSeq = mMsg.header.seq;
971 *outEvent = touchModeEvent;
972 break;
973 }
Jeff Brown5912f952013-07-01 19:10:31 -0700974 }
975 }
976 return OK;
977}
978
979status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800980 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -0700981 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -0700982 for (size_t i = mBatches.size(); i > 0; ) {
983 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500984 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -0700985 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800986 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500987 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -0700988 return result;
989 }
990
Michael Wright32232172013-10-21 12:05:22 -0700991 nsecs_t sampleTime = frameTime;
992 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800993 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -0700994 }
Jeff Brown5912f952013-07-01 19:10:31 -0700995 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
996 if (split < 0) {
997 continue;
998 }
999
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001000 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001001 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001002 if (batch.samples.empty()) {
1003 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001004 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001005 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001006 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001007 }
Michael Wright32232172013-10-21 12:05:22 -07001008 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001009 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1010 }
1011 return result;
1012 }
1013
1014 return WOULD_BLOCK;
1015}
1016
1017status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001018 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001019 MotionEvent* motionEvent = factory->createMotionEvent();
1020 if (! motionEvent) return NO_MEMORY;
1021
1022 uint32_t chain = 0;
1023 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001024 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001025 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001026 if (i) {
1027 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001028 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001029 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001030 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001031 addSample(motionEvent, &msg);
1032 } else {
1033 initializeMotionEvent(motionEvent, &msg);
1034 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001035 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001036 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001037 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001038
1039 *outSeq = chain;
1040 *outEvent = motionEvent;
1041 return OK;
1042}
1043
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001044void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001045 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001046 return;
1047 }
1048
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001049 int32_t deviceId = msg.body.motion.deviceId;
1050 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001051
1052 // Update the touch state history to incorporate the new input message.
1053 // If the message is in the past relative to the most recently produced resampled
1054 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001055 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001056 case AMOTION_EVENT_ACTION_DOWN: {
1057 ssize_t index = findTouchState(deviceId, source);
1058 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001059 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001060 index = mTouchStates.size() - 1;
1061 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001062 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001063 touchState.initialize(deviceId, source);
1064 touchState.addHistory(msg);
1065 break;
1066 }
1067
1068 case AMOTION_EVENT_ACTION_MOVE: {
1069 ssize_t index = findTouchState(deviceId, source);
1070 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001071 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001072 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001073 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001074 }
1075 break;
1076 }
1077
1078 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1079 ssize_t index = findTouchState(deviceId, source);
1080 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001081 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001082 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001083 rewriteMessage(touchState, msg);
1084 }
1085 break;
1086 }
1087
1088 case AMOTION_EVENT_ACTION_POINTER_UP: {
1089 ssize_t index = findTouchState(deviceId, source);
1090 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001091 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001092 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001093 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001094 }
1095 break;
1096 }
1097
1098 case AMOTION_EVENT_ACTION_SCROLL: {
1099 ssize_t index = findTouchState(deviceId, source);
1100 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001101 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001102 rewriteMessage(touchState, msg);
1103 }
1104 break;
1105 }
1106
1107 case AMOTION_EVENT_ACTION_UP:
1108 case AMOTION_EVENT_ACTION_CANCEL: {
1109 ssize_t index = findTouchState(deviceId, source);
1110 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001111 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001112 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001113 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001114 }
1115 break;
1116 }
1117 }
1118}
1119
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001120/**
1121 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1122 *
1123 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1124 * is in the past relative to msg and the past two events do not contain identical coordinates),
1125 * then invalidate the lastResample data for that pointer.
1126 * If the two past events have identical coordinates, then lastResample data for that pointer will
1127 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1128 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1129 * not equal to x0 is received.
1130 */
1131void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001132 nsecs_t eventTime = msg.body.motion.eventTime;
1133 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1134 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001135 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001136 if (eventTime < state.lastResample.eventTime ||
1137 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001138 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1139 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001140 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1141 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1142 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001143 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1144 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001145 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001146 } else {
1147 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001148 }
Jeff Brown5912f952013-07-01 19:10:31 -07001149 }
1150 }
1151}
1152
1153void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1154 const InputMessage* next) {
1155 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001156 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001157 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1158 return;
1159 }
1160
1161 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1162 if (index < 0) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001163 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001164 return;
1165 }
1166
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001167 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001168 if (touchState.historySize < 1) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001169 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001170 return;
1171 }
1172
1173 // Ensure that the current sample has all of the pointers that need to be reported.
1174 const History* current = touchState.getHistory(0);
1175 size_t pointerCount = event->getPointerCount();
1176 for (size_t i = 0; i < pointerCount; i++) {
1177 uint32_t id = event->getPointerId(i);
1178 if (!current->idBits.hasBit(id)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001179 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001180 return;
1181 }
1182 }
1183
1184 // Find the data to use for resampling.
1185 const History* other;
1186 History future;
1187 float alpha;
1188 if (next) {
1189 // Interpolate between current sample and future sample.
1190 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001191 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001192 other = &future;
1193 nsecs_t delta = future.eventTime - current->eventTime;
1194 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001195 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1196 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001197 return;
1198 }
1199 alpha = float(sampleTime - current->eventTime) / delta;
1200 } else if (touchState.historySize >= 2) {
1201 // Extrapolate future sample using current sample and past sample.
1202 // So other->eventTime <= current->eventTime <= sampleTime.
1203 other = touchState.getHistory(1);
1204 nsecs_t delta = current->eventTime - other->eventTime;
1205 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001206 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1207 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001208 return;
1209 } else if (delta > RESAMPLE_MAX_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001210 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too large: %" PRId64 " ns.",
1211 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001212 return;
1213 }
1214 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1215 if (sampleTime > maxPredict) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001216 ALOGD_IF(DEBUG_RESAMPLING,
1217 "Sample time is too far in the future, adjusting prediction "
1218 "from %" PRId64 " to %" PRId64 " ns.",
1219 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001220 sampleTime = maxPredict;
1221 }
1222 alpha = float(current->eventTime - sampleTime) / delta;
1223 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001224 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001225 return;
1226 }
1227
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001228 if (current->eventTime == sampleTime) {
1229 // Prevents having 2 events with identical times and coordinates.
1230 return;
1231 }
1232
Jeff Brown5912f952013-07-01 19:10:31 -07001233 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001234 History oldLastResample;
1235 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001236 touchState.lastResample.eventTime = sampleTime;
1237 touchState.lastResample.idBits.clear();
1238 for (size_t i = 0; i < pointerCount; i++) {
1239 uint32_t id = event->getPointerId(i);
1240 touchState.lastResample.idToIndex[id] = i;
1241 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001242 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1243 // We maintain the previously resampled value for this pointer (stored in
1244 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1245 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001246 // The isResampled flag isn't cleared as the values don't reflect what the device is
1247 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001248
1249 // We know here that the coordinates for the pointer haven't changed because we
1250 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1251 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1252 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1253 continue;
1254 }
1255
Jeff Brown5912f952013-07-01 19:10:31 -07001256 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1257 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001258 resampledCoords.copyFrom(currentCoords);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001259 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001260 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001261 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001262 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001263 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001264 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001265 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001266 ALOGD_IF(DEBUG_RESAMPLING,
1267 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1268 "other (%0.3f, %0.3f), alpha %0.3f",
1269 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1270 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001271 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001272 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
1273 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1274 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001275 }
1276 }
1277
1278 event->addSample(sampleTime, touchState.lastResample.pointers);
1279}
1280
Jeff Brown5912f952013-07-01 19:10:31 -07001281status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001282 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1283 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1284 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001285
1286 if (!seq) {
1287 ALOGE("Attempted to send a finished signal with sequence number 0.");
1288 return BAD_VALUE;
1289 }
1290
1291 // Send finished signals for the batch sequence chain first.
1292 size_t seqChainCount = mSeqChains.size();
1293 if (seqChainCount) {
1294 uint32_t currentSeq = seq;
1295 uint32_t chainSeqs[seqChainCount];
1296 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001297 for (size_t i = seqChainCount; i > 0; ) {
1298 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001299 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001300 if (seqChain.seq == currentSeq) {
1301 currentSeq = seqChain.chain;
1302 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001303 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001304 }
1305 }
1306 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001307 while (!status && chainIndex > 0) {
1308 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001309 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1310 }
1311 if (status) {
1312 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001313 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001314 SeqChain seqChain;
1315 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1316 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001317 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001318 if (!chainIndex) break;
1319 chainIndex--;
1320 }
Jeff Brown5912f952013-07-01 19:10:31 -07001321 return status;
1322 }
1323 }
1324
1325 // Send finished signal for the last message in the batch.
1326 return sendUnchainedFinishedSignal(seq, handled);
1327}
1328
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001329status_t InputConsumer::sendTimeline(int32_t inputEventId,
1330 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001331 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1332 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1333 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1334 mChannel->getName().c_str(), inputEventId,
1335 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1336 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001337
1338 InputMessage msg;
1339 msg.header.type = InputMessage::Type::TIMELINE;
1340 msg.header.seq = 0;
1341 msg.body.timeline.eventId = inputEventId;
1342 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1343 return mChannel->sendMessage(&msg);
1344}
1345
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001346nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1347 auto it = mConsumeTimes.find(seq);
1348 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1349 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1350 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1351 seq);
1352 return it->second;
1353}
1354
1355void InputConsumer::popConsumeTime(uint32_t seq) {
1356 mConsumeTimes.erase(seq);
1357}
1358
Jeff Brown5912f952013-07-01 19:10:31 -07001359status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1360 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001361 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001362 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001363 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001364 msg.body.finished.consumeTime = getConsumeTime(seq);
1365 status_t result = mChannel->sendMessage(&msg);
1366 if (result == OK) {
1367 // Remove the consume time if the socket write succeeded. We will not need to ack this
1368 // message anymore. If the socket write did not succeed, we will try again and will still
1369 // need consume time.
1370 popConsumeTime(seq);
1371 }
1372 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001373}
1374
Jeff Brown5912f952013-07-01 19:10:31 -07001375bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001376 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001377}
1378
Arthur Hungc7812be2020-02-27 22:40:27 +08001379int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001380 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001381 return AINPUT_SOURCE_CLASS_NONE;
1382 }
1383
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001384 const Batch& batch = mBatches[0];
1385 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001386 return head.body.motion.source;
1387}
1388
Jeff Brown5912f952013-07-01 19:10:31 -07001389ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1390 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001391 const Batch& batch = mBatches[i];
1392 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001393 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1394 return i;
1395 }
1396 }
1397 return -1;
1398}
1399
1400ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1401 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001402 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001403 if (touchState.deviceId == deviceId && touchState.source == source) {
1404 return i;
1405 }
1406 }
1407 return -1;
1408}
1409
1410void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001411 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001412 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1413 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1414 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1415 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001416}
1417
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001418void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001419 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001420}
1421
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001422void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001423 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001424}
1425
arthurhung7632c332020-12-30 16:58:01 +08001426void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1427 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1428 msg->body.drag.isExiting);
1429}
1430
Jeff Brown5912f952013-07-01 19:10:31 -07001431void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001432 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001433 PointerProperties pointerProperties[pointerCount];
1434 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001435 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001436 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1437 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1438 }
1439
chaviw9eaa22c2020-07-01 16:21:27 -07001440 ui::Transform transform;
1441 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1442 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001443 ui::Transform displayTransform;
1444 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1445 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1446 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001447 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1448 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1449 msg->body.motion.actionButton, msg->body.motion.flags,
1450 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001451 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1452 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1453 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001454 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1455 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001456}
1457
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001458void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1459 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1460}
1461
Jeff Brown5912f952013-07-01 19:10:31 -07001462void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001463 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001464 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001465 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001466 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1467 }
1468
1469 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1470 event->addSample(msg->body.motion.eventTime, pointerCoords);
1471}
1472
1473bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001474 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001475 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001476 if (head.body.motion.pointerCount != pointerCount
1477 || head.body.motion.action != msg->body.motion.action) {
1478 return false;
1479 }
1480 for (size_t i = 0; i < pointerCount; i++) {
1481 if (head.body.motion.pointers[i].properties
1482 != msg->body.motion.pointers[i].properties) {
1483 return false;
1484 }
1485 }
1486 return true;
1487}
1488
1489ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1490 size_t numSamples = batch.samples.size();
1491 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001492 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001493 index += 1;
1494 }
1495 return ssize_t(index) - 1;
1496}
1497
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001498std::string InputConsumer::dump() const {
1499 std::string out;
1500 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1501 out = out + "mChannel = " + mChannel->getName() + "\n";
1502 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1503 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001504 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001505 }
1506 out += "Batches:\n";
1507 for (const Batch& batch : mBatches) {
1508 out += " Batch:\n";
1509 for (const InputMessage& msg : batch.samples) {
1510 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001511 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001512 switch (msg.header.type) {
1513 case InputMessage::Type::KEY: {
1514 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1515 KeyEvent::actionToString(
1516 msg.body.key.action),
1517 msg.body.key.keyCode);
1518 break;
1519 }
1520 case InputMessage::Type::MOTION: {
1521 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1522 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1523 const float x = msg.body.motion.pointers[i].coords.getX();
1524 const float y = msg.body.motion.pointers[i].coords.getY();
1525 out += android::base::StringPrintf("\n Pointer %" PRIu32
1526 " : x=%.1f y=%.1f",
1527 i, x, y);
1528 }
1529 break;
1530 }
1531 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001532 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1533 toString(msg.body.finished.handled),
1534 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001535 break;
1536 }
1537 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001538 out += android::base::StringPrintf("hasFocus=%s",
1539 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001540 break;
1541 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001542 case InputMessage::Type::CAPTURE: {
1543 out += android::base::StringPrintf("hasCapture=%s",
1544 toString(msg.body.capture
1545 .pointerCaptureEnabled));
1546 break;
1547 }
arthurhung7632c332020-12-30 16:58:01 +08001548 case InputMessage::Type::DRAG: {
1549 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1550 msg.body.drag.x, msg.body.drag.y,
1551 toString(msg.body.drag.isExiting));
1552 break;
1553 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001554 case InputMessage::Type::TIMELINE: {
1555 const nsecs_t gpuCompletedTime =
1556 msg.body.timeline
1557 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1558 const nsecs_t presentTime =
1559 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1560 out += android::base::StringPrintf("inputEventId=%" PRId32
1561 ", gpuCompletedTime=%" PRId64
1562 ", presentTime=%" PRId64,
1563 msg.body.timeline.eventId, gpuCompletedTime,
1564 presentTime);
1565 break;
1566 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001567 case InputMessage::Type::TOUCH_MODE: {
1568 out += android::base::StringPrintf("isInTouchMode=%s",
1569 toString(msg.body.touchMode.isInTouchMode));
1570 break;
1571 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001572 }
1573 out += "\n";
1574 }
1575 }
1576 if (mBatches.empty()) {
1577 out += " <empty>\n";
1578 }
1579 out += "mSeqChains:\n";
1580 for (const SeqChain& chain : mSeqChains) {
1581 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1582 chain.chain);
1583 }
1584 if (mSeqChains.empty()) {
1585 out += " <empty>\n";
1586 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001587 out += "mConsumeTimes:\n";
1588 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1589 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1590 consumeTime);
1591 }
1592 if (mConsumeTimes.empty()) {
1593 out += " <empty>\n";
1594 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001595 return out;
1596}
1597
Jeff Brown5912f952013-07-01 19:10:31 -07001598} // namespace android