blob: f337d009a0676da46a9353776a6000eb88b91ae2 [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>
33
Atif Niyaz3d3fa522019-07-25 11:12:39 -070034#include <android-base/chrono_utils.h>
35
Robert Carr803535b2018-08-02 16:38:15 -070036#include <binder/IBinder.h>
Chris Ye0783e992020-06-02 21:34:49 -070037#include <binder/Parcelable.h>
Jeff Brown5912f952013-07-01 19:10:31 -070038#include <input/Input.h>
Chris Ye0783e992020-06-02 21:34:49 -070039#include <sys/stat.h>
Jeff Brown5912f952013-07-01 19:10:31 -070040#include <utils/BitSet.h>
Atif Niyaz3d3fa522019-07-25 11:12:39 -070041#include <utils/Errors.h>
42#include <utils/RefBase.h>
43#include <utils/Timers.h>
Jeff Brown5912f952013-07-01 19:10:31 -070044
Josh Gao2ccbe3a2019-08-09 14:35:36 -070045#include <android-base/unique_fd.h>
46
Jeff Brown5912f952013-07-01 19:10:31 -070047namespace android {
Robert Carr3720ed02018-08-08 16:08:27 -070048class Parcel;
Jeff Brown5912f952013-07-01 19:10:31 -070049
50/*
51 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080052 *
53 * Note that this structure is used for IPCs so its layout must be identical
54 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080055 *
56 * Since the struct must be aligned to an 8-byte boundary, there could be uninitialized bytes
57 * in-between the defined fields. This padding data should be explicitly accounted for by adding
58 * "empty" fields into the struct. This data is memset to zero before sending the struct across
59 * the socket. Adding the explicit fields ensures that the memset is not optimized away by the
60 * compiler. When a new field is added to the struct, the corresponding change
61 * in StructLayout_test should be made.
Jeff Brown5912f952013-07-01 19:10:31 -070062 */
63struct InputMessage {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070064 enum class Type : uint32_t {
65 KEY,
66 MOTION,
67 FINISHED,
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -080068 FOCUS,
Jeff Brown5912f952013-07-01 19:10:31 -070069 };
70
71 struct Header {
Siarhei Vishniakou52402772019-10-22 09:32:30 -070072 Type type; // 4 bytes
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050073 uint32_t seq;
Jeff Brown5912f952013-07-01 19:10:31 -070074 } header;
75
Fengwei Yin83e0e422014-05-24 05:32:09 +080076 // Body *must* be 8 byte aligned.
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060077 // For keys and motions, rely on the fact that std::array takes up exactly as much space
78 // as the underlying data. This is not guaranteed by C++, but it simplifies the conversions.
79 static_assert(sizeof(std::array<uint8_t, 32>) == 32);
Jeff Brown5912f952013-07-01 19:10:31 -070080 union Body {
81 struct Key {
Garfield Tan1c7bc862020-01-28 13:24:04 -080082 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -050083 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080084 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070085 int32_t deviceId;
86 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010087 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -060088 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -070089 int32_t action;
90 int32_t flags;
91 int32_t keyCode;
92 int32_t scanCode;
93 int32_t metaState;
94 int32_t repeatCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080095 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +080096 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070097
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -080098 inline size_t size() const { return sizeof(Key); }
Jeff Brown5912f952013-07-01 19:10:31 -070099 } key;
100
101 struct Motion {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800102 int32_t eventId;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500103 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800104 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700105 int32_t deviceId;
106 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700107 int32_t displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600108 std::array<uint8_t, 32> hmac;
Jeff Brown5912f952013-07-01 19:10:31 -0700109 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100110 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700111 int32_t flags;
112 int32_t metaState;
113 int32_t buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800114 MotionClassification classification; // base type: uint8_t
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800115 uint8_t empty2[3]; // 3 bytes to fill gap created by classification
Jeff Brown5912f952013-07-01 19:10:31 -0700116 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800117 nsecs_t downTime __attribute__((aligned(8)));
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600118 float xScale;
119 float yScale;
Jeff Brown5912f952013-07-01 19:10:31 -0700120 float xOffset;
121 float yOffset;
122 float xPrecision;
123 float yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700124 float xCursorPosition;
125 float yCursorPosition;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100126 uint32_t pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800127 uint32_t empty3;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800128 /**
129 * The "pointers" field must be the last field of the struct InputMessage.
130 * When we send the struct InputMessage across the socket, we are not
131 * writing the entire "pointers" array, but only the pointerCount portion
132 * of it as an optimization. Adding a field after "pointers" would break this.
133 */
Michael Wrightb03f1032015-05-14 16:29:13 +0100134 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700135 PointerProperties properties;
136 PointerCoords coords;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800137 } pointers[MAX_POINTERS] __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700138
139 int32_t getActionId() const {
140 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
141 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
142 return pointers[index].properties.id;
143 }
144
145 inline size_t size() const {
146 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
147 + sizeof(Pointer) * pointerCount;
148 }
149 } motion;
150
151 struct Finished {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500152 uint32_t empty1;
Siarhei Vishniakou10fe6762019-11-25 11:44:11 -0800153 uint32_t handled; // actually a bool, but we must maintain 8-byte alignment
Jeff Brown5912f952013-07-01 19:10:31 -0700154
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800155 inline size_t size() const { return sizeof(Finished); }
Jeff Brown5912f952013-07-01 19:10:31 -0700156 } finished;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800157
158 struct Focus {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800159 int32_t eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800160 // The following two fields take up 4 bytes total
161 uint16_t hasFocus; // actually a bool
162 uint16_t inTouchMode; // actually a bool, but we must maintain 8-byte alignment
163
164 inline size_t size() const { return sizeof(Focus); }
165 } focus;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800166 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700167
168 bool isValid(size_t actualSize) const;
169 size_t size() const;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800170 void getSanitizedCopy(InputMessage* msg) const;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500171
172 static const char* typeToString(Type type) {
173 switch (type) {
174 case Type::KEY:
175 return "KEY";
176 case Type::MOTION:
177 return "MOTION";
178 case Type::FINISHED:
179 return "FINISHED";
180 case Type::FOCUS:
181 return "FOCUS";
182 }
183 }
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 Vishniakouce5ab082020-07-09 17:03:21 -0500196 static std::shared_ptr<InputChannel> create(const std::string& name,
197 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 Vishniakouce5ab082020-07-09 17:03:21 -0500211 std::shared_ptr<InputChannel>& outServerChannel,
212 std::shared_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 Vishniakouce5ab082020-07-09 17:03:21 -0500244 std::shared_ptr<InputChannel> dup() const;
Jeff Brown5912f952013-07-01 19:10:31 -0700245
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500246 status_t readFromParcel(const android::Parcel* parcel) override;
247 status_t writeToParcel(android::Parcel* parcel) const override;
Robert Carr3720ed02018-08-08 16:08:27 -0700248
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700249 /**
250 * The connection token is used to identify the input connection, i.e.
251 * the pair of input channels that were created simultaneously. Input channels
252 * are always created in pairs, and the token can be used to find the server-side
253 * input channel from the client-side input channel, and vice versa.
254 *
255 * Do not use connection token to check equality of a specific input channel object
256 * to another, because two different (client and server) input channels will share the
257 * same connection token.
258 *
259 * Return the token that identifies this connection.
260 */
261 sp<IBinder> getConnectionToken() const;
Robert Carr803535b2018-08-02 16:38:15 -0700262
Chris Ye0783e992020-06-02 21:34:49 -0700263 bool operator==(const InputChannel& inputChannel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500264 struct stat lhs, rhs;
265 if (fstat(mFd.get(), &lhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700266 return false;
267 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500268 if (fstat(inputChannel.getFd(), &rhs) != 0) {
Chris Ye0783e992020-06-02 21:34:49 -0700269 return false;
270 }
271 // If file descriptors are pointing to same inode they are duplicated fds.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500272 return inputChannel.getName() == getName() && inputChannel.getConnectionToken() == mToken &&
273 lhs.st_ino == rhs.st_ino;
Chris Ye0783e992020-06-02 21:34:49 -0700274 }
275
Jeff Brown5912f952013-07-01 19:10:31 -0700276private:
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500277 std::string mName;
278 android::base::unique_fd mFd;
279
280 sp<IBinder> mToken;
Jeff Brown5912f952013-07-01 19:10:31 -0700281};
282
283/*
284 * Publishes input events to an input channel.
285 */
286class InputPublisher {
287public:
288 /* Creates a publisher associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500289 explicit InputPublisher(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700290
291 /* Destroys the publisher and releases its input channel. */
292 ~InputPublisher();
293
294 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500295 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700296
297 /* Publishes a key event to the input channel.
298 *
299 * Returns OK on success.
300 * Returns WOULD_BLOCK if the channel is full.
301 * Returns DEAD_OBJECT if the channel's peer has been closed.
302 * Returns BAD_VALUE if seq is 0.
303 * Other errors probably indicate that the channel is broken.
304 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800305 status_t publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
306 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
307 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600308 int32_t repeatCount, nsecs_t downTime, nsecs_t eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700309
310 /* Publishes a motion event to the input channel.
311 *
312 * Returns OK on success.
313 * Returns WOULD_BLOCK if the channel is full.
314 * Returns DEAD_OBJECT if the channel's peer has been closed.
315 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
316 * Other errors probably indicate that the channel is broken.
317 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800318 status_t publishMotionEvent(uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source,
319 int32_t displayId, std::array<uint8_t, 32> hmac, int32_t action,
320 int32_t actionButton, int32_t flags, int32_t edgeFlags,
321 int32_t metaState, int32_t buttonState,
322 MotionClassification classification, float xScale, float yScale,
323 float xOffset, float yOffset, float xPrecision, float yPrecision,
324 float xCursorPosition, float yCursorPosition, nsecs_t downTime,
325 nsecs_t eventTime, uint32_t pointerCount,
326 const PointerProperties* pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -0700327 const PointerCoords* pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -0700328
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800329 /* Publishes a focus event to the input channel.
330 *
331 * Returns OK on success.
332 * Returns WOULD_BLOCK if the channel is full.
333 * Returns DEAD_OBJECT if the channel's peer has been closed.
334 * Other errors probably indicate that the channel is broken.
335 */
Garfield Tan1c7bc862020-01-28 13:24:04 -0800336 status_t publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus, bool inTouchMode);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800337
Jeff Brown5912f952013-07-01 19:10:31 -0700338 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
339 * If a signal was received, returns the message sequence number,
340 * and whether the consumer handled the message.
341 *
342 * The returned sequence number is never 0 unless the operation failed.
343 *
344 * Returns OK on success.
345 * Returns WOULD_BLOCK if there is no signal present.
346 * Returns DEAD_OBJECT if the channel's peer has been closed.
347 * Other errors probably indicate that the channel is broken.
348 */
349 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
350
351private:
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500352 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700353};
354
355/*
356 * Consumes input events from an input channel.
357 */
358class InputConsumer {
359public:
360 /* Creates a consumer associated with an input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500361 explicit InputConsumer(const std::shared_ptr<InputChannel>& channel);
Jeff Brown5912f952013-07-01 19:10:31 -0700362
363 /* Destroys the consumer and releases its input channel. */
364 ~InputConsumer();
365
366 /* Gets the underlying input channel. */
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500367 inline std::shared_ptr<InputChannel> getChannel() { return mChannel; }
Jeff Brown5912f952013-07-01 19:10:31 -0700368
369 /* Consumes an input event from the input channel and copies its contents into
370 * an InputEvent object created using the specified factory.
371 *
372 * Tries to combine a series of move events into larger batches whenever possible.
373 *
374 * If consumeBatches is false, then defers consuming pending batched events if it
375 * is possible for additional samples to be added to them later. Call hasPendingBatch()
376 * to determine whether a pending batch is available to be consumed.
377 *
378 * If consumeBatches is true, then events are still batched but they are consumed
379 * immediately as soon as the input channel is exhausted.
380 *
381 * The frameTime parameter specifies the time when the current display frame started
382 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
383 *
384 * The returned sequence number is never 0 unless the operation failed.
385 *
386 * Returns OK on success.
387 * Returns WOULD_BLOCK if there is no event present.
388 * Returns DEAD_OBJECT if the channel's peer has been closed.
389 * Returns NO_MEMORY if the event could not be created.
390 * Other errors probably indicate that the channel is broken.
391 */
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800392 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches, nsecs_t frameTime,
393 uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700394
395 /* Sends a finished signal to the publisher to inform it that the message
396 * with the specified sequence number has finished being process and whether
397 * the message was handled by the consumer.
398 *
399 * Returns OK on success.
400 * Returns BAD_VALUE if seq is 0.
401 * Other errors probably indicate that the channel is broken.
402 */
403 status_t sendFinishedSignal(uint32_t seq, bool handled);
404
405 /* Returns true if there is a deferred event waiting.
406 *
407 * Should be called after calling consume() to determine whether the consumer
408 * has a deferred event to be processed. Deferred events are somewhat special in
409 * that they have already been removed from the input channel. If the input channel
410 * becomes empty, the client may need to do extra work to ensure that it processes
411 * the deferred event despite the fact that the input channel's file descriptor
412 * is not readable.
413 *
414 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
415 * This guarantees that all deferred events will be processed.
416 *
417 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
418 * a deferred event waiting and then ensure that its event loop wakes up at least
419 * one more time to consume the deferred event.
420 */
421 bool hasDeferredEvent() const;
422
423 /* Returns true if there is a pending batch.
424 *
425 * Should be called after calling consume() with consumeBatches == false to determine
426 * whether consume() should be called again later on with consumeBatches == true.
427 */
428 bool hasPendingBatch() const;
429
Arthur Hungc7812be2020-02-27 22:40:27 +0800430 /* Returns the source of first pending batch if exist.
431 *
432 * Should be called after calling consume() with consumeBatches == false to determine
433 * whether consume() should be called again later on with consumeBatches == true.
434 */
435 int32_t getPendingBatchSource() const;
436
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500437 std::string dump() const;
438
Jeff Brown5912f952013-07-01 19:10:31 -0700439private:
440 // True if touch resampling is enabled.
441 const bool mResampleTouch;
442
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500443 std::shared_ptr<InputChannel> mChannel;
Jeff Brown5912f952013-07-01 19:10:31 -0700444
445 // The current input message.
446 InputMessage mMsg;
447
448 // True if mMsg contains a valid input message that was deferred from the previous
449 // call to consume and that still needs to be handled.
450 bool mMsgDeferred;
451
452 // Batched motion events per device and source.
453 struct Batch {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500454 std::vector<InputMessage> samples;
Jeff Brown5912f952013-07-01 19:10:31 -0700455 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500456 std::vector<Batch> mBatches;
Jeff Brown5912f952013-07-01 19:10:31 -0700457
458 // Touch state per device and source, only for sources of class pointer.
459 struct History {
460 nsecs_t eventTime;
461 BitSet32 idBits;
462 int32_t idToIndex[MAX_POINTER_ID + 1];
463 PointerCoords pointers[MAX_POINTERS];
464
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100465 void initializeFrom(const InputMessage& msg) {
466 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700467 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100468 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
469 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700470 idBits.markBit(id);
471 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100472 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700473 }
474 }
475
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800476 void initializeFrom(const History& other) {
477 eventTime = other.eventTime;
478 idBits = other.idBits; // temporary copy
479 for (size_t i = 0; i < other.idBits.count(); i++) {
480 uint32_t id = idBits.clearFirstMarkedBit();
481 int32_t index = other.idToIndex[id];
482 idToIndex[id] = index;
483 pointers[index].copyFrom(other.pointers[index]);
484 }
485 idBits = other.idBits; // final copy
486 }
487
Jeff Brown5912f952013-07-01 19:10:31 -0700488 const PointerCoords& getPointerById(uint32_t id) const {
489 return pointers[idToIndex[id]];
490 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700491
492 bool hasPointerId(uint32_t id) const {
493 return idBits.hasBit(id);
494 }
Jeff Brown5912f952013-07-01 19:10:31 -0700495 };
496 struct TouchState {
497 int32_t deviceId;
498 int32_t source;
499 size_t historyCurrent;
500 size_t historySize;
501 History history[2];
502 History lastResample;
503
504 void initialize(int32_t deviceId, int32_t source) {
505 this->deviceId = deviceId;
506 this->source = source;
507 historyCurrent = 0;
508 historySize = 0;
509 lastResample.eventTime = 0;
510 lastResample.idBits.clear();
511 }
512
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100513 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700514 historyCurrent ^= 1;
515 if (historySize < 2) {
516 historySize += 1;
517 }
518 history[historyCurrent].initializeFrom(msg);
519 }
520
521 const History* getHistory(size_t index) const {
522 return &history[(historyCurrent + index) & 1];
523 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100524
525 bool recentCoordinatesAreIdentical(uint32_t id) const {
526 // Return true if the two most recently received "raw" coordinates are identical
527 if (historySize < 2) {
528 return false;
529 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700530 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
531 return false;
532 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100533 float currentX = getHistory(0)->getPointerById(id).getX();
534 float currentY = getHistory(0)->getPointerById(id).getY();
535 float previousX = getHistory(1)->getPointerById(id).getX();
536 float previousY = getHistory(1)->getPointerById(id).getY();
537 if (currentX == previousX && currentY == previousY) {
538 return true;
539 }
540 return false;
541 }
Jeff Brown5912f952013-07-01 19:10:31 -0700542 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500543 std::vector<TouchState> mTouchStates;
Jeff Brown5912f952013-07-01 19:10:31 -0700544
545 // Chain of batched sequence numbers. When multiple input messages are combined into
546 // a batch, we append a record here that associates the last sequence number in the
547 // batch with the previous one. When the finished signal is sent, we traverse the
548 // chain to individually finish all input messages that were part of the batch.
549 struct SeqChain {
550 uint32_t seq; // sequence number of batched input message
551 uint32_t chain; // sequence number of previous batched input message
552 };
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500553 std::vector<SeqChain> mSeqChains;
Jeff Brown5912f952013-07-01 19:10:31 -0700554
555 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800556 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700557 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800558 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700559
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100560 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700561 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
562 const InputMessage *next);
563
564 ssize_t findBatch(int32_t deviceId, int32_t source) const;
565 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
566
567 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
568
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800569 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700570 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
571 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800572 static void initializeFocusEvent(FocusEvent* event, const InputMessage* msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700573 static void addSample(MotionEvent* event, const InputMessage* msg);
574 static bool canAddSample(const Batch& batch, const InputMessage* msg);
575 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
576 static bool shouldResampleTool(int32_t toolType);
577
578 static bool isTouchResamplingEnabled();
579};
580
581} // namespace android
582
583#endif // _LIBINPUT_INPUT_TRANSPORT_H