blob: 750e170c245e73bb88900e3030c0a8c75c16848f [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
Prabir Pradhanc08b0db2022-09-10 00:57:15 +000017#pragma once
Jeff Brown5912f952013-07-01 19:10:31 -070018
Robert Carr2c358bf2018-08-08 15:58:15 -070019#pragma GCC system_header
20
Jeff Brown5912f952013-07-01 19:10:31 -070021/**
22 * Native input transport.
23 *
24 * The InputChannel provides a mechanism for exchanging InputMessage structures across processes.
25 *
26 * The InputPublisher and InputConsumer each handle one end-point of an input channel.
27 * The InputPublisher is used by the input dispatcher to send events to the application.
28 * The InputConsumer is used by the application to receive events from the input dispatcher.
29 */
30
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010031#include <string>
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -100032#include <unordered_map>
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010033
Atif Niyaz3d3fa522019-07-25 11:12:39 -070034#include <android-base/chrono_utils.h>
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000035#include <android-base/result.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>
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -080041#include <input/InputVerifier.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,
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -070075 TOUCH_MODE,
Dominik Laskowski75788452021-02-09 18:51:25 -080076
77 ftl_last = TOUCH_MODE
Jeff Brown5912f952013-07-01 19:10:31 -070078 };
79
80 struct Header {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070081 Type type; // 4 bytes
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050082 uint32_t seq;
Jeff Brown5912f952013-07-01 19:10:31 -070083 } header;
84
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060085 // For keys and motions, rely on the fact that std::array takes up exactly as much space
86 // as the underlying data. This is not guaranteed by C++, but it simplifies the conversions.
87 static_assert(sizeof(std::array<uint8_t, 32>) == 32);
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +000088
89 // For bool values, rely on the fact that they take up exactly one byte. This is not guaranteed
90 // by C++ and is implementation-dependent, but it simplifies the conversions.
91 static_assert(sizeof(bool) == 1);
92
93 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070094 union Body {
95 struct Key {
Garfield Tan1c7bc862020-01-28 13:24:04 -080096 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050097 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080098 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070099 int32_t deviceId;
100 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100101 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600102 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700103 int32_t action;
104 int32_t flags;
105 int32_t keyCode;
106 int32_t scanCode;
107 int32_t metaState;
108 int32_t repeatCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800109 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800110 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700111
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800112 inline size_t size() const { return sizeof(Key); }
Jeff Brown5912f952013-07-01 19:10:31 -0700113 } key;
114
115 struct Motion {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800116 int32_t eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700117 uint32_t pointerCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800118 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700119 int32_t deviceId;
120 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700121 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600122 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700123 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100124 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700125 int32_t flags;
126 int32_t metaState;
127 int32_t buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800128 MotionClassification classification; // base type: uint8_t
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800129 uint8_t empty2[3]; // 3 bytes to fill gap created by classification
Jeff Brown5912f952013-07-01 19:10:31 -0700130 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800131 nsecs_t downTime __attribute__((aligned(8)));
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700132 float dsdx; // Begin window transform
133 float dtdx; //
134 float dtdy; //
135 float dsdy; //
136 float tx; //
137 float ty; // End window transform
Jeff Brown5912f952013-07-01 19:10:31 -0700138 float xPrecision;
139 float yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700140 float xCursorPosition;
141 float yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700142 float dsdxRaw; // Begin raw transform
143 float dtdxRaw; //
144 float dtdyRaw; //
145 float dsdyRaw; //
146 float txRaw; //
147 float tyRaw; // End raw transform
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800148 /**
149 * The "pointers" field must be the last field of the struct InputMessage.
150 * When we send the struct InputMessage across the socket, we are not
151 * writing the entire "pointers" array, but only the pointerCount portion
152 * of it as an optimization. Adding a field after "pointers" would break this.
153 */
Michael Wrightb03f1032015-05-14 16:29:13 +0100154 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700155 PointerProperties properties;
156 PointerCoords coords;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800157 } pointers[MAX_POINTERS] __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700158
159 int32_t getActionId() const {
160 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
161 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
162 return pointers[index].properties.id;
163 }
164
165 inline size_t size() const {
166 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
167 + sizeof(Pointer) * pointerCount;
168 }
169 } motion;
170
171 struct Finished {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000172 bool handled;
173 uint8_t empty[7];
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000174 nsecs_t consumeTime; // The time when the event was consumed by the receiving end
Jeff Brown5912f952013-07-01 19:10:31 -0700175
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800176 inline size_t size() const { return sizeof(Finished); }
Jeff Brown5912f952013-07-01 19:10:31 -0700177 } finished;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800178
179 struct Focus {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800180 int32_t eventId;
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700181 // The following 2 fields take up 4 bytes total
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000182 bool hasFocus;
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700183 uint8_t empty[3];
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800184
185 inline size_t size() const { return sizeof(Focus); }
186 } focus;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800187
188 struct Capture {
189 int32_t eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000190 bool pointerCaptureEnabled;
191 uint8_t empty[3];
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800192
193 inline size_t size() const { return sizeof(Capture); }
194 } capture;
arthurhung7632c332020-12-30 16:58:01 +0800195
196 struct Drag {
197 int32_t eventId;
198 float x;
199 float y;
200 bool isExiting;
201 uint8_t empty[3];
202
203 inline size_t size() const { return sizeof(Drag); }
204 } drag;
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000205
206 struct Timeline {
207 int32_t eventId;
208 uint32_t empty;
209 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
210
211 inline size_t size() const { return sizeof(Timeline); }
212 } timeline;
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700213
214 struct TouchMode {
215 int32_t eventId;
216 // The following 2 fields take up 4 bytes total
217 bool isInTouchMode;
218 uint8_t empty[3];
219
220 inline size_t size() const { return sizeof(TouchMode); }
221 } touchMode;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800222 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700223
224 bool isValid(size_t actualSize) const;
225 size_t size() const;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800226 void getSanitizedCopy(InputMessage* msg) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700227};
228
229/*
230 * An input channel consists of a local unix domain socket used to send and receive
231 * input messages across processes. Each channel has a descriptive name for debugging purposes.
232 *
233 * Each endpoint has its own InputChannel object that specifies its file descriptor.
234 *
235 * The input channel is closed when all references to it are released.
236 */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500237class InputChannel : public Parcelable {
Chris Ye0783e992020-06-02 21:34:49 -0700238public:
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500239 static std::unique_ptr<InputChannel> create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500240 android::base::unique_fd fd, sp<IBinder> token);
241 InputChannel() = default;
242 InputChannel(const InputChannel& other)
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800243 : mName(other.mName), mFd(other.dupFd()), mToken(other.mToken){};
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500244 InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000245 ~InputChannel() override;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700246 /**
247 * Create a pair of input channels.
248 * The two returned input channels are equivalent, and are labeled as "server" and "client"
249 * for convenience. The two input channels share the same token.
Jeff Brown5912f952013-07-01 19:10:31 -0700250 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700251 * Return OK on success.
Jeff Brown5912f952013-07-01 19:10:31 -0700252 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800253 static status_t openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500254 std::unique_ptr<InputChannel>& outServerChannel,
255 std::unique_ptr<InputChannel>& outClientChannel);
Jeff Brown5912f952013-07-01 19:10:31 -0700256
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500257 inline std::string getName() const { return mName; }
258 inline const android::base::unique_fd& getFd() const { return mFd; }
259 inline sp<IBinder> getToken() const { return mToken; }
Jeff Brown5912f952013-07-01 19:10:31 -0700260
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700261 /* Send a message to the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700262 *
263 * If the channel is full then the message is guaranteed not to have been sent at all.
264 * Try again after the consumer has sent a finished signal indicating that it has
265 * consumed some of the pending messages from the channel.
266 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700267 * Return OK on success.
268 * Return WOULD_BLOCK if the channel is full.
269 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700270 * Other errors probably indicate that the channel is broken.
271 */
272 status_t sendMessage(const InputMessage* msg);
273
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700274 /* Receive a message sent by the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700275 *
276 * If there is no message present, try again after poll() indicates that the fd
277 * is readable.
278 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700279 * Return OK on success.
280 * Return WOULD_BLOCK if there is no message present.
281 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700282 * Other errors probably indicate that the channel is broken.
283 */
284 status_t receiveMessage(InputMessage* msg);
285
Egor Paskoa0d32af2023-12-14 17:45:41 +0100286 /* Tells whether there is a message in the channel available to be received.
287 *
288 * This is only a performance hint and may return false negative results. Clients should not
289 * rely on availability of the message based on the return value.
290 */
291 bool probablyHasInput() const;
292
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700293 /* Return a new object that has a duplicate of this channel's fd. */
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500294 std::unique_ptr<InputChannel> dup() const;
Jeff Brown5912f952013-07-01 19:10:31 -0700295
Garfield Tan15601662020-09-22 15:32:38 -0700296 void copyTo(InputChannel& outChannel) const;
297
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500298 status_t readFromParcel(const android::Parcel* parcel) override;
299 status_t writeToParcel(android::Parcel* parcel) const override;
Robert Carr3720ed02018-08-08 16:08:27 -0700300
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700301 /**
302 * The connection token is used to identify the input connection, i.e.
303 * the pair of input channels that were created simultaneously. Input channels
304 * are always created in pairs, and the token can be used to find the server-side
305 * input channel from the client-side input channel, and vice versa.
306 *
307 * Do not use connection token to check equality of a specific input channel object
308 * to another, because two different (client and server) input channels will share the
309 * same connection token.
310 *
311 * Return the token that identifies this connection.
312 */
313 sp<IBinder> getConnectionToken() const;
Robert Carr803535b2018-08-02 16:38:15 -0700314
Chris Ye0783e992020-06-02 21:34:49 -0700315 bool operator==(const InputChannel& inputChannel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500316 struct stat lhs, rhs;
317 if (fstat(mFd.get(), &lhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700318 return false;
319 }
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800320 if (fstat(inputChannel.getFd().get(), &rhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700321 return false;
322 }
323 // If file descriptors are pointing to same inode they are duplicated fds.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500324 return inputChannel.getName() == getName() && inputChannel.getConnectionToken() == mToken &&
325 lhs.st_ino == rhs.st_ino;
Chris Ye0783e992020-06-02 21:34:49 -0700326 }
327
Jeff Brown5912f952013-07-01 19:10:31 -0700328private:
Garfield Tan15601662020-09-22 15:32:38 -0700329 base::unique_fd dupFd() const;
330
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500331 std::string mName;
Tomasz Wasilczyk32024602023-11-16 10:17:54 -0800332 base::unique_fd mFd;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500333
334 sp<IBinder> mToken;
Jeff Brown5912f952013-07-01 19:10:31 -0700335};
336
337/*
338 * Publishes input events to an input channel.
339 */
340class InputPublisher {
341public:
342 /* Creates a publisher associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500343 explicit InputPublisher(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700344
345 /* Destroys the publisher and releases its input channel. */
346 ~InputPublisher();
347
348 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500349 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700350
351 /* Publishes a key event to the input channel.
352 *
353 * Returns OK on success.
354 * Returns WOULD_BLOCK if the channel is full.
355 * Returns DEAD_OBJECT if the channel's peer has been closed.
356 * Returns BAD_VALUE if seq is 0.
357 * Other errors probably indicate that the channel is broken.
358 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800359 status_t publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
360 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
361 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600362 int32_t repeatCount, nsecs_t downTime, nsecs_t eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700363
364 /* Publishes a motion event to the input channel.
365 *
366 * Returns OK on success.
367 * Returns WOULD_BLOCK if the channel is full.
368 * Returns DEAD_OBJECT if the channel's peer has been closed.
369 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
370 * Other errors probably indicate that the channel is broken.
371 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800372 status_t publishMotionEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
373 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
374 int32_t actionButton, int32_t flags, int32_t edgeFlags,
375 int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700376 MotionClassification classification, const ui::Transform& transform,
377 float xPrecision, float yPrecision, float xCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700378 float yCursorPosition, const ui::Transform& rawTransform,
379 nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
Evan Rosky84f07f02021-04-16 10:42:42 -0700380 const PointerProperties* pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -0700381 const PointerCoords* pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700382
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800383 /* Publishes a focus event to the input channel.
384 *
385 * Returns OK on success.
386 * Returns WOULD_BLOCK if the channel is full.
387 * Returns DEAD_OBJECT if the channel's peer has been closed.
388 * Other errors probably indicate that the channel is broken.
389 */
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700390 status_t publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800391
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800392 /* Publishes a capture event to the input channel.
393 *
394 * Returns OK on success.
395 * Returns WOULD_BLOCK if the channel is full.
396 * Returns DEAD_OBJECT if the channel's peer has been closed.
397 * Other errors probably indicate that the channel is broken.
398 */
399 status_t publishCaptureEvent(uint32_t seq, int32_t eventId, bool pointerCaptureEnabled);
400
arthurhung7632c332020-12-30 16:58:01 +0800401 /* Publishes a drag event to the input channel.
402 *
403 * Returns OK on success.
404 * Returns WOULD_BLOCK if the channel is full.
405 * Returns DEAD_OBJECT if the channel's peer has been closed.
406 * Other errors probably indicate that the channel is broken.
407 */
408 status_t publishDragEvent(uint32_t seq, int32_t eventId, float x, float y, bool isExiting);
409
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700410 /* Publishes a touch mode event to the input channel.
411 *
412 * Returns OK on success.
413 * Returns WOULD_BLOCK if the channel is full.
414 * Returns DEAD_OBJECT if the channel's peer has been closed.
415 * Other errors probably indicate that the channel is broken.
416 */
417 status_t publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode);
418
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000419 struct Finished {
420 uint32_t seq;
421 bool handled;
422 nsecs_t consumeTime;
423 };
424
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000425 struct Timeline {
426 int32_t inputEventId;
427 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
428 };
429
430 typedef std::variant<Finished, Timeline> ConsumerResponse;
431 /* Receive a signal from the consumer in reply to the original dispatch signal.
432 * If a signal was received, returns a Finished or a Timeline object.
433 * The InputConsumer should return a Finished object for every InputMessage that it is sent
434 * to confirm that it has been processed and that the InputConsumer is responsive.
435 * If several InputMessages are sent to InputConsumer, it's possible to receive Finished
436 * events out of order for those messages.
Jeff Brown5912f952013-07-01 19:10:31 -0700437 *
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000438 * The Timeline object is returned whenever the receiving end has processed a graphical frame
439 * and is returning the timeline of the frame. Not all input events will cause a Timeline
440 * object to be returned, and there is not guarantee about when it will arrive.
441 *
442 * If an object of Finished is returned, the returned sequence number is never 0 unless the
443 * operation failed.
Jeff Brown5912f952013-07-01 19:10:31 -0700444 *
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000445 * Returned error codes:
446 * OK on success.
447 * WOULD_BLOCK if there is no signal present.
448 * DEAD_OBJECT if the channel's peer has been closed.
449 * Other errors probably indicate that the channel is broken.
Jeff Brown5912f952013-07-01 19:10:31 -0700450 */
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000451 android::base::Result<ConsumerResponse> receiveConsumerResponse();
Jeff Brown5912f952013-07-01 19:10:31 -0700452
453private:
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500454 std::shared_ptr<InputChannel> mChannel;
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800455 InputVerifier mInputVerifier;
Jeff Brown5912f952013-07-01 19:10:31 -0700456};
457
458/*
459 * Consumes input events from an input channel.
460 */
461class InputConsumer {
462public:
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800463 /* Create a consumer associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500464 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel);
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800465 /* Create a consumer associated with an input channel, override resampling system property */
466 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel,
467 bool enableTouchResampling);
Jeff Brown5912f952013-07-01 19:10:31 -0700468
469 /* Destroys the consumer and releases its input channel. */
470 ~InputConsumer();
471
472 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500473 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700474
475 /* Consumes an input event from the input channel and copies its contents into
476 * an InputEvent object created using the specified factory.
477 *
478 * Tries to combine a series of move events into larger batches whenever possible.
479 *
480 * If consumeBatches is false, then defers consuming pending batched events if it
481 * is possible for additional samples to be added to them later. Call hasPendingBatch()
482 * to determine whether a pending batch is available to be consumed.
483 *
484 * If consumeBatches is true, then events are still batched but they are consumed
485 * immediately as soon as the input channel is exhausted.
486 *
487 * The frameTime parameter specifies the time when the current display frame started
488 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
489 *
490 * The returned sequence number is never 0 unless the operation failed.
491 *
492 * Returns OK on success.
493 * Returns WOULD_BLOCK if there is no event present.
494 * Returns DEAD_OBJECT if the channel's peer has been closed.
495 * Returns NO_MEMORY if the event could not be created.
496 * Other errors probably indicate that the channel is broken.
497 */
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800498 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, nsecs_t frameTime,
499 uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700500
501 /* Sends a finished signal to the publisher to inform it that the message
502 * with the specified sequence number has finished being process and whether
503 * the message was handled by the consumer.
504 *
505 * Returns OK on success.
506 * Returns BAD_VALUE if seq is 0.
507 * Other errors probably indicate that the channel is broken.
508 */
509 status_t sendFinishedSignal(uint32_t seq, bool handled);
510
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000511 status_t sendTimeline(int32_t inputEventId,
512 std::array<nsecs_t, GraphicsTimeline::SIZE> timeline);
513
Jeff Brown5912f952013-07-01 19:10:31 -0700514 /* Returns true if there is a pending batch.
515 *
516 * Should be called after calling consume() with consumeBatches == false to determine
517 * whether consume() should be called again later on with consumeBatches == true.
518 */
519 bool hasPendingBatch() const;
520
Arthur Hungc7812be2020-02-27 22:40:27 +0800521 /* Returns the source of first pending batch if exist.
522 *
523 * Should be called after calling consume() with consumeBatches == false to determine
524 * whether consume() should be called again later on with consumeBatches == true.
525 */
526 int32_t getPendingBatchSource() const;
527
Egor Paskoa0d32af2023-12-14 17:45:41 +0100528 /* Returns true when there is *likely* a pending batch or a pending event in the channel.
529 *
530 * This is only a performance hint and may return false negative results. Clients should not
531 * rely on availability of the message based on the return value.
532 */
533 bool probablyHasInput() const;
534
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500535 std::string dump() const;
536
Jeff Brown5912f952013-07-01 19:10:31 -0700537private:
538 // True if touch resampling is enabled.
539 const bool mResampleTouch;
540
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500541 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700542
543 // The current input message.
544 InputMessage mMsg;
545
546 // True if mMsg contains a valid input message that was deferred from the previous
547 // call to consume and that still needs to be handled.
548 bool mMsgDeferred;
549
550 // Batched motion events per device and source.
551 struct Batch {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500552 std::vector<InputMessage> samples;
Jeff Brown5912f952013-07-01 19:10:31 -0700553 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500554 std::vector<Batch> mBatches;
Jeff Brown5912f952013-07-01 19:10:31 -0700555
556 // Touch state per device and source, only for sources of class pointer.
557 struct History {
558 nsecs_t eventTime;
559 BitSet32 idBits;
560 int32_t idToIndex[MAX_POINTER_ID + 1];
561 PointerCoords pointers[MAX_POINTERS];
562
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100563 void initializeFrom(const InputMessage& msg) {
564 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700565 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100566 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
567 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700568 idBits.markBit(id);
569 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100570 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700571 }
572 }
573
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800574 void initializeFrom(const History& other) {
575 eventTime = other.eventTime;
576 idBits = other.idBits; // temporary copy
577 for (size_t i = 0; i < other.idBits.count(); i++) {
578 uint32_t id = idBits.clearFirstMarkedBit();
579 int32_t index = other.idToIndex[id];
580 idToIndex[id] = index;
581 pointers[index].copyFrom(other.pointers[index]);
582 }
583 idBits = other.idBits; // final copy
584 }
585
Jeff Brown5912f952013-07-01 19:10:31 -0700586 const PointerCoords& getPointerById(uint32_t id) const {
587 return pointers[idToIndex[id]];
588 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700589
590 bool hasPointerId(uint32_t id) const {
591 return idBits.hasBit(id);
592 }
Jeff Brown5912f952013-07-01 19:10:31 -0700593 };
594 struct TouchState {
595 int32_t deviceId;
596 int32_t source;
597 size_t historyCurrent;
598 size_t historySize;
599 History history[2];
600 History lastResample;
601
602 void initialize(int32_t deviceId, int32_t source) {
603 this->deviceId = deviceId;
604 this->source = source;
605 historyCurrent = 0;
606 historySize = 0;
607 lastResample.eventTime = 0;
608 lastResample.idBits.clear();
609 }
610
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100611 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700612 historyCurrent ^= 1;
613 if (historySize < 2) {
614 historySize += 1;
615 }
616 history[historyCurrent].initializeFrom(msg);
617 }
618
619 const History* getHistory(size_t index) const {
620 return &history[(historyCurrent + index) & 1];
621 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100622
623 bool recentCoordinatesAreIdentical(uint32_t id) const {
624 // Return true if the two most recently received "raw" coordinates are identical
625 if (historySize < 2) {
626 return false;
627 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700628 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
629 return false;
630 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100631 float currentX = getHistory(0)->getPointerById(id).getX();
632 float currentY = getHistory(0)->getPointerById(id).getY();
633 float previousX = getHistory(1)->getPointerById(id).getX();
634 float previousY = getHistory(1)->getPointerById(id).getY();
635 if (currentX == previousX && currentY == previousY) {
636 return true;
637 }
638 return false;
639 }
Jeff Brown5912f952013-07-01 19:10:31 -0700640 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500641 std::vector<TouchState> mTouchStates;
Jeff Brown5912f952013-07-01 19:10:31 -0700642
643 // Chain of batched sequence numbers. When multiple input messages are combined into
644 // a batch, we append a record here that associates the last sequence number in the
645 // batch with the previous one. When the finished signal is sent, we traverse the
646 // chain to individually finish all input messages that were part of the batch.
647 struct SeqChain {
648 uint32_t seq; // sequence number of batched input message
649 uint32_t chain; // sequence number of previous batched input message
650 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500651 std::vector<SeqChain> mSeqChains;
Jeff Brown5912f952013-07-01 19:10:31 -0700652
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000653 // The time at which each event with the sequence number 'seq' was consumed.
654 // This data is provided in 'finishInputEvent' so that the receiving end can measure the latency
655 // This collection is populated when the event is received, and the entries are erased when the
656 // events are finished. It should not grow infinitely because if an event is not ack'd, ANR
657 // will be raised for that connection, and no further events will be posted to that channel.
658 std::unordered_map<uint32_t /*seq*/, nsecs_t /*consumeTime*/> mConsumeTimes;
659
Jeff Brown5912f952013-07-01 19:10:31 -0700660 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800661 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700662 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800663 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700664
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100665 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700666 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
667 const InputMessage *next);
668
669 ssize_t findBatch(int32_t deviceId, int32_t source) const;
670 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
671
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000672 nsecs_t getConsumeTime(uint32_t seq) const;
673 void popConsumeTime(uint32_t seq);
Jeff Brown5912f952013-07-01 19:10:31 -0700674 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
675
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800676 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700677 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
678 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800679 static void initializeFocusEvent(FocusEvent* event, const InputMessage* msg);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800680 static void initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg);
arthurhung7632c332020-12-30 16:58:01 +0800681 static void initializeDragEvent(DragEvent* event, const InputMessage* msg);
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700682 static void initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700683 static void addSample(MotionEvent* event, const InputMessage* msg);
684 static bool canAddSample(const Batch& batch, const InputMessage* msg);
685 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
Jeff Brown5912f952013-07-01 19:10:31 -0700686
687 static bool isTouchResamplingEnabled();
688};
689
690} // namespace android