blob: 3b46cb5997126f70fe2d28a519873f3d1c207bff [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>
36
Robert Carr803535b2018-08-02 16:38:15 -070037#include <binder/IBinder.h>
Chris Ye0783e992020-06-02 21:34:49 -070038#include <binder/Parcelable.h>
Jeff Brown5912f952013-07-01 19:10:31 -070039#include <input/Input.h>
Chris Ye0783e992020-06-02 21:34:49 -070040#include <sys/stat.h>
chaviw9eaa22c2020-07-01 16:21:27 -070041#include <ui/Transform.h>
Jeff Brown5912f952013-07-01 19:10:31 -070042#include <utils/BitSet.h>
Atif Niyaz3d3fa522019-07-25 11:12:39 -070043#include <utils/Errors.h>
44#include <utils/RefBase.h>
45#include <utils/Timers.h>
Jeff Brown5912f952013-07-01 19:10:31 -070046
Josh Gao2ccbe3a2019-08-09 14:35:36 -070047#include <android-base/unique_fd.h>
48
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
Fengwei Yin83e0e422014-05-24 05:32:09 +080079 // Body *must* be 8 byte aligned.
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060080 // For keys and motions, rely on the fact that std::array takes up exactly as much space
81 // as the underlying data. This is not guaranteed by C++, but it simplifies the conversions.
82 static_assert(sizeof(std::array<uint8_t, 32>) == 32);
Jeff Brown5912f952013-07-01 19:10:31 -070083 union Body {
84 struct Key {
Garfield Tan1c7bc862020-01-28 13:24:04 -080085 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050086 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080087 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070088 int32_t deviceId;
89 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010090 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060091 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -070092 int32_t action;
93 int32_t flags;
94 int32_t keyCode;
95 int32_t scanCode;
96 int32_t metaState;
97 int32_t repeatCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080098 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +080099 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700100
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800101 inline size_t size() const { return sizeof(Key); }
Jeff Brown5912f952013-07-01 19:10:31 -0700102 } key;
103
104 struct Motion {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800105 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500106 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800107 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700108 int32_t deviceId;
109 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700110 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600111 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700112 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100113 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700114 int32_t flags;
115 int32_t metaState;
116 int32_t buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800117 MotionClassification classification; // base type: uint8_t
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800118 uint8_t empty2[3]; // 3 bytes to fill gap created by classification
Jeff Brown5912f952013-07-01 19:10:31 -0700119 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800120 nsecs_t downTime __attribute__((aligned(8)));
chaviw9eaa22c2020-07-01 16:21:27 -0700121 float dsdx;
122 float dtdx;
123 float dtdy;
124 float dsdy;
125 float tx;
126 float ty;
Jeff Brown5912f952013-07-01 19:10:31 -0700127 float xPrecision;
128 float yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700129 float xCursorPosition;
130 float yCursorPosition;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100131 uint32_t pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800132 uint32_t empty3;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800133 /**
134 * The "pointers" field must be the last field of the struct InputMessage.
135 * When we send the struct InputMessage across the socket, we are not
136 * writing the entire "pointers" array, but only the pointerCount portion
137 * of it as an optimization. Adding a field after "pointers" would break this.
138 */
Michael Wrightb03f1032015-05-14 16:29:13 +0100139 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700140 PointerProperties properties;
141 PointerCoords coords;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800142 } pointers[MAX_POINTERS] __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700143
144 int32_t getActionId() const {
145 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
146 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
147 return pointers[index].properties.id;
148 }
149
150 inline size_t size() const {
151 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
152 + sizeof(Pointer) * pointerCount;
153 }
154 } motion;
155
156 struct Finished {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500157 uint32_t empty1;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800158 uint32_t handled; // actually a bool, but we must maintain 8-byte alignment
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000159 nsecs_t consumeTime; // The time when the event was consumed by the receiving end
Jeff Brown5912f952013-07-01 19:10:31 -0700160
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800161 inline size_t size() const { return sizeof(Finished); }
Jeff Brown5912f952013-07-01 19:10:31 -0700162 } finished;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800163
164 struct Focus {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800165 int32_t eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800166 // The following two fields take up 4 bytes total
167 uint16_t hasFocus; // actually a bool
168 uint16_t inTouchMode; // actually a bool, but we must maintain 8-byte alignment
169
170 inline size_t size() const { return sizeof(Focus); }
171 } focus;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800172
173 struct Capture {
174 int32_t eventId;
175 uint32_t pointerCaptureEnabled; // actually a bool, but we maintain 8-byte alignment
176
177 inline size_t size() const { return sizeof(Capture); }
178 } capture;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800179 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700180
181 bool isValid(size_t actualSize) const;
182 size_t size() const;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800183 void getSanitizedCopy(InputMessage* msg) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700184};
185
186/*
187 * An input channel consists of a local unix domain socket used to send and receive
188 * input messages across processes. Each channel has a descriptive name for debugging purposes.
189 *
190 * Each endpoint has its own InputChannel object that specifies its file descriptor.
191 *
192 * The input channel is closed when all references to it are released.
193 */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500194class InputChannel : public Parcelable {
Chris Ye0783e992020-06-02 21:34:49 -0700195public:
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500196 static std::unique_ptr<InputChannel> create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500197 android::base::unique_fd fd, sp<IBinder> token);
198 InputChannel() = default;
199 InputChannel(const InputChannel& other)
200 : mName(other.mName), mFd(::dup(other.mFd)), mToken(other.mToken){};
201 InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token);
Jeff Brown5912f952013-07-01 19:10:31 -0700202 virtual ~InputChannel();
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700203 /**
204 * Create a pair of input channels.
205 * The two returned input channels are equivalent, and are labeled as "server" and "client"
206 * for convenience. The two input channels share the same token.
Jeff Brown5912f952013-07-01 19:10:31 -0700207 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700208 * Return OK on success.
Jeff Brown5912f952013-07-01 19:10:31 -0700209 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800210 static status_t openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500211 std::unique_ptr<InputChannel>& outServerChannel,
212 std::unique_ptr<InputChannel>& outClientChannel);
Jeff Brown5912f952013-07-01 19:10:31 -0700213
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500214 inline std::string getName() const { return mName; }
215 inline const android::base::unique_fd& getFd() const { return mFd; }
216 inline sp<IBinder> getToken() const { return mToken; }
Jeff Brown5912f952013-07-01 19:10:31 -0700217
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700218 /* Send a message to the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700219 *
220 * If the channel is full then the message is guaranteed not to have been sent at all.
221 * Try again after the consumer has sent a finished signal indicating that it has
222 * consumed some of the pending messages from the channel.
223 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700224 * Return OK on success.
225 * Return WOULD_BLOCK if the channel is full.
226 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700227 * Other errors probably indicate that the channel is broken.
228 */
229 status_t sendMessage(const InputMessage* msg);
230
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700231 /* Receive a message sent by the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700232 *
233 * If there is no message present, try again after poll() indicates that the fd
234 * is readable.
235 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700236 * Return OK on success.
237 * Return WOULD_BLOCK if there is no message present.
238 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700239 * Other errors probably indicate that the channel is broken.
240 */
241 status_t receiveMessage(InputMessage* msg);
242
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700243 /* Return a new object that has a duplicate of this channel's fd. */
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500244 std::unique_ptr<InputChannel> dup() const;
Jeff Brown5912f952013-07-01 19:10:31 -0700245
Garfield Tan15601662020-09-22 15:32:38 -0700246 void copyTo(InputChannel& outChannel) const;
247
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500248 status_t readFromParcel(const android::Parcel* parcel) override;
249 status_t writeToParcel(android::Parcel* parcel) const override;
Robert Carr3720ed02018-08-08 16:08:27 -0700250
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700251 /**
252 * The connection token is used to identify the input connection, i.e.
253 * the pair of input channels that were created simultaneously. Input channels
254 * are always created in pairs, and the token can be used to find the server-side
255 * input channel from the client-side input channel, and vice versa.
256 *
257 * Do not use connection token to check equality of a specific input channel object
258 * to another, because two different (client and server) input channels will share the
259 * same connection token.
260 *
261 * Return the token that identifies this connection.
262 */
263 sp<IBinder> getConnectionToken() const;
Robert Carr803535b2018-08-02 16:38:15 -0700264
Chris Ye0783e992020-06-02 21:34:49 -0700265 bool operator==(const InputChannel& inputChannel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500266 struct stat lhs, rhs;
267 if (fstat(mFd.get(), &lhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700268 return false;
269 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500270 if (fstat(inputChannel.getFd(), &rhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700271 return false;
272 }
273 // If file descriptors are pointing to same inode they are duplicated fds.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500274 return inputChannel.getName() == getName() && inputChannel.getConnectionToken() == mToken &&
275 lhs.st_ino == rhs.st_ino;
Chris Ye0783e992020-06-02 21:34:49 -0700276 }
277
Jeff Brown5912f952013-07-01 19:10:31 -0700278private:
Garfield Tan15601662020-09-22 15:32:38 -0700279 base::unique_fd dupFd() const;
280
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500281 std::string mName;
282 android::base::unique_fd mFd;
283
284 sp<IBinder> mToken;
Jeff Brown5912f952013-07-01 19:10:31 -0700285};
286
287/*
288 * Publishes input events to an input channel.
289 */
290class InputPublisher {
291public:
292 /* Creates a publisher associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500293 explicit InputPublisher(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700294
295 /* Destroys the publisher and releases its input channel. */
296 ~InputPublisher();
297
298 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500299 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700300
301 /* Publishes a key event to the input channel.
302 *
303 * Returns OK on success.
304 * Returns WOULD_BLOCK if the channel is full.
305 * Returns DEAD_OBJECT if the channel's peer has been closed.
306 * Returns BAD_VALUE if seq is 0.
307 * Other errors probably indicate that the channel is broken.
308 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800309 status_t publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
310 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
311 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600312 int32_t repeatCount, nsecs_t downTime, nsecs_t eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700313
314 /* Publishes a motion event to the input channel.
315 *
316 * Returns OK on success.
317 * Returns WOULD_BLOCK if the channel is full.
318 * Returns DEAD_OBJECT if the channel's peer has been closed.
319 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
320 * Other errors probably indicate that the channel is broken.
321 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800322 status_t publishMotionEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
323 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
324 int32_t actionButton, int32_t flags, int32_t edgeFlags,
325 int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700326 MotionClassification classification, const ui::Transform& transform,
327 float xPrecision, float yPrecision, float xCursorPosition,
328 float yCursorPosition, nsecs_t downTime, nsecs_t eventTime,
329 uint32_t pointerCount, const PointerProperties* pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -0700330 const PointerCoords* pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700331
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800332 /* Publishes a focus event to the input channel.
333 *
334 * Returns OK on success.
335 * Returns WOULD_BLOCK if the channel is full.
336 * Returns DEAD_OBJECT if the channel's peer has been closed.
337 * Other errors probably indicate that the channel is broken.
338 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800339 status_t publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus, bool inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800340
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800341 /* Publishes a capture event to the input channel.
342 *
343 * Returns OK on success.
344 * Returns WOULD_BLOCK if the channel is full.
345 * Returns DEAD_OBJECT if the channel's peer has been closed.
346 * Other errors probably indicate that the channel is broken.
347 */
348 status_t publishCaptureEvent(uint32_t seq, int32_t eventId, bool pointerCaptureEnabled);
349
Jeff Brown5912f952013-07-01 19:10:31 -0700350 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
351 * If a signal was received, returns the message sequence number,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000352 * whether the consumer handled the message, and the time the event was first read by the
353 * consumer.
Jeff Brown5912f952013-07-01 19:10:31 -0700354 *
355 * The returned sequence number is never 0 unless the operation failed.
356 *
357 * Returns OK on success.
358 * Returns WOULD_BLOCK if there is no signal present.
359 * Returns DEAD_OBJECT if the channel's peer has been closed.
360 * Other errors probably indicate that the channel is broken.
361 */
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000362 status_t receiveFinishedSignal(
363 const std::function<void(uint32_t seq, bool handled, nsecs_t consumeTime)>& callback);
Jeff Brown5912f952013-07-01 19:10:31 -0700364
365private:
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500366 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700367};
368
369/*
370 * Consumes input events from an input channel.
371 */
372class InputConsumer {
373public:
374 /* Creates a consumer associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500375 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700376
377 /* Destroys the consumer and releases its input channel. */
378 ~InputConsumer();
379
380 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500381 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700382
383 /* Consumes an input event from the input channel and copies its contents into
384 * an InputEvent object created using the specified factory.
385 *
386 * Tries to combine a series of move events into larger batches whenever possible.
387 *
388 * If consumeBatches is false, then defers consuming pending batched events if it
389 * is possible for additional samples to be added to them later. Call hasPendingBatch()
390 * to determine whether a pending batch is available to be consumed.
391 *
392 * If consumeBatches is true, then events are still batched but they are consumed
393 * immediately as soon as the input channel is exhausted.
394 *
395 * The frameTime parameter specifies the time when the current display frame started
396 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
397 *
398 * The returned sequence number is never 0 unless the operation failed.
399 *
400 * Returns OK on success.
401 * Returns WOULD_BLOCK if there is no event present.
402 * Returns DEAD_OBJECT if the channel's peer has been closed.
403 * Returns NO_MEMORY if the event could not be created.
404 * Other errors probably indicate that the channel is broken.
405 */
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800406 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, nsecs_t frameTime,
407 uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700408
409 /* Sends a finished signal to the publisher to inform it that the message
410 * with the specified sequence number has finished being process and whether
411 * the message was handled by the consumer.
412 *
413 * Returns OK on success.
414 * Returns BAD_VALUE if seq is 0.
415 * Other errors probably indicate that the channel is broken.
416 */
417 status_t sendFinishedSignal(uint32_t seq, bool handled);
418
419 /* Returns true if there is a deferred event waiting.
420 *
421 * Should be called after calling consume() to determine whether the consumer
422 * has a deferred event to be processed. Deferred events are somewhat special in
423 * that they have already been removed from the input channel. If the input channel
424 * becomes empty, the client may need to do extra work to ensure that it processes
425 * the deferred event despite the fact that the input channel's file descriptor
426 * is not readable.
427 *
428 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
429 * This guarantees that all deferred events will be processed.
430 *
431 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
432 * a deferred event waiting and then ensure that its event loop wakes up at least
433 * one more time to consume the deferred event.
434 */
435 bool hasDeferredEvent() const;
436
437 /* Returns true if there is a pending batch.
438 *
439 * Should be called after calling consume() with consumeBatches == false to determine
440 * whether consume() should be called again later on with consumeBatches == true.
441 */
442 bool hasPendingBatch() const;
443
Arthur Hungc7812be2020-02-27 22:40:27 +0800444 /* Returns the source of first pending batch if exist.
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 int32_t getPendingBatchSource() const;
450
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500451 std::string dump() const;
452
Jeff Brown5912f952013-07-01 19:10:31 -0700453private:
454 // True if touch resampling is enabled.
455 const bool mResampleTouch;
456
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500457 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700458
459 // The current input message.
460 InputMessage mMsg;
461
462 // True if mMsg contains a valid input message that was deferred from the previous
463 // call to consume and that still needs to be handled.
464 bool mMsgDeferred;
465
466 // Batched motion events per device and source.
467 struct Batch {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500468 std::vector<InputMessage> samples;
Jeff Brown5912f952013-07-01 19:10:31 -0700469 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500470 std::vector<Batch> mBatches;
Jeff Brown5912f952013-07-01 19:10:31 -0700471
472 // Touch state per device and source, only for sources of class pointer.
473 struct History {
474 nsecs_t eventTime;
475 BitSet32 idBits;
476 int32_t idToIndex[MAX_POINTER_ID + 1];
477 PointerCoords pointers[MAX_POINTERS];
478
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100479 void initializeFrom(const InputMessage& msg) {
480 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700481 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100482 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
483 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700484 idBits.markBit(id);
485 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100486 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700487 }
488 }
489
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800490 void initializeFrom(const History& other) {
491 eventTime = other.eventTime;
492 idBits = other.idBits; // temporary copy
493 for (size_t i = 0; i < other.idBits.count(); i++) {
494 uint32_t id = idBits.clearFirstMarkedBit();
495 int32_t index = other.idToIndex[id];
496 idToIndex[id] = index;
497 pointers[index].copyFrom(other.pointers[index]);
498 }
499 idBits = other.idBits; // final copy
500 }
501
Jeff Brown5912f952013-07-01 19:10:31 -0700502 const PointerCoords& getPointerById(uint32_t id) const {
503 return pointers[idToIndex[id]];
504 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700505
506 bool hasPointerId(uint32_t id) const {
507 return idBits.hasBit(id);
508 }
Jeff Brown5912f952013-07-01 19:10:31 -0700509 };
510 struct TouchState {
511 int32_t deviceId;
512 int32_t source;
513 size_t historyCurrent;
514 size_t historySize;
515 History history[2];
516 History lastResample;
517
518 void initialize(int32_t deviceId, int32_t source) {
519 this->deviceId = deviceId;
520 this->source = source;
521 historyCurrent = 0;
522 historySize = 0;
523 lastResample.eventTime = 0;
524 lastResample.idBits.clear();
525 }
526
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100527 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700528 historyCurrent ^= 1;
529 if (historySize < 2) {
530 historySize += 1;
531 }
532 history[historyCurrent].initializeFrom(msg);
533 }
534
535 const History* getHistory(size_t index) const {
536 return &history[(historyCurrent + index) & 1];
537 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100538
539 bool recentCoordinatesAreIdentical(uint32_t id) const {
540 // Return true if the two most recently received "raw" coordinates are identical
541 if (historySize < 2) {
542 return false;
543 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700544 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
545 return false;
546 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100547 float currentX = getHistory(0)->getPointerById(id).getX();
548 float currentY = getHistory(0)->getPointerById(id).getY();
549 float previousX = getHistory(1)->getPointerById(id).getX();
550 float previousY = getHistory(1)->getPointerById(id).getY();
551 if (currentX == previousX && currentY == previousY) {
552 return true;
553 }
554 return false;
555 }
Jeff Brown5912f952013-07-01 19:10:31 -0700556 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500557 std::vector<TouchState> mTouchStates;
Jeff Brown5912f952013-07-01 19:10:31 -0700558
559 // Chain of batched sequence numbers. When multiple input messages are combined into
560 // a batch, we append a record here that associates the last sequence number in the
561 // batch with the previous one. When the finished signal is sent, we traverse the
562 // chain to individually finish all input messages that were part of the batch.
563 struct SeqChain {
564 uint32_t seq; // sequence number of batched input message
565 uint32_t chain; // sequence number of previous batched input message
566 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500567 std::vector<SeqChain> mSeqChains;
Jeff Brown5912f952013-07-01 19:10:31 -0700568
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000569 // The time at which each event with the sequence number 'seq' was consumed.
570 // This data is provided in 'finishInputEvent' so that the receiving end can measure the latency
571 // This collection is populated when the event is received, and the entries are erased when the
572 // events are finished. It should not grow infinitely because if an event is not ack'd, ANR
573 // will be raised for that connection, and no further events will be posted to that channel.
574 std::unordered_map<uint32_t /*seq*/, nsecs_t /*consumeTime*/> mConsumeTimes;
575
Jeff Brown5912f952013-07-01 19:10:31 -0700576 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800577 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700578 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800579 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700580
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100581 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700582 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
583 const InputMessage *next);
584
585 ssize_t findBatch(int32_t deviceId, int32_t source) const;
586 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
587
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000588 nsecs_t getConsumeTime(uint32_t seq) const;
589 void popConsumeTime(uint32_t seq);
Jeff Brown5912f952013-07-01 19:10:31 -0700590 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
591
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800592 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700593 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
594 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800595 static void initializeFocusEvent(FocusEvent* event, const InputMessage* msg);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800596 static void initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700597 static void addSample(MotionEvent* event, const InputMessage* msg);
598 static bool canAddSample(const Batch& batch, const InputMessage* msg);
599 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
600 static bool shouldResampleTool(int32_t toolType);
601
602 static bool isTouchResamplingEnabled();
603};
604
605} // namespace android
606
607#endif // _LIBINPUT_INPUT_TRANSPORT_H