blob: 8b1c2a3ff0eb927995f6e99130c3c712c9c84f61 [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
Siarhei Vishniakou8d660132024-01-11 16:48:44 -080038#include <android/os/InputChannelCore.h>
Robert Carr803535b2018-08-02 16:38:15 -070039#include <binder/IBinder.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>
Atif Niyaz3d3fa522019-07-25 11:12:39 -070046#include <utils/Timers.h>
Jeff Brown5912f952013-07-01 19:10:31 -070047
48namespace android {
Robert Carr3720ed02018-08-08 16:08:27 -070049class Parcel;
Jeff Brown5912f952013-07-01 19:10:31 -070050
51/*
52 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080053 *
54 * Note that this structure is used for IPCs so its layout must be identical
55 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080056 *
57 * Since the struct must be aligned to an 8-byte boundary, there could be uninitialized bytes
58 * in-between the defined fields. This padding data should be explicitly accounted for by adding
59 * "empty" fields into the struct. This data is memset to zero before sending the struct across
60 * the socket. Adding the explicit fields ensures that the memset is not optimized away by the
61 * compiler. When a new field is added to the struct, the corresponding change
62 * in StructLayout_test should be made.
Jeff Brown5912f952013-07-01 19:10:31 -070063 */
64struct InputMessage {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070065 enum class Type : uint32_t {
66 KEY,
67 MOTION,
68 FINISHED,
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -080069 FOCUS,
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -080070 CAPTURE,
arthurhung7632c332020-12-30 16:58:01 +080071 DRAG,
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +000072 TIMELINE,
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -070073 TOUCH_MODE,
Dominik Laskowski75788452021-02-09 18:51:25 -080074
75 ftl_last = TOUCH_MODE
Jeff Brown5912f952013-07-01 19:10:31 -070076 };
77
78 struct Header {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070079 Type type; // 4 bytes
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050080 uint32_t seq;
Jeff Brown5912f952013-07-01 19:10:31 -070081 } header;
82
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060083 // For keys and motions, rely on the fact that std::array takes up exactly as much space
84 // as the underlying data. This is not guaranteed by C++, but it simplifies the conversions.
85 static_assert(sizeof(std::array<uint8_t, 32>) == 32);
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +000086
87 // For bool values, rely on the fact that they take up exactly one byte. This is not guaranteed
88 // by C++ and is implementation-dependent, but it simplifies the conversions.
89 static_assert(sizeof(bool) == 1);
90
91 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070092 union Body {
93 struct Key {
Garfield Tan1c7bc862020-01-28 13:24:04 -080094 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050095 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080096 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070097 int32_t deviceId;
98 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010099 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600100 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700101 int32_t action;
102 int32_t flags;
103 int32_t keyCode;
104 int32_t scanCode;
105 int32_t metaState;
106 int32_t repeatCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800107 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800108 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700109
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800110 inline size_t size() const { return sizeof(Key); }
Jeff Brown5912f952013-07-01 19:10:31 -0700111 } key;
112
113 struct Motion {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800114 int32_t eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700115 uint32_t pointerCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800116 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700117 int32_t deviceId;
118 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700119 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600120 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700121 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100122 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700123 int32_t flags;
124 int32_t metaState;
125 int32_t buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800126 MotionClassification classification; // base type: uint8_t
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800127 uint8_t empty2[3]; // 3 bytes to fill gap created by classification
Jeff Brown5912f952013-07-01 19:10:31 -0700128 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800129 nsecs_t downTime __attribute__((aligned(8)));
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700130 float dsdx; // Begin window transform
131 float dtdx; //
132 float dtdy; //
133 float dsdy; //
134 float tx; //
135 float ty; // End window transform
Jeff Brown5912f952013-07-01 19:10:31 -0700136 float xPrecision;
137 float yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700138 float xCursorPosition;
139 float yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700140 float dsdxRaw; // Begin raw transform
141 float dtdxRaw; //
142 float dtdyRaw; //
143 float dsdyRaw; //
144 float txRaw; //
145 float tyRaw; // End raw transform
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800146 /**
147 * The "pointers" field must be the last field of the struct InputMessage.
148 * When we send the struct InputMessage across the socket, we are not
149 * writing the entire "pointers" array, but only the pointerCount portion
150 * of it as an optimization. Adding a field after "pointers" would break this.
151 */
Michael Wrightb03f1032015-05-14 16:29:13 +0100152 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700153 PointerProperties properties;
154 PointerCoords coords;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800155 } pointers[MAX_POINTERS] __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700156
157 int32_t getActionId() const {
158 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
159 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
160 return pointers[index].properties.id;
161 }
162
163 inline size_t size() const {
164 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
165 + sizeof(Pointer) * pointerCount;
166 }
167 } motion;
168
169 struct Finished {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000170 bool handled;
171 uint8_t empty[7];
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000172 nsecs_t consumeTime; // The time when the event was consumed by the receiving end
Jeff Brown5912f952013-07-01 19:10:31 -0700173
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800174 inline size_t size() const { return sizeof(Finished); }
Jeff Brown5912f952013-07-01 19:10:31 -0700175 } finished;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800176
177 struct Focus {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800178 int32_t eventId;
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700179 // The following 2 fields take up 4 bytes total
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000180 bool hasFocus;
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700181 uint8_t empty[3];
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800182
183 inline size_t size() const { return sizeof(Focus); }
184 } focus;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800185
186 struct Capture {
187 int32_t eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000188 bool pointerCaptureEnabled;
189 uint8_t empty[3];
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800190
191 inline size_t size() const { return sizeof(Capture); }
192 } capture;
arthurhung7632c332020-12-30 16:58:01 +0800193
194 struct Drag {
195 int32_t eventId;
196 float x;
197 float y;
198 bool isExiting;
199 uint8_t empty[3];
200
201 inline size_t size() const { return sizeof(Drag); }
202 } drag;
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000203
204 struct Timeline {
205 int32_t eventId;
206 uint32_t empty;
207 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
208
209 inline size_t size() const { return sizeof(Timeline); }
210 } timeline;
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700211
212 struct TouchMode {
213 int32_t eventId;
214 // The following 2 fields take up 4 bytes total
215 bool isInTouchMode;
216 uint8_t empty[3];
217
218 inline size_t size() const { return sizeof(TouchMode); }
219 } touchMode;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800220 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700221
222 bool isValid(size_t actualSize) const;
223 size_t size() const;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800224 void getSanitizedCopy(InputMessage* msg) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700225};
226
227/*
228 * An input channel consists of a local unix domain socket used to send and receive
229 * input messages across processes. Each channel has a descriptive name for debugging purposes.
230 *
231 * Each endpoint has its own InputChannel object that specifies its file descriptor.
Siarhei Vishniakou8d660132024-01-11 16:48:44 -0800232 * For parceling, this relies on android::os::InputChannelCore, defined in aidl.
Jeff Brown5912f952013-07-01 19:10:31 -0700233 *
234 * The input channel is closed when all references to it are released.
235 */
Siarhei Vishniakou8d660132024-01-11 16:48:44 -0800236class InputChannel : private android::os::InputChannelCore {
Chris Ye0783e992020-06-02 21:34:49 -0700237public:
Siarhei Vishniakou8d660132024-01-11 16:48:44 -0800238 static std::unique_ptr<InputChannel> create(android::os::InputChannelCore&& parceledChannel);
239 ~InputChannel();
240
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700241 /**
242 * Create a pair of input channels.
243 * The two returned input channels are equivalent, and are labeled as "server" and "client"
244 * for convenience. The two input channels share the same token.
Jeff Brown5912f952013-07-01 19:10:31 -0700245 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700246 * Return OK on success.
Jeff Brown5912f952013-07-01 19:10:31 -0700247 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800248 static status_t openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500249 std::unique_ptr<InputChannel>& outServerChannel,
250 std::unique_ptr<InputChannel>& outClientChannel);
Jeff Brown5912f952013-07-01 19:10:31 -0700251
Siarhei Vishniakou8d660132024-01-11 16:48:44 -0800252 inline std::string getName() const { return name; }
253 inline int getFd() const { return fd.get(); }
Jeff Brown5912f952013-07-01 19:10:31 -0700254
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700255 /* Send a message to the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700256 *
257 * If the channel is full then the message is guaranteed not to have been sent at all.
258 * Try again after the consumer has sent a finished signal indicating that it has
259 * consumed some of the pending messages from the channel.
260 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700261 * Return OK on success.
262 * Return WOULD_BLOCK if the channel is full.
263 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700264 * Other errors probably indicate that the channel is broken.
265 */
266 status_t sendMessage(const InputMessage* msg);
267
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700268 /* Receive a message sent by the other endpoint.
Jeff Brown5912f952013-07-01 19:10:31 -0700269 *
270 * If there is no message present, try again after poll() indicates that the fd
271 * is readable.
272 *
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700273 * Return OK on success.
274 * Return WOULD_BLOCK if there is no message present.
275 * Return DEAD_OBJECT if the channel's peer has been closed.
Jeff Brown5912f952013-07-01 19:10:31 -0700276 * Other errors probably indicate that the channel is broken.
277 */
278 status_t receiveMessage(InputMessage* msg);
279
Egor Paskoa0d32af2023-12-14 17:45:41 +0100280 /* Tells whether there is a message in the channel available to be received.
281 *
282 * This is only a performance hint and may return false negative results. Clients should not
283 * rely on availability of the message based on the return value.
284 */
285 bool probablyHasInput() const;
286
Egor Pasko5a67a562024-01-16 16:46:45 +0100287 /* Wait until there is a message in the channel.
288 *
289 * The |timeout| specifies how long to block waiting for an input event to appear. Negative
290 * values are not allowed.
291 *
292 * In some cases returning before timeout expiration can happen without a message available.
293 * This could happen after the channel was closed on the other side. Another possible reason
294 * is incorrect setup of the channel.
295 */
296 void waitForMessage(std::chrono::milliseconds timeout) const;
297
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700298 /* Return a new object that has a duplicate of this channel's fd. */
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500299 std::unique_ptr<InputChannel> dup() const;
Jeff Brown5912f952013-07-01 19:10:31 -0700300
Siarhei Vishniakou8d660132024-01-11 16:48:44 -0800301 void copyTo(android::os::InputChannelCore& outChannel) const;
Robert Carr3720ed02018-08-08 16:08:27 -0700302
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700303 /**
304 * The connection token is used to identify the input connection, i.e.
305 * the pair of input channels that were created simultaneously. Input channels
306 * are always created in pairs, and the token can be used to find the server-side
307 * input channel from the client-side input channel, and vice versa.
308 *
309 * Do not use connection token to check equality of a specific input channel object
310 * to another, because two different (client and server) input channels will share the
311 * same connection token.
312 *
313 * Return the token that identifies this connection.
314 */
315 sp<IBinder> getConnectionToken() const;
Robert Carr803535b2018-08-02 16:38:15 -0700316
Jeff Brown5912f952013-07-01 19:10:31 -0700317private:
Siarhei Vishniakou8d660132024-01-11 16:48:44 -0800318 static std::unique_ptr<InputChannel> create(const std::string& name,
319 android::base::unique_fd fd, sp<IBinder> token);
Garfield Tan15601662020-09-22 15:32:38 -0700320
Siarhei Vishniakou8d660132024-01-11 16:48:44 -0800321 InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token);
Jeff Brown5912f952013-07-01 19:10:31 -0700322};
323
324/*
325 * Publishes input events to an input channel.
326 */
327class InputPublisher {
328public:
329 /* Creates a publisher associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500330 explicit InputPublisher(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700331
332 /* Destroys the publisher and releases its input channel. */
333 ~InputPublisher();
334
335 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500336 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700337
338 /* Publishes a key event to the input channel.
339 *
340 * Returns OK on success.
341 * Returns WOULD_BLOCK if the channel is full.
342 * Returns DEAD_OBJECT if the channel's peer has been closed.
343 * Returns BAD_VALUE if seq is 0.
344 * Other errors probably indicate that the channel is broken.
345 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800346 status_t publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
347 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
348 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600349 int32_t repeatCount, nsecs_t downTime, nsecs_t eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700350
351 /* Publishes a motion 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 or if pointerCount is less than 1 or greater than MAX_POINTERS.
357 * Other errors probably indicate that the channel is broken.
358 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800359 status_t publishMotionEvent(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 actionButton, int32_t flags, int32_t edgeFlags,
362 int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700363 MotionClassification classification, const ui::Transform& transform,
364 float xPrecision, float yPrecision, float xCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700365 float yCursorPosition, const ui::Transform& rawTransform,
366 nsecs_t downTime, nsecs_t eventTime, uint32_t pointerCount,
Evan Rosky84f07f02021-04-16 10:42:42 -0700367 const PointerProperties* pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -0700368 const PointerCoords* pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700369
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800370 /* Publishes a focus event to the input channel.
371 *
372 * Returns OK on success.
373 * Returns WOULD_BLOCK if the channel is full.
374 * Returns DEAD_OBJECT if the channel's peer has been closed.
375 * Other errors probably indicate that the channel is broken.
376 */
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700377 status_t publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800378
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800379 /* Publishes a capture event to the input channel.
380 *
381 * Returns OK on success.
382 * Returns WOULD_BLOCK if the channel is full.
383 * Returns DEAD_OBJECT if the channel's peer has been closed.
384 * Other errors probably indicate that the channel is broken.
385 */
386 status_t publishCaptureEvent(uint32_t seq, int32_t eventId, bool pointerCaptureEnabled);
387
arthurhung7632c332020-12-30 16:58:01 +0800388 /* Publishes a drag event to the input channel.
389 *
390 * Returns OK on success.
391 * Returns WOULD_BLOCK if the channel is full.
392 * Returns DEAD_OBJECT if the channel's peer has been closed.
393 * Other errors probably indicate that the channel is broken.
394 */
395 status_t publishDragEvent(uint32_t seq, int32_t eventId, float x, float y, bool isExiting);
396
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700397 /* Publishes a touch mode event to the input channel.
398 *
399 * Returns OK on success.
400 * Returns WOULD_BLOCK if the channel is full.
401 * Returns DEAD_OBJECT if the channel's peer has been closed.
402 * Other errors probably indicate that the channel is broken.
403 */
404 status_t publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode);
405
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000406 struct Finished {
407 uint32_t seq;
408 bool handled;
409 nsecs_t consumeTime;
410 };
411
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000412 struct Timeline {
413 int32_t inputEventId;
414 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
415 };
416
417 typedef std::variant<Finished, Timeline> ConsumerResponse;
418 /* Receive a signal from the consumer in reply to the original dispatch signal.
419 * If a signal was received, returns a Finished or a Timeline object.
420 * The InputConsumer should return a Finished object for every InputMessage that it is sent
421 * to confirm that it has been processed and that the InputConsumer is responsive.
422 * If several InputMessages are sent to InputConsumer, it's possible to receive Finished
423 * events out of order for those messages.
Jeff Brown5912f952013-07-01 19:10:31 -0700424 *
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000425 * The Timeline object is returned whenever the receiving end has processed a graphical frame
426 * and is returning the timeline of the frame. Not all input events will cause a Timeline
427 * object to be returned, and there is not guarantee about when it will arrive.
428 *
429 * If an object of Finished is returned, the returned sequence number is never 0 unless the
430 * operation failed.
Jeff Brown5912f952013-07-01 19:10:31 -0700431 *
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000432 * Returned error codes:
433 * OK on success.
434 * WOULD_BLOCK if there is no signal present.
435 * DEAD_OBJECT if the channel's peer has been closed.
436 * Other errors probably indicate that the channel is broken.
Jeff Brown5912f952013-07-01 19:10:31 -0700437 */
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000438 android::base::Result<ConsumerResponse> receiveConsumerResponse();
Jeff Brown5912f952013-07-01 19:10:31 -0700439
440private:
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500441 std::shared_ptr<InputChannel> mChannel;
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800442 InputVerifier mInputVerifier;
Jeff Brown5912f952013-07-01 19:10:31 -0700443};
444
445/*
446 * Consumes input events from an input channel.
447 */
448class InputConsumer {
449public:
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800450 /* Create a consumer associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500451 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel);
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800452 /* Create a consumer associated with an input channel, override resampling system property */
453 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel,
454 bool enableTouchResampling);
Jeff Brown5912f952013-07-01 19:10:31 -0700455
456 /* Destroys the consumer and releases its input channel. */
457 ~InputConsumer();
458
459 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500460 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700461
462 /* Consumes an input event from the input channel and copies its contents into
463 * an InputEvent object created using the specified factory.
464 *
465 * Tries to combine a series of move events into larger batches whenever possible.
466 *
467 * If consumeBatches is false, then defers consuming pending batched events if it
468 * is possible for additional samples to be added to them later. Call hasPendingBatch()
469 * to determine whether a pending batch is available to be consumed.
470 *
471 * If consumeBatches is true, then events are still batched but they are consumed
472 * immediately as soon as the input channel is exhausted.
473 *
474 * The frameTime parameter specifies the time when the current display frame started
475 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
476 *
477 * The returned sequence number is never 0 unless the operation failed.
478 *
479 * Returns OK on success.
480 * Returns WOULD_BLOCK if there is no event present.
481 * Returns DEAD_OBJECT if the channel's peer has been closed.
482 * Returns NO_MEMORY if the event could not be created.
483 * Other errors probably indicate that the channel is broken.
484 */
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800485 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, nsecs_t frameTime,
486 uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700487
488 /* Sends a finished signal to the publisher to inform it that the message
489 * with the specified sequence number has finished being process and whether
490 * the message was handled by the consumer.
491 *
492 * Returns OK on success.
493 * Returns BAD_VALUE if seq is 0.
494 * Other errors probably indicate that the channel is broken.
495 */
496 status_t sendFinishedSignal(uint32_t seq, bool handled);
497
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000498 status_t sendTimeline(int32_t inputEventId,
499 std::array<nsecs_t, GraphicsTimeline::SIZE> timeline);
500
Jeff Brown5912f952013-07-01 19:10:31 -0700501 /* Returns true if there is a pending batch.
502 *
503 * Should be called after calling consume() with consumeBatches == false to determine
504 * whether consume() should be called again later on with consumeBatches == true.
505 */
506 bool hasPendingBatch() const;
507
Arthur Hungc7812be2020-02-27 22:40:27 +0800508 /* Returns the source of first pending batch if exist.
509 *
510 * Should be called after calling consume() with consumeBatches == false to determine
511 * whether consume() should be called again later on with consumeBatches == true.
512 */
513 int32_t getPendingBatchSource() const;
514
Egor Paskoa0d32af2023-12-14 17:45:41 +0100515 /* Returns true when there is *likely* a pending batch or a pending event in the channel.
516 *
517 * This is only a performance hint and may return false negative results. Clients should not
518 * rely on availability of the message based on the return value.
519 */
520 bool probablyHasInput() const;
521
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500522 std::string dump() const;
523
Jeff Brown5912f952013-07-01 19:10:31 -0700524private:
525 // True if touch resampling is enabled.
526 const bool mResampleTouch;
527
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500528 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700529
530 // The current input message.
531 InputMessage mMsg;
532
533 // True if mMsg contains a valid input message that was deferred from the previous
534 // call to consume and that still needs to be handled.
535 bool mMsgDeferred;
536
537 // Batched motion events per device and source.
538 struct Batch {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500539 std::vector<InputMessage> samples;
Jeff Brown5912f952013-07-01 19:10:31 -0700540 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500541 std::vector<Batch> mBatches;
Jeff Brown5912f952013-07-01 19:10:31 -0700542
543 // Touch state per device and source, only for sources of class pointer.
544 struct History {
545 nsecs_t eventTime;
546 BitSet32 idBits;
547 int32_t idToIndex[MAX_POINTER_ID + 1];
548 PointerCoords pointers[MAX_POINTERS];
549
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100550 void initializeFrom(const InputMessage& msg) {
551 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700552 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100553 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
554 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700555 idBits.markBit(id);
556 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100557 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700558 }
559 }
560
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800561 void initializeFrom(const History& other) {
562 eventTime = other.eventTime;
563 idBits = other.idBits; // temporary copy
564 for (size_t i = 0; i < other.idBits.count(); i++) {
565 uint32_t id = idBits.clearFirstMarkedBit();
566 int32_t index = other.idToIndex[id];
567 idToIndex[id] = index;
568 pointers[index].copyFrom(other.pointers[index]);
569 }
570 idBits = other.idBits; // final copy
571 }
572
Jeff Brown5912f952013-07-01 19:10:31 -0700573 const PointerCoords& getPointerById(uint32_t id) const {
574 return pointers[idToIndex[id]];
575 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700576
577 bool hasPointerId(uint32_t id) const {
578 return idBits.hasBit(id);
579 }
Jeff Brown5912f952013-07-01 19:10:31 -0700580 };
581 struct TouchState {
582 int32_t deviceId;
583 int32_t source;
584 size_t historyCurrent;
585 size_t historySize;
586 History history[2];
587 History lastResample;
588
589 void initialize(int32_t deviceId, int32_t source) {
590 this->deviceId = deviceId;
591 this->source = source;
592 historyCurrent = 0;
593 historySize = 0;
594 lastResample.eventTime = 0;
595 lastResample.idBits.clear();
596 }
597
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100598 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700599 historyCurrent ^= 1;
600 if (historySize < 2) {
601 historySize += 1;
602 }
603 history[historyCurrent].initializeFrom(msg);
604 }
605
606 const History* getHistory(size_t index) const {
607 return &history[(historyCurrent + index) & 1];
608 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100609
610 bool recentCoordinatesAreIdentical(uint32_t id) const {
611 // Return true if the two most recently received "raw" coordinates are identical
612 if (historySize < 2) {
613 return false;
614 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700615 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
616 return false;
617 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100618 float currentX = getHistory(0)->getPointerById(id).getX();
619 float currentY = getHistory(0)->getPointerById(id).getY();
620 float previousX = getHistory(1)->getPointerById(id).getX();
621 float previousY = getHistory(1)->getPointerById(id).getY();
622 if (currentX == previousX && currentY == previousY) {
623 return true;
624 }
625 return false;
626 }
Jeff Brown5912f952013-07-01 19:10:31 -0700627 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500628 std::vector<TouchState> mTouchStates;
Jeff Brown5912f952013-07-01 19:10:31 -0700629
630 // Chain of batched sequence numbers. When multiple input messages are combined into
631 // a batch, we append a record here that associates the last sequence number in the
632 // batch with the previous one. When the finished signal is sent, we traverse the
633 // chain to individually finish all input messages that were part of the batch.
634 struct SeqChain {
635 uint32_t seq; // sequence number of batched input message
636 uint32_t chain; // sequence number of previous batched input message
637 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500638 std::vector<SeqChain> mSeqChains;
Jeff Brown5912f952013-07-01 19:10:31 -0700639
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000640 // The time at which each event with the sequence number 'seq' was consumed.
641 // This data is provided in 'finishInputEvent' so that the receiving end can measure the latency
642 // This collection is populated when the event is received, and the entries are erased when the
643 // events are finished. It should not grow infinitely because if an event is not ack'd, ANR
644 // will be raised for that connection, and no further events will be posted to that channel.
645 std::unordered_map<uint32_t /*seq*/, nsecs_t /*consumeTime*/> mConsumeTimes;
646
Jeff Brown5912f952013-07-01 19:10:31 -0700647 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800648 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700649 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800650 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700651
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100652 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700653 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
654 const InputMessage *next);
655
656 ssize_t findBatch(int32_t deviceId, int32_t source) const;
657 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
658
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000659 nsecs_t getConsumeTime(uint32_t seq) const;
660 void popConsumeTime(uint32_t seq);
Jeff Brown5912f952013-07-01 19:10:31 -0700661 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
662
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800663 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700664 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
665 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800666 static void initializeFocusEvent(FocusEvent* event, const InputMessage* msg);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800667 static void initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg);
arthurhung7632c332020-12-30 16:58:01 +0800668 static void initializeDragEvent(DragEvent* event, const InputMessage* msg);
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700669 static void initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700670 static void addSample(MotionEvent* event, const InputMessage* msg);
671 static bool canAddSample(const Batch& batch, const InputMessage* msg);
672 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
Jeff Brown5912f952013-07-01 19:10:31 -0700673
674 static bool isTouchResamplingEnabled();
675};
676
677} // namespace android