blob: ba9ae204eb1165c7fd519d38528c80d0165ed03f [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 Vishniakou38b7f7f2021-03-05 01:57:08 +000036#include <android-base/unique_fd.h>
Atif Niyaz3d3fa522019-07-25 11:12:39 -070037
Robert Carr803535b2018-08-02 16:38:15 -070038#include <binder/IBinder.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <binder/Parcelable.h>
Jeff Brown5912f952013-07-01 19:10:31 -070040#include <input/Input.h>
Chris Ye0783e992020-06-02 21:34:49 -070041#include <sys/stat.h>
chaviw9eaa22c2020-07-01 16:21:27 -070042#include <ui/Transform.h>
Jeff Brown5912f952013-07-01 19:10:31 -070043#include <utils/BitSet.h>
Atif Niyaz3d3fa522019-07-25 11:12:39 -070044#include <utils/Errors.h>
45#include <utils/RefBase.h>
46#include <utils/Timers.h>
Jeff Brown5912f952013-07-01 19:10:31 -070047
Josh Gao2ccbe3a2019-08-09 14:35:36 -070048
Jeff Brown5912f952013-07-01 19:10:31 -070049namespace android {
Robert Carr3720ed02018-08-08 16:08:27 -070050class Parcel;
Jeff Brown5912f952013-07-01 19:10:31 -070051
52/*
53 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080054 *
55 * Note that this structure is used for IPCs so its layout must be identical
56 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080057 *
58 * Since the struct must be aligned to an 8-byte boundary, there could be uninitialized bytes
59 * in-between the defined fields. This padding data should be explicitly accounted for by adding
60 * "empty" fields into the struct. This data is memset to zero before sending the struct across
61 * the socket. Adding the explicit fields ensures that the memset is not optimized away by the
62 * compiler. When a new field is added to the struct, the corresponding change
63 * in StructLayout_test should be made.
Jeff Brown5912f952013-07-01 19:10:31 -070064 */
65struct InputMessage {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070066 enum class Type : uint32_t {
67 KEY,
68 MOTION,
69 FINISHED,
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -080070 FOCUS,
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -080071 CAPTURE,
Jeff Brown5912f952013-07-01 19:10:31 -070072 };
73
74 struct Header {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070075 Type type; // 4 bytes
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050076 uint32_t seq;
Jeff Brown5912f952013-07-01 19:10:31 -070077 } header;
78
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060079 // For keys and motions, rely on the fact that std::array takes up exactly as much space
80 // as the underlying data. This is not guaranteed by C++, but it simplifies the conversions.
81 static_assert(sizeof(std::array<uint8_t, 32>) == 32);
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +000082
83 // For bool values, rely on the fact that they take up exactly one byte. This is not guaranteed
84 // by C++ and is implementation-dependent, but it simplifies the conversions.
85 static_assert(sizeof(bool) == 1);
86
87 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070088 union Body {
89 struct Key {
Garfield Tan1c7bc862020-01-28 13:24:04 -080090 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050091 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080092 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070093 int32_t deviceId;
94 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010095 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060096 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -070097 int32_t action;
98 int32_t flags;
99 int32_t keyCode;
100 int32_t scanCode;
101 int32_t metaState;
102 int32_t repeatCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800103 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800104 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700105
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800106 inline size_t size() const { return sizeof(Key); }
Jeff Brown5912f952013-07-01 19:10:31 -0700107 } key;
108
109 struct Motion {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800110 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500111 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800112 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700113 int32_t deviceId;
114 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700115 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600116 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700117 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100118 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700119 int32_t flags;
120 int32_t metaState;
121 int32_t buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800122 MotionClassification classification; // base type: uint8_t
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800123 uint8_t empty2[3]; // 3 bytes to fill gap created by classification
Jeff Brown5912f952013-07-01 19:10:31 -0700124 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800125 nsecs_t downTime __attribute__((aligned(8)));
chaviw9eaa22c2020-07-01 16:21:27 -0700126 float dsdx;
127 float dtdx;
128 float dtdy;
129 float dsdy;
130 float tx;
131 float ty;
Jeff Brown5912f952013-07-01 19:10:31 -0700132 float xPrecision;
133 float yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700134 float xCursorPosition;
135 float yCursorPosition;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100136 uint32_t pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800137 uint32_t empty3;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800138 /**
139 * The "pointers" field must be the last field of the struct InputMessage.
140 * When we send the struct InputMessage across the socket, we are not
141 * writing the entire "pointers" array, but only the pointerCount portion
142 * of it as an optimization. Adding a field after "pointers" would break this.
143 */
Michael Wrightb03f1032015-05-14 16:29:13 +0100144 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700145 PointerProperties properties;
146 PointerCoords coords;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800147 } pointers[MAX_POINTERS] __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700148
149 int32_t getActionId() const {
150 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
151 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
152 return pointers[index].properties.id;
153 }
154
155 inline size_t size() const {
156 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
157 + sizeof(Pointer) * pointerCount;
158 }
159 } motion;
160
161 struct Finished {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000162 bool handled;
163 uint8_t empty[7];
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000164 nsecs_t consumeTime; // The time when the event was consumed by the receiving end
Jeff Brown5912f952013-07-01 19:10:31 -0700165
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800166 inline size_t size() const { return sizeof(Finished); }
Jeff Brown5912f952013-07-01 19:10:31 -0700167 } finished;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800168
169 struct Focus {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800170 int32_t eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000171 // The following 3 fields take up 4 bytes total
172 bool hasFocus;
173 bool inTouchMode;
174 uint8_t empty[2];
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800175
176 inline size_t size() const { return sizeof(Focus); }
177 } focus;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800178
179 struct Capture {
180 int32_t eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000181 bool pointerCaptureEnabled;
182 uint8_t empty[3];
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800183
184 inline size_t size() const { return sizeof(Capture); }
185 } capture;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800186 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700187
188 bool isValid(size_t actualSize) const;
189 size_t size() const;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800190 void getSanitizedCopy(InputMessage* msg) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700191};
192
193/*
194 * An input channel consists of a local unix domain socket used to send and receive
195 * input messages across processes. Each channel has a descriptive name for debugging purposes.
196 *
197 * Each endpoint has its own InputChannel object that specifies its file descriptor.
198 *
199 * The input channel is closed when all references to it are released.
200 */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500201class InputChannel : public Parcelable {
Chris Ye0783e992020-06-02 21:34:49 -0700202public:
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500203 static std::unique_ptr<InputChannel> create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500204 android::base::unique_fd fd, sp<IBinder> token);
205 InputChannel() = default;
206 InputChannel(const InputChannel& other)
207 : mName(other.mName), mFd(::dup(other.mFd)), mToken(other.mToken){};
208 InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token);
Jeff Brown5912f952013-07-01 19:10:31 -0700209 virtual ~InputChannel();
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700210 /**
211 * Create a pair of input channels.
212 * The two returned input channels are equivalent, and are labeled as "server" and "client"
213 * for convenience. The two input channels share the same token.
Jeff Brown5912f952013-07-01 19:10:31 -0700214 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700215 * Return OK on success.
Jeff Brown5912f952013-07-01 19:10:31 -0700216 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800217 static status_t openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500218 std::unique_ptr<InputChannel>& outServerChannel,
219 std::unique_ptr<InputChannel>& outClientChannel);
Jeff Brown5912f952013-07-01 19:10:31 -0700220
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500221 inline std::string getName() const { return mName; }
222 inline const android::base::unique_fd& getFd() const { return mFd; }
223 inline sp<IBinder> getToken() const { return mToken; }
Jeff Brown5912f952013-07-01 19:10:31 -0700224
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700225 /* Send a message to the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700226 *
227 * If the channel is full then the message is guaranteed not to have been sent at all.
228 * Try again after the consumer has sent a finished signal indicating that it has
229 * consumed some of the pending messages from the channel.
230 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700231 * Return OK on success.
232 * Return WOULD_BLOCK if the channel is full.
233 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700234 * Other errors probably indicate that the channel is broken.
235 */
236 status_t sendMessage(const InputMessage* msg);
237
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700238 /* Receive a message sent by the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700239 *
240 * If there is no message present, try again after poll() indicates that the fd
241 * is readable.
242 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700243 * Return OK on success.
244 * Return WOULD_BLOCK if there is no message present.
245 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700246 * Other errors probably indicate that the channel is broken.
247 */
248 status_t receiveMessage(InputMessage* msg);
249
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700250 /* Return a new object that has a duplicate of this channel's fd. */
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500251 std::unique_ptr<InputChannel> dup() const;
Jeff Brown5912f952013-07-01 19:10:31 -0700252
Garfield Tan15601662020-09-22 15:32:38 -0700253 void copyTo(InputChannel& outChannel) const;
254
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500255 status_t readFromParcel(const android::Parcel* parcel) override;
256 status_t writeToParcel(android::Parcel* parcel) const override;
Robert Carr3720ed02018-08-08 16:08:27 -0700257
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700258 /**
259 * The connection token is used to identify the input connection, i.e.
260 * the pair of input channels that were created simultaneously. Input channels
261 * are always created in pairs, and the token can be used to find the server-side
262 * input channel from the client-side input channel, and vice versa.
263 *
264 * Do not use connection token to check equality of a specific input channel object
265 * to another, because two different (client and server) input channels will share the
266 * same connection token.
267 *
268 * Return the token that identifies this connection.
269 */
270 sp<IBinder> getConnectionToken() const;
Robert Carr803535b2018-08-02 16:38:15 -0700271
Chris Ye0783e992020-06-02 21:34:49 -0700272 bool operator==(const InputChannel& inputChannel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500273 struct stat lhs, rhs;
274 if (fstat(mFd.get(), &lhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700275 return false;
276 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500277 if (fstat(inputChannel.getFd(), &rhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700278 return false;
279 }
280 // If file descriptors are pointing to same inode they are duplicated fds.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500281 return inputChannel.getName() == getName() && inputChannel.getConnectionToken() == mToken &&
282 lhs.st_ino == rhs.st_ino;
Chris Ye0783e992020-06-02 21:34:49 -0700283 }
284
Jeff Brown5912f952013-07-01 19:10:31 -0700285private:
Garfield Tan15601662020-09-22 15:32:38 -0700286 base::unique_fd dupFd() const;
287
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500288 std::string mName;
289 android::base::unique_fd mFd;
290
291 sp<IBinder> mToken;
Jeff Brown5912f952013-07-01 19:10:31 -0700292};
293
294/*
295 * Publishes input events to an input channel.
296 */
297class InputPublisher {
298public:
299 /* Creates a publisher associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500300 explicit InputPublisher(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700301
302 /* Destroys the publisher and releases its input channel. */
303 ~InputPublisher();
304
305 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500306 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700307
308 /* Publishes a key event to the input channel.
309 *
310 * Returns OK on success.
311 * Returns WOULD_BLOCK if the channel is full.
312 * Returns DEAD_OBJECT if the channel's peer has been closed.
313 * Returns BAD_VALUE if seq is 0.
314 * Other errors probably indicate that the channel is broken.
315 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800316 status_t publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
317 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
318 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600319 int32_t repeatCount, nsecs_t downTime, nsecs_t eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700320
321 /* Publishes a motion event to the input channel.
322 *
323 * Returns OK on success.
324 * Returns WOULD_BLOCK if the channel is full.
325 * Returns DEAD_OBJECT if the channel's peer has been closed.
326 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
327 * Other errors probably indicate that the channel is broken.
328 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800329 status_t publishMotionEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
330 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
331 int32_t actionButton, int32_t flags, int32_t edgeFlags,
332 int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700333 MotionClassification classification, const ui::Transform& transform,
334 float xPrecision, float yPrecision, float xCursorPosition,
335 float yCursorPosition, nsecs_t downTime, nsecs_t eventTime,
336 uint32_t pointerCount, const PointerProperties* pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -0700337 const PointerCoords* pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700338
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800339 /* Publishes a focus event to the input channel.
340 *
341 * Returns OK on success.
342 * Returns WOULD_BLOCK if the channel is full.
343 * Returns DEAD_OBJECT if the channel's peer has been closed.
344 * Other errors probably indicate that the channel is broken.
345 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800346 status_t publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus, bool inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800347
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800348 /* Publishes a capture event to the input channel.
349 *
350 * Returns OK on success.
351 * Returns WOULD_BLOCK if the channel is full.
352 * Returns DEAD_OBJECT if the channel's peer has been closed.
353 * Other errors probably indicate that the channel is broken.
354 */
355 status_t publishCaptureEvent(uint32_t seq, int32_t eventId, bool pointerCaptureEnabled);
356
Jeff Brown5912f952013-07-01 19:10:31 -0700357 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
358 * If a signal was received, returns the message sequence number,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000359 * whether the consumer handled the message, and the time the event was first read by the
360 * consumer.
Jeff Brown5912f952013-07-01 19:10:31 -0700361 *
362 * The returned sequence number is never 0 unless the operation failed.
363 *
364 * Returns OK on success.
365 * Returns WOULD_BLOCK if there is no signal present.
366 * Returns DEAD_OBJECT if the channel's peer has been closed.
367 * Other errors probably indicate that the channel is broken.
368 */
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000369 status_t receiveFinishedSignal(
370 const std::function<void(uint32_t seq, bool handled, nsecs_t consumeTime)>& callback);
Jeff Brown5912f952013-07-01 19:10:31 -0700371
372private:
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500373 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700374};
375
376/*
377 * Consumes input events from an input channel.
378 */
379class InputConsumer {
380public:
381 /* Creates a consumer associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500382 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700383
384 /* Destroys the consumer and releases its input channel. */
385 ~InputConsumer();
386
387 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500388 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700389
390 /* Consumes an input event from the input channel and copies its contents into
391 * an InputEvent object created using the specified factory.
392 *
393 * Tries to combine a series of move events into larger batches whenever possible.
394 *
395 * If consumeBatches is false, then defers consuming pending batched events if it
396 * is possible for additional samples to be added to them later. Call hasPendingBatch()
397 * to determine whether a pending batch is available to be consumed.
398 *
399 * If consumeBatches is true, then events are still batched but they are consumed
400 * immediately as soon as the input channel is exhausted.
401 *
402 * The frameTime parameter specifies the time when the current display frame started
403 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
404 *
405 * The returned sequence number is never 0 unless the operation failed.
406 *
407 * Returns OK on success.
408 * Returns WOULD_BLOCK if there is no event present.
409 * Returns DEAD_OBJECT if the channel's peer has been closed.
410 * Returns NO_MEMORY if the event could not be created.
411 * Other errors probably indicate that the channel is broken.
412 */
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800413 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, nsecs_t frameTime,
414 uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700415
416 /* Sends a finished signal to the publisher to inform it that the message
417 * with the specified sequence number has finished being process and whether
418 * the message was handled by the consumer.
419 *
420 * Returns OK on success.
421 * Returns BAD_VALUE if seq is 0.
422 * Other errors probably indicate that the channel is broken.
423 */
424 status_t sendFinishedSignal(uint32_t seq, bool handled);
425
426 /* Returns true if there is a deferred event waiting.
427 *
428 * Should be called after calling consume() to determine whether the consumer
429 * has a deferred event to be processed. Deferred events are somewhat special in
430 * that they have already been removed from the input channel. If the input channel
431 * becomes empty, the client may need to do extra work to ensure that it processes
432 * the deferred event despite the fact that the input channel's file descriptor
433 * is not readable.
434 *
435 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
436 * This guarantees that all deferred events will be processed.
437 *
438 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
439 * a deferred event waiting and then ensure that its event loop wakes up at least
440 * one more time to consume the deferred event.
441 */
442 bool hasDeferredEvent() const;
443
444 /* Returns true if there is a pending batch.
445 *
446 * Should be called after calling consume() with consumeBatches == false to determine
447 * whether consume() should be called again later on with consumeBatches == true.
448 */
449 bool hasPendingBatch() const;
450
Arthur Hungc7812be2020-02-27 22:40:27 +0800451 /* Returns the source of first pending batch if exist.
452 *
453 * Should be called after calling consume() with consumeBatches == false to determine
454 * whether consume() should be called again later on with consumeBatches == true.
455 */
456 int32_t getPendingBatchSource() const;
457
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500458 std::string dump() const;
459
Jeff Brown5912f952013-07-01 19:10:31 -0700460private:
461 // True if touch resampling is enabled.
462 const bool mResampleTouch;
463
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500464 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700465
466 // The current input message.
467 InputMessage mMsg;
468
469 // True if mMsg contains a valid input message that was deferred from the previous
470 // call to consume and that still needs to be handled.
471 bool mMsgDeferred;
472
473 // Batched motion events per device and source.
474 struct Batch {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500475 std::vector<InputMessage> samples;
Jeff Brown5912f952013-07-01 19:10:31 -0700476 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500477 std::vector<Batch> mBatches;
Jeff Brown5912f952013-07-01 19:10:31 -0700478
479 // Touch state per device and source, only for sources of class pointer.
480 struct History {
481 nsecs_t eventTime;
482 BitSet32 idBits;
483 int32_t idToIndex[MAX_POINTER_ID + 1];
484 PointerCoords pointers[MAX_POINTERS];
485
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100486 void initializeFrom(const InputMessage& msg) {
487 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700488 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100489 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
490 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700491 idBits.markBit(id);
492 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100493 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700494 }
495 }
496
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800497 void initializeFrom(const History& other) {
498 eventTime = other.eventTime;
499 idBits = other.idBits; // temporary copy
500 for (size_t i = 0; i < other.idBits.count(); i++) {
501 uint32_t id = idBits.clearFirstMarkedBit();
502 int32_t index = other.idToIndex[id];
503 idToIndex[id] = index;
504 pointers[index].copyFrom(other.pointers[index]);
505 }
506 idBits = other.idBits; // final copy
507 }
508
Jeff Brown5912f952013-07-01 19:10:31 -0700509 const PointerCoords& getPointerById(uint32_t id) const {
510 return pointers[idToIndex[id]];
511 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700512
513 bool hasPointerId(uint32_t id) const {
514 return idBits.hasBit(id);
515 }
Jeff Brown5912f952013-07-01 19:10:31 -0700516 };
517 struct TouchState {
518 int32_t deviceId;
519 int32_t source;
520 size_t historyCurrent;
521 size_t historySize;
522 History history[2];
523 History lastResample;
524
525 void initialize(int32_t deviceId, int32_t source) {
526 this->deviceId = deviceId;
527 this->source = source;
528 historyCurrent = 0;
529 historySize = 0;
530 lastResample.eventTime = 0;
531 lastResample.idBits.clear();
532 }
533
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100534 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700535 historyCurrent ^= 1;
536 if (historySize < 2) {
537 historySize += 1;
538 }
539 history[historyCurrent].initializeFrom(msg);
540 }
541
542 const History* getHistory(size_t index) const {
543 return &history[(historyCurrent + index) & 1];
544 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100545
546 bool recentCoordinatesAreIdentical(uint32_t id) const {
547 // Return true if the two most recently received "raw" coordinates are identical
548 if (historySize < 2) {
549 return false;
550 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700551 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
552 return false;
553 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100554 float currentX = getHistory(0)->getPointerById(id).getX();
555 float currentY = getHistory(0)->getPointerById(id).getY();
556 float previousX = getHistory(1)->getPointerById(id).getX();
557 float previousY = getHistory(1)->getPointerById(id).getY();
558 if (currentX == previousX && currentY == previousY) {
559 return true;
560 }
561 return false;
562 }
Jeff Brown5912f952013-07-01 19:10:31 -0700563 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500564 std::vector<TouchState> mTouchStates;
Jeff Brown5912f952013-07-01 19:10:31 -0700565
566 // Chain of batched sequence numbers. When multiple input messages are combined into
567 // a batch, we append a record here that associates the last sequence number in the
568 // batch with the previous one. When the finished signal is sent, we traverse the
569 // chain to individually finish all input messages that were part of the batch.
570 struct SeqChain {
571 uint32_t seq; // sequence number of batched input message
572 uint32_t chain; // sequence number of previous batched input message
573 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500574 std::vector<SeqChain> mSeqChains;
Jeff Brown5912f952013-07-01 19:10:31 -0700575
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000576 // The time at which each event with the sequence number 'seq' was consumed.
577 // This data is provided in 'finishInputEvent' so that the receiving end can measure the latency
578 // This collection is populated when the event is received, and the entries are erased when the
579 // events are finished. It should not grow infinitely because if an event is not ack'd, ANR
580 // will be raised for that connection, and no further events will be posted to that channel.
581 std::unordered_map<uint32_t /*seq*/, nsecs_t /*consumeTime*/> mConsumeTimes;
582
Jeff Brown5912f952013-07-01 19:10:31 -0700583 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800584 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700585 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800586 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700587
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100588 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700589 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
590 const InputMessage *next);
591
592 ssize_t findBatch(int32_t deviceId, int32_t source) const;
593 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
594
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000595 nsecs_t getConsumeTime(uint32_t seq) const;
596 void popConsumeTime(uint32_t seq);
Jeff Brown5912f952013-07-01 19:10:31 -0700597 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
598
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800599 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700600 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
601 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800602 static void initializeFocusEvent(FocusEvent* event, const InputMessage* msg);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800603 static void initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700604 static void addSample(MotionEvent* event, const InputMessage* msg);
605 static bool canAddSample(const Batch& batch, const InputMessage* msg);
606 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
607 static bool shouldResampleTool(int32_t toolType);
608
609 static bool isTouchResamplingEnabled();
610};
611
612} // namespace android
613
614#endif // _LIBINPUT_INPUT_TRANSPORT_H