blob: 898d1a937cf155a178627e108ff575e128a6a7a5 [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _LIBINPUT_INPUT_TRANSPORT_H
18#define _LIBINPUT_INPUT_TRANSPORT_H
19
Robert Carr2c358bf2018-08-08 15:58:15 -070020#pragma GCC system_header
21
Jeff Brown5912f952013-07-01 19:10:31 -070022/**
23 * Native input transport.
24 *
25 * The InputChannel provides a mechanism for exchanging InputMessage structures across processes.
26 *
27 * The InputPublisher and InputConsumer each handle one end-point of an input channel.
28 * The InputPublisher is used by the input dispatcher to send events to the application.
29 * The InputConsumer is used by the application to receive events from the input dispatcher.
30 */
31
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010032#include <string>
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -100033#include <unordered_map>
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010034
Atif Niyaz3d3fa522019-07-25 11:12:39 -070035#include <android-base/chrono_utils.h>
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000036#include <android-base/result.h>
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +000037#include <android-base/unique_fd.h>
Atif Niyaz3d3fa522019-07-25 11:12:39 -070038
Robert Carr803535b2018-08-02 16:38:15 -070039#include <binder/IBinder.h>
Chris Ye0783e992020-06-02 21:34:49 -070040#include <binder/Parcelable.h>
Jeff Brown5912f952013-07-01 19:10:31 -070041#include <input/Input.h>
Chris Ye0783e992020-06-02 21:34:49 -070042#include <sys/stat.h>
chaviw9eaa22c2020-07-01 16:21:27 -070043#include <ui/Transform.h>
Jeff Brown5912f952013-07-01 19:10:31 -070044#include <utils/BitSet.h>
Atif Niyaz3d3fa522019-07-25 11:12:39 -070045#include <utils/Errors.h>
46#include <utils/RefBase.h>
47#include <utils/Timers.h>
Jeff Brown5912f952013-07-01 19:10:31 -070048
Josh Gao2ccbe3a2019-08-09 14:35:36 -070049
Jeff Brown5912f952013-07-01 19:10:31 -070050namespace android {
Robert Carr3720ed02018-08-08 16:08:27 -070051class Parcel;
Jeff Brown5912f952013-07-01 19:10:31 -070052
53/*
54 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080055 *
56 * Note that this structure is used for IPCs so its layout must be identical
57 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080058 *
59 * Since the struct must be aligned to an 8-byte boundary, there could be uninitialized bytes
60 * in-between the defined fields. This padding data should be explicitly accounted for by adding
61 * "empty" fields into the struct. This data is memset to zero before sending the struct across
62 * the socket. Adding the explicit fields ensures that the memset is not optimized away by the
63 * compiler. When a new field is added to the struct, the corresponding change
64 * in StructLayout_test should be made.
Jeff Brown5912f952013-07-01 19:10:31 -070065 */
66struct InputMessage {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070067 enum class Type : uint32_t {
68 KEY,
69 MOTION,
70 FINISHED,
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -080071 FOCUS,
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -080072 CAPTURE,
arthurhung7632c332020-12-30 16:58:01 +080073 DRAG,
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +000074 TIMELINE,
Jeff Brown5912f952013-07-01 19:10:31 -070075 };
76
77 struct Header {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070078 Type type; // 4 bytes
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050079 uint32_t seq;
Jeff Brown5912f952013-07-01 19:10:31 -070080 } header;
81
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060082 // For keys and motions, rely on the fact that std::array takes up exactly as much space
83 // as the underlying data. This is not guaranteed by C++, but it simplifies the conversions.
84 static_assert(sizeof(std::array<uint8_t, 32>) == 32);
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +000085
86 // For bool values, rely on the fact that they take up exactly one byte. This is not guaranteed
87 // by C++ and is implementation-dependent, but it simplifies the conversions.
88 static_assert(sizeof(bool) == 1);
89
90 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070091 union Body {
92 struct Key {
Garfield Tan1c7bc862020-01-28 13:24:04 -080093 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050094 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080095 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070096 int32_t deviceId;
97 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010098 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060099 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700100 int32_t action;
101 int32_t flags;
102 int32_t keyCode;
103 int32_t scanCode;
104 int32_t metaState;
105 int32_t repeatCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800106 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800107 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700108
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800109 inline size_t size() const { return sizeof(Key); }
Jeff Brown5912f952013-07-01 19:10:31 -0700110 } key;
111
112 struct Motion {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800113 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500114 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800115 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700116 int32_t deviceId;
117 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700118 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600119 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700120 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100121 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700122 int32_t flags;
123 int32_t metaState;
124 int32_t buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800125 MotionClassification classification; // base type: uint8_t
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800126 uint8_t empty2[3]; // 3 bytes to fill gap created by classification
Jeff Brown5912f952013-07-01 19:10:31 -0700127 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800128 nsecs_t downTime __attribute__((aligned(8)));
chaviw9eaa22c2020-07-01 16:21:27 -0700129 float dsdx;
130 float dtdx;
131 float dtdy;
132 float dsdy;
133 float tx;
134 float ty;
Jeff Brown5912f952013-07-01 19:10:31 -0700135 float xPrecision;
136 float yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700137 float xCursorPosition;
138 float yCursorPosition;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100139 uint32_t pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800140 uint32_t empty3;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800141 /**
142 * The "pointers" field must be the last field of the struct InputMessage.
143 * When we send the struct InputMessage across the socket, we are not
144 * writing the entire "pointers" array, but only the pointerCount portion
145 * of it as an optimization. Adding a field after "pointers" would break this.
146 */
Michael Wrightb03f1032015-05-14 16:29:13 +0100147 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700148 PointerProperties properties;
149 PointerCoords coords;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800150 } pointers[MAX_POINTERS] __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700151
152 int32_t getActionId() const {
153 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
154 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
155 return pointers[index].properties.id;
156 }
157
158 inline size_t size() const {
159 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
160 + sizeof(Pointer) * pointerCount;
161 }
162 } motion;
163
164 struct Finished {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000165 bool handled;
166 uint8_t empty[7];
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000167 nsecs_t consumeTime; // The time when the event was consumed by the receiving end
Jeff Brown5912f952013-07-01 19:10:31 -0700168
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800169 inline size_t size() const { return sizeof(Finished); }
Jeff Brown5912f952013-07-01 19:10:31 -0700170 } finished;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800171
172 struct Focus {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800173 int32_t eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000174 // The following 3 fields take up 4 bytes total
175 bool hasFocus;
176 bool inTouchMode;
177 uint8_t empty[2];
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800178
179 inline size_t size() const { return sizeof(Focus); }
180 } focus;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800181
182 struct Capture {
183 int32_t eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000184 bool pointerCaptureEnabled;
185 uint8_t empty[3];
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800186
187 inline size_t size() const { return sizeof(Capture); }
188 } capture;
arthurhung7632c332020-12-30 16:58:01 +0800189
190 struct Drag {
191 int32_t eventId;
192 float x;
193 float y;
194 bool isExiting;
195 uint8_t empty[3];
196
197 inline size_t size() const { return sizeof(Drag); }
198 } drag;
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000199
200 struct Timeline {
201 int32_t eventId;
202 uint32_t empty;
203 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
204
205 inline size_t size() const { return sizeof(Timeline); }
206 } timeline;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800207 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700208
209 bool isValid(size_t actualSize) const;
210 size_t size() const;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800211 void getSanitizedCopy(InputMessage* msg) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700212};
213
214/*
215 * An input channel consists of a local unix domain socket used to send and receive
216 * input messages across processes. Each channel has a descriptive name for debugging purposes.
217 *
218 * Each endpoint has its own InputChannel object that specifies its file descriptor.
219 *
220 * The input channel is closed when all references to it are released.
221 */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500222class InputChannel : public Parcelable {
Chris Ye0783e992020-06-02 21:34:49 -0700223public:
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500224 static std::unique_ptr<InputChannel> create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500225 android::base::unique_fd fd, sp<IBinder> token);
226 InputChannel() = default;
227 InputChannel(const InputChannel& other)
228 : mName(other.mName), mFd(::dup(other.mFd)), mToken(other.mToken){};
229 InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token);
Jeff Brown5912f952013-07-01 19:10:31 -0700230 virtual ~InputChannel();
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700231 /**
232 * Create a pair of input channels.
233 * The two returned input channels are equivalent, and are labeled as "server" and "client"
234 * for convenience. The two input channels share the same token.
Jeff Brown5912f952013-07-01 19:10:31 -0700235 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700236 * Return OK on success.
Jeff Brown5912f952013-07-01 19:10:31 -0700237 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800238 static status_t openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500239 std::unique_ptr<InputChannel>& outServerChannel,
240 std::unique_ptr<InputChannel>& outClientChannel);
Jeff Brown5912f952013-07-01 19:10:31 -0700241
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500242 inline std::string getName() const { return mName; }
243 inline const android::base::unique_fd& getFd() const { return mFd; }
244 inline sp<IBinder> getToken() const { return mToken; }
Jeff Brown5912f952013-07-01 19:10:31 -0700245
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700246 /* Send a message to the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700247 *
248 * If the channel is full then the message is guaranteed not to have been sent at all.
249 * Try again after the consumer has sent a finished signal indicating that it has
250 * consumed some of the pending messages from the channel.
251 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700252 * Return OK on success.
253 * Return WOULD_BLOCK if the channel is full.
254 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700255 * Other errors probably indicate that the channel is broken.
256 */
257 status_t sendMessage(const InputMessage* msg);
258
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700259 /* Receive a message sent by the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700260 *
261 * If there is no message present, try again after poll() indicates that the fd
262 * is readable.
263 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700264 * Return OK on success.
265 * Return WOULD_BLOCK if there is no message present.
266 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700267 * Other errors probably indicate that the channel is broken.
268 */
269 status_t receiveMessage(InputMessage* msg);
270
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700271 /* Return a new object that has a duplicate of this channel's fd. */
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500272 std::unique_ptr<InputChannel> dup() const;
Jeff Brown5912f952013-07-01 19:10:31 -0700273
Garfield Tan15601662020-09-22 15:32:38 -0700274 void copyTo(InputChannel& outChannel) const;
275
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500276 status_t readFromParcel(const android::Parcel* parcel) override;
277 status_t writeToParcel(android::Parcel* parcel) const override;
Robert Carr3720ed02018-08-08 16:08:27 -0700278
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700279 /**
280 * The connection token is used to identify the input connection, i.e.
281 * the pair of input channels that were created simultaneously. Input channels
282 * are always created in pairs, and the token can be used to find the server-side
283 * input channel from the client-side input channel, and vice versa.
284 *
285 * Do not use connection token to check equality of a specific input channel object
286 * to another, because two different (client and server) input channels will share the
287 * same connection token.
288 *
289 * Return the token that identifies this connection.
290 */
291 sp<IBinder> getConnectionToken() const;
Robert Carr803535b2018-08-02 16:38:15 -0700292
Chris Ye0783e992020-06-02 21:34:49 -0700293 bool operator==(const InputChannel& inputChannel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500294 struct stat lhs, rhs;
295 if (fstat(mFd.get(), &lhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700296 return false;
297 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500298 if (fstat(inputChannel.getFd(), &rhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700299 return false;
300 }
301 // If file descriptors are pointing to same inode they are duplicated fds.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500302 return inputChannel.getName() == getName() && inputChannel.getConnectionToken() == mToken &&
303 lhs.st_ino == rhs.st_ino;
Chris Ye0783e992020-06-02 21:34:49 -0700304 }
305
Jeff Brown5912f952013-07-01 19:10:31 -0700306private:
Garfield Tan15601662020-09-22 15:32:38 -0700307 base::unique_fd dupFd() const;
308
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500309 std::string mName;
310 android::base::unique_fd mFd;
311
312 sp<IBinder> mToken;
Jeff Brown5912f952013-07-01 19:10:31 -0700313};
314
315/*
316 * Publishes input events to an input channel.
317 */
318class InputPublisher {
319public:
320 /* Creates a publisher associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500321 explicit InputPublisher(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700322
323 /* Destroys the publisher and releases its input channel. */
324 ~InputPublisher();
325
326 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500327 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700328
329 /* Publishes a key event to the input channel.
330 *
331 * Returns OK on success.
332 * Returns WOULD_BLOCK if the channel is full.
333 * Returns DEAD_OBJECT if the channel's peer has been closed.
334 * Returns BAD_VALUE if seq is 0.
335 * Other errors probably indicate that the channel is broken.
336 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800337 status_t publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
338 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
339 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600340 int32_t repeatCount, nsecs_t downTime, nsecs_t eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700341
342 /* Publishes a motion event to the input channel.
343 *
344 * Returns OK on success.
345 * Returns WOULD_BLOCK if the channel is full.
346 * Returns DEAD_OBJECT if the channel's peer has been closed.
347 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
348 * Other errors probably indicate that the channel is broken.
349 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800350 status_t publishMotionEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
351 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
352 int32_t actionButton, int32_t flags, int32_t edgeFlags,
353 int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700354 MotionClassification classification, const ui::Transform& transform,
355 float xPrecision, float yPrecision, float xCursorPosition,
356 float yCursorPosition, nsecs_t downTime, nsecs_t eventTime,
357 uint32_t pointerCount, const PointerProperties* pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -0700358 const PointerCoords* pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700359
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800360 /* Publishes a focus event to the input channel.
361 *
362 * Returns OK on success.
363 * Returns WOULD_BLOCK if the channel is full.
364 * Returns DEAD_OBJECT if the channel's peer has been closed.
365 * Other errors probably indicate that the channel is broken.
366 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800367 status_t publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus, bool inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800368
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800369 /* Publishes a capture event to the input channel.
370 *
371 * Returns OK on success.
372 * Returns WOULD_BLOCK if the channel is full.
373 * Returns DEAD_OBJECT if the channel's peer has been closed.
374 * Other errors probably indicate that the channel is broken.
375 */
376 status_t publishCaptureEvent(uint32_t seq, int32_t eventId, bool pointerCaptureEnabled);
377
arthurhung7632c332020-12-30 16:58:01 +0800378 /* Publishes a drag event to the input channel.
379 *
380 * Returns OK on success.
381 * Returns WOULD_BLOCK if the channel is full.
382 * Returns DEAD_OBJECT if the channel's peer has been closed.
383 * Other errors probably indicate that the channel is broken.
384 */
385 status_t publishDragEvent(uint32_t seq, int32_t eventId, float x, float y, bool isExiting);
386
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000387 struct Finished {
388 uint32_t seq;
389 bool handled;
390 nsecs_t consumeTime;
391 };
392
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000393 struct Timeline {
394 int32_t inputEventId;
395 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
396 };
397
398 typedef std::variant<Finished, Timeline> ConsumerResponse;
399 /* Receive a signal from the consumer in reply to the original dispatch signal.
400 * If a signal was received, returns a Finished or a Timeline object.
401 * The InputConsumer should return a Finished object for every InputMessage that it is sent
402 * to confirm that it has been processed and that the InputConsumer is responsive.
403 * If several InputMessages are sent to InputConsumer, it's possible to receive Finished
404 * events out of order for those messages.
Jeff Brown5912f952013-07-01 19:10:31 -0700405 *
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000406 * The Timeline object is returned whenever the receiving end has processed a graphical frame
407 * and is returning the timeline of the frame. Not all input events will cause a Timeline
408 * object to be returned, and there is not guarantee about when it will arrive.
409 *
410 * If an object of Finished is returned, the returned sequence number is never 0 unless the
411 * operation failed.
Jeff Brown5912f952013-07-01 19:10:31 -0700412 *
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000413 * Returned error codes:
414 * OK on success.
415 * WOULD_BLOCK if there is no signal present.
416 * DEAD_OBJECT if the channel's peer has been closed.
417 * Other errors probably indicate that the channel is broken.
Jeff Brown5912f952013-07-01 19:10:31 -0700418 */
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000419 android::base::Result<ConsumerResponse> receiveConsumerResponse();
Jeff Brown5912f952013-07-01 19:10:31 -0700420
421private:
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500422 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700423};
424
425/*
426 * Consumes input events from an input channel.
427 */
428class InputConsumer {
429public:
430 /* Creates a consumer associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500431 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700432
433 /* Destroys the consumer and releases its input channel. */
434 ~InputConsumer();
435
436 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500437 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700438
439 /* Consumes an input event from the input channel and copies its contents into
440 * an InputEvent object created using the specified factory.
441 *
442 * Tries to combine a series of move events into larger batches whenever possible.
443 *
444 * If consumeBatches is false, then defers consuming pending batched events if it
445 * is possible for additional samples to be added to them later. Call hasPendingBatch()
446 * to determine whether a pending batch is available to be consumed.
447 *
448 * If consumeBatches is true, then events are still batched but they are consumed
449 * immediately as soon as the input channel is exhausted.
450 *
451 * The frameTime parameter specifies the time when the current display frame started
452 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
453 *
454 * The returned sequence number is never 0 unless the operation failed.
455 *
456 * Returns OK on success.
457 * Returns WOULD_BLOCK if there is no event present.
458 * Returns DEAD_OBJECT if the channel's peer has been closed.
459 * Returns NO_MEMORY if the event could not be created.
460 * Other errors probably indicate that the channel is broken.
461 */
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800462 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, nsecs_t frameTime,
463 uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700464
465 /* Sends a finished signal to the publisher to inform it that the message
466 * with the specified sequence number has finished being process and whether
467 * the message was handled by the consumer.
468 *
469 * Returns OK on success.
470 * Returns BAD_VALUE if seq is 0.
471 * Other errors probably indicate that the channel is broken.
472 */
473 status_t sendFinishedSignal(uint32_t seq, bool handled);
474
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000475 status_t sendTimeline(int32_t inputEventId,
476 std::array<nsecs_t, GraphicsTimeline::SIZE> timeline);
477
Jeff Brown5912f952013-07-01 19:10:31 -0700478 /* Returns true if there is a deferred event waiting.
479 *
480 * Should be called after calling consume() to determine whether the consumer
481 * has a deferred event to be processed. Deferred events are somewhat special in
482 * that they have already been removed from the input channel. If the input channel
483 * becomes empty, the client may need to do extra work to ensure that it processes
484 * the deferred event despite the fact that the input channel's file descriptor
485 * is not readable.
486 *
487 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
488 * This guarantees that all deferred events will be processed.
489 *
490 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
491 * a deferred event waiting and then ensure that its event loop wakes up at least
492 * one more time to consume the deferred event.
493 */
494 bool hasDeferredEvent() const;
495
496 /* Returns true if there is a pending batch.
497 *
498 * Should be called after calling consume() with consumeBatches == false to determine
499 * whether consume() should be called again later on with consumeBatches == true.
500 */
501 bool hasPendingBatch() const;
502
Arthur Hungc7812be2020-02-27 22:40:27 +0800503 /* Returns the source of first pending batch if exist.
504 *
505 * Should be called after calling consume() with consumeBatches == false to determine
506 * whether consume() should be called again later on with consumeBatches == true.
507 */
508 int32_t getPendingBatchSource() const;
509
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500510 std::string dump() const;
511
Jeff Brown5912f952013-07-01 19:10:31 -0700512private:
513 // True if touch resampling is enabled.
514 const bool mResampleTouch;
515
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500516 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700517
518 // The current input message.
519 InputMessage mMsg;
520
521 // True if mMsg contains a valid input message that was deferred from the previous
522 // call to consume and that still needs to be handled.
523 bool mMsgDeferred;
524
525 // Batched motion events per device and source.
526 struct Batch {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500527 std::vector<InputMessage> samples;
Jeff Brown5912f952013-07-01 19:10:31 -0700528 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500529 std::vector<Batch> mBatches;
Jeff Brown5912f952013-07-01 19:10:31 -0700530
531 // Touch state per device and source, only for sources of class pointer.
532 struct History {
533 nsecs_t eventTime;
534 BitSet32 idBits;
535 int32_t idToIndex[MAX_POINTER_ID + 1];
536 PointerCoords pointers[MAX_POINTERS];
537
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100538 void initializeFrom(const InputMessage& msg) {
539 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700540 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100541 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
542 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700543 idBits.markBit(id);
544 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100545 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700546 }
547 }
548
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800549 void initializeFrom(const History& other) {
550 eventTime = other.eventTime;
551 idBits = other.idBits; // temporary copy
552 for (size_t i = 0; i < other.idBits.count(); i++) {
553 uint32_t id = idBits.clearFirstMarkedBit();
554 int32_t index = other.idToIndex[id];
555 idToIndex[id] = index;
556 pointers[index].copyFrom(other.pointers[index]);
557 }
558 idBits = other.idBits; // final copy
559 }
560
Jeff Brown5912f952013-07-01 19:10:31 -0700561 const PointerCoords& getPointerById(uint32_t id) const {
562 return pointers[idToIndex[id]];
563 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700564
565 bool hasPointerId(uint32_t id) const {
566 return idBits.hasBit(id);
567 }
Jeff Brown5912f952013-07-01 19:10:31 -0700568 };
569 struct TouchState {
570 int32_t deviceId;
571 int32_t source;
572 size_t historyCurrent;
573 size_t historySize;
574 History history[2];
575 History lastResample;
576
577 void initialize(int32_t deviceId, int32_t source) {
578 this->deviceId = deviceId;
579 this->source = source;
580 historyCurrent = 0;
581 historySize = 0;
582 lastResample.eventTime = 0;
583 lastResample.idBits.clear();
584 }
585
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100586 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700587 historyCurrent ^= 1;
588 if (historySize < 2) {
589 historySize += 1;
590 }
591 history[historyCurrent].initializeFrom(msg);
592 }
593
594 const History* getHistory(size_t index) const {
595 return &history[(historyCurrent + index) & 1];
596 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100597
598 bool recentCoordinatesAreIdentical(uint32_t id) const {
599 // Return true if the two most recently received "raw" coordinates are identical
600 if (historySize < 2) {
601 return false;
602 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700603 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
604 return false;
605 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100606 float currentX = getHistory(0)->getPointerById(id).getX();
607 float currentY = getHistory(0)->getPointerById(id).getY();
608 float previousX = getHistory(1)->getPointerById(id).getX();
609 float previousY = getHistory(1)->getPointerById(id).getY();
610 if (currentX == previousX && currentY == previousY) {
611 return true;
612 }
613 return false;
614 }
Jeff Brown5912f952013-07-01 19:10:31 -0700615 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500616 std::vector<TouchState> mTouchStates;
Jeff Brown5912f952013-07-01 19:10:31 -0700617
618 // Chain of batched sequence numbers. When multiple input messages are combined into
619 // a batch, we append a record here that associates the last sequence number in the
620 // batch with the previous one. When the finished signal is sent, we traverse the
621 // chain to individually finish all input messages that were part of the batch.
622 struct SeqChain {
623 uint32_t seq; // sequence number of batched input message
624 uint32_t chain; // sequence number of previous batched input message
625 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500626 std::vector<SeqChain> mSeqChains;
Jeff Brown5912f952013-07-01 19:10:31 -0700627
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000628 // The time at which each event with the sequence number 'seq' was consumed.
629 // This data is provided in 'finishInputEvent' so that the receiving end can measure the latency
630 // This collection is populated when the event is received, and the entries are erased when the
631 // events are finished. It should not grow infinitely because if an event is not ack'd, ANR
632 // will be raised for that connection, and no further events will be posted to that channel.
633 std::unordered_map<uint32_t /*seq*/, nsecs_t /*consumeTime*/> mConsumeTimes;
634
Jeff Brown5912f952013-07-01 19:10:31 -0700635 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800636 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700637 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800638 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700639
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100640 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700641 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
642 const InputMessage *next);
643
644 ssize_t findBatch(int32_t deviceId, int32_t source) const;
645 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
646
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000647 nsecs_t getConsumeTime(uint32_t seq) const;
648 void popConsumeTime(uint32_t seq);
Jeff Brown5912f952013-07-01 19:10:31 -0700649 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
650
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800651 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700652 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
653 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800654 static void initializeFocusEvent(FocusEvent* event, const InputMessage* msg);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800655 static void initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg);
arthurhung7632c332020-12-30 16:58:01 +0800656 static void initializeDragEvent(DragEvent* event, const InputMessage* msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700657 static void addSample(MotionEvent* event, const InputMessage* msg);
658 static bool canAddSample(const Batch& batch, const InputMessage* msg);
659 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
660 static bool shouldResampleTool(int32_t toolType);
661
662 static bool isTouchResamplingEnabled();
663};
664
665} // namespace android
666
667#endif // _LIBINPUT_INPUT_TRANSPORT_H