blob: 843ef273f603634f731e0a56a690dc5c47986286 [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
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070017#include <android-base/logging.h>
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000018#include <android-base/properties.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000019#include <android-base/stringprintf.h>
20#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070021#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080022#include <ftl/enum.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070023#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000024#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070025
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <input/InputTransport.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000027#include <input/TraceTools.h>
Jeff Brown5912f952013-07-01 19:10:31 -070028
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000029namespace {
30
31/**
32 * Log debug messages about channel messages (send message, receive message).
33 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
34 * (requires restart)
35 */
36const bool DEBUG_CHANNEL_MESSAGES =
37 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
38
39/**
40 * Log debug messages whenever InputChannel objects are created/destroyed.
41 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
42 * (requires restart)
43 */
44const bool DEBUG_CHANNEL_LIFECYCLE =
45 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
46
47/**
48 * Log debug messages relating to the consumer end of the transport channel.
49 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
50 */
51
52const bool DEBUG_TRANSPORT_CONSUMER =
53 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
54
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000055const bool IS_DEBUGGABLE_BUILD =
56#if defined(__ANDROID__)
57 android::base::GetBoolProperty("ro.debuggable", false);
58#else
59 true;
60#endif
61
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000062/**
63 * Log debug messages relating to the producer end of the transport channel.
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000064 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
65 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
66 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000067 */
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000068bool debugTransportPublisher() {
69 if (!IS_DEBUGGABLE_BUILD) {
70 static const bool DEBUG_TRANSPORT_PUBLISHER =
71 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
72 return DEBUG_TRANSPORT_PUBLISHER;
73 }
74 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
75}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000076
77/**
78 * Log debug messages about touch event resampling.
Harry Cutts6c658cc2023-08-02 14:40:40 +000079 *
80 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG".
81 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
82 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000083 */
Harry Cutts6c658cc2023-08-02 14:40:40 +000084bool debugResampling() {
85 if (!IS_DEBUGGABLE_BUILD) {
86 static const bool DEBUG_TRANSPORT_RESAMPLING =
87 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling",
88 ANDROID_LOG_INFO);
89 return DEBUG_TRANSPORT_RESAMPLING;
90 }
91 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
92}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000093
94} // namespace
95
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070096using android::base::Result;
Michael Wright3dd60e22019-03-27 22:06:44 +000097using android::base::StringPrintf;
98
Jeff Brown5912f952013-07-01 19:10:31 -070099namespace android {
100
101// Socket buffer size. The default is typically about 128KB, which is much larger than
102// we really need. So we make it smaller. It just needs to be big enough to hold
103// a few dozen large multi-finger motion events in the case where an application gets
104// behind processing touches.
105static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
106
107// Nanoseconds per milliseconds.
108static const nsecs_t NANOS_PER_MS = 1000000;
109
110// Latency added during resampling. A few milliseconds doesn't hurt much but
111// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800112const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -0700113
114// Minimum time difference between consecutive samples before attempting to resample.
115static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
116
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700117// Maximum time difference between consecutive samples before attempting to resample
118// by extrapolation.
119static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
120
Jeff Brown5912f952013-07-01 19:10:31 -0700121// Maximum time to predict forward from the last known state, to avoid predicting too
122// far into the future. This time is further bounded by 50% of the last time delta.
123static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
124
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600125/**
126 * System property for enabling / disabling touch resampling.
127 * Resampling extrapolates / interpolates the reported touch event coordinates to better
128 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
129 * Resampling is not needed (and should be disabled) on hardware that already
130 * has touch events triggered by VSYNC.
131 * Set to "1" to enable resampling (default).
132 * Set to "0" to disable resampling.
133 * Resampling is enabled by default.
134 */
135static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
136
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800137/**
138 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
139 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
140 */
141static bool verifyEvents() {
142 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
143}
144
Jeff Brown5912f952013-07-01 19:10:31 -0700145template<typename T>
146inline static T min(const T& a, const T& b) {
147 return a < b ? a : b;
148}
149
150inline static float lerp(float a, float b, float alpha) {
151 return a + alpha * (b - a);
152}
153
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800154inline static bool isPointerEvent(int32_t source) {
155 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
156}
157
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800158inline static const char* toString(bool value) {
159 return value ? "true" : "false";
160}
161
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700162static bool shouldResampleTool(ToolType toolType) {
163 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
164}
165
Jeff Brown5912f952013-07-01 19:10:31 -0700166// --- InputMessage ---
167
168bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000169 if (size() != actualSize) {
170 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
171 return false;
172 }
173
174 switch (header.type) {
175 case Type::KEY:
176 return true;
177 case Type::MOTION: {
178 const bool valid =
179 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
180 if (!valid) {
181 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
182 }
183 return valid;
184 }
185 case Type::FINISHED:
186 case Type::FOCUS:
187 case Type::CAPTURE:
188 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700189 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000190 return true;
191 case Type::TIMELINE: {
192 const nsecs_t gpuCompletedTime =
193 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
194 const nsecs_t presentTime =
195 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
196 const bool valid = presentTime > gpuCompletedTime;
197 if (!valid) {
198 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
199 " presentTime = %" PRId64,
200 gpuCompletedTime, presentTime);
201 }
202 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700203 }
204 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000205 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700206 return false;
207}
208
209size_t InputMessage::size() const {
210 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700211 case Type::KEY:
212 return sizeof(Header) + body.key.size();
213 case Type::MOTION:
214 return sizeof(Header) + body.motion.size();
215 case Type::FINISHED:
216 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800217 case Type::FOCUS:
218 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800219 case Type::CAPTURE:
220 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800221 case Type::DRAG:
222 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000223 case Type::TIMELINE:
224 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700225 case Type::TOUCH_MODE:
226 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700227 }
228 return sizeof(Header);
229}
230
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800231/**
232 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
233 * memory to zero, then only copy the valid bytes on a per-field basis.
234 */
235void InputMessage::getSanitizedCopy(InputMessage* msg) const {
236 memset(msg, 0, sizeof(*msg));
237
238 // Write the header
239 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500240 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800241
242 // Write the body
243 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700244 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800245 // int32_t eventId
246 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800247 // nsecs_t eventTime
248 msg->body.key.eventTime = body.key.eventTime;
249 // int32_t deviceId
250 msg->body.key.deviceId = body.key.deviceId;
251 // int32_t source
252 msg->body.key.source = body.key.source;
253 // int32_t displayId
254 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600255 // std::array<uint8_t, 32> hmac
256 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800257 // int32_t action
258 msg->body.key.action = body.key.action;
259 // int32_t flags
260 msg->body.key.flags = body.key.flags;
261 // int32_t keyCode
262 msg->body.key.keyCode = body.key.keyCode;
263 // int32_t scanCode
264 msg->body.key.scanCode = body.key.scanCode;
265 // int32_t metaState
266 msg->body.key.metaState = body.key.metaState;
267 // int32_t repeatCount
268 msg->body.key.repeatCount = body.key.repeatCount;
269 // nsecs_t downTime
270 msg->body.key.downTime = body.key.downTime;
271 break;
272 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700273 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800274 // int32_t eventId
275 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700276 // uint32_t pointerCount
277 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800278 // nsecs_t eventTime
279 msg->body.motion.eventTime = body.motion.eventTime;
280 // int32_t deviceId
281 msg->body.motion.deviceId = body.motion.deviceId;
282 // int32_t source
283 msg->body.motion.source = body.motion.source;
284 // int32_t displayId
285 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600286 // std::array<uint8_t, 32> hmac
287 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800288 // int32_t action
289 msg->body.motion.action = body.motion.action;
290 // int32_t actionButton
291 msg->body.motion.actionButton = body.motion.actionButton;
292 // int32_t flags
293 msg->body.motion.flags = body.motion.flags;
294 // int32_t metaState
295 msg->body.motion.metaState = body.motion.metaState;
296 // int32_t buttonState
297 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800298 // MotionClassification classification
299 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800300 // int32_t edgeFlags
301 msg->body.motion.edgeFlags = body.motion.edgeFlags;
302 // nsecs_t downTime
303 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700304
305 msg->body.motion.dsdx = body.motion.dsdx;
306 msg->body.motion.dtdx = body.motion.dtdx;
307 msg->body.motion.dtdy = body.motion.dtdy;
308 msg->body.motion.dsdy = body.motion.dsdy;
309 msg->body.motion.tx = body.motion.tx;
310 msg->body.motion.ty = body.motion.ty;
311
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800312 // float xPrecision
313 msg->body.motion.xPrecision = body.motion.xPrecision;
314 // float yPrecision
315 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700316 // float xCursorPosition
317 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
318 // float yCursorPosition
319 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700320
321 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
322 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
323 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
324 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
325 msg->body.motion.txRaw = body.motion.txRaw;
326 msg->body.motion.tyRaw = body.motion.tyRaw;
327
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800328 //struct Pointer pointers[MAX_POINTERS]
329 for (size_t i = 0; i < body.motion.pointerCount; i++) {
330 // PointerProperties properties
331 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
332 msg->body.motion.pointers[i].properties.toolType =
333 body.motion.pointers[i].properties.toolType,
334 // PointerCoords coords
335 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
336 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
337 memcpy(&msg->body.motion.pointers[i].coords.values[0],
338 &body.motion.pointers[i].coords.values[0],
339 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800340 msg->body.motion.pointers[i].coords.isResampled =
341 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800342 }
343 break;
344 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700345 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800346 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000347 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800348 break;
349 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800350 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800351 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800352 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800353 break;
354 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800355 case InputMessage::Type::CAPTURE: {
356 msg->body.capture.eventId = body.capture.eventId;
357 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
358 break;
359 }
arthurhung7632c332020-12-30 16:58:01 +0800360 case InputMessage::Type::DRAG: {
361 msg->body.drag.eventId = body.drag.eventId;
362 msg->body.drag.x = body.drag.x;
363 msg->body.drag.y = body.drag.y;
364 msg->body.drag.isExiting = body.drag.isExiting;
365 break;
366 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000367 case InputMessage::Type::TIMELINE: {
368 msg->body.timeline.eventId = body.timeline.eventId;
369 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
370 break;
371 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700372 case InputMessage::Type::TOUCH_MODE: {
373 msg->body.touchMode.eventId = body.touchMode.eventId;
374 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
375 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800376 }
377}
Jeff Brown5912f952013-07-01 19:10:31 -0700378
379// --- InputChannel ---
380
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500381std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500382 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700383 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
384 if (result != 0) {
385 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
386 strerror(errno));
387 return nullptr;
388 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500389 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500390 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700391}
392
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500393InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
394 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000395 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
396 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700397}
398
399InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000400 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
401 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700402}
403
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800404status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500405 std::unique_ptr<InputChannel>& outServerChannel,
406 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700407 int sockets[2];
408 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
409 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000410 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
411 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500412 outServerChannel.reset();
413 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700414 return result;
415 }
416
417 int bufferSize = SOCKET_BUFFER_SIZE;
418 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
419 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
420 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
421 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
422
Siarhei Vishniakou4c155eb2023-06-30 11:47:12 -0700423 sp<IBinder> token = sp<BBinder>::make();
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700424
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700425 std::string serverChannelName = name + " (server)";
426 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700427 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700428
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700429 std::string clientChannelName = name + " (client)";
430 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700431 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700432 return OK;
433}
434
435status_t InputChannel::sendMessage(const InputMessage* msg) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000436 ATRACE_NAME_IF(ATRACE_ENABLED(), [&]() {
437 return StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=0x%" PRIx32 ")",
438 mName.c_str(), msg->header.seq, msg->header.type);
439 });
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800440 const size_t msgLength = msg->size();
441 InputMessage cleanMsg;
442 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700443 ssize_t nWrite;
444 do {
Chris Ye0783e992020-06-02 21:34:49 -0700445 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700446 } while (nWrite == -1 && errno == EINTR);
447
448 if (nWrite < 0) {
449 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000450 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
451 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700452 if (error == EAGAIN || error == EWOULDBLOCK) {
453 return WOULD_BLOCK;
454 }
455 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
456 return DEAD_OBJECT;
457 }
458 return -error;
459 }
460
461 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000462 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
463 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
464 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700465 return DEAD_OBJECT;
466 }
467
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000468 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
469 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100470
Jeff Brown5912f952013-07-01 19:10:31 -0700471 return OK;
472}
473
474status_t InputChannel::receiveMessage(InputMessage* msg) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000475 ATRACE_NAME_IF(ATRACE_ENABLED(), [&]() {
476 return StringPrintf("receiveMessage(inputChannel=%s)", mName.c_str());
477 });
Jeff Brown5912f952013-07-01 19:10:31 -0700478 ssize_t nRead;
479 do {
Chris Ye0783e992020-06-02 21:34:49 -0700480 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700481 } while (nRead == -1 && errno == EINTR);
482
483 if (nRead < 0) {
484 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000485 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
486 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700487 if (error == EAGAIN || error == EWOULDBLOCK) {
488 return WOULD_BLOCK;
489 }
490 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
491 return DEAD_OBJECT;
492 }
493 return -error;
494 }
495
496 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000497 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
498 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700499 return DEAD_OBJECT;
500 }
501
502 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000503 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700504 return BAD_VALUE;
505 }
506
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000507 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
508 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100509 if (ATRACE_ENABLED()) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000510 // Add an additional trace point to include data about the received message.
Zimd8402b62023-06-02 11:56:26 +0100511 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
512 ", type=0x%" PRIx32 ")",
513 mName.c_str(), msg->header.seq, msg->header.type);
514 ATRACE_NAME(message.c_str());
515 }
Jeff Brown5912f952013-07-01 19:10:31 -0700516 return OK;
517}
518
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500519std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700520 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700521 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700522}
523
Garfield Tan15601662020-09-22 15:32:38 -0700524void InputChannel::copyTo(InputChannel& outChannel) const {
525 outChannel.mName = getName();
526 outChannel.mFd = dupFd();
527 outChannel.mToken = getConnectionToken();
528}
529
Chris Ye0783e992020-06-02 21:34:49 -0700530status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500531 if (parcel == nullptr) {
532 ALOGE("%s: Null parcel", __func__);
533 return BAD_VALUE;
534 }
535 return parcel->writeStrongBinder(mToken)
536 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700537}
538
Chris Ye0783e992020-06-02 21:34:49 -0700539status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500540 if (parcel == nullptr) {
541 ALOGE("%s: Null parcel", __func__);
542 return BAD_VALUE;
543 }
544 mToken = parcel->readStrongBinder();
545 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700546}
547
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700548sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500549 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700550}
551
Garfield Tan15601662020-09-22 15:32:38 -0700552base::unique_fd InputChannel::dupFd() const {
553 android::base::unique_fd newFd(::dup(getFd()));
554 if (!newFd.ok()) {
555 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
556 strerror(errno));
557 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
558 // If this process is out of file descriptors, then throwing that might end up exploding
559 // on the other side of a binder call, which isn't really helpful.
560 // Better to just crash here and hope that the FD leak is slow.
561 // Other failures could be client errors, so we still propagate those back to the caller.
562 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
563 getName().c_str());
564 return {};
565 }
566 return newFd;
567}
568
Jeff Brown5912f952013-07-01 19:10:31 -0700569// --- InputPublisher ---
570
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800571InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
572 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700573
574InputPublisher::~InputPublisher() {
575}
576
Garfield Tan1c7bc862020-01-28 13:24:04 -0800577status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
578 int32_t source, int32_t displayId,
579 std::array<uint8_t, 32> hmac, int32_t action,
580 int32_t flags, int32_t keyCode, int32_t scanCode,
581 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
582 nsecs_t eventTime) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000583 ATRACE_NAME_IF(ATRACE_ENABLED(), [&]() {
584 return StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
585 mChannel->getName().c_str(), KeyEvent::actionToString(action),
586 KeyEvent::getLabel(keyCode));
587 });
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000588 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000589 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000590 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
591 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000592 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000593 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
594 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700595
596 if (!seq) {
597 ALOGE("Attempted to publish a key event with sequence number 0.");
598 return BAD_VALUE;
599 }
600
601 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700602 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500603 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800604 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700605 msg.body.key.deviceId = deviceId;
606 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100607 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700608 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700609 msg.body.key.action = action;
610 msg.body.key.flags = flags;
611 msg.body.key.keyCode = keyCode;
612 msg.body.key.scanCode = scanCode;
613 msg.body.key.metaState = metaState;
614 msg.body.key.repeatCount = repeatCount;
615 msg.body.key.downTime = downTime;
616 msg.body.key.eventTime = eventTime;
617 return mChannel->sendMessage(&msg);
618}
619
620status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800621 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600622 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
623 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700624 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700625 float yPrecision, float xCursorPosition, float yCursorPosition,
626 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700627 uint32_t pointerCount, const PointerProperties* pointerProperties,
628 const PointerCoords* pointerCoords) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000629 ATRACE_NAME_IF(ATRACE_ENABLED(), [&]() {
630 return StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
631 mChannel->getName().c_str(),
632 MotionEvent::actionToString(action).c_str());
633 });
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800634 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700635 Result<void> result =
636 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
637 pointerCoords, flags);
638 if (!result.ok()) {
639 LOG(FATAL) << "Bad stream: " << result.error();
640 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800641 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000642 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700643 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700644 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000645 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800646 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000647 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700648 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800649 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700650 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000651 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000652 inputEventSourceToString(source).c_str(), displayId,
653 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
654 metaState, buttonState, motionClassificationToString(classification), xPrecision,
655 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800656 }
Jeff Brown5912f952013-07-01 19:10:31 -0700657
658 if (!seq) {
659 ALOGE("Attempted to publish a motion event with sequence number 0.");
660 return BAD_VALUE;
661 }
662
663 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700664 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800665 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700666 return BAD_VALUE;
667 }
668
669 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700670 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500671 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800672 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700673 msg.body.motion.deviceId = deviceId;
674 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700675 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700676 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700677 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100678 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700679 msg.body.motion.flags = flags;
680 msg.body.motion.edgeFlags = edgeFlags;
681 msg.body.motion.metaState = metaState;
682 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800683 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700684 msg.body.motion.dsdx = transform.dsdx();
685 msg.body.motion.dtdx = transform.dtdx();
686 msg.body.motion.dtdy = transform.dtdy();
687 msg.body.motion.dsdy = transform.dsdy();
688 msg.body.motion.tx = transform.tx();
689 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700690 msg.body.motion.xPrecision = xPrecision;
691 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700692 msg.body.motion.xCursorPosition = xCursorPosition;
693 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700694 msg.body.motion.dsdxRaw = rawTransform.dsdx();
695 msg.body.motion.dtdxRaw = rawTransform.dtdx();
696 msg.body.motion.dtdyRaw = rawTransform.dtdy();
697 msg.body.motion.dsdyRaw = rawTransform.dsdy();
698 msg.body.motion.txRaw = rawTransform.tx();
699 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700700 msg.body.motion.downTime = downTime;
701 msg.body.motion.eventTime = eventTime;
702 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100703 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -0700704 msg.body.motion.pointers[i].properties = pointerProperties[i];
705 msg.body.motion.pointers[i].coords = pointerCoords[i];
Jeff Brown5912f952013-07-01 19:10:31 -0700706 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700707
Jeff Brown5912f952013-07-01 19:10:31 -0700708 return mChannel->sendMessage(&msg);
709}
710
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700711status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000712 ATRACE_NAME_IF(ATRACE_ENABLED(), [&]() {
713 return StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
714 mChannel->getName().c_str(), toString(hasFocus));
715 });
Prabir Pradhan96282b02023-02-24 22:36:17 +0000716 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
717 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800718
719 InputMessage msg;
720 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500721 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800722 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000723 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800724 return mChannel->sendMessage(&msg);
725}
726
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800727status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
728 bool pointerCaptureEnabled) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000729 ATRACE_NAME_IF(ATRACE_ENABLED(), [&]() {
730 return StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
731 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
732 });
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000733 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000734 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
735 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800736
737 InputMessage msg;
738 msg.header.type = InputMessage::Type::CAPTURE;
739 msg.header.seq = seq;
740 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000741 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800742 return mChannel->sendMessage(&msg);
743}
744
arthurhung7632c332020-12-30 16:58:01 +0800745status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
746 bool isExiting) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000747 ATRACE_NAME_IF(ATRACE_ENABLED(), [&]() {
748 return StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
749 mChannel->getName().c_str(), x, y, toString(isExiting));
750 });
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000751 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000752 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
753 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800754
755 InputMessage msg;
756 msg.header.type = InputMessage::Type::DRAG;
757 msg.header.seq = seq;
758 msg.body.drag.eventId = eventId;
759 msg.body.drag.isExiting = isExiting;
760 msg.body.drag.x = x;
761 msg.body.drag.y = y;
762 return mChannel->sendMessage(&msg);
763}
764
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700765status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000766 ATRACE_NAME_IF(ATRACE_ENABLED(), [&]() {
767 return StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
768 mChannel->getName().c_str(), toString(isInTouchMode));
769 });
Prabir Pradhan96282b02023-02-24 22:36:17 +0000770 ALOGD_IF(debugTransportPublisher(),
771 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
772 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700773
774 InputMessage msg;
775 msg.header.type = InputMessage::Type::TOUCH_MODE;
776 msg.header.seq = seq;
777 msg.body.touchMode.eventId = eventId;
778 msg.body.touchMode.isInTouchMode = isInTouchMode;
779 return mChannel->sendMessage(&msg);
780}
781
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000782android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700783 InputMessage msg;
784 status_t result = mChannel->receiveMessage(&msg);
785 if (result) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000786 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: %s",
787 mChannel->getName().c_str(), __func__, strerror(result));
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000788 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700789 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000790 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000791 ALOGD_IF(debugTransportPublisher(),
792 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
793 mChannel->getName().c_str(), __func__, msg.header.seq,
794 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000795 return Finished{
796 .seq = msg.header.seq,
797 .handled = msg.body.finished.handled,
798 .consumeTime = msg.body.finished.consumeTime,
799 };
Jeff Brown5912f952013-07-01 19:10:31 -0700800 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000801
802 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000803 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
804 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000805 return Timeline{
806 .inputEventId = msg.body.timeline.eventId,
807 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
808 };
809 }
810
811 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800812 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000813 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700814}
815
816// --- InputConsumer ---
817
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500818InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800819 : InputConsumer(channel, isTouchResamplingEnabled()) {}
820
821InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
822 bool enableTouchResampling)
823 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700824
825InputConsumer::~InputConsumer() {
826}
827
828bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600829 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700830}
831
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800832status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
833 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000834 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
835 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
836 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700837
838 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700839 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700840
841 // Fetch the next input message.
842 // Loop until an event can be returned or no additional events are received.
843 while (!*outEvent) {
844 if (mMsgDeferred) {
845 // mMsg contains a valid input message from the previous call to consume
846 // that has not yet been processed.
847 mMsgDeferred = false;
848 } else {
849 // Receive a fresh message.
850 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000851 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800852 const auto [_, inserted] =
853 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
854 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
855 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000856 }
Jeff Brown5912f952013-07-01 19:10:31 -0700857 if (result) {
858 // Consume the next batched event unless batches are being held for later.
859 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800860 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700861 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000862 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
863 "channel '%s' consumer ~ consumed batch event, seq=%u",
864 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700865 break;
866 }
867 }
868 return result;
869 }
870 }
871
872 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700873 case InputMessage::Type::KEY: {
874 KeyEvent* keyEvent = factory->createKeyEvent();
875 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700876
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700877 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500878 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700879 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000880 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
881 "channel '%s' consumer ~ consumed key event, seq=%u",
882 mChannel->getName().c_str(), *outSeq);
883 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700884 }
Jeff Brown5912f952013-07-01 19:10:31 -0700885
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700886 case InputMessage::Type::MOTION: {
887 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
888 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500889 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700890 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500891 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000892 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
893 "channel '%s' consumer ~ appended to batch event",
894 mChannel->getName().c_str());
895 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700896 } else if (isPointerEvent(mMsg.body.motion.source) &&
897 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
898 // No need to process events that we are going to cancel anyways
899 const size_t count = batch.samples.size();
900 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500901 const InputMessage& msg = batch.samples[i];
902 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700903 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500904 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
905 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700906 } else {
907 // We cannot append to the batch in progress, so we need to consume
908 // the previous batch right now and defer the new message until later.
909 mMsgDeferred = true;
910 status_t result = consumeSamples(factory, batch, batch.samples.size(),
911 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500912 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700913 if (result) {
914 return result;
915 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000916 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
917 "channel '%s' consumer ~ consumed batch event and "
918 "deferred current event, seq=%u",
919 mChannel->getName().c_str(), *outSeq);
920 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700921 }
Jeff Brown5912f952013-07-01 19:10:31 -0700922 }
Jeff Brown5912f952013-07-01 19:10:31 -0700923
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800924 // Start a new batch if needed.
925 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
926 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500927 Batch batch;
928 batch.samples.push_back(mMsg);
929 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000930 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
931 "channel '%s' consumer ~ started batch event",
932 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800933 break;
934 }
Jeff Brown5912f952013-07-01 19:10:31 -0700935
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800936 MotionEvent* motionEvent = factory->createMotionEvent();
937 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700938
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800939 updateTouchState(mMsg);
940 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500941 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800942 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800943
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000944 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
945 "channel '%s' consumer ~ consumed motion event, seq=%u",
946 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800947 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700948 }
Jeff Brown5912f952013-07-01 19:10:31 -0700949
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000950 case InputMessage::Type::FINISHED:
951 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000952 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
953 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800954 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800955 break;
956 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800957
958 case InputMessage::Type::FOCUS: {
959 FocusEvent* focusEvent = factory->createFocusEvent();
960 if (!focusEvent) return NO_MEMORY;
961
962 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500963 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800964 *outEvent = focusEvent;
965 break;
966 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800967
968 case InputMessage::Type::CAPTURE: {
969 CaptureEvent* captureEvent = factory->createCaptureEvent();
970 if (!captureEvent) return NO_MEMORY;
971
972 initializeCaptureEvent(captureEvent, &mMsg);
973 *outSeq = mMsg.header.seq;
974 *outEvent = captureEvent;
975 break;
976 }
arthurhung7632c332020-12-30 16:58:01 +0800977
978 case InputMessage::Type::DRAG: {
979 DragEvent* dragEvent = factory->createDragEvent();
980 if (!dragEvent) return NO_MEMORY;
981
982 initializeDragEvent(dragEvent, &mMsg);
983 *outSeq = mMsg.header.seq;
984 *outEvent = dragEvent;
985 break;
986 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700987
988 case InputMessage::Type::TOUCH_MODE: {
989 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
990 if (!touchModeEvent) return NO_MEMORY;
991
992 initializeTouchModeEvent(touchModeEvent, &mMsg);
993 *outSeq = mMsg.header.seq;
994 *outEvent = touchModeEvent;
995 break;
996 }
Jeff Brown5912f952013-07-01 19:10:31 -0700997 }
998 }
999 return OK;
1000}
1001
1002status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001003 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001004 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001005 for (size_t i = mBatches.size(); i > 0; ) {
1006 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001007 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001008 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001009 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001010 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001011 return result;
1012 }
1013
Michael Wright32232172013-10-21 12:05:22 -07001014 nsecs_t sampleTime = frameTime;
1015 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001016 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001017 }
Jeff Brown5912f952013-07-01 19:10:31 -07001018 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1019 if (split < 0) {
1020 continue;
1021 }
1022
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001023 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001024 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001025 if (batch.samples.empty()) {
1026 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001027 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001028 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001029 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001030 }
Michael Wright32232172013-10-21 12:05:22 -07001031 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001032 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1033 }
1034 return result;
1035 }
1036
1037 return WOULD_BLOCK;
1038}
1039
1040status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001041 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001042 MotionEvent* motionEvent = factory->createMotionEvent();
1043 if (! motionEvent) return NO_MEMORY;
1044
1045 uint32_t chain = 0;
1046 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001047 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001048 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001049 if (i) {
1050 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001051 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001052 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001053 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001054 addSample(motionEvent, &msg);
1055 } else {
1056 initializeMotionEvent(motionEvent, &msg);
1057 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001058 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001059 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001060 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001061
1062 *outSeq = chain;
1063 *outEvent = motionEvent;
1064 return OK;
1065}
1066
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001067void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001068 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001069 return;
1070 }
1071
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001072 int32_t deviceId = msg.body.motion.deviceId;
1073 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001074
1075 // Update the touch state history to incorporate the new input message.
1076 // If the message is in the past relative to the most recently produced resampled
1077 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001078 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001079 case AMOTION_EVENT_ACTION_DOWN: {
1080 ssize_t index = findTouchState(deviceId, source);
1081 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001082 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001083 index = mTouchStates.size() - 1;
1084 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001085 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001086 touchState.initialize(deviceId, source);
1087 touchState.addHistory(msg);
1088 break;
1089 }
1090
1091 case AMOTION_EVENT_ACTION_MOVE: {
1092 ssize_t index = findTouchState(deviceId, source);
1093 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001094 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001095 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001096 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001097 }
1098 break;
1099 }
1100
1101 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1102 ssize_t index = findTouchState(deviceId, source);
1103 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001104 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001105 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001106 rewriteMessage(touchState, msg);
1107 }
1108 break;
1109 }
1110
1111 case AMOTION_EVENT_ACTION_POINTER_UP: {
1112 ssize_t index = findTouchState(deviceId, source);
1113 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001114 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001115 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001116 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001117 }
1118 break;
1119 }
1120
1121 case AMOTION_EVENT_ACTION_SCROLL: {
1122 ssize_t index = findTouchState(deviceId, source);
1123 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001124 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001125 rewriteMessage(touchState, msg);
1126 }
1127 break;
1128 }
1129
1130 case AMOTION_EVENT_ACTION_UP:
1131 case AMOTION_EVENT_ACTION_CANCEL: {
1132 ssize_t index = findTouchState(deviceId, source);
1133 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001134 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001135 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001136 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001137 }
1138 break;
1139 }
1140 }
1141}
1142
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001143/**
1144 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1145 *
1146 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1147 * is in the past relative to msg and the past two events do not contain identical coordinates),
1148 * then invalidate the lastResample data for that pointer.
1149 * If the two past events have identical coordinates, then lastResample data for that pointer will
1150 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1151 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1152 * not equal to x0 is received.
1153 */
1154void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001155 nsecs_t eventTime = msg.body.motion.eventTime;
1156 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1157 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001158 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001159 if (eventTime < state.lastResample.eventTime ||
1160 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001161 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1162 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001163 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001164 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1165 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001166 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1167 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001168 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001169 } else {
1170 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001171 }
Jeff Brown5912f952013-07-01 19:10:31 -07001172 }
1173 }
1174}
1175
1176void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1177 const InputMessage* next) {
1178 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001179 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001180 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1181 return;
1182 }
1183
1184 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1185 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001186 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001187 return;
1188 }
1189
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001190 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001191 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001192 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001193 return;
1194 }
1195
1196 // Ensure that the current sample has all of the pointers that need to be reported.
1197 const History* current = touchState.getHistory(0);
1198 size_t pointerCount = event->getPointerCount();
1199 for (size_t i = 0; i < pointerCount; i++) {
1200 uint32_t id = event->getPointerId(i);
1201 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001202 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001203 return;
1204 }
1205 }
1206
1207 // Find the data to use for resampling.
1208 const History* other;
1209 History future;
1210 float alpha;
1211 if (next) {
1212 // Interpolate between current sample and future sample.
1213 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001214 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001215 other = &future;
1216 nsecs_t delta = future.eventTime - current->eventTime;
1217 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001218 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001219 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001220 return;
1221 }
1222 alpha = float(sampleTime - current->eventTime) / delta;
1223 } else if (touchState.historySize >= 2) {
1224 // Extrapolate future sample using current sample and past sample.
1225 // So other->eventTime <= current->eventTime <= sampleTime.
1226 other = touchState.getHistory(1);
1227 nsecs_t delta = current->eventTime - other->eventTime;
1228 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001229 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001230 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001231 return;
1232 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001233 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001234 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001235 return;
1236 }
1237 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1238 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001239 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001240 "Sample time is too far in the future, adjusting prediction "
1241 "from %" PRId64 " to %" PRId64 " ns.",
1242 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001243 sampleTime = maxPredict;
1244 }
1245 alpha = float(current->eventTime - sampleTime) / delta;
1246 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001247 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001248 return;
1249 }
1250
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001251 if (current->eventTime == sampleTime) {
1252 // Prevents having 2 events with identical times and coordinates.
1253 return;
1254 }
1255
Jeff Brown5912f952013-07-01 19:10:31 -07001256 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001257 History oldLastResample;
1258 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001259 touchState.lastResample.eventTime = sampleTime;
1260 touchState.lastResample.idBits.clear();
1261 for (size_t i = 0; i < pointerCount; i++) {
1262 uint32_t id = event->getPointerId(i);
1263 touchState.lastResample.idToIndex[id] = i;
1264 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001265 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1266 // We maintain the previously resampled value for this pointer (stored in
1267 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1268 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001269 // The isResampled flag isn't cleared as the values don't reflect what the device is
1270 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001271
1272 // We know here that the coordinates for the pointer haven't changed because we
1273 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1274 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001275 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001276 continue;
1277 }
1278
Jeff Brown5912f952013-07-01 19:10:31 -07001279 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1280 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001281 resampledCoords = currentCoords;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001282 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001283 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001284 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001285 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001286 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001287 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001288 resampledCoords.isResampled = true;
Harry Cutts6c658cc2023-08-02 14:40:40 +00001289 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001290 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1291 "other (%0.3f, %0.3f), alpha %0.3f",
1292 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1293 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001294 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001295 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001296 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1297 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001298 }
1299 }
1300
1301 event->addSample(sampleTime, touchState.lastResample.pointers);
1302}
1303
Jeff Brown5912f952013-07-01 19:10:31 -07001304status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001305 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1306 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1307 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001308
1309 if (!seq) {
1310 ALOGE("Attempted to send a finished signal with sequence number 0.");
1311 return BAD_VALUE;
1312 }
1313
1314 // Send finished signals for the batch sequence chain first.
1315 size_t seqChainCount = mSeqChains.size();
1316 if (seqChainCount) {
1317 uint32_t currentSeq = seq;
1318 uint32_t chainSeqs[seqChainCount];
1319 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001320 for (size_t i = seqChainCount; i > 0; ) {
1321 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001322 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001323 if (seqChain.seq == currentSeq) {
1324 currentSeq = seqChain.chain;
1325 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001326 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001327 }
1328 }
1329 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001330 while (!status && chainIndex > 0) {
1331 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001332 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1333 }
1334 if (status) {
1335 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001336 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001337 SeqChain seqChain;
1338 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1339 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001340 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001341 if (!chainIndex) break;
1342 chainIndex--;
1343 }
Jeff Brown5912f952013-07-01 19:10:31 -07001344 return status;
1345 }
1346 }
1347
1348 // Send finished signal for the last message in the batch.
1349 return sendUnchainedFinishedSignal(seq, handled);
1350}
1351
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001352status_t InputConsumer::sendTimeline(int32_t inputEventId,
1353 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001354 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1355 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1356 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1357 mChannel->getName().c_str(), inputEventId,
1358 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1359 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001360
1361 InputMessage msg;
1362 msg.header.type = InputMessage::Type::TIMELINE;
1363 msg.header.seq = 0;
1364 msg.body.timeline.eventId = inputEventId;
1365 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1366 return mChannel->sendMessage(&msg);
1367}
1368
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001369nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1370 auto it = mConsumeTimes.find(seq);
1371 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1372 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1373 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1374 seq);
1375 return it->second;
1376}
1377
1378void InputConsumer::popConsumeTime(uint32_t seq) {
1379 mConsumeTimes.erase(seq);
1380}
1381
Jeff Brown5912f952013-07-01 19:10:31 -07001382status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1383 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001384 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001385 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001386 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001387 msg.body.finished.consumeTime = getConsumeTime(seq);
1388 status_t result = mChannel->sendMessage(&msg);
1389 if (result == OK) {
1390 // Remove the consume time if the socket write succeeded. We will not need to ack this
1391 // message anymore. If the socket write did not succeed, we will try again and will still
1392 // need consume time.
1393 popConsumeTime(seq);
1394 }
1395 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001396}
1397
Jeff Brown5912f952013-07-01 19:10:31 -07001398bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001399 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001400}
1401
Arthur Hungc7812be2020-02-27 22:40:27 +08001402int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001403 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001404 return AINPUT_SOURCE_CLASS_NONE;
1405 }
1406
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001407 const Batch& batch = mBatches[0];
1408 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001409 return head.body.motion.source;
1410}
1411
Jeff Brown5912f952013-07-01 19:10:31 -07001412ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1413 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001414 const Batch& batch = mBatches[i];
1415 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001416 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1417 return i;
1418 }
1419 }
1420 return -1;
1421}
1422
1423ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1424 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001425 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001426 if (touchState.deviceId == deviceId && touchState.source == source) {
1427 return i;
1428 }
1429 }
1430 return -1;
1431}
1432
1433void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001434 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001435 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1436 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1437 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1438 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001439}
1440
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001441void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001442 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001443}
1444
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001445void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001446 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001447}
1448
arthurhung7632c332020-12-30 16:58:01 +08001449void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1450 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1451 msg->body.drag.isExiting);
1452}
1453
Jeff Brown5912f952013-07-01 19:10:31 -07001454void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001455 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001456 PointerProperties pointerProperties[pointerCount];
1457 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001458 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001459 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1460 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001461 }
1462
chaviw9eaa22c2020-07-01 16:21:27 -07001463 ui::Transform transform;
1464 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1465 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001466 ui::Transform displayTransform;
1467 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1468 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1469 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001470 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1471 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1472 msg->body.motion.actionButton, msg->body.motion.flags,
1473 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001474 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1475 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1476 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001477 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1478 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001479}
1480
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001481void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1482 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1483}
1484
Jeff Brown5912f952013-07-01 19:10:31 -07001485void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001486 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001487 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001488 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001489 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001490 }
1491
1492 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1493 event->addSample(msg->body.motion.eventTime, pointerCoords);
1494}
1495
1496bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001497 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001498 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001499 if (head.body.motion.pointerCount != pointerCount
1500 || head.body.motion.action != msg->body.motion.action) {
1501 return false;
1502 }
1503 for (size_t i = 0; i < pointerCount; i++) {
1504 if (head.body.motion.pointers[i].properties
1505 != msg->body.motion.pointers[i].properties) {
1506 return false;
1507 }
1508 }
1509 return true;
1510}
1511
1512ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1513 size_t numSamples = batch.samples.size();
1514 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001515 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001516 index += 1;
1517 }
1518 return ssize_t(index) - 1;
1519}
1520
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001521std::string InputConsumer::dump() const {
1522 std::string out;
1523 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1524 out = out + "mChannel = " + mChannel->getName() + "\n";
1525 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1526 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001527 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001528 }
1529 out += "Batches:\n";
1530 for (const Batch& batch : mBatches) {
1531 out += " Batch:\n";
1532 for (const InputMessage& msg : batch.samples) {
1533 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001534 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001535 switch (msg.header.type) {
1536 case InputMessage::Type::KEY: {
1537 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1538 KeyEvent::actionToString(
1539 msg.body.key.action),
1540 msg.body.key.keyCode);
1541 break;
1542 }
1543 case InputMessage::Type::MOTION: {
1544 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1545 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1546 const float x = msg.body.motion.pointers[i].coords.getX();
1547 const float y = msg.body.motion.pointers[i].coords.getY();
1548 out += android::base::StringPrintf("\n Pointer %" PRIu32
1549 " : x=%.1f y=%.1f",
1550 i, x, y);
1551 }
1552 break;
1553 }
1554 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001555 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1556 toString(msg.body.finished.handled),
1557 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001558 break;
1559 }
1560 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001561 out += android::base::StringPrintf("hasFocus=%s",
1562 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001563 break;
1564 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001565 case InputMessage::Type::CAPTURE: {
1566 out += android::base::StringPrintf("hasCapture=%s",
1567 toString(msg.body.capture
1568 .pointerCaptureEnabled));
1569 break;
1570 }
arthurhung7632c332020-12-30 16:58:01 +08001571 case InputMessage::Type::DRAG: {
1572 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1573 msg.body.drag.x, msg.body.drag.y,
1574 toString(msg.body.drag.isExiting));
1575 break;
1576 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001577 case InputMessage::Type::TIMELINE: {
1578 const nsecs_t gpuCompletedTime =
1579 msg.body.timeline
1580 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1581 const nsecs_t presentTime =
1582 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1583 out += android::base::StringPrintf("inputEventId=%" PRId32
1584 ", gpuCompletedTime=%" PRId64
1585 ", presentTime=%" PRId64,
1586 msg.body.timeline.eventId, gpuCompletedTime,
1587 presentTime);
1588 break;
1589 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001590 case InputMessage::Type::TOUCH_MODE: {
1591 out += android::base::StringPrintf("isInTouchMode=%s",
1592 toString(msg.body.touchMode.isInTouchMode));
1593 break;
1594 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001595 }
1596 out += "\n";
1597 }
1598 }
1599 if (mBatches.empty()) {
1600 out += " <empty>\n";
1601 }
1602 out += "mSeqChains:\n";
1603 for (const SeqChain& chain : mSeqChains) {
1604 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1605 chain.chain);
1606 }
1607 if (mSeqChains.empty()) {
1608 out += " <empty>\n";
1609 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001610 out += "mConsumeTimes:\n";
1611 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1612 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1613 consumeTime);
1614 }
1615 if (mConsumeTimes.empty()) {
1616 out += " <empty>\n";
1617 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001618 return out;
1619}
1620
Jeff Brown5912f952013-07-01 19:10:31 -07001621} // namespace android