blob: 1f1439608b139848452b562657bcfeb223897463 [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) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000479 ATRACE_NAME_IF(ATRACE_ENABLED(),
480 StringPrintf("receiveMessage(inputChannel=%s)", mName.c_str()));
Jeff Brown5912f952013-07-01 19:10:31 -0700481 ssize_t nRead;
482 do {
Chris Ye0783e992020-06-02 21:34:49 -0700483 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700484 } while (nRead == -1 && errno == EINTR);
485
486 if (nRead < 0) {
487 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000488 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
489 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700490 if (error == EAGAIN || error == EWOULDBLOCK) {
491 return WOULD_BLOCK;
492 }
493 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
494 return DEAD_OBJECT;
495 }
496 return -error;
497 }
498
499 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000500 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
501 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700502 return DEAD_OBJECT;
503 }
504
505 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000506 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700507 return BAD_VALUE;
508 }
509
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000510 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
511 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100512 if (ATRACE_ENABLED()) {
Prabir Pradhana37bad12023-08-18 15:55:32 +0000513 // Add an additional trace point to include data about the received message.
Zimd8402b62023-06-02 11:56:26 +0100514 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
515 ", type=0x%" PRIx32 ")",
516 mName.c_str(), msg->header.seq, msg->header.type);
517 ATRACE_NAME(message.c_str());
518 }
Jeff Brown5912f952013-07-01 19:10:31 -0700519 return OK;
520}
521
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500522std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700523 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700524 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700525}
526
Garfield Tan15601662020-09-22 15:32:38 -0700527void InputChannel::copyTo(InputChannel& outChannel) const {
528 outChannel.mName = getName();
529 outChannel.mFd = dupFd();
530 outChannel.mToken = getConnectionToken();
531}
532
Chris Ye0783e992020-06-02 21:34:49 -0700533status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500534 if (parcel == nullptr) {
535 ALOGE("%s: Null parcel", __func__);
536 return BAD_VALUE;
537 }
538 return parcel->writeStrongBinder(mToken)
539 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700540}
541
Chris Ye0783e992020-06-02 21:34:49 -0700542status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500543 if (parcel == nullptr) {
544 ALOGE("%s: Null parcel", __func__);
545 return BAD_VALUE;
546 }
547 mToken = parcel->readStrongBinder();
548 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700549}
550
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700551sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500552 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700553}
554
Garfield Tan15601662020-09-22 15:32:38 -0700555base::unique_fd InputChannel::dupFd() const {
556 android::base::unique_fd newFd(::dup(getFd()));
557 if (!newFd.ok()) {
558 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
559 strerror(errno));
560 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
561 // If this process is out of file descriptors, then throwing that might end up exploding
562 // on the other side of a binder call, which isn't really helpful.
563 // Better to just crash here and hope that the FD leak is slow.
564 // Other failures could be client errors, so we still propagate those back to the caller.
565 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
566 getName().c_str());
567 return {};
568 }
569 return newFd;
570}
571
Jeff Brown5912f952013-07-01 19:10:31 -0700572// --- InputPublisher ---
573
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800574InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
575 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700576
577InputPublisher::~InputPublisher() {
578}
579
Garfield Tan1c7bc862020-01-28 13:24:04 -0800580status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
581 int32_t source, int32_t displayId,
582 std::array<uint8_t, 32> hmac, int32_t action,
583 int32_t flags, int32_t keyCode, int32_t scanCode,
584 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
585 nsecs_t eventTime) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000586 ATRACE_NAME_IF(ATRACE_ENABLED(),
587 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
588 mChannel->getName().c_str(), KeyEvent::actionToString(action),
589 KeyEvent::getLabel(keyCode)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000590 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000591 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000592 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
593 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000594 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000595 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
596 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700597
598 if (!seq) {
599 ALOGE("Attempted to publish a key event with sequence number 0.");
600 return BAD_VALUE;
601 }
602
603 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700604 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500605 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800606 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700607 msg.body.key.deviceId = deviceId;
608 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100609 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700610 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700611 msg.body.key.action = action;
612 msg.body.key.flags = flags;
613 msg.body.key.keyCode = keyCode;
614 msg.body.key.scanCode = scanCode;
615 msg.body.key.metaState = metaState;
616 msg.body.key.repeatCount = repeatCount;
617 msg.body.key.downTime = downTime;
618 msg.body.key.eventTime = eventTime;
619 return mChannel->sendMessage(&msg);
620}
621
622status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800623 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600624 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
625 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700626 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700627 float yPrecision, float xCursorPosition, float yCursorPosition,
628 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700629 uint32_t pointerCount, const PointerProperties* pointerProperties,
630 const PointerCoords* pointerCoords) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000631 ATRACE_NAME_IF(ATRACE_ENABLED(),
632 StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
633 mChannel->getName().c_str(),
634 MotionEvent::actionToString(action).c_str()));
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800635 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700636 Result<void> result =
637 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
638 pointerCoords, flags);
639 if (!result.ok()) {
640 LOG(FATAL) << "Bad stream: " << result.error();
641 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800642 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000643 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700644 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700645 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000646 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800647 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000648 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700649 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800650 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700651 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000652 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000653 inputEventSourceToString(source).c_str(), displayId,
654 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
655 metaState, buttonState, motionClassificationToString(classification), xPrecision,
656 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800657 }
Jeff Brown5912f952013-07-01 19:10:31 -0700658
659 if (!seq) {
660 ALOGE("Attempted to publish a motion event with sequence number 0.");
661 return BAD_VALUE;
662 }
663
664 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700665 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800666 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700667 return BAD_VALUE;
668 }
669
670 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700671 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500672 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800673 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700674 msg.body.motion.deviceId = deviceId;
675 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700676 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700677 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700678 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100679 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700680 msg.body.motion.flags = flags;
681 msg.body.motion.edgeFlags = edgeFlags;
682 msg.body.motion.metaState = metaState;
683 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800684 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700685 msg.body.motion.dsdx = transform.dsdx();
686 msg.body.motion.dtdx = transform.dtdx();
687 msg.body.motion.dtdy = transform.dtdy();
688 msg.body.motion.dsdy = transform.dsdy();
689 msg.body.motion.tx = transform.tx();
690 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700691 msg.body.motion.xPrecision = xPrecision;
692 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700693 msg.body.motion.xCursorPosition = xCursorPosition;
694 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700695 msg.body.motion.dsdxRaw = rawTransform.dsdx();
696 msg.body.motion.dtdxRaw = rawTransform.dtdx();
697 msg.body.motion.dtdyRaw = rawTransform.dtdy();
698 msg.body.motion.dsdyRaw = rawTransform.dsdy();
699 msg.body.motion.txRaw = rawTransform.tx();
700 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700701 msg.body.motion.downTime = downTime;
702 msg.body.motion.eventTime = eventTime;
703 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100704 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -0700705 msg.body.motion.pointers[i].properties = pointerProperties[i];
706 msg.body.motion.pointers[i].coords = pointerCoords[i];
Jeff Brown5912f952013-07-01 19:10:31 -0700707 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700708
Jeff Brown5912f952013-07-01 19:10:31 -0700709 return mChannel->sendMessage(&msg);
710}
711
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700712status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000713 ATRACE_NAME_IF(ATRACE_ENABLED(),
714 StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
715 mChannel->getName().c_str(), toString(hasFocus)));
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 Pradhan2dac8b82023-09-06 01:11:51 +0000729 ATRACE_NAME_IF(ATRACE_ENABLED(),
730 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
731 mChannel->getName().c_str(), toString(pointerCaptureEnabled)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000732 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000733 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
734 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800735
736 InputMessage msg;
737 msg.header.type = InputMessage::Type::CAPTURE;
738 msg.header.seq = seq;
739 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000740 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800741 return mChannel->sendMessage(&msg);
742}
743
arthurhung7632c332020-12-30 16:58:01 +0800744status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
745 bool isExiting) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000746 ATRACE_NAME_IF(ATRACE_ENABLED(),
747 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
748 mChannel->getName().c_str(), x, y, toString(isExiting)));
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000749 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000750 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
751 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800752
753 InputMessage msg;
754 msg.header.type = InputMessage::Type::DRAG;
755 msg.header.seq = seq;
756 msg.body.drag.eventId = eventId;
757 msg.body.drag.isExiting = isExiting;
758 msg.body.drag.x = x;
759 msg.body.drag.y = y;
760 return mChannel->sendMessage(&msg);
761}
762
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700763status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +0000764 ATRACE_NAME_IF(ATRACE_ENABLED(),
765 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
766 mChannel->getName().c_str(), toString(isInTouchMode)));
Prabir Pradhan96282b02023-02-24 22:36:17 +0000767 ALOGD_IF(debugTransportPublisher(),
768 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
769 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700770
771 InputMessage msg;
772 msg.header.type = InputMessage::Type::TOUCH_MODE;
773 msg.header.seq = seq;
774 msg.body.touchMode.eventId = eventId;
775 msg.body.touchMode.isInTouchMode = isInTouchMode;
776 return mChannel->sendMessage(&msg);
777}
778
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000779android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700780 InputMessage msg;
781 status_t result = mChannel->receiveMessage(&msg);
782 if (result) {
Siarhei Vishniakou69112652023-08-24 08:34:18 -0700783 if (debugTransportPublisher() && result != WOULD_BLOCK) {
784 LOG(INFO) << "channel '" << mChannel->getName() << "' publisher ~ " << __func__ << ": "
785 << strerror(result);
786 }
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000787 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700788 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000789 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000790 ALOGD_IF(debugTransportPublisher(),
791 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
792 mChannel->getName().c_str(), __func__, msg.header.seq,
793 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000794 return Finished{
795 .seq = msg.header.seq,
796 .handled = msg.body.finished.handled,
797 .consumeTime = msg.body.finished.consumeTime,
798 };
Jeff Brown5912f952013-07-01 19:10:31 -0700799 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000800
801 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000802 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
803 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000804 return Timeline{
805 .inputEventId = msg.body.timeline.eventId,
806 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
807 };
808 }
809
810 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800811 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000812 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700813}
814
815// --- InputConsumer ---
816
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500817InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800818 : InputConsumer(channel, isTouchResamplingEnabled()) {}
819
820InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
821 bool enableTouchResampling)
822 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700823
824InputConsumer::~InputConsumer() {
825}
826
827bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600828 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700829}
830
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800831status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
832 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000833 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
834 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
835 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700836
837 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700838 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700839
840 // Fetch the next input message.
841 // Loop until an event can be returned or no additional events are received.
842 while (!*outEvent) {
843 if (mMsgDeferred) {
844 // mMsg contains a valid input message from the previous call to consume
845 // that has not yet been processed.
846 mMsgDeferred = false;
847 } else {
848 // Receive a fresh message.
849 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000850 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800851 const auto [_, inserted] =
852 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
853 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
854 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000855 }
Jeff Brown5912f952013-07-01 19:10:31 -0700856 if (result) {
857 // Consume the next batched event unless batches are being held for later.
858 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800859 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700860 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000861 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
862 "channel '%s' consumer ~ consumed batch event, seq=%u",
863 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700864 break;
865 }
866 }
867 return result;
868 }
869 }
870
871 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700872 case InputMessage::Type::KEY: {
873 KeyEvent* keyEvent = factory->createKeyEvent();
874 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700875
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700876 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500877 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700878 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000879 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
880 "channel '%s' consumer ~ consumed key event, seq=%u",
881 mChannel->getName().c_str(), *outSeq);
882 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700883 }
Jeff Brown5912f952013-07-01 19:10:31 -0700884
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700885 case InputMessage::Type::MOTION: {
886 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
887 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500888 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700889 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500890 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000891 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
892 "channel '%s' consumer ~ appended to batch event",
893 mChannel->getName().c_str());
894 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700895 } else if (isPointerEvent(mMsg.body.motion.source) &&
896 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
897 // No need to process events that we are going to cancel anyways
898 const size_t count = batch.samples.size();
899 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500900 const InputMessage& msg = batch.samples[i];
901 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700902 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500903 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
904 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700905 } else {
906 // We cannot append to the batch in progress, so we need to consume
907 // the previous batch right now and defer the new message until later.
908 mMsgDeferred = true;
909 status_t result = consumeSamples(factory, batch, batch.samples.size(),
910 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500911 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700912 if (result) {
913 return result;
914 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000915 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
916 "channel '%s' consumer ~ consumed batch event and "
917 "deferred current event, seq=%u",
918 mChannel->getName().c_str(), *outSeq);
919 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700920 }
Jeff Brown5912f952013-07-01 19:10:31 -0700921 }
Jeff Brown5912f952013-07-01 19:10:31 -0700922
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800923 // Start a new batch if needed.
924 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
925 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500926 Batch batch;
927 batch.samples.push_back(mMsg);
928 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000929 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
930 "channel '%s' consumer ~ started batch event",
931 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800932 break;
933 }
Jeff Brown5912f952013-07-01 19:10:31 -0700934
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800935 MotionEvent* motionEvent = factory->createMotionEvent();
936 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700937
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800938 updateTouchState(mMsg);
939 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500940 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800941 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800942
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000943 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
944 "channel '%s' consumer ~ consumed motion event, seq=%u",
945 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800946 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700947 }
Jeff Brown5912f952013-07-01 19:10:31 -0700948
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000949 case InputMessage::Type::FINISHED:
950 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000951 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
952 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800953 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800954 break;
955 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800956
957 case InputMessage::Type::FOCUS: {
958 FocusEvent* focusEvent = factory->createFocusEvent();
959 if (!focusEvent) return NO_MEMORY;
960
961 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500962 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800963 *outEvent = focusEvent;
964 break;
965 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800966
967 case InputMessage::Type::CAPTURE: {
968 CaptureEvent* captureEvent = factory->createCaptureEvent();
969 if (!captureEvent) return NO_MEMORY;
970
971 initializeCaptureEvent(captureEvent, &mMsg);
972 *outSeq = mMsg.header.seq;
973 *outEvent = captureEvent;
974 break;
975 }
arthurhung7632c332020-12-30 16:58:01 +0800976
977 case InputMessage::Type::DRAG: {
978 DragEvent* dragEvent = factory->createDragEvent();
979 if (!dragEvent) return NO_MEMORY;
980
981 initializeDragEvent(dragEvent, &mMsg);
982 *outSeq = mMsg.header.seq;
983 *outEvent = dragEvent;
984 break;
985 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700986
987 case InputMessage::Type::TOUCH_MODE: {
988 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
989 if (!touchModeEvent) return NO_MEMORY;
990
991 initializeTouchModeEvent(touchModeEvent, &mMsg);
992 *outSeq = mMsg.header.seq;
993 *outEvent = touchModeEvent;
994 break;
995 }
Jeff Brown5912f952013-07-01 19:10:31 -0700996 }
997 }
998 return OK;
999}
1000
1001status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001002 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001003 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001004 for (size_t i = mBatches.size(); i > 0; ) {
1005 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001006 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001007 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001008 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001009 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001010 return result;
1011 }
1012
Michael Wright32232172013-10-21 12:05:22 -07001013 nsecs_t sampleTime = frameTime;
1014 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001015 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001016 }
Jeff Brown5912f952013-07-01 19:10:31 -07001017 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1018 if (split < 0) {
1019 continue;
1020 }
1021
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001022 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001023 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001024 if (batch.samples.empty()) {
1025 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001026 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001027 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001028 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001029 }
Michael Wright32232172013-10-21 12:05:22 -07001030 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001031 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1032 }
1033 return result;
1034 }
1035
1036 return WOULD_BLOCK;
1037}
1038
1039status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001040 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001041 MotionEvent* motionEvent = factory->createMotionEvent();
1042 if (! motionEvent) return NO_MEMORY;
1043
1044 uint32_t chain = 0;
1045 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001046 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001047 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001048 if (i) {
1049 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001050 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001051 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001052 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001053 addSample(motionEvent, &msg);
1054 } else {
1055 initializeMotionEvent(motionEvent, &msg);
1056 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001057 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001058 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001059 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001060
1061 *outSeq = chain;
1062 *outEvent = motionEvent;
1063 return OK;
1064}
1065
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001066void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001067 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001068 return;
1069 }
1070
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001071 int32_t deviceId = msg.body.motion.deviceId;
1072 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001073
1074 // Update the touch state history to incorporate the new input message.
1075 // If the message is in the past relative to the most recently produced resampled
1076 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001077 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001078 case AMOTION_EVENT_ACTION_DOWN: {
1079 ssize_t index = findTouchState(deviceId, source);
1080 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001081 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001082 index = mTouchStates.size() - 1;
1083 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001084 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001085 touchState.initialize(deviceId, source);
1086 touchState.addHistory(msg);
1087 break;
1088 }
1089
1090 case AMOTION_EVENT_ACTION_MOVE: {
1091 ssize_t index = findTouchState(deviceId, source);
1092 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001093 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001094 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001095 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001096 }
1097 break;
1098 }
1099
1100 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1101 ssize_t index = findTouchState(deviceId, source);
1102 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001103 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001104 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001105 rewriteMessage(touchState, msg);
1106 }
1107 break;
1108 }
1109
1110 case AMOTION_EVENT_ACTION_POINTER_UP: {
1111 ssize_t index = findTouchState(deviceId, source);
1112 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001113 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001114 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001115 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001116 }
1117 break;
1118 }
1119
1120 case AMOTION_EVENT_ACTION_SCROLL: {
1121 ssize_t index = findTouchState(deviceId, source);
1122 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001123 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001124 rewriteMessage(touchState, msg);
1125 }
1126 break;
1127 }
1128
1129 case AMOTION_EVENT_ACTION_UP:
1130 case AMOTION_EVENT_ACTION_CANCEL: {
1131 ssize_t index = findTouchState(deviceId, source);
1132 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001133 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001134 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001135 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001136 }
1137 break;
1138 }
1139 }
1140}
1141
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001142/**
1143 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1144 *
1145 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1146 * is in the past relative to msg and the past two events do not contain identical coordinates),
1147 * then invalidate the lastResample data for that pointer.
1148 * If the two past events have identical coordinates, then lastResample data for that pointer will
1149 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1150 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1151 * not equal to x0 is received.
1152 */
1153void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001154 nsecs_t eventTime = msg.body.motion.eventTime;
1155 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1156 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001157 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001158 if (eventTime < state.lastResample.eventTime ||
1159 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001160 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1161 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001162 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001163 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1164 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001165 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1166 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001167 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001168 } else {
1169 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001170 }
Jeff Brown5912f952013-07-01 19:10:31 -07001171 }
1172 }
1173}
1174
1175void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1176 const InputMessage* next) {
1177 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001178 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001179 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1180 return;
1181 }
1182
1183 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1184 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001185 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001186 return;
1187 }
1188
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001189 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001190 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001191 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001192 return;
1193 }
1194
1195 // Ensure that the current sample has all of the pointers that need to be reported.
1196 const History* current = touchState.getHistory(0);
1197 size_t pointerCount = event->getPointerCount();
1198 for (size_t i = 0; i < pointerCount; i++) {
1199 uint32_t id = event->getPointerId(i);
1200 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001201 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001202 return;
1203 }
1204 }
1205
1206 // Find the data to use for resampling.
1207 const History* other;
1208 History future;
1209 float alpha;
1210 if (next) {
1211 // Interpolate between current sample and future sample.
1212 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001213 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001214 other = &future;
1215 nsecs_t delta = future.eventTime - current->eventTime;
1216 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001217 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001218 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001219 return;
1220 }
1221 alpha = float(sampleTime - current->eventTime) / delta;
1222 } else if (touchState.historySize >= 2) {
1223 // Extrapolate future sample using current sample and past sample.
1224 // So other->eventTime <= current->eventTime <= sampleTime.
1225 other = touchState.getHistory(1);
1226 nsecs_t delta = current->eventTime - other->eventTime;
1227 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001228 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001229 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001230 return;
1231 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001232 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001233 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001234 return;
1235 }
1236 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1237 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001238 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001239 "Sample time is too far in the future, adjusting prediction "
1240 "from %" PRId64 " to %" PRId64 " ns.",
1241 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001242 sampleTime = maxPredict;
1243 }
1244 alpha = float(current->eventTime - sampleTime) / delta;
1245 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001246 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001247 return;
1248 }
1249
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001250 if (current->eventTime == sampleTime) {
1251 // Prevents having 2 events with identical times and coordinates.
1252 return;
1253 }
1254
Jeff Brown5912f952013-07-01 19:10:31 -07001255 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001256 History oldLastResample;
1257 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001258 touchState.lastResample.eventTime = sampleTime;
1259 touchState.lastResample.idBits.clear();
1260 for (size_t i = 0; i < pointerCount; i++) {
1261 uint32_t id = event->getPointerId(i);
1262 touchState.lastResample.idToIndex[id] = i;
1263 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001264 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1265 // We maintain the previously resampled value for this pointer (stored in
1266 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1267 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001268 // The isResampled flag isn't cleared as the values don't reflect what the device is
1269 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001270
1271 // We know here that the coordinates for the pointer haven't changed because we
1272 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1273 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001274 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001275 continue;
1276 }
1277
Jeff Brown5912f952013-07-01 19:10:31 -07001278 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1279 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001280 resampledCoords = currentCoords;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001281 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001282 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001283 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001284 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001285 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001286 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001287 resampledCoords.isResampled = true;
Harry Cutts6c658cc2023-08-02 14:40:40 +00001288 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001289 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1290 "other (%0.3f, %0.3f), alpha %0.3f",
1291 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1292 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001293 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001294 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001295 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1296 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001297 }
1298 }
1299
1300 event->addSample(sampleTime, touchState.lastResample.pointers);
1301}
1302
Jeff Brown5912f952013-07-01 19:10:31 -07001303status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001304 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1305 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1306 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001307
1308 if (!seq) {
1309 ALOGE("Attempted to send a finished signal with sequence number 0.");
1310 return BAD_VALUE;
1311 }
1312
1313 // Send finished signals for the batch sequence chain first.
1314 size_t seqChainCount = mSeqChains.size();
1315 if (seqChainCount) {
1316 uint32_t currentSeq = seq;
1317 uint32_t chainSeqs[seqChainCount];
1318 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001319 for (size_t i = seqChainCount; i > 0; ) {
1320 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001321 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001322 if (seqChain.seq == currentSeq) {
1323 currentSeq = seqChain.chain;
1324 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001325 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001326 }
1327 }
1328 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001329 while (!status && chainIndex > 0) {
1330 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001331 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1332 }
1333 if (status) {
1334 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001335 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001336 SeqChain seqChain;
1337 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1338 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001339 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001340 if (!chainIndex) break;
1341 chainIndex--;
1342 }
Jeff Brown5912f952013-07-01 19:10:31 -07001343 return status;
1344 }
1345 }
1346
1347 // Send finished signal for the last message in the batch.
1348 return sendUnchainedFinishedSignal(seq, handled);
1349}
1350
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001351status_t InputConsumer::sendTimeline(int32_t inputEventId,
1352 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001353 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1354 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1355 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1356 mChannel->getName().c_str(), inputEventId,
1357 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1358 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001359
1360 InputMessage msg;
1361 msg.header.type = InputMessage::Type::TIMELINE;
1362 msg.header.seq = 0;
1363 msg.body.timeline.eventId = inputEventId;
1364 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1365 return mChannel->sendMessage(&msg);
1366}
1367
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001368nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1369 auto it = mConsumeTimes.find(seq);
1370 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1371 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1372 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1373 seq);
1374 return it->second;
1375}
1376
1377void InputConsumer::popConsumeTime(uint32_t seq) {
1378 mConsumeTimes.erase(seq);
1379}
1380
Jeff Brown5912f952013-07-01 19:10:31 -07001381status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1382 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001383 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001384 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001385 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001386 msg.body.finished.consumeTime = getConsumeTime(seq);
1387 status_t result = mChannel->sendMessage(&msg);
1388 if (result == OK) {
1389 // Remove the consume time if the socket write succeeded. We will not need to ack this
1390 // message anymore. If the socket write did not succeed, we will try again and will still
1391 // need consume time.
1392 popConsumeTime(seq);
1393 }
1394 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001395}
1396
Jeff Brown5912f952013-07-01 19:10:31 -07001397bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001398 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001399}
1400
Arthur Hungc7812be2020-02-27 22:40:27 +08001401int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001402 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001403 return AINPUT_SOURCE_CLASS_NONE;
1404 }
1405
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001406 const Batch& batch = mBatches[0];
1407 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001408 return head.body.motion.source;
1409}
1410
Jeff Brown5912f952013-07-01 19:10:31 -07001411ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1412 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001413 const Batch& batch = mBatches[i];
1414 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001415 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1416 return i;
1417 }
1418 }
1419 return -1;
1420}
1421
1422ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1423 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001424 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001425 if (touchState.deviceId == deviceId && touchState.source == source) {
1426 return i;
1427 }
1428 }
1429 return -1;
1430}
1431
1432void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001433 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001434 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1435 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1436 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1437 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001438}
1439
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001440void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001441 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001442}
1443
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001444void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001445 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001446}
1447
arthurhung7632c332020-12-30 16:58:01 +08001448void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1449 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1450 msg->body.drag.isExiting);
1451}
1452
Jeff Brown5912f952013-07-01 19:10:31 -07001453void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001454 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001455 PointerProperties pointerProperties[pointerCount];
1456 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001457 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001458 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1459 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001460 }
1461
chaviw9eaa22c2020-07-01 16:21:27 -07001462 ui::Transform transform;
1463 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1464 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001465 ui::Transform displayTransform;
1466 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1467 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1468 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001469 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1470 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1471 msg->body.motion.actionButton, msg->body.motion.flags,
1472 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001473 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1474 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1475 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001476 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1477 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001478}
1479
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001480void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1481 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1482}
1483
Jeff Brown5912f952013-07-01 19:10:31 -07001484void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001485 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001486 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001487 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001488 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001489 }
1490
1491 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1492 event->addSample(msg->body.motion.eventTime, pointerCoords);
1493}
1494
1495bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001496 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001497 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001498 if (head.body.motion.pointerCount != pointerCount
1499 || head.body.motion.action != msg->body.motion.action) {
1500 return false;
1501 }
1502 for (size_t i = 0; i < pointerCount; i++) {
1503 if (head.body.motion.pointers[i].properties
1504 != msg->body.motion.pointers[i].properties) {
1505 return false;
1506 }
1507 }
1508 return true;
1509}
1510
1511ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1512 size_t numSamples = batch.samples.size();
1513 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001514 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001515 index += 1;
1516 }
1517 return ssize_t(index) - 1;
1518}
1519
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001520std::string InputConsumer::dump() const {
1521 std::string out;
1522 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1523 out = out + "mChannel = " + mChannel->getName() + "\n";
1524 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1525 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001526 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001527 }
1528 out += "Batches:\n";
1529 for (const Batch& batch : mBatches) {
1530 out += " Batch:\n";
1531 for (const InputMessage& msg : batch.samples) {
1532 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001533 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001534 switch (msg.header.type) {
1535 case InputMessage::Type::KEY: {
1536 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1537 KeyEvent::actionToString(
1538 msg.body.key.action),
1539 msg.body.key.keyCode);
1540 break;
1541 }
1542 case InputMessage::Type::MOTION: {
1543 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1544 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1545 const float x = msg.body.motion.pointers[i].coords.getX();
1546 const float y = msg.body.motion.pointers[i].coords.getY();
1547 out += android::base::StringPrintf("\n Pointer %" PRIu32
1548 " : x=%.1f y=%.1f",
1549 i, x, y);
1550 }
1551 break;
1552 }
1553 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001554 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1555 toString(msg.body.finished.handled),
1556 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001557 break;
1558 }
1559 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001560 out += android::base::StringPrintf("hasFocus=%s",
1561 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001562 break;
1563 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001564 case InputMessage::Type::CAPTURE: {
1565 out += android::base::StringPrintf("hasCapture=%s",
1566 toString(msg.body.capture
1567 .pointerCaptureEnabled));
1568 break;
1569 }
arthurhung7632c332020-12-30 16:58:01 +08001570 case InputMessage::Type::DRAG: {
1571 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1572 msg.body.drag.x, msg.body.drag.y,
1573 toString(msg.body.drag.isExiting));
1574 break;
1575 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001576 case InputMessage::Type::TIMELINE: {
1577 const nsecs_t gpuCompletedTime =
1578 msg.body.timeline
1579 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1580 const nsecs_t presentTime =
1581 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1582 out += android::base::StringPrintf("inputEventId=%" PRId32
1583 ", gpuCompletedTime=%" PRId64
1584 ", presentTime=%" PRId64,
1585 msg.body.timeline.eventId, gpuCompletedTime,
1586 presentTime);
1587 break;
1588 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001589 case InputMessage::Type::TOUCH_MODE: {
1590 out += android::base::StringPrintf("isInTouchMode=%s",
1591 toString(msg.body.touchMode.isInTouchMode));
1592 break;
1593 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001594 }
1595 out += "\n";
1596 }
1597 }
1598 if (mBatches.empty()) {
1599 out += " <empty>\n";
1600 }
1601 out += "mSeqChains:\n";
1602 for (const SeqChain& chain : mSeqChains) {
1603 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1604 chain.chain);
1605 }
1606 if (mSeqChains.empty()) {
1607 out += " <empty>\n";
1608 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001609 out += "mConsumeTimes:\n";
1610 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1611 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1612 consumeTime);
1613 }
1614 if (mConsumeTimes.empty()) {
1615 out += " <empty>\n";
1616 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001617 return out;
1618}
1619
Jeff Brown5912f952013-07-01 19:10:31 -07001620} // namespace android