blob: b5a823d76adc588102570dccd31653dca4bc25fe [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
Siarhei Vishniakou96818962023-08-23 10:19:02 -070026#include <com_android_input_flags.h>
Jeff Brown5912f952013-07-01 19:10:31 -070027#include <input/InputTransport.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000028#include <input/TraceTools.h>
Jeff Brown5912f952013-07-01 19:10:31 -070029
Siarhei Vishniakou96818962023-08-23 10:19:02 -070030namespace input_flags = com::android::input::flags;
31
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000032namespace {
33
34/**
35 * Log debug messages about channel messages (send message, receive message).
36 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
37 * (requires restart)
38 */
39const bool DEBUG_CHANNEL_MESSAGES =
40 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
41
42/**
43 * Log debug messages whenever InputChannel objects are created/destroyed.
44 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
45 * (requires restart)
46 */
47const bool DEBUG_CHANNEL_LIFECYCLE =
48 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
49
50/**
51 * Log debug messages relating to the consumer end of the transport channel.
52 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
53 */
54
55const bool DEBUG_TRANSPORT_CONSUMER =
56 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
57
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000058const bool IS_DEBUGGABLE_BUILD =
59#if defined(__ANDROID__)
60 android::base::GetBoolProperty("ro.debuggable", false);
61#else
62 true;
63#endif
64
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000065/**
66 * Log debug messages relating to the producer end of the transport channel.
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000067 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
68 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
69 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000070 */
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000071bool debugTransportPublisher() {
72 if (!IS_DEBUGGABLE_BUILD) {
73 static const bool DEBUG_TRANSPORT_PUBLISHER =
74 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
75 return DEBUG_TRANSPORT_PUBLISHER;
76 }
77 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
78}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000079
80/**
81 * Log debug messages about touch event resampling.
Harry Cutts6c658cc2023-08-02 14:40:40 +000082 *
83 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG".
84 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
85 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000086 */
Harry Cutts6c658cc2023-08-02 14:40:40 +000087bool debugResampling() {
88 if (!IS_DEBUGGABLE_BUILD) {
89 static const bool DEBUG_TRANSPORT_RESAMPLING =
90 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling",
91 ANDROID_LOG_INFO);
92 return DEBUG_TRANSPORT_RESAMPLING;
93 }
94 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
95}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000096
97} // namespace
98
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070099using android::base::Result;
Michael Wright3dd60e22019-03-27 22:06:44 +0000100using android::base::StringPrintf;
101
Jeff Brown5912f952013-07-01 19:10:31 -0700102namespace android {
103
104// Socket buffer size. The default is typically about 128KB, which is much larger than
105// we really need. So we make it smaller. It just needs to be big enough to hold
106// a few dozen large multi-finger motion events in the case where an application gets
107// behind processing touches.
108static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
109
110// Nanoseconds per milliseconds.
111static const nsecs_t NANOS_PER_MS = 1000000;
112
113// Latency added during resampling. A few milliseconds doesn't hurt much but
114// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800115const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -0700116
117// Minimum time difference between consecutive samples before attempting to resample.
118static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
119
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700120// Maximum time difference between consecutive samples before attempting to resample
121// by extrapolation.
122static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
123
Jeff Brown5912f952013-07-01 19:10:31 -0700124// Maximum time to predict forward from the last known state, to avoid predicting too
125// far into the future. This time is further bounded by 50% of the last time delta.
126static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
127
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600128/**
129 * System property for enabling / disabling touch resampling.
130 * Resampling extrapolates / interpolates the reported touch event coordinates to better
131 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
132 * Resampling is not needed (and should be disabled) on hardware that already
133 * has touch events triggered by VSYNC.
134 * Set to "1" to enable resampling (default).
135 * Set to "0" to disable resampling.
136 * Resampling is enabled by default.
137 */
138static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
139
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800140/**
141 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
142 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
143 */
144static bool verifyEvents() {
Siarhei Vishniakou96818962023-08-23 10:19:02 -0700145 return input_flags::enable_outbound_event_verification() ||
146 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800147}
148
Jeff Brown5912f952013-07-01 19:10:31 -0700149template<typename T>
150inline static T min(const T& a, const T& b) {
151 return a < b ? a : b;
152}
153
154inline static float lerp(float a, float b, float alpha) {
155 return a + alpha * (b - a);
156}
157
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800158inline static bool isPointerEvent(int32_t source) {
159 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
160}
161
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800162inline static const char* toString(bool value) {
163 return value ? "true" : "false";
164}
165
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700166static bool shouldResampleTool(ToolType toolType) {
167 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
168}
169
Jeff Brown5912f952013-07-01 19:10:31 -0700170// --- InputMessage ---
171
172bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000173 if (size() != actualSize) {
174 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
175 return false;
176 }
177
178 switch (header.type) {
179 case Type::KEY:
180 return true;
181 case Type::MOTION: {
182 const bool valid =
183 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
184 if (!valid) {
185 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
186 }
187 return valid;
188 }
189 case Type::FINISHED:
190 case Type::FOCUS:
191 case Type::CAPTURE:
192 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700193 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000194 return true;
195 case Type::TIMELINE: {
196 const nsecs_t gpuCompletedTime =
197 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
198 const nsecs_t presentTime =
199 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
200 const bool valid = presentTime > gpuCompletedTime;
201 if (!valid) {
202 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
203 " presentTime = %" PRId64,
204 gpuCompletedTime, presentTime);
205 }
206 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700207 }
208 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000209 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700210 return false;
211}
212
213size_t InputMessage::size() const {
214 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700215 case Type::KEY:
216 return sizeof(Header) + body.key.size();
217 case Type::MOTION:
218 return sizeof(Header) + body.motion.size();
219 case Type::FINISHED:
220 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800221 case Type::FOCUS:
222 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800223 case Type::CAPTURE:
224 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800225 case Type::DRAG:
226 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000227 case Type::TIMELINE:
228 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700229 case Type::TOUCH_MODE:
230 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700231 }
232 return sizeof(Header);
233}
234
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800235/**
236 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
237 * memory to zero, then only copy the valid bytes on a per-field basis.
238 */
239void InputMessage::getSanitizedCopy(InputMessage* msg) const {
240 memset(msg, 0, sizeof(*msg));
241
242 // Write the header
243 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500244 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800245
246 // Write the body
247 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700248 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800249 // int32_t eventId
250 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800251 // nsecs_t eventTime
252 msg->body.key.eventTime = body.key.eventTime;
253 // int32_t deviceId
254 msg->body.key.deviceId = body.key.deviceId;
255 // int32_t source
256 msg->body.key.source = body.key.source;
257 // int32_t displayId
258 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600259 // std::array<uint8_t, 32> hmac
260 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800261 // int32_t action
262 msg->body.key.action = body.key.action;
263 // int32_t flags
264 msg->body.key.flags = body.key.flags;
265 // int32_t keyCode
266 msg->body.key.keyCode = body.key.keyCode;
267 // int32_t scanCode
268 msg->body.key.scanCode = body.key.scanCode;
269 // int32_t metaState
270 msg->body.key.metaState = body.key.metaState;
271 // int32_t repeatCount
272 msg->body.key.repeatCount = body.key.repeatCount;
273 // nsecs_t downTime
274 msg->body.key.downTime = body.key.downTime;
275 break;
276 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700277 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800278 // int32_t eventId
279 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700280 // uint32_t pointerCount
281 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800282 // nsecs_t eventTime
283 msg->body.motion.eventTime = body.motion.eventTime;
284 // int32_t deviceId
285 msg->body.motion.deviceId = body.motion.deviceId;
286 // int32_t source
287 msg->body.motion.source = body.motion.source;
288 // int32_t displayId
289 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600290 // std::array<uint8_t, 32> hmac
291 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800292 // int32_t action
293 msg->body.motion.action = body.motion.action;
294 // int32_t actionButton
295 msg->body.motion.actionButton = body.motion.actionButton;
296 // int32_t flags
297 msg->body.motion.flags = body.motion.flags;
298 // int32_t metaState
299 msg->body.motion.metaState = body.motion.metaState;
300 // int32_t buttonState
301 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800302 // MotionClassification classification
303 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800304 // int32_t edgeFlags
305 msg->body.motion.edgeFlags = body.motion.edgeFlags;
306 // nsecs_t downTime
307 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700308
309 msg->body.motion.dsdx = body.motion.dsdx;
310 msg->body.motion.dtdx = body.motion.dtdx;
311 msg->body.motion.dtdy = body.motion.dtdy;
312 msg->body.motion.dsdy = body.motion.dsdy;
313 msg->body.motion.tx = body.motion.tx;
314 msg->body.motion.ty = body.motion.ty;
315
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800316 // float xPrecision
317 msg->body.motion.xPrecision = body.motion.xPrecision;
318 // float yPrecision
319 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700320 // float xCursorPosition
321 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
322 // float yCursorPosition
323 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700324
325 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
326 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
327 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
328 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
329 msg->body.motion.txRaw = body.motion.txRaw;
330 msg->body.motion.tyRaw = body.motion.tyRaw;
331
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800332 //struct Pointer pointers[MAX_POINTERS]
333 for (size_t i = 0; i < body.motion.pointerCount; i++) {
334 // PointerProperties properties
335 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
336 msg->body.motion.pointers[i].properties.toolType =
337 body.motion.pointers[i].properties.toolType,
338 // PointerCoords coords
339 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
340 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
341 memcpy(&msg->body.motion.pointers[i].coords.values[0],
342 &body.motion.pointers[i].coords.values[0],
343 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800344 msg->body.motion.pointers[i].coords.isResampled =
345 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800346 }
347 break;
348 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700349 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800350 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000351 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800352 break;
353 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800354 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800355 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800356 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800357 break;
358 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800359 case InputMessage::Type::CAPTURE: {
360 msg->body.capture.eventId = body.capture.eventId;
361 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
362 break;
363 }
arthurhung7632c332020-12-30 16:58:01 +0800364 case InputMessage::Type::DRAG: {
365 msg->body.drag.eventId = body.drag.eventId;
366 msg->body.drag.x = body.drag.x;
367 msg->body.drag.y = body.drag.y;
368 msg->body.drag.isExiting = body.drag.isExiting;
369 break;
370 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000371 case InputMessage::Type::TIMELINE: {
372 msg->body.timeline.eventId = body.timeline.eventId;
373 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
374 break;
375 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700376 case InputMessage::Type::TOUCH_MODE: {
377 msg->body.touchMode.eventId = body.touchMode.eventId;
378 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
379 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800380 }
381}
Jeff Brown5912f952013-07-01 19:10:31 -0700382
383// --- InputChannel ---
384
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500385std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500386 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700387 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
388 if (result != 0) {
389 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
390 strerror(errno));
391 return nullptr;
392 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500393 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500394 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700395}
396
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500397InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
398 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000399 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
400 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700401}
402
403InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000404 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
405 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700406}
407
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800408status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500409 std::unique_ptr<InputChannel>& outServerChannel,
410 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700411 int sockets[2];
412 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
413 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000414 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
415 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500416 outServerChannel.reset();
417 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700418 return result;
419 }
420
421 int bufferSize = SOCKET_BUFFER_SIZE;
422 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
423 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
424 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
425 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
426
Siarhei Vishniakou4c155eb2023-06-30 11:47:12 -0700427 sp<IBinder> token = sp<BBinder>::make();
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700428
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700429 std::string serverChannelName = name + " (server)";
430 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700431 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700432
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700433 std::string clientChannelName = name + " (client)";
434 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700435 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700436 return OK;
437}
438
439status_t InputChannel::sendMessage(const InputMessage* msg) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000440 ATRACE_NAME_IF(ATRACE_ENABLED(),
441 StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=0x%" PRIx32
442 ")",
443 mName.c_str(), msg->header.seq, msg->header.type));
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800444 const size_t msgLength = msg->size();
445 InputMessage cleanMsg;
446 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700447 ssize_t nWrite;
448 do {
Chris Ye0783e992020-06-02 21:34:49 -0700449 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700450 } while (nWrite == -1 && errno == EINTR);
451
452 if (nWrite < 0) {
453 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000454 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
455 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700456 if (error == EAGAIN || error == EWOULDBLOCK) {
457 return WOULD_BLOCK;
458 }
459 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
460 return DEAD_OBJECT;
461 }
462 return -error;
463 }
464
465 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000466 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
467 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
468 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700469 return DEAD_OBJECT;
470 }
471
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000472 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
473 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100474
Jeff Brown5912f952013-07-01 19:10:31 -0700475 return OK;
476}
477
478status_t InputChannel::receiveMessage(InputMessage* msg) {
479 ssize_t nRead;
480 do {
Chris Ye0783e992020-06-02 21:34:49 -0700481 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700482 } while (nRead == -1 && errno == EINTR);
483
484 if (nRead < 0) {
485 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000486 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
487 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700488 if (error == EAGAIN || error == EWOULDBLOCK) {
489 return WOULD_BLOCK;
490 }
491 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
492 return DEAD_OBJECT;
493 }
494 return -error;
495 }
496
497 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000498 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
499 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700500 return DEAD_OBJECT;
501 }
502
503 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000504 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700505 return BAD_VALUE;
506 }
507
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000508 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
509 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100510 if (ATRACE_ENABLED()) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000511 // Add an additional trace point to include data about the received message.
Zimd8402b62023-06-02 11:56:26 +0100512 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
513 ", type=0x%" PRIx32 ")",
514 mName.c_str(), msg->header.seq, msg->header.type);
515 ATRACE_NAME(message.c_str());
516 }
Jeff Brown5912f952013-07-01 19:10:31 -0700517 return OK;
518}
519
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500520std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700521 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700522 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700523}
524
Garfield Tan15601662020-09-22 15:32:38 -0700525void InputChannel::copyTo(InputChannel& outChannel) const {
526 outChannel.mName = getName();
527 outChannel.mFd = dupFd();
528 outChannel.mToken = getConnectionToken();
529}
530
Chris Ye0783e992020-06-02 21:34:49 -0700531status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500532 if (parcel == nullptr) {
533 ALOGE("%s: Null parcel", __func__);
534 return BAD_VALUE;
535 }
536 return parcel->writeStrongBinder(mToken)
537 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700538}
539
Chris Ye0783e992020-06-02 21:34:49 -0700540status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500541 if (parcel == nullptr) {
542 ALOGE("%s: Null parcel", __func__);
543 return BAD_VALUE;
544 }
545 mToken = parcel->readStrongBinder();
546 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700547}
548
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700549sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500550 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700551}
552
Garfield Tan15601662020-09-22 15:32:38 -0700553base::unique_fd InputChannel::dupFd() const {
554 android::base::unique_fd newFd(::dup(getFd()));
555 if (!newFd.ok()) {
556 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
557 strerror(errno));
558 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
559 // If this process is out of file descriptors, then throwing that might end up exploding
560 // on the other side of a binder call, which isn't really helpful.
561 // Better to just crash here and hope that the FD leak is slow.
562 // Other failures could be client errors, so we still propagate those back to the caller.
563 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
564 getName().c_str());
565 return {};
566 }
567 return newFd;
568}
569
Jeff Brown5912f952013-07-01 19:10:31 -0700570// --- InputPublisher ---
571
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800572InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
573 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700574
575InputPublisher::~InputPublisher() {
576}
577
Garfield Tan1c7bc862020-01-28 13:24:04 -0800578status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
579 int32_t source, int32_t displayId,
580 std::array<uint8_t, 32> hmac, int32_t action,
581 int32_t flags, int32_t keyCode, int32_t scanCode,
582 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
583 nsecs_t eventTime) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000584 ATRACE_NAME_IF(ATRACE_ENABLED(),
585 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
586 mChannel->getName().c_str(), KeyEvent::actionToString(action),
587 KeyEvent::getLabel(keyCode)));
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 Pradhan2dac8b82023-09-06 01:11:51 +0000629 ATRACE_NAME_IF(ATRACE_ENABLED(),
630 StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
631 mChannel->getName().c_str(),
632 MotionEvent::actionToString(action).c_str()));
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800633 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700634 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -0700635 mInputVerifier.processMovement(deviceId, source, action, pointerCount,
636 pointerProperties, pointerCoords, flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700637 if (!result.ok()) {
638 LOG(FATAL) << "Bad stream: " << result.error();
639 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800640 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000641 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700642 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700643 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000644 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800645 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000646 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700647 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800648 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700649 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000650 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000651 inputEventSourceToString(source).c_str(), displayId,
652 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
653 metaState, buttonState, motionClassificationToString(classification), xPrecision,
654 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800655 }
Jeff Brown5912f952013-07-01 19:10:31 -0700656
657 if (!seq) {
658 ALOGE("Attempted to publish a motion event with sequence number 0.");
659 return BAD_VALUE;
660 }
661
662 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700663 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800664 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700665 return BAD_VALUE;
666 }
667
668 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700669 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500670 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800671 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700672 msg.body.motion.deviceId = deviceId;
673 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700674 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700675 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700676 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100677 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700678 msg.body.motion.flags = flags;
679 msg.body.motion.edgeFlags = edgeFlags;
680 msg.body.motion.metaState = metaState;
681 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800682 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700683 msg.body.motion.dsdx = transform.dsdx();
684 msg.body.motion.dtdx = transform.dtdx();
685 msg.body.motion.dtdy = transform.dtdy();
686 msg.body.motion.dsdy = transform.dsdy();
687 msg.body.motion.tx = transform.tx();
688 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700689 msg.body.motion.xPrecision = xPrecision;
690 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700691 msg.body.motion.xCursorPosition = xCursorPosition;
692 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700693 msg.body.motion.dsdxRaw = rawTransform.dsdx();
694 msg.body.motion.dtdxRaw = rawTransform.dtdx();
695 msg.body.motion.dtdyRaw = rawTransform.dtdy();
696 msg.body.motion.dsdyRaw = rawTransform.dsdy();
697 msg.body.motion.txRaw = rawTransform.tx();
698 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700699 msg.body.motion.downTime = downTime;
700 msg.body.motion.eventTime = eventTime;
701 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100702 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -0700703 msg.body.motion.pointers[i].properties = pointerProperties[i];
704 msg.body.motion.pointers[i].coords = pointerCoords[i];
Jeff Brown5912f952013-07-01 19:10:31 -0700705 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700706
Jeff Brown5912f952013-07-01 19:10:31 -0700707 return mChannel->sendMessage(&msg);
708}
709
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700710status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000711 ATRACE_NAME_IF(ATRACE_ENABLED(),
712 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
713 mChannel->getName().c_str(), toString(hasFocus)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000714 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
715 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800716
717 InputMessage msg;
718 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500719 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800720 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000721 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800722 return mChannel->sendMessage(&msg);
723}
724
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800725status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
726 bool pointerCaptureEnabled) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000727 ATRACE_NAME_IF(ATRACE_ENABLED(),
728 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
729 mChannel->getName().c_str(), toString(pointerCaptureEnabled)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000730 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000731 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
732 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800733
734 InputMessage msg;
735 msg.header.type = InputMessage::Type::CAPTURE;
736 msg.header.seq = seq;
737 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000738 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800739 return mChannel->sendMessage(&msg);
740}
741
arthurhung7632c332020-12-30 16:58:01 +0800742status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
743 bool isExiting) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000744 ATRACE_NAME_IF(ATRACE_ENABLED(),
745 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
746 mChannel->getName().c_str(), x, y, toString(isExiting)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000747 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000748 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
749 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800750
751 InputMessage msg;
752 msg.header.type = InputMessage::Type::DRAG;
753 msg.header.seq = seq;
754 msg.body.drag.eventId = eventId;
755 msg.body.drag.isExiting = isExiting;
756 msg.body.drag.x = x;
757 msg.body.drag.y = y;
758 return mChannel->sendMessage(&msg);
759}
760
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700761status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000762 ATRACE_NAME_IF(ATRACE_ENABLED(),
763 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
764 mChannel->getName().c_str(), toString(isInTouchMode)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000765 ALOGD_IF(debugTransportPublisher(),
766 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
767 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700768
769 InputMessage msg;
770 msg.header.type = InputMessage::Type::TOUCH_MODE;
771 msg.header.seq = seq;
772 msg.body.touchMode.eventId = eventId;
773 msg.body.touchMode.isInTouchMode = isInTouchMode;
774 return mChannel->sendMessage(&msg);
775}
776
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000777android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700778 InputMessage msg;
779 status_t result = mChannel->receiveMessage(&msg);
780 if (result) {
Siarhei Vishniakou69112652023-08-24 08:34:18 -0700781 if (debugTransportPublisher() && result != WOULD_BLOCK) {
782 LOG(INFO) << "channel '" << mChannel->getName() << "' publisher ~ " << __func__ << ": "
783 << strerror(result);
784 }
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000785 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700786 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000787 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000788 ALOGD_IF(debugTransportPublisher(),
789 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
790 mChannel->getName().c_str(), __func__, msg.header.seq,
791 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000792 return Finished{
793 .seq = msg.header.seq,
794 .handled = msg.body.finished.handled,
795 .consumeTime = msg.body.finished.consumeTime,
796 };
Jeff Brown5912f952013-07-01 19:10:31 -0700797 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000798
799 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000800 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
801 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000802 return Timeline{
803 .inputEventId = msg.body.timeline.eventId,
804 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
805 };
806 }
807
808 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800809 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000810 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700811}
812
813// --- InputConsumer ---
814
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500815InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800816 : InputConsumer(channel, isTouchResamplingEnabled()) {}
817
818InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
819 bool enableTouchResampling)
820 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700821
822InputConsumer::~InputConsumer() {
823}
824
825bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600826 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700827}
828
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800829status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
830 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000831 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
832 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
833 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700834
835 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700836 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700837
838 // Fetch the next input message.
839 // Loop until an event can be returned or no additional events are received.
840 while (!*outEvent) {
841 if (mMsgDeferred) {
842 // mMsg contains a valid input message from the previous call to consume
843 // that has not yet been processed.
844 mMsgDeferred = false;
845 } else {
846 // Receive a fresh message.
847 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000848 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800849 const auto [_, inserted] =
850 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
851 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
852 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000853 }
Jeff Brown5912f952013-07-01 19:10:31 -0700854 if (result) {
855 // Consume the next batched event unless batches are being held for later.
856 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800857 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700858 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000859 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
860 "channel '%s' consumer ~ consumed batch event, seq=%u",
861 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700862 break;
863 }
864 }
865 return result;
866 }
867 }
868
869 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700870 case InputMessage::Type::KEY: {
871 KeyEvent* keyEvent = factory->createKeyEvent();
872 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700873
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700874 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500875 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700876 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000877 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
878 "channel '%s' consumer ~ consumed key event, seq=%u",
879 mChannel->getName().c_str(), *outSeq);
880 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700881 }
Jeff Brown5912f952013-07-01 19:10:31 -0700882
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700883 case InputMessage::Type::MOTION: {
884 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
885 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500886 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700887 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500888 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000889 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
890 "channel '%s' consumer ~ appended to batch event",
891 mChannel->getName().c_str());
892 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700893 } else if (isPointerEvent(mMsg.body.motion.source) &&
894 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
895 // No need to process events that we are going to cancel anyways
896 const size_t count = batch.samples.size();
897 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500898 const InputMessage& msg = batch.samples[i];
899 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700900 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500901 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
902 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700903 } else {
904 // We cannot append to the batch in progress, so we need to consume
905 // the previous batch right now and defer the new message until later.
906 mMsgDeferred = true;
907 status_t result = consumeSamples(factory, batch, batch.samples.size(),
908 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500909 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700910 if (result) {
911 return result;
912 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000913 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
914 "channel '%s' consumer ~ consumed batch event and "
915 "deferred current event, seq=%u",
916 mChannel->getName().c_str(), *outSeq);
917 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700918 }
Jeff Brown5912f952013-07-01 19:10:31 -0700919 }
Jeff Brown5912f952013-07-01 19:10:31 -0700920
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800921 // Start a new batch if needed.
922 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
923 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500924 Batch batch;
925 batch.samples.push_back(mMsg);
926 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000927 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
928 "channel '%s' consumer ~ started batch event",
929 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800930 break;
931 }
Jeff Brown5912f952013-07-01 19:10:31 -0700932
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800933 MotionEvent* motionEvent = factory->createMotionEvent();
934 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700935
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800936 updateTouchState(mMsg);
937 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500938 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800939 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800940
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000941 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
942 "channel '%s' consumer ~ consumed motion event, seq=%u",
943 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800944 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700945 }
Jeff Brown5912f952013-07-01 19:10:31 -0700946
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000947 case InputMessage::Type::FINISHED:
948 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000949 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
950 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800951 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800952 break;
953 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800954
955 case InputMessage::Type::FOCUS: {
956 FocusEvent* focusEvent = factory->createFocusEvent();
957 if (!focusEvent) return NO_MEMORY;
958
959 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500960 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800961 *outEvent = focusEvent;
962 break;
963 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800964
965 case InputMessage::Type::CAPTURE: {
966 CaptureEvent* captureEvent = factory->createCaptureEvent();
967 if (!captureEvent) return NO_MEMORY;
968
969 initializeCaptureEvent(captureEvent, &mMsg);
970 *outSeq = mMsg.header.seq;
971 *outEvent = captureEvent;
972 break;
973 }
arthurhung7632c332020-12-30 16:58:01 +0800974
975 case InputMessage::Type::DRAG: {
976 DragEvent* dragEvent = factory->createDragEvent();
977 if (!dragEvent) return NO_MEMORY;
978
979 initializeDragEvent(dragEvent, &mMsg);
980 *outSeq = mMsg.header.seq;
981 *outEvent = dragEvent;
982 break;
983 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700984
985 case InputMessage::Type::TOUCH_MODE: {
986 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
987 if (!touchModeEvent) return NO_MEMORY;
988
989 initializeTouchModeEvent(touchModeEvent, &mMsg);
990 *outSeq = mMsg.header.seq;
991 *outEvent = touchModeEvent;
992 break;
993 }
Jeff Brown5912f952013-07-01 19:10:31 -0700994 }
995 }
996 return OK;
997}
998
999status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001000 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001001 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001002 for (size_t i = mBatches.size(); i > 0; ) {
1003 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001004 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001005 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001006 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001007 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001008 return result;
1009 }
1010
Michael Wright32232172013-10-21 12:05:22 -07001011 nsecs_t sampleTime = frameTime;
1012 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001013 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001014 }
Jeff Brown5912f952013-07-01 19:10:31 -07001015 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1016 if (split < 0) {
1017 continue;
1018 }
1019
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001020 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001021 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001022 if (batch.samples.empty()) {
1023 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001024 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001025 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001026 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001027 }
Michael Wright32232172013-10-21 12:05:22 -07001028 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001029 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1030 }
1031 return result;
1032 }
1033
1034 return WOULD_BLOCK;
1035}
1036
1037status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001038 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001039 MotionEvent* motionEvent = factory->createMotionEvent();
1040 if (! motionEvent) return NO_MEMORY;
1041
1042 uint32_t chain = 0;
1043 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001044 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001045 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001046 if (i) {
1047 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001048 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001049 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001050 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001051 addSample(motionEvent, &msg);
1052 } else {
1053 initializeMotionEvent(motionEvent, &msg);
1054 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001055 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001056 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001057 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001058
1059 *outSeq = chain;
1060 *outEvent = motionEvent;
1061 return OK;
1062}
1063
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001064void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001065 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001066 return;
1067 }
1068
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001069 int32_t deviceId = msg.body.motion.deviceId;
1070 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001071
1072 // Update the touch state history to incorporate the new input message.
1073 // If the message is in the past relative to the most recently produced resampled
1074 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001075 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001076 case AMOTION_EVENT_ACTION_DOWN: {
1077 ssize_t index = findTouchState(deviceId, source);
1078 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001079 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001080 index = mTouchStates.size() - 1;
1081 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001082 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001083 touchState.initialize(deviceId, source);
1084 touchState.addHistory(msg);
1085 break;
1086 }
1087
1088 case AMOTION_EVENT_ACTION_MOVE: {
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 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001093 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001094 }
1095 break;
1096 }
1097
1098 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1099 ssize_t index = findTouchState(deviceId, source);
1100 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001101 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001102 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001103 rewriteMessage(touchState, msg);
1104 }
1105 break;
1106 }
1107
1108 case AMOTION_EVENT_ACTION_POINTER_UP: {
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 Vishniakou0aeec072017-06-12 15:01:41 +01001113 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001114 }
1115 break;
1116 }
1117
1118 case AMOTION_EVENT_ACTION_SCROLL: {
1119 ssize_t index = findTouchState(deviceId, source);
1120 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001121 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001122 rewriteMessage(touchState, msg);
1123 }
1124 break;
1125 }
1126
1127 case AMOTION_EVENT_ACTION_UP:
1128 case AMOTION_EVENT_ACTION_CANCEL: {
1129 ssize_t index = findTouchState(deviceId, source);
1130 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001131 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001132 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001133 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001134 }
1135 break;
1136 }
1137 }
1138}
1139
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001140/**
1141 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1142 *
1143 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1144 * is in the past relative to msg and the past two events do not contain identical coordinates),
1145 * then invalidate the lastResample data for that pointer.
1146 * If the two past events have identical coordinates, then lastResample data for that pointer will
1147 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1148 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1149 * not equal to x0 is received.
1150 */
1151void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001152 nsecs_t eventTime = msg.body.motion.eventTime;
1153 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1154 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001155 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001156 if (eventTime < state.lastResample.eventTime ||
1157 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001158 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1159 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001160 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001161 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1162 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001163 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1164 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001165 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001166 } else {
1167 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001168 }
Jeff Brown5912f952013-07-01 19:10:31 -07001169 }
1170 }
1171}
1172
1173void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1174 const InputMessage* next) {
1175 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001176 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001177 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1178 return;
1179 }
1180
1181 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1182 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001183 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001184 return;
1185 }
1186
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001187 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001188 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001189 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001190 return;
1191 }
1192
1193 // Ensure that the current sample has all of the pointers that need to be reported.
1194 const History* current = touchState.getHistory(0);
1195 size_t pointerCount = event->getPointerCount();
1196 for (size_t i = 0; i < pointerCount; i++) {
1197 uint32_t id = event->getPointerId(i);
1198 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001199 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001200 return;
1201 }
1202 }
1203
1204 // Find the data to use for resampling.
1205 const History* other;
1206 History future;
1207 float alpha;
1208 if (next) {
1209 // Interpolate between current sample and future sample.
1210 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001211 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001212 other = &future;
1213 nsecs_t delta = future.eventTime - current->eventTime;
1214 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001215 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001216 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001217 return;
1218 }
1219 alpha = float(sampleTime - current->eventTime) / delta;
1220 } else if (touchState.historySize >= 2) {
1221 // Extrapolate future sample using current sample and past sample.
1222 // So other->eventTime <= current->eventTime <= sampleTime.
1223 other = touchState.getHistory(1);
1224 nsecs_t delta = current->eventTime - other->eventTime;
1225 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001226 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001227 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001228 return;
1229 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001230 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001231 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001232 return;
1233 }
1234 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1235 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001236 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001237 "Sample time is too far in the future, adjusting prediction "
1238 "from %" PRId64 " to %" PRId64 " ns.",
1239 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001240 sampleTime = maxPredict;
1241 }
1242 alpha = float(current->eventTime - sampleTime) / delta;
1243 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001244 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001245 return;
1246 }
1247
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001248 if (current->eventTime == sampleTime) {
1249 // Prevents having 2 events with identical times and coordinates.
1250 return;
1251 }
1252
Jeff Brown5912f952013-07-01 19:10:31 -07001253 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001254 History oldLastResample;
1255 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001256 touchState.lastResample.eventTime = sampleTime;
1257 touchState.lastResample.idBits.clear();
1258 for (size_t i = 0; i < pointerCount; i++) {
1259 uint32_t id = event->getPointerId(i);
1260 touchState.lastResample.idToIndex[id] = i;
1261 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001262 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1263 // We maintain the previously resampled value for this pointer (stored in
1264 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1265 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001266 // The isResampled flag isn't cleared as the values don't reflect what the device is
1267 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001268
1269 // We know here that the coordinates for the pointer haven't changed because we
1270 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1271 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001272 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001273 continue;
1274 }
1275
Jeff Brown5912f952013-07-01 19:10:31 -07001276 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1277 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001278 resampledCoords = currentCoords;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001279 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001280 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001281 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001282 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001283 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001284 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001285 resampledCoords.isResampled = true;
Harry Cutts6c658cc2023-08-02 14:40:40 +00001286 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001287 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1288 "other (%0.3f, %0.3f), alpha %0.3f",
1289 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1290 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001291 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001292 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001293 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1294 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001295 }
1296 }
1297
1298 event->addSample(sampleTime, touchState.lastResample.pointers);
1299}
1300
Jeff Brown5912f952013-07-01 19:10:31 -07001301status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001302 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1303 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1304 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001305
1306 if (!seq) {
1307 ALOGE("Attempted to send a finished signal with sequence number 0.");
1308 return BAD_VALUE;
1309 }
1310
1311 // Send finished signals for the batch sequence chain first.
1312 size_t seqChainCount = mSeqChains.size();
1313 if (seqChainCount) {
1314 uint32_t currentSeq = seq;
1315 uint32_t chainSeqs[seqChainCount];
1316 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001317 for (size_t i = seqChainCount; i > 0; ) {
1318 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001319 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001320 if (seqChain.seq == currentSeq) {
1321 currentSeq = seqChain.chain;
1322 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001323 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001324 }
1325 }
1326 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001327 while (!status && chainIndex > 0) {
1328 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001329 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1330 }
1331 if (status) {
1332 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001333 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001334 SeqChain seqChain;
1335 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1336 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001337 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001338 if (!chainIndex) break;
1339 chainIndex--;
1340 }
Jeff Brown5912f952013-07-01 19:10:31 -07001341 return status;
1342 }
1343 }
1344
1345 // Send finished signal for the last message in the batch.
1346 return sendUnchainedFinishedSignal(seq, handled);
1347}
1348
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001349status_t InputConsumer::sendTimeline(int32_t inputEventId,
1350 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001351 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1352 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1353 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1354 mChannel->getName().c_str(), inputEventId,
1355 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1356 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001357
1358 InputMessage msg;
1359 msg.header.type = InputMessage::Type::TIMELINE;
1360 msg.header.seq = 0;
1361 msg.body.timeline.eventId = inputEventId;
1362 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1363 return mChannel->sendMessage(&msg);
1364}
1365
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001366nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1367 auto it = mConsumeTimes.find(seq);
1368 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1369 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1370 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1371 seq);
1372 return it->second;
1373}
1374
1375void InputConsumer::popConsumeTime(uint32_t seq) {
1376 mConsumeTimes.erase(seq);
1377}
1378
Jeff Brown5912f952013-07-01 19:10:31 -07001379status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1380 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001381 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001382 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001383 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001384 msg.body.finished.consumeTime = getConsumeTime(seq);
1385 status_t result = mChannel->sendMessage(&msg);
1386 if (result == OK) {
1387 // Remove the consume time if the socket write succeeded. We will not need to ack this
1388 // message anymore. If the socket write did not succeed, we will try again and will still
1389 // need consume time.
1390 popConsumeTime(seq);
1391 }
1392 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001393}
1394
Jeff Brown5912f952013-07-01 19:10:31 -07001395bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001396 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001397}
1398
Arthur Hungc7812be2020-02-27 22:40:27 +08001399int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001400 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001401 return AINPUT_SOURCE_CLASS_NONE;
1402 }
1403
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001404 const Batch& batch = mBatches[0];
1405 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001406 return head.body.motion.source;
1407}
1408
Jeff Brown5912f952013-07-01 19:10:31 -07001409ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1410 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001411 const Batch& batch = mBatches[i];
1412 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001413 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1414 return i;
1415 }
1416 }
1417 return -1;
1418}
1419
1420ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1421 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001422 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001423 if (touchState.deviceId == deviceId && touchState.source == source) {
1424 return i;
1425 }
1426 }
1427 return -1;
1428}
1429
1430void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001431 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001432 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1433 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1434 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1435 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001436}
1437
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001438void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001439 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001440}
1441
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001442void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001443 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001444}
1445
arthurhung7632c332020-12-30 16:58:01 +08001446void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1447 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1448 msg->body.drag.isExiting);
1449}
1450
Jeff Brown5912f952013-07-01 19:10:31 -07001451void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001452 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001453 PointerProperties pointerProperties[pointerCount];
1454 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001455 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001456 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1457 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001458 }
1459
chaviw9eaa22c2020-07-01 16:21:27 -07001460 ui::Transform transform;
1461 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1462 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001463 ui::Transform displayTransform;
1464 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1465 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1466 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001467 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1468 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1469 msg->body.motion.actionButton, msg->body.motion.flags,
1470 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001471 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1472 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1473 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001474 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1475 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001476}
1477
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001478void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1479 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1480}
1481
Jeff Brown5912f952013-07-01 19:10:31 -07001482void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001483 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001484 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001485 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001486 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001487 }
1488
1489 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1490 event->addSample(msg->body.motion.eventTime, pointerCoords);
1491}
1492
1493bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001494 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001495 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001496 if (head.body.motion.pointerCount != pointerCount
1497 || head.body.motion.action != msg->body.motion.action) {
1498 return false;
1499 }
1500 for (size_t i = 0; i < pointerCount; i++) {
1501 if (head.body.motion.pointers[i].properties
1502 != msg->body.motion.pointers[i].properties) {
1503 return false;
1504 }
1505 }
1506 return true;
1507}
1508
1509ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1510 size_t numSamples = batch.samples.size();
1511 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001512 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001513 index += 1;
1514 }
1515 return ssize_t(index) - 1;
1516}
1517
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001518std::string InputConsumer::dump() const {
1519 std::string out;
1520 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1521 out = out + "mChannel = " + mChannel->getName() + "\n";
1522 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1523 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001524 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001525 }
1526 out += "Batches:\n";
1527 for (const Batch& batch : mBatches) {
1528 out += " Batch:\n";
1529 for (const InputMessage& msg : batch.samples) {
1530 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001531 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001532 switch (msg.header.type) {
1533 case InputMessage::Type::KEY: {
1534 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1535 KeyEvent::actionToString(
1536 msg.body.key.action),
1537 msg.body.key.keyCode);
1538 break;
1539 }
1540 case InputMessage::Type::MOTION: {
1541 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1542 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1543 const float x = msg.body.motion.pointers[i].coords.getX();
1544 const float y = msg.body.motion.pointers[i].coords.getY();
1545 out += android::base::StringPrintf("\n Pointer %" PRIu32
1546 " : x=%.1f y=%.1f",
1547 i, x, y);
1548 }
1549 break;
1550 }
1551 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001552 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1553 toString(msg.body.finished.handled),
1554 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001555 break;
1556 }
1557 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001558 out += android::base::StringPrintf("hasFocus=%s",
1559 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001560 break;
1561 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001562 case InputMessage::Type::CAPTURE: {
1563 out += android::base::StringPrintf("hasCapture=%s",
1564 toString(msg.body.capture
1565 .pointerCaptureEnabled));
1566 break;
1567 }
arthurhung7632c332020-12-30 16:58:01 +08001568 case InputMessage::Type::DRAG: {
1569 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1570 msg.body.drag.x, msg.body.drag.y,
1571 toString(msg.body.drag.isExiting));
1572 break;
1573 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001574 case InputMessage::Type::TIMELINE: {
1575 const nsecs_t gpuCompletedTime =
1576 msg.body.timeline
1577 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1578 const nsecs_t presentTime =
1579 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1580 out += android::base::StringPrintf("inputEventId=%" PRId32
1581 ", gpuCompletedTime=%" PRId64
1582 ", presentTime=%" PRId64,
1583 msg.body.timeline.eventId, gpuCompletedTime,
1584 presentTime);
1585 break;
1586 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001587 case InputMessage::Type::TOUCH_MODE: {
1588 out += android::base::StringPrintf("isInTouchMode=%s",
1589 toString(msg.body.touchMode.isInTouchMode));
1590 break;
1591 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001592 }
1593 out += "\n";
1594 }
1595 }
1596 if (mBatches.empty()) {
1597 out += " <empty>\n";
1598 }
1599 out += "mSeqChains:\n";
1600 for (const SeqChain& chain : mSeqChains) {
1601 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1602 chain.chain);
1603 }
1604 if (mSeqChains.empty()) {
1605 out += " <empty>\n";
1606 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001607 out += "mConsumeTimes:\n";
1608 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1609 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1610 consumeTime);
1611 }
1612 if (mConsumeTimes.empty()) {
1613 out += " <empty>\n";
1614 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001615 return out;
1616}
1617
Jeff Brown5912f952013-07-01 19:10:31 -07001618} // namespace android