1 //
2 // Copyright 2010 The Android Open Source Project
3 //
4 // Provides a shared memory transport for input events.
5 //
6 #define LOG_TAG "InputTransport"
7 #define ATRACE_TAG ATRACE_TAG_INPUT
8
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <inttypes.h>
12 #include <math.h>
13 #include <sys/socket.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16
17 #include <android-base/logging.h>
18 #include <android-base/properties.h>
19 #include <android-base/stringprintf.h>
20 #include <binder/Parcel.h>
21 #include <cutils/properties.h>
22 #include <ftl/enum.h>
23 #include <log/log.h>
24 #include <utils/Trace.h>
25
26 #include <input/InputTransport.h>
27
28 namespace {
29
30 /**
31 * Log debug messages about channel messages (send message, receive message).
32 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
33 * (requires restart)
34 */
35 const bool DEBUG_CHANNEL_MESSAGES =
36 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
37
38 /**
39 * Log debug messages whenever InputChannel objects are created/destroyed.
40 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
41 * (requires restart)
42 */
43 const bool DEBUG_CHANNEL_LIFECYCLE =
44 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
45
46 /**
47 * Log debug messages relating to the consumer end of the transport channel.
48 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
49 */
50
51 const bool DEBUG_TRANSPORT_CONSUMER =
52 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
53
54 const bool IS_DEBUGGABLE_BUILD =
55 #if defined(__ANDROID__)
56 android::base::GetBoolProperty("ro.debuggable", false);
57 #else
58 true;
59 #endif
60
61 /**
62 * Log debug messages relating to the producer end of the transport channel.
63 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
64 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
65 * on debuggable builds (e.g. userdebug).
66 */
debugTransportPublisher()67 bool debugTransportPublisher() {
68 if (!IS_DEBUGGABLE_BUILD) {
69 static const bool DEBUG_TRANSPORT_PUBLISHER =
70 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
71 return DEBUG_TRANSPORT_PUBLISHER;
72 }
73 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
74 }
75
76 /**
77 * Log debug messages about touch event resampling.
78 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG" (requires restart)
79 */
80 const bool DEBUG_RESAMPLING =
81 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
82
83 } // namespace
84
85 using android::base::Result;
86 using android::base::StringPrintf;
87
88 namespace android {
89
90 // Socket buffer size. The default is typically about 128KB, which is much larger than
91 // we really need. So we make it smaller. It just needs to be big enough to hold
92 // a few dozen large multi-finger motion events in the case where an application gets
93 // behind processing touches.
94 static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
95
96 // Nanoseconds per milliseconds.
97 static const nsecs_t NANOS_PER_MS = 1000000;
98
99 // Latency added during resampling. A few milliseconds doesn't hurt much but
100 // reduces the impact of mispredicted touch positions.
101 const std::chrono::duration RESAMPLE_LATENCY = 5ms;
102
103 // Minimum time difference between consecutive samples before attempting to resample.
104 static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
105
106 // Maximum time difference between consecutive samples before attempting to resample
107 // by extrapolation.
108 static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
109
110 // Maximum time to predict forward from the last known state, to avoid predicting too
111 // far into the future. This time is further bounded by 50% of the last time delta.
112 static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
113
114 /**
115 * System property for enabling / disabling touch resampling.
116 * Resampling extrapolates / interpolates the reported touch event coordinates to better
117 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
118 * Resampling is not needed (and should be disabled) on hardware that already
119 * has touch events triggered by VSYNC.
120 * Set to "1" to enable resampling (default).
121 * Set to "0" to disable resampling.
122 * Resampling is enabled by default.
123 */
124 static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
125
126 /**
127 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
128 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
129 */
verifyEvents()130 static bool verifyEvents() {
131 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
132 }
133
134 template<typename T>
min(const T & a,const T & b)135 inline static T min(const T& a, const T& b) {
136 return a < b ? a : b;
137 }
138
lerp(float a,float b,float alpha)139 inline static float lerp(float a, float b, float alpha) {
140 return a + alpha * (b - a);
141 }
142
isPointerEvent(int32_t source)143 inline static bool isPointerEvent(int32_t source) {
144 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
145 }
146
toString(bool value)147 inline static const char* toString(bool value) {
148 return value ? "true" : "false";
149 }
150
shouldResampleTool(ToolType toolType)151 static bool shouldResampleTool(ToolType toolType) {
152 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
153 }
154
155 // --- InputMessage ---
156
isValid(size_t actualSize) const157 bool InputMessage::isValid(size_t actualSize) const {
158 if (size() != actualSize) {
159 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
160 return false;
161 }
162
163 switch (header.type) {
164 case Type::KEY:
165 return true;
166 case Type::MOTION: {
167 const bool valid =
168 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
169 if (!valid) {
170 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
171 }
172 return valid;
173 }
174 case Type::FINISHED:
175 case Type::FOCUS:
176 case Type::CAPTURE:
177 case Type::DRAG:
178 case Type::TOUCH_MODE:
179 return true;
180 case Type::TIMELINE: {
181 const nsecs_t gpuCompletedTime =
182 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
183 const nsecs_t presentTime =
184 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
185 const bool valid = presentTime > gpuCompletedTime;
186 if (!valid) {
187 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
188 " presentTime = %" PRId64,
189 gpuCompletedTime, presentTime);
190 }
191 return valid;
192 }
193 }
194 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
195 return false;
196 }
197
size() const198 size_t InputMessage::size() const {
199 switch (header.type) {
200 case Type::KEY:
201 return sizeof(Header) + body.key.size();
202 case Type::MOTION:
203 return sizeof(Header) + body.motion.size();
204 case Type::FINISHED:
205 return sizeof(Header) + body.finished.size();
206 case Type::FOCUS:
207 return sizeof(Header) + body.focus.size();
208 case Type::CAPTURE:
209 return sizeof(Header) + body.capture.size();
210 case Type::DRAG:
211 return sizeof(Header) + body.drag.size();
212 case Type::TIMELINE:
213 return sizeof(Header) + body.timeline.size();
214 case Type::TOUCH_MODE:
215 return sizeof(Header) + body.touchMode.size();
216 }
217 return sizeof(Header);
218 }
219
220 /**
221 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
222 * memory to zero, then only copy the valid bytes on a per-field basis.
223 */
getSanitizedCopy(InputMessage * msg) const224 void InputMessage::getSanitizedCopy(InputMessage* msg) const {
225 memset(msg, 0, sizeof(*msg));
226
227 // Write the header
228 msg->header.type = header.type;
229 msg->header.seq = header.seq;
230
231 // Write the body
232 switch(header.type) {
233 case InputMessage::Type::KEY: {
234 // int32_t eventId
235 msg->body.key.eventId = body.key.eventId;
236 // nsecs_t eventTime
237 msg->body.key.eventTime = body.key.eventTime;
238 // int32_t deviceId
239 msg->body.key.deviceId = body.key.deviceId;
240 // int32_t source
241 msg->body.key.source = body.key.source;
242 // int32_t displayId
243 msg->body.key.displayId = body.key.displayId;
244 // std::array<uint8_t, 32> hmac
245 msg->body.key.hmac = body.key.hmac;
246 // int32_t action
247 msg->body.key.action = body.key.action;
248 // int32_t flags
249 msg->body.key.flags = body.key.flags;
250 // int32_t keyCode
251 msg->body.key.keyCode = body.key.keyCode;
252 // int32_t scanCode
253 msg->body.key.scanCode = body.key.scanCode;
254 // int32_t metaState
255 msg->body.key.metaState = body.key.metaState;
256 // int32_t repeatCount
257 msg->body.key.repeatCount = body.key.repeatCount;
258 // nsecs_t downTime
259 msg->body.key.downTime = body.key.downTime;
260 break;
261 }
262 case InputMessage::Type::MOTION: {
263 // int32_t eventId
264 msg->body.motion.eventId = body.motion.eventId;
265 // uint32_t pointerCount
266 msg->body.motion.pointerCount = body.motion.pointerCount;
267 // nsecs_t eventTime
268 msg->body.motion.eventTime = body.motion.eventTime;
269 // int32_t deviceId
270 msg->body.motion.deviceId = body.motion.deviceId;
271 // int32_t source
272 msg->body.motion.source = body.motion.source;
273 // int32_t displayId
274 msg->body.motion.displayId = body.motion.displayId;
275 // std::array<uint8_t, 32> hmac
276 msg->body.motion.hmac = body.motion.hmac;
277 // int32_t action
278 msg->body.motion.action = body.motion.action;
279 // int32_t actionButton
280 msg->body.motion.actionButton = body.motion.actionButton;
281 // int32_t flags
282 msg->body.motion.flags = body.motion.flags;
283 // int32_t metaState
284 msg->body.motion.metaState = body.motion.metaState;
285 // int32_t buttonState
286 msg->body.motion.buttonState = body.motion.buttonState;
287 // MotionClassification classification
288 msg->body.motion.classification = body.motion.classification;
289 // int32_t edgeFlags
290 msg->body.motion.edgeFlags = body.motion.edgeFlags;
291 // nsecs_t downTime
292 msg->body.motion.downTime = body.motion.downTime;
293
294 msg->body.motion.dsdx = body.motion.dsdx;
295 msg->body.motion.dtdx = body.motion.dtdx;
296 msg->body.motion.dtdy = body.motion.dtdy;
297 msg->body.motion.dsdy = body.motion.dsdy;
298 msg->body.motion.tx = body.motion.tx;
299 msg->body.motion.ty = body.motion.ty;
300
301 // float xPrecision
302 msg->body.motion.xPrecision = body.motion.xPrecision;
303 // float yPrecision
304 msg->body.motion.yPrecision = body.motion.yPrecision;
305 // float xCursorPosition
306 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
307 // float yCursorPosition
308 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
309
310 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
311 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
312 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
313 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
314 msg->body.motion.txRaw = body.motion.txRaw;
315 msg->body.motion.tyRaw = body.motion.tyRaw;
316
317 //struct Pointer pointers[MAX_POINTERS]
318 for (size_t i = 0; i < body.motion.pointerCount; i++) {
319 // PointerProperties properties
320 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
321 msg->body.motion.pointers[i].properties.toolType =
322 body.motion.pointers[i].properties.toolType,
323 // PointerCoords coords
324 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
325 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
326 memcpy(&msg->body.motion.pointers[i].coords.values[0],
327 &body.motion.pointers[i].coords.values[0],
328 count * (sizeof(body.motion.pointers[i].coords.values[0])));
329 msg->body.motion.pointers[i].coords.isResampled =
330 body.motion.pointers[i].coords.isResampled;
331 }
332 break;
333 }
334 case InputMessage::Type::FINISHED: {
335 msg->body.finished.handled = body.finished.handled;
336 msg->body.finished.consumeTime = body.finished.consumeTime;
337 break;
338 }
339 case InputMessage::Type::FOCUS: {
340 msg->body.focus.eventId = body.focus.eventId;
341 msg->body.focus.hasFocus = body.focus.hasFocus;
342 break;
343 }
344 case InputMessage::Type::CAPTURE: {
345 msg->body.capture.eventId = body.capture.eventId;
346 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
347 break;
348 }
349 case InputMessage::Type::DRAG: {
350 msg->body.drag.eventId = body.drag.eventId;
351 msg->body.drag.x = body.drag.x;
352 msg->body.drag.y = body.drag.y;
353 msg->body.drag.isExiting = body.drag.isExiting;
354 break;
355 }
356 case InputMessage::Type::TIMELINE: {
357 msg->body.timeline.eventId = body.timeline.eventId;
358 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
359 break;
360 }
361 case InputMessage::Type::TOUCH_MODE: {
362 msg->body.touchMode.eventId = body.touchMode.eventId;
363 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
364 }
365 }
366 }
367
368 // --- InputChannel ---
369
create(const std::string & name,android::base::unique_fd fd,sp<IBinder> token)370 std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
371 android::base::unique_fd fd, sp<IBinder> token) {
372 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
373 if (result != 0) {
374 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
375 strerror(errno));
376 return nullptr;
377 }
378 // using 'new' to access a non-public constructor
379 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
380 }
381
InputChannel(const std::string name,android::base::unique_fd fd,sp<IBinder> token)382 InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
383 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
384 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
385 getName().c_str(), getFd().get());
386 }
387
~InputChannel()388 InputChannel::~InputChannel() {
389 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
390 getName().c_str(), getFd().get());
391 }
392
openInputChannelPair(const std::string & name,std::unique_ptr<InputChannel> & outServerChannel,std::unique_ptr<InputChannel> & outClientChannel)393 status_t InputChannel::openInputChannelPair(const std::string& name,
394 std::unique_ptr<InputChannel>& outServerChannel,
395 std::unique_ptr<InputChannel>& outClientChannel) {
396 int sockets[2];
397 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
398 status_t result = -errno;
399 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
400 strerror(errno), errno);
401 outServerChannel.reset();
402 outClientChannel.reset();
403 return result;
404 }
405
406 int bufferSize = SOCKET_BUFFER_SIZE;
407 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
408 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
409 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
410 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
411
412 sp<IBinder> token = new BBinder();
413
414 std::string serverChannelName = name + " (server)";
415 android::base::unique_fd serverFd(sockets[0]);
416 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
417
418 std::string clientChannelName = name + " (client)";
419 android::base::unique_fd clientFd(sockets[1]);
420 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
421 return OK;
422 }
423
sendMessage(const InputMessage * msg)424 status_t InputChannel::sendMessage(const InputMessage* msg) {
425 const size_t msgLength = msg->size();
426 InputMessage cleanMsg;
427 msg->getSanitizedCopy(&cleanMsg);
428 ssize_t nWrite;
429 do {
430 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
431 } while (nWrite == -1 && errno == EINTR);
432
433 if (nWrite < 0) {
434 int error = errno;
435 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
436 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
437 if (error == EAGAIN || error == EWOULDBLOCK) {
438 return WOULD_BLOCK;
439 }
440 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
441 return DEAD_OBJECT;
442 }
443 return -error;
444 }
445
446 if (size_t(nWrite) != msgLength) {
447 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
448 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
449 ftl::enum_string(msg->header.type).c_str());
450 return DEAD_OBJECT;
451 }
452
453 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
454 ftl::enum_string(msg->header.type).c_str());
455
456 if (ATRACE_ENABLED()) {
457 std::string message =
458 StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=0x%" PRIx32 ")",
459 mName.c_str(), msg->header.seq, msg->header.type);
460 ATRACE_NAME(message.c_str());
461 }
462 return OK;
463 }
464
receiveMessage(InputMessage * msg)465 status_t InputChannel::receiveMessage(InputMessage* msg) {
466 ssize_t nRead;
467 do {
468 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
469 } while (nRead == -1 && errno == EINTR);
470
471 if (nRead < 0) {
472 int error = errno;
473 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
474 mName.c_str(), errno);
475 if (error == EAGAIN || error == EWOULDBLOCK) {
476 return WOULD_BLOCK;
477 }
478 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
479 return DEAD_OBJECT;
480 }
481 return -error;
482 }
483
484 if (nRead == 0) { // check for EOF
485 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
486 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
487 return DEAD_OBJECT;
488 }
489
490 if (!msg->isValid(nRead)) {
491 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
492 return BAD_VALUE;
493 }
494
495 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
496 ftl::enum_string(msg->header.type).c_str());
497
498 if (ATRACE_ENABLED()) {
499 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
500 ", type=0x%" PRIx32 ")",
501 mName.c_str(), msg->header.seq, msg->header.type);
502 ATRACE_NAME(message.c_str());
503 }
504 return OK;
505 }
506
dup() const507 std::unique_ptr<InputChannel> InputChannel::dup() const {
508 base::unique_fd newFd(dupFd());
509 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
510 }
511
copyTo(InputChannel & outChannel) const512 void InputChannel::copyTo(InputChannel& outChannel) const {
513 outChannel.mName = getName();
514 outChannel.mFd = dupFd();
515 outChannel.mToken = getConnectionToken();
516 }
517
writeToParcel(android::Parcel * parcel) const518 status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
519 if (parcel == nullptr) {
520 ALOGE("%s: Null parcel", __func__);
521 return BAD_VALUE;
522 }
523 return parcel->writeStrongBinder(mToken)
524 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
525 }
526
readFromParcel(const android::Parcel * parcel)527 status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
528 if (parcel == nullptr) {
529 ALOGE("%s: Null parcel", __func__);
530 return BAD_VALUE;
531 }
532 mToken = parcel->readStrongBinder();
533 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
534 }
535
getConnectionToken() const536 sp<IBinder> InputChannel::getConnectionToken() const {
537 return mToken;
538 }
539
dupFd() const540 base::unique_fd InputChannel::dupFd() const {
541 android::base::unique_fd newFd(::dup(getFd()));
542 if (!newFd.ok()) {
543 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
544 strerror(errno));
545 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
546 // If this process is out of file descriptors, then throwing that might end up exploding
547 // on the other side of a binder call, which isn't really helpful.
548 // Better to just crash here and hope that the FD leak is slow.
549 // Other failures could be client errors, so we still propagate those back to the caller.
550 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
551 getName().c_str());
552 return {};
553 }
554 return newFd;
555 }
556
557 // --- InputPublisher ---
558
InputPublisher(const std::shared_ptr<InputChannel> & channel)559 InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
560 : mChannel(channel), mInputVerifier(channel->getName()) {}
561
~InputPublisher()562 InputPublisher::~InputPublisher() {
563 }
564
publishKeyEvent(uint32_t seq,int32_t eventId,int32_t deviceId,int32_t source,int32_t displayId,std::array<uint8_t,32> hmac,int32_t action,int32_t flags,int32_t keyCode,int32_t scanCode,int32_t metaState,int32_t repeatCount,nsecs_t downTime,nsecs_t eventTime)565 status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
566 int32_t source, int32_t displayId,
567 std::array<uint8_t, 32> hmac, int32_t action,
568 int32_t flags, int32_t keyCode, int32_t scanCode,
569 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
570 nsecs_t eventTime) {
571 if (ATRACE_ENABLED()) {
572 std::string message =
573 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
574 mChannel->getName().c_str(), KeyEvent::actionToString(action),
575 KeyEvent::getLabel(keyCode));
576 ATRACE_NAME(message.c_str());
577 }
578 ALOGD_IF(debugTransportPublisher(),
579 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
580 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
581 "downTime=%" PRId64 ", eventTime=%" PRId64,
582 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
583 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
584 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
585
586 if (!seq) {
587 ALOGE("Attempted to publish a key event with sequence number 0.");
588 return BAD_VALUE;
589 }
590
591 InputMessage msg;
592 msg.header.type = InputMessage::Type::KEY;
593 msg.header.seq = seq;
594 msg.body.key.eventId = eventId;
595 msg.body.key.deviceId = deviceId;
596 msg.body.key.source = source;
597 msg.body.key.displayId = displayId;
598 msg.body.key.hmac = std::move(hmac);
599 msg.body.key.action = action;
600 msg.body.key.flags = flags;
601 msg.body.key.keyCode = keyCode;
602 msg.body.key.scanCode = scanCode;
603 msg.body.key.metaState = metaState;
604 msg.body.key.repeatCount = repeatCount;
605 msg.body.key.downTime = downTime;
606 msg.body.key.eventTime = eventTime;
607 return mChannel->sendMessage(&msg);
608 }
609
publishMotionEvent(uint32_t seq,int32_t eventId,int32_t deviceId,int32_t source,int32_t displayId,std::array<uint8_t,32> hmac,int32_t action,int32_t actionButton,int32_t flags,int32_t edgeFlags,int32_t metaState,int32_t buttonState,MotionClassification classification,const ui::Transform & transform,float xPrecision,float yPrecision,float xCursorPosition,float yCursorPosition,const ui::Transform & rawTransform,nsecs_t downTime,nsecs_t eventTime,uint32_t pointerCount,const PointerProperties * pointerProperties,const PointerCoords * pointerCoords)610 status_t InputPublisher::publishMotionEvent(
611 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
612 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
613 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
614 MotionClassification classification, const ui::Transform& transform, float xPrecision,
615 float yPrecision, float xCursorPosition, float yCursorPosition,
616 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
617 uint32_t pointerCount, const PointerProperties* pointerProperties,
618 const PointerCoords* pointerCoords) {
619 if (ATRACE_ENABLED()) {
620 std::string message = StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
621 mChannel->getName().c_str(),
622 MotionEvent::actionToString(action).c_str());
623 ATRACE_NAME(message.c_str());
624 }
625 if (verifyEvents()) {
626 Result<void> result =
627 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
628 pointerCoords, flags);
629 if (!result.ok()) {
630 LOG(FATAL) << "Bad stream: " << result.error();
631 }
632 }
633 if (debugTransportPublisher()) {
634 std::string transformString;
635 transform.dump(transformString, "transform", " ");
636 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
637 "displayId=%" PRId32 ", "
638 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
639 "metaState=0x%x, buttonState=0x%x, classification=%s,"
640 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
641 "pointerCount=%" PRIu32 " \n%s",
642 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
643 inputEventSourceToString(source).c_str(), displayId,
644 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
645 metaState, buttonState, motionClassificationToString(classification), xPrecision,
646 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
647 }
648
649 if (!seq) {
650 ALOGE("Attempted to publish a motion event with sequence number 0.");
651 return BAD_VALUE;
652 }
653
654 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
655 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
656 mChannel->getName().c_str(), pointerCount);
657 return BAD_VALUE;
658 }
659
660 InputMessage msg;
661 msg.header.type = InputMessage::Type::MOTION;
662 msg.header.seq = seq;
663 msg.body.motion.eventId = eventId;
664 msg.body.motion.deviceId = deviceId;
665 msg.body.motion.source = source;
666 msg.body.motion.displayId = displayId;
667 msg.body.motion.hmac = std::move(hmac);
668 msg.body.motion.action = action;
669 msg.body.motion.actionButton = actionButton;
670 msg.body.motion.flags = flags;
671 msg.body.motion.edgeFlags = edgeFlags;
672 msg.body.motion.metaState = metaState;
673 msg.body.motion.buttonState = buttonState;
674 msg.body.motion.classification = classification;
675 msg.body.motion.dsdx = transform.dsdx();
676 msg.body.motion.dtdx = transform.dtdx();
677 msg.body.motion.dtdy = transform.dtdy();
678 msg.body.motion.dsdy = transform.dsdy();
679 msg.body.motion.tx = transform.tx();
680 msg.body.motion.ty = transform.ty();
681 msg.body.motion.xPrecision = xPrecision;
682 msg.body.motion.yPrecision = yPrecision;
683 msg.body.motion.xCursorPosition = xCursorPosition;
684 msg.body.motion.yCursorPosition = yCursorPosition;
685 msg.body.motion.dsdxRaw = rawTransform.dsdx();
686 msg.body.motion.dtdxRaw = rawTransform.dtdx();
687 msg.body.motion.dtdyRaw = rawTransform.dtdy();
688 msg.body.motion.dsdyRaw = rawTransform.dsdy();
689 msg.body.motion.txRaw = rawTransform.tx();
690 msg.body.motion.tyRaw = rawTransform.ty();
691 msg.body.motion.downTime = downTime;
692 msg.body.motion.eventTime = eventTime;
693 msg.body.motion.pointerCount = pointerCount;
694 for (uint32_t i = 0; i < pointerCount; i++) {
695 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
696 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
697 }
698
699 return mChannel->sendMessage(&msg);
700 }
701
publishFocusEvent(uint32_t seq,int32_t eventId,bool hasFocus)702 status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
703 if (ATRACE_ENABLED()) {
704 std::string message = StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
705 mChannel->getName().c_str(), toString(hasFocus));
706 ATRACE_NAME(message.c_str());
707 }
708 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
709 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
710
711 InputMessage msg;
712 msg.header.type = InputMessage::Type::FOCUS;
713 msg.header.seq = seq;
714 msg.body.focus.eventId = eventId;
715 msg.body.focus.hasFocus = hasFocus;
716 return mChannel->sendMessage(&msg);
717 }
718
publishCaptureEvent(uint32_t seq,int32_t eventId,bool pointerCaptureEnabled)719 status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
720 bool pointerCaptureEnabled) {
721 if (ATRACE_ENABLED()) {
722 std::string message =
723 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
724 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
725 ATRACE_NAME(message.c_str());
726 }
727 ALOGD_IF(debugTransportPublisher(),
728 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
729 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
730
731 InputMessage msg;
732 msg.header.type = InputMessage::Type::CAPTURE;
733 msg.header.seq = seq;
734 msg.body.capture.eventId = eventId;
735 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
736 return mChannel->sendMessage(&msg);
737 }
738
publishDragEvent(uint32_t seq,int32_t eventId,float x,float y,bool isExiting)739 status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
740 bool isExiting) {
741 if (ATRACE_ENABLED()) {
742 std::string message =
743 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
744 mChannel->getName().c_str(), x, y, toString(isExiting));
745 ATRACE_NAME(message.c_str());
746 }
747 ALOGD_IF(debugTransportPublisher(),
748 "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));
750
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
publishTouchModeEvent(uint32_t seq,int32_t eventId,bool isInTouchMode)761 status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
762 if (ATRACE_ENABLED()) {
763 std::string message =
764 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
765 mChannel->getName().c_str(), toString(isInTouchMode));
766 ATRACE_NAME(message.c_str());
767 }
768 ALOGD_IF(debugTransportPublisher(),
769 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
770 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
771
772 InputMessage msg;
773 msg.header.type = InputMessage::Type::TOUCH_MODE;
774 msg.header.seq = seq;
775 msg.body.touchMode.eventId = eventId;
776 msg.body.touchMode.isInTouchMode = isInTouchMode;
777 return mChannel->sendMessage(&msg);
778 }
779
receiveConsumerResponse()780 android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
781 InputMessage msg;
782 status_t result = mChannel->receiveMessage(&msg);
783 if (result) {
784 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: %s",
785 mChannel->getName().c_str(), __func__, strerror(result));
786 return android::base::Error(result);
787 }
788 if (msg.header.type == InputMessage::Type::FINISHED) {
789 ALOGD_IF(debugTransportPublisher(),
790 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
791 mChannel->getName().c_str(), __func__, msg.header.seq,
792 toString(msg.body.finished.handled));
793 return Finished{
794 .seq = msg.header.seq,
795 .handled = msg.body.finished.handled,
796 .consumeTime = msg.body.finished.consumeTime,
797 };
798 }
799
800 if (msg.header.type == InputMessage::Type::TIMELINE) {
801 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
802 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
803 return Timeline{
804 .inputEventId = msg.body.timeline.eventId,
805 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
806 };
807 }
808
809 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
810 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
811 return android::base::Error(UNKNOWN_ERROR);
812 }
813
814 // --- InputConsumer ---
815
InputConsumer(const std::shared_ptr<InputChannel> & channel)816 InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
817 : InputConsumer(channel, isTouchResamplingEnabled()) {}
818
InputConsumer(const std::shared_ptr<InputChannel> & channel,bool enableTouchResampling)819 InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
820 bool enableTouchResampling)
821 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
822
~InputConsumer()823 InputConsumer::~InputConsumer() {
824 }
825
isTouchResamplingEnabled()826 bool InputConsumer::isTouchResamplingEnabled() {
827 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
828 }
829
consume(InputEventFactoryInterface * factory,bool consumeBatches,nsecs_t frameTime,uint32_t * outSeq,InputEvent ** outEvent)830 status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
831 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
832 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
833 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
834 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
835
836 *outSeq = 0;
837 *outEvent = nullptr;
838
839 // Fetch the next input message.
840 // Loop until an event can be returned or no additional events are received.
841 while (!*outEvent) {
842 if (mMsgDeferred) {
843 // mMsg contains a valid input message from the previous call to consume
844 // that has not yet been processed.
845 mMsgDeferred = false;
846 } else {
847 // Receive a fresh message.
848 status_t result = mChannel->receiveMessage(&mMsg);
849 if (result == OK) {
850 const auto [_, inserted] =
851 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
852 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
853 mMsg.header.seq);
854 }
855 if (result) {
856 // Consume the next batched event unless batches are being held for later.
857 if (consumeBatches || result != WOULD_BLOCK) {
858 result = consumeBatch(factory, frameTime, outSeq, outEvent);
859 if (*outEvent) {
860 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
861 "channel '%s' consumer ~ consumed batch event, seq=%u",
862 mChannel->getName().c_str(), *outSeq);
863 break;
864 }
865 }
866 return result;
867 }
868 }
869
870 switch (mMsg.header.type) {
871 case InputMessage::Type::KEY: {
872 KeyEvent* keyEvent = factory->createKeyEvent();
873 if (!keyEvent) return NO_MEMORY;
874
875 initializeKeyEvent(keyEvent, &mMsg);
876 *outSeq = mMsg.header.seq;
877 *outEvent = keyEvent;
878 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
879 "channel '%s' consumer ~ consumed key event, seq=%u",
880 mChannel->getName().c_str(), *outSeq);
881 break;
882 }
883
884 case InputMessage::Type::MOTION: {
885 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
886 if (batchIndex >= 0) {
887 Batch& batch = mBatches[batchIndex];
888 if (canAddSample(batch, &mMsg)) {
889 batch.samples.push_back(mMsg);
890 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
891 "channel '%s' consumer ~ appended to batch event",
892 mChannel->getName().c_str());
893 break;
894 } else if (isPointerEvent(mMsg.body.motion.source) &&
895 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
896 // No need to process events that we are going to cancel anyways
897 const size_t count = batch.samples.size();
898 for (size_t i = 0; i < count; i++) {
899 const InputMessage& msg = batch.samples[i];
900 sendFinishedSignal(msg.header.seq, false);
901 }
902 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
903 mBatches.erase(mBatches.begin() + batchIndex);
904 } else {
905 // We cannot append to the batch in progress, so we need to consume
906 // the previous batch right now and defer the new message until later.
907 mMsgDeferred = true;
908 status_t result = consumeSamples(factory, batch, batch.samples.size(),
909 outSeq, outEvent);
910 mBatches.erase(mBatches.begin() + batchIndex);
911 if (result) {
912 return result;
913 }
914 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
915 "channel '%s' consumer ~ consumed batch event and "
916 "deferred current event, seq=%u",
917 mChannel->getName().c_str(), *outSeq);
918 break;
919 }
920 }
921
922 // Start a new batch if needed.
923 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
924 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
925 Batch batch;
926 batch.samples.push_back(mMsg);
927 mBatches.push_back(batch);
928 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
929 "channel '%s' consumer ~ started batch event",
930 mChannel->getName().c_str());
931 break;
932 }
933
934 MotionEvent* motionEvent = factory->createMotionEvent();
935 if (!motionEvent) return NO_MEMORY;
936
937 updateTouchState(mMsg);
938 initializeMotionEvent(motionEvent, &mMsg);
939 *outSeq = mMsg.header.seq;
940 *outEvent = motionEvent;
941
942 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
943 "channel '%s' consumer ~ consumed motion event, seq=%u",
944 mChannel->getName().c_str(), *outSeq);
945 break;
946 }
947
948 case InputMessage::Type::FINISHED:
949 case InputMessage::Type::TIMELINE: {
950 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
951 "InputConsumer!",
952 ftl::enum_string(mMsg.header.type).c_str());
953 break;
954 }
955
956 case InputMessage::Type::FOCUS: {
957 FocusEvent* focusEvent = factory->createFocusEvent();
958 if (!focusEvent) return NO_MEMORY;
959
960 initializeFocusEvent(focusEvent, &mMsg);
961 *outSeq = mMsg.header.seq;
962 *outEvent = focusEvent;
963 break;
964 }
965
966 case InputMessage::Type::CAPTURE: {
967 CaptureEvent* captureEvent = factory->createCaptureEvent();
968 if (!captureEvent) return NO_MEMORY;
969
970 initializeCaptureEvent(captureEvent, &mMsg);
971 *outSeq = mMsg.header.seq;
972 *outEvent = captureEvent;
973 break;
974 }
975
976 case InputMessage::Type::DRAG: {
977 DragEvent* dragEvent = factory->createDragEvent();
978 if (!dragEvent) return NO_MEMORY;
979
980 initializeDragEvent(dragEvent, &mMsg);
981 *outSeq = mMsg.header.seq;
982 *outEvent = dragEvent;
983 break;
984 }
985
986 case InputMessage::Type::TOUCH_MODE: {
987 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
988 if (!touchModeEvent) return NO_MEMORY;
989
990 initializeTouchModeEvent(touchModeEvent, &mMsg);
991 *outSeq = mMsg.header.seq;
992 *outEvent = touchModeEvent;
993 break;
994 }
995 }
996 }
997 return OK;
998 }
999
consumeBatch(InputEventFactoryInterface * factory,nsecs_t frameTime,uint32_t * outSeq,InputEvent ** outEvent)1000 status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
1001 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
1002 status_t result;
1003 for (size_t i = mBatches.size(); i > 0; ) {
1004 i--;
1005 Batch& batch = mBatches[i];
1006 if (frameTime < 0) {
1007 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
1008 mBatches.erase(mBatches.begin() + i);
1009 return result;
1010 }
1011
1012 nsecs_t sampleTime = frameTime;
1013 if (mResampleTouch) {
1014 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
1015 }
1016 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1017 if (split < 0) {
1018 continue;
1019 }
1020
1021 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
1022 const InputMessage* next;
1023 if (batch.samples.empty()) {
1024 mBatches.erase(mBatches.begin() + i);
1025 next = nullptr;
1026 } else {
1027 next = &batch.samples[0];
1028 }
1029 if (!result && mResampleTouch) {
1030 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1031 }
1032 return result;
1033 }
1034
1035 return WOULD_BLOCK;
1036 }
1037
consumeSamples(InputEventFactoryInterface * factory,Batch & batch,size_t count,uint32_t * outSeq,InputEvent ** outEvent)1038 status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
1039 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
1040 MotionEvent* motionEvent = factory->createMotionEvent();
1041 if (! motionEvent) return NO_MEMORY;
1042
1043 uint32_t chain = 0;
1044 for (size_t i = 0; i < count; i++) {
1045 InputMessage& msg = batch.samples[i];
1046 updateTouchState(msg);
1047 if (i) {
1048 SeqChain seqChain;
1049 seqChain.seq = msg.header.seq;
1050 seqChain.chain = chain;
1051 mSeqChains.push_back(seqChain);
1052 addSample(motionEvent, &msg);
1053 } else {
1054 initializeMotionEvent(motionEvent, &msg);
1055 }
1056 chain = msg.header.seq;
1057 }
1058 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
1059
1060 *outSeq = chain;
1061 *outEvent = motionEvent;
1062 return OK;
1063 }
1064
updateTouchState(InputMessage & msg)1065 void InputConsumer::updateTouchState(InputMessage& msg) {
1066 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
1067 return;
1068 }
1069
1070 int32_t deviceId = msg.body.motion.deviceId;
1071 int32_t source = msg.body.motion.source;
1072
1073 // Update the touch state history to incorporate the new input message.
1074 // If the message is in the past relative to the most recently produced resampled
1075 // touch, then use the resampled time and coordinates instead.
1076 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
1077 case AMOTION_EVENT_ACTION_DOWN: {
1078 ssize_t index = findTouchState(deviceId, source);
1079 if (index < 0) {
1080 mTouchStates.push_back({});
1081 index = mTouchStates.size() - 1;
1082 }
1083 TouchState& touchState = mTouchStates[index];
1084 touchState.initialize(deviceId, source);
1085 touchState.addHistory(msg);
1086 break;
1087 }
1088
1089 case AMOTION_EVENT_ACTION_MOVE: {
1090 ssize_t index = findTouchState(deviceId, source);
1091 if (index >= 0) {
1092 TouchState& touchState = mTouchStates[index];
1093 touchState.addHistory(msg);
1094 rewriteMessage(touchState, msg);
1095 }
1096 break;
1097 }
1098
1099 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1100 ssize_t index = findTouchState(deviceId, source);
1101 if (index >= 0) {
1102 TouchState& touchState = mTouchStates[index];
1103 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
1104 rewriteMessage(touchState, msg);
1105 }
1106 break;
1107 }
1108
1109 case AMOTION_EVENT_ACTION_POINTER_UP: {
1110 ssize_t index = findTouchState(deviceId, source);
1111 if (index >= 0) {
1112 TouchState& touchState = mTouchStates[index];
1113 rewriteMessage(touchState, msg);
1114 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
1115 }
1116 break;
1117 }
1118
1119 case AMOTION_EVENT_ACTION_SCROLL: {
1120 ssize_t index = findTouchState(deviceId, source);
1121 if (index >= 0) {
1122 TouchState& touchState = mTouchStates[index];
1123 rewriteMessage(touchState, msg);
1124 }
1125 break;
1126 }
1127
1128 case AMOTION_EVENT_ACTION_UP:
1129 case AMOTION_EVENT_ACTION_CANCEL: {
1130 ssize_t index = findTouchState(deviceId, source);
1131 if (index >= 0) {
1132 TouchState& touchState = mTouchStates[index];
1133 rewriteMessage(touchState, msg);
1134 mTouchStates.erase(mTouchStates.begin() + index);
1135 }
1136 break;
1137 }
1138 }
1139 }
1140
1141 /**
1142 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1143 *
1144 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1145 * is in the past relative to msg and the past two events do not contain identical coordinates),
1146 * then invalidate the lastResample data for that pointer.
1147 * If the two past events have identical coordinates, then lastResample data for that pointer will
1148 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1149 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1150 * not equal to x0 is received.
1151 */
rewriteMessage(TouchState & state,InputMessage & msg)1152 void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
1153 nsecs_t eventTime = msg.body.motion.eventTime;
1154 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1155 uint32_t id = msg.body.motion.pointers[i].properties.id;
1156 if (state.lastResample.idBits.hasBit(id)) {
1157 if (eventTime < state.lastResample.eventTime ||
1158 state.recentCoordinatesAreIdentical(id)) {
1159 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1160 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
1161 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1162 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1163 msgCoords.getY());
1164 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1165 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
1166 msgCoords.isResampled = true;
1167 } else {
1168 state.lastResample.idBits.clearBit(id);
1169 }
1170 }
1171 }
1172 }
1173
resampleTouchState(nsecs_t sampleTime,MotionEvent * event,const InputMessage * next)1174 void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1175 const InputMessage* next) {
1176 if (!mResampleTouch
1177 || !(isPointerEvent(event->getSource()))
1178 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1179 return;
1180 }
1181
1182 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1183 if (index < 0) {
1184 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no touch state for device.");
1185 return;
1186 }
1187
1188 TouchState& touchState = mTouchStates[index];
1189 if (touchState.historySize < 1) {
1190 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no history for device.");
1191 return;
1192 }
1193
1194 // Ensure that the current sample has all of the pointers that need to be reported.
1195 const History* current = touchState.getHistory(0);
1196 size_t pointerCount = event->getPointerCount();
1197 for (size_t i = 0; i < pointerCount; i++) {
1198 uint32_t id = event->getPointerId(i);
1199 if (!current->idBits.hasBit(id)) {
1200 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, missing id %d", id);
1201 return;
1202 }
1203 }
1204
1205 // Find the data to use for resampling.
1206 const History* other;
1207 History future;
1208 float alpha;
1209 if (next) {
1210 // Interpolate between current sample and future sample.
1211 // So current->eventTime <= sampleTime <= future.eventTime.
1212 future.initializeFrom(*next);
1213 other = &future;
1214 nsecs_t delta = future.eventTime - current->eventTime;
1215 if (delta < RESAMPLE_MIN_DELTA) {
1216 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1217 delta);
1218 return;
1219 }
1220 alpha = float(sampleTime - current->eventTime) / delta;
1221 } else if (touchState.historySize >= 2) {
1222 // Extrapolate future sample using current sample and past sample.
1223 // So other->eventTime <= current->eventTime <= sampleTime.
1224 other = touchState.getHistory(1);
1225 nsecs_t delta = current->eventTime - other->eventTime;
1226 if (delta < RESAMPLE_MIN_DELTA) {
1227 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1228 delta);
1229 return;
1230 } else if (delta > RESAMPLE_MAX_DELTA) {
1231 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too large: %" PRId64 " ns.",
1232 delta);
1233 return;
1234 }
1235 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1236 if (sampleTime > maxPredict) {
1237 ALOGD_IF(DEBUG_RESAMPLING,
1238 "Sample time is too far in the future, adjusting prediction "
1239 "from %" PRId64 " to %" PRId64 " ns.",
1240 sampleTime - current->eventTime, maxPredict - current->eventTime);
1241 sampleTime = maxPredict;
1242 }
1243 alpha = float(current->eventTime - sampleTime) / delta;
1244 } else {
1245 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, insufficient data.");
1246 return;
1247 }
1248
1249 if (current->eventTime == sampleTime) {
1250 // Prevents having 2 events with identical times and coordinates.
1251 return;
1252 }
1253
1254 // Resample touch coordinates.
1255 History oldLastResample;
1256 oldLastResample.initializeFrom(touchState.lastResample);
1257 touchState.lastResample.eventTime = sampleTime;
1258 touchState.lastResample.idBits.clear();
1259 for (size_t i = 0; i < pointerCount; i++) {
1260 uint32_t id = event->getPointerId(i);
1261 touchState.lastResample.idToIndex[id] = i;
1262 touchState.lastResample.idBits.markBit(id);
1263 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1264 // We maintain the previously resampled value for this pointer (stored in
1265 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1266 // This way we don't introduce artificial jitter when pointers haven't actually moved.
1267 // The isResampled flag isn't cleared as the values don't reflect what the device is
1268 // actually reporting.
1269
1270 // We know here that the coordinates for the pointer haven't changed because we
1271 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1272 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1273 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1274 continue;
1275 }
1276
1277 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1278 const PointerCoords& currentCoords = current->getPointerById(id);
1279 resampledCoords.copyFrom(currentCoords);
1280 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
1281 const PointerCoords& otherCoords = other->getPointerById(id);
1282 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
1283 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
1284 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
1285 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
1286 resampledCoords.isResampled = true;
1287 ALOGD_IF(DEBUG_RESAMPLING,
1288 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1289 "other (%0.3f, %0.3f), alpha %0.3f",
1290 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1291 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
1292 } else {
1293 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
1294 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1295 currentCoords.getY());
1296 }
1297 }
1298
1299 event->addSample(sampleTime, touchState.lastResample.pointers);
1300 }
1301
sendFinishedSignal(uint32_t seq,bool handled)1302 status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
1303 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1304 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1305 mChannel->getName().c_str(), seq, toString(handled));
1306
1307 if (!seq) {
1308 ALOGE("Attempted to send a finished signal with sequence number 0.");
1309 return BAD_VALUE;
1310 }
1311
1312 // Send finished signals for the batch sequence chain first.
1313 size_t seqChainCount = mSeqChains.size();
1314 if (seqChainCount) {
1315 uint32_t currentSeq = seq;
1316 uint32_t chainSeqs[seqChainCount];
1317 size_t chainIndex = 0;
1318 for (size_t i = seqChainCount; i > 0; ) {
1319 i--;
1320 const SeqChain& seqChain = mSeqChains[i];
1321 if (seqChain.seq == currentSeq) {
1322 currentSeq = seqChain.chain;
1323 chainSeqs[chainIndex++] = currentSeq;
1324 mSeqChains.erase(mSeqChains.begin() + i);
1325 }
1326 }
1327 status_t status = OK;
1328 while (!status && chainIndex > 0) {
1329 chainIndex--;
1330 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1331 }
1332 if (status) {
1333 // An error occurred so at least one signal was not sent, reconstruct the chain.
1334 for (;;) {
1335 SeqChain seqChain;
1336 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1337 seqChain.chain = chainSeqs[chainIndex];
1338 mSeqChains.push_back(seqChain);
1339 if (!chainIndex) break;
1340 chainIndex--;
1341 }
1342 return status;
1343 }
1344 }
1345
1346 // Send finished signal for the last message in the batch.
1347 return sendUnchainedFinishedSignal(seq, handled);
1348 }
1349
sendTimeline(int32_t inputEventId,std::array<nsecs_t,GraphicsTimeline::SIZE> graphicsTimeline)1350 status_t InputConsumer::sendTimeline(int32_t inputEventId,
1351 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
1352 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1353 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1354 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1355 mChannel->getName().c_str(), inputEventId,
1356 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1357 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
1358
1359 InputMessage msg;
1360 msg.header.type = InputMessage::Type::TIMELINE;
1361 msg.header.seq = 0;
1362 msg.body.timeline.eventId = inputEventId;
1363 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1364 return mChannel->sendMessage(&msg);
1365 }
1366
getConsumeTime(uint32_t seq) const1367 nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1368 auto it = mConsumeTimes.find(seq);
1369 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1370 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1371 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1372 seq);
1373 return it->second;
1374 }
1375
popConsumeTime(uint32_t seq)1376 void InputConsumer::popConsumeTime(uint32_t seq) {
1377 mConsumeTimes.erase(seq);
1378 }
1379
sendUnchainedFinishedSignal(uint32_t seq,bool handled)1380 status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1381 InputMessage msg;
1382 msg.header.type = InputMessage::Type::FINISHED;
1383 msg.header.seq = seq;
1384 msg.body.finished.handled = handled;
1385 msg.body.finished.consumeTime = getConsumeTime(seq);
1386 status_t result = mChannel->sendMessage(&msg);
1387 if (result == OK) {
1388 // Remove the consume time if the socket write succeeded. We will not need to ack this
1389 // message anymore. If the socket write did not succeed, we will try again and will still
1390 // need consume time.
1391 popConsumeTime(seq);
1392 }
1393 return result;
1394 }
1395
hasPendingBatch() const1396 bool InputConsumer::hasPendingBatch() const {
1397 return !mBatches.empty();
1398 }
1399
getPendingBatchSource() const1400 int32_t InputConsumer::getPendingBatchSource() const {
1401 if (mBatches.empty()) {
1402 return AINPUT_SOURCE_CLASS_NONE;
1403 }
1404
1405 const Batch& batch = mBatches[0];
1406 const InputMessage& head = batch.samples[0];
1407 return head.body.motion.source;
1408 }
1409
findBatch(int32_t deviceId,int32_t source) const1410 ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1411 for (size_t i = 0; i < mBatches.size(); i++) {
1412 const Batch& batch = mBatches[i];
1413 const InputMessage& head = batch.samples[0];
1414 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1415 return i;
1416 }
1417 }
1418 return -1;
1419 }
1420
findTouchState(int32_t deviceId,int32_t source) const1421 ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1422 for (size_t i = 0; i < mTouchStates.size(); i++) {
1423 const TouchState& touchState = mTouchStates[i];
1424 if (touchState.deviceId == deviceId && touchState.source == source) {
1425 return i;
1426 }
1427 }
1428 return -1;
1429 }
1430
initializeKeyEvent(KeyEvent * event,const InputMessage * msg)1431 void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
1432 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
1433 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1434 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1435 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1436 msg->body.key.eventTime);
1437 }
1438
initializeFocusEvent(FocusEvent * event,const InputMessage * msg)1439 void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
1440 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
1441 }
1442
initializeCaptureEvent(CaptureEvent * event,const InputMessage * msg)1443 void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
1444 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
1445 }
1446
initializeDragEvent(DragEvent * event,const InputMessage * msg)1447 void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1448 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1449 msg->body.drag.isExiting);
1450 }
1451
initializeMotionEvent(MotionEvent * event,const InputMessage * msg)1452 void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
1453 uint32_t pointerCount = msg->body.motion.pointerCount;
1454 PointerProperties pointerProperties[pointerCount];
1455 PointerCoords pointerCoords[pointerCount];
1456 for (uint32_t i = 0; i < pointerCount; i++) {
1457 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1458 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1459 }
1460
1461 ui::Transform transform;
1462 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1463 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
1464 ui::Transform displayTransform;
1465 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1466 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1467 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
1468 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1469 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1470 msg->body.motion.actionButton, msg->body.motion.flags,
1471 msg->body.motion.edgeFlags, msg->body.motion.metaState,
1472 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1473 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1474 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
1475 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1476 pointerCount, pointerProperties, pointerCoords);
1477 }
1478
initializeTouchModeEvent(TouchModeEvent * event,const InputMessage * msg)1479 void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1480 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1481 }
1482
addSample(MotionEvent * event,const InputMessage * msg)1483 void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
1484 uint32_t pointerCount = msg->body.motion.pointerCount;
1485 PointerCoords pointerCoords[pointerCount];
1486 for (uint32_t i = 0; i < pointerCount; i++) {
1487 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1488 }
1489
1490 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1491 event->addSample(msg->body.motion.eventTime, pointerCoords);
1492 }
1493
canAddSample(const Batch & batch,const InputMessage * msg)1494 bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
1495 const InputMessage& head = batch.samples[0];
1496 uint32_t pointerCount = msg->body.motion.pointerCount;
1497 if (head.body.motion.pointerCount != pointerCount
1498 || head.body.motion.action != msg->body.motion.action) {
1499 return false;
1500 }
1501 for (size_t i = 0; i < pointerCount; i++) {
1502 if (head.body.motion.pointers[i].properties
1503 != msg->body.motion.pointers[i].properties) {
1504 return false;
1505 }
1506 }
1507 return true;
1508 }
1509
findSampleNoLaterThan(const Batch & batch,nsecs_t time)1510 ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1511 size_t numSamples = batch.samples.size();
1512 size_t index = 0;
1513 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
1514 index += 1;
1515 }
1516 return ssize_t(index) - 1;
1517 }
1518
dump() const1519 std::string InputConsumer::dump() const {
1520 std::string out;
1521 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1522 out = out + "mChannel = " + mChannel->getName() + "\n";
1523 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1524 if (mMsgDeferred) {
1525 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
1526 }
1527 out += "Batches:\n";
1528 for (const Batch& batch : mBatches) {
1529 out += " Batch:\n";
1530 for (const InputMessage& msg : batch.samples) {
1531 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
1532 ftl::enum_string(msg.header.type).c_str());
1533 switch (msg.header.type) {
1534 case InputMessage::Type::KEY: {
1535 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1536 KeyEvent::actionToString(
1537 msg.body.key.action),
1538 msg.body.key.keyCode);
1539 break;
1540 }
1541 case InputMessage::Type::MOTION: {
1542 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1543 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1544 const float x = msg.body.motion.pointers[i].coords.getX();
1545 const float y = msg.body.motion.pointers[i].coords.getY();
1546 out += android::base::StringPrintf("\n Pointer %" PRIu32
1547 " : x=%.1f y=%.1f",
1548 i, x, y);
1549 }
1550 break;
1551 }
1552 case InputMessage::Type::FINISHED: {
1553 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1554 toString(msg.body.finished.handled),
1555 msg.body.finished.consumeTime);
1556 break;
1557 }
1558 case InputMessage::Type::FOCUS: {
1559 out += android::base::StringPrintf("hasFocus=%s",
1560 toString(msg.body.focus.hasFocus));
1561 break;
1562 }
1563 case InputMessage::Type::CAPTURE: {
1564 out += android::base::StringPrintf("hasCapture=%s",
1565 toString(msg.body.capture
1566 .pointerCaptureEnabled));
1567 break;
1568 }
1569 case InputMessage::Type::DRAG: {
1570 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1571 msg.body.drag.x, msg.body.drag.y,
1572 toString(msg.body.drag.isExiting));
1573 break;
1574 }
1575 case InputMessage::Type::TIMELINE: {
1576 const nsecs_t gpuCompletedTime =
1577 msg.body.timeline
1578 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1579 const nsecs_t presentTime =
1580 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1581 out += android::base::StringPrintf("inputEventId=%" PRId32
1582 ", gpuCompletedTime=%" PRId64
1583 ", presentTime=%" PRId64,
1584 msg.body.timeline.eventId, gpuCompletedTime,
1585 presentTime);
1586 break;
1587 }
1588 case InputMessage::Type::TOUCH_MODE: {
1589 out += android::base::StringPrintf("isInTouchMode=%s",
1590 toString(msg.body.touchMode.isInTouchMode));
1591 break;
1592 }
1593 }
1594 out += "\n";
1595 }
1596 }
1597 if (mBatches.empty()) {
1598 out += " <empty>\n";
1599 }
1600 out += "mSeqChains:\n";
1601 for (const SeqChain& chain : mSeqChains) {
1602 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1603 chain.chain);
1604 }
1605 if (mSeqChains.empty()) {
1606 out += " <empty>\n";
1607 }
1608 out += "mConsumeTimes:\n";
1609 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1610 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1611 consumeTime);
1612 }
1613 if (mConsumeTimes.empty()) {
1614 out += " <empty>\n";
1615 }
1616 return out;
1617 }
1618
1619 } // namespace android
1620