blob: d906db3c0edec1188a565a87718f4d3e5ed77d72 [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
Robert Carr803535b2018-08-02 16:38:15 -070034#include <binder/IBinder.h>
Jeff Brown5912f952013-07-01 19:10:31 -070035#include <input/Input.h>
36#include <utils/Errors.h>
37#include <utils/Timers.h>
38#include <utils/RefBase.h>
Jeff Brown5912f952013-07-01 19:10:31 -070039#include <utils/Vector.h>
40#include <utils/BitSet.h>
41
42namespace android {
Robert Carr3720ed02018-08-08 16:08:27 -070043class Parcel;
Jeff Brown5912f952013-07-01 19:10:31 -070044
45/*
46 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080047 *
48 * Note that this structure is used for IPCs so its layout must be identical
49 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Jeff Brown5912f952013-07-01 19:10:31 -070050 */
51struct InputMessage {
52 enum {
53 TYPE_KEY = 1,
54 TYPE_MOTION = 2,
55 TYPE_FINISHED = 3,
56 };
57
58 struct Header {
59 uint32_t type;
Fengwei Yin83e0e422014-05-24 05:32:09 +080060 // We don't need this field in order to align the body below but we
61 // leave it here because InputMessage::size() and other functions
62 // compute the size of this structure as sizeof(Header) + sizeof(Body).
63 uint32_t padding;
Jeff Brown5912f952013-07-01 19:10:31 -070064 } header;
65
Fengwei Yin83e0e422014-05-24 05:32:09 +080066 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070067 union Body {
68 struct Key {
69 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080070 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070071 int32_t deviceId;
72 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010073 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070074 int32_t action;
75 int32_t flags;
76 int32_t keyCode;
77 int32_t scanCode;
78 int32_t metaState;
79 int32_t repeatCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +080080 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070081
82 inline size_t size() const {
83 return sizeof(Key);
84 }
85 } key;
86
87 struct Motion {
88 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080089 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070090 int32_t deviceId;
91 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070092 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070093 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +010094 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -070095 int32_t flags;
96 int32_t metaState;
97 int32_t buttonState;
98 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +080099 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700100 float xOffset;
101 float yOffset;
102 float xPrecision;
103 float yPrecision;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100104 uint32_t pointerCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800105 // Note that PointerCoords requires 8 byte alignment.
Michael Wrightb03f1032015-05-14 16:29:13 +0100106 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700107 PointerProperties properties;
108 PointerCoords coords;
109 } pointers[MAX_POINTERS];
110
111 int32_t getActionId() const {
112 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
113 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
114 return pointers[index].properties.id;
115 }
116
117 inline size_t size() const {
118 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
119 + sizeof(Pointer) * pointerCount;
120 }
121 } motion;
122
123 struct Finished {
124 uint32_t seq;
125 bool handled;
126
127 inline size_t size() const {
128 return sizeof(Finished);
129 }
130 } finished;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800131 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700132
133 bool isValid(size_t actualSize) const;
134 size_t size() const;
135};
136
137/*
138 * An input channel consists of a local unix domain socket used to send and receive
139 * input messages across processes. Each channel has a descriptive name for debugging purposes.
140 *
141 * Each endpoint has its own InputChannel object that specifies its file descriptor.
142 *
143 * The input channel is closed when all references to it are released.
144 */
145class InputChannel : public RefBase {
146protected:
147 virtual ~InputChannel();
148
149public:
Robert Carr3720ed02018-08-08 16:08:27 -0700150 InputChannel() = default;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800151 InputChannel(const std::string& name, int fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700152
153 /* Creates a pair of input channels.
154 *
155 * Returns OK on success.
156 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800157 static status_t openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700158 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
159
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800160 inline std::string getName() const { return mName; }
Jeff Brown5912f952013-07-01 19:10:31 -0700161 inline int getFd() const { return mFd; }
162
163 /* Sends a message to the other endpoint.
164 *
165 * If the channel is full then the message is guaranteed not to have been sent at all.
166 * Try again after the consumer has sent a finished signal indicating that it has
167 * consumed some of the pending messages from the channel.
168 *
169 * Returns OK on success.
170 * Returns WOULD_BLOCK if the channel is full.
171 * Returns DEAD_OBJECT if the channel's peer has been closed.
172 * Other errors probably indicate that the channel is broken.
173 */
174 status_t sendMessage(const InputMessage* msg);
175
176 /* Receives a message sent by the other endpoint.
177 *
178 * If there is no message present, try again after poll() indicates that the fd
179 * is readable.
180 *
181 * Returns OK on success.
182 * Returns WOULD_BLOCK if there is no message present.
183 * Returns DEAD_OBJECT if the channel's peer has been closed.
184 * Other errors probably indicate that the channel is broken.
185 */
186 status_t receiveMessage(InputMessage* msg);
187
188 /* Returns a new object that has a duplicate of this channel's fd. */
189 sp<InputChannel> dup() const;
190
Robert Carr3720ed02018-08-08 16:08:27 -0700191 status_t write(Parcel& out) const;
192 status_t read(const Parcel& from);
193
Robert Carr803535b2018-08-02 16:38:15 -0700194 sp<IBinder> getToken() const;
195 void setToken(const sp<IBinder>& token);
196
Jeff Brown5912f952013-07-01 19:10:31 -0700197private:
Robert Carr3720ed02018-08-08 16:08:27 -0700198 void setFd(int fd);
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200 std::string mName;
Robert Carr3720ed02018-08-08 16:08:27 -0700201 int mFd = -1;
Robert Carr803535b2018-08-02 16:38:15 -0700202
203 sp<IBinder> mToken = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700204};
205
206/*
207 * Publishes input events to an input channel.
208 */
209class InputPublisher {
210public:
211 /* Creates a publisher associated with an input channel. */
212 explicit InputPublisher(const sp<InputChannel>& channel);
213
214 /* Destroys the publisher and releases its input channel. */
215 ~InputPublisher();
216
217 /* Gets the underlying input channel. */
218 inline sp<InputChannel> getChannel() { return mChannel; }
219
220 /* Publishes a key event to the input channel.
221 *
222 * Returns OK on success.
223 * Returns WOULD_BLOCK if the channel is full.
224 * Returns DEAD_OBJECT if the channel's peer has been closed.
225 * Returns BAD_VALUE if seq is 0.
226 * Other errors probably indicate that the channel is broken.
227 */
228 status_t publishKeyEvent(
229 uint32_t seq,
230 int32_t deviceId,
231 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100232 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700233 int32_t action,
234 int32_t flags,
235 int32_t keyCode,
236 int32_t scanCode,
237 int32_t metaState,
238 int32_t repeatCount,
239 nsecs_t downTime,
240 nsecs_t eventTime);
241
242 /* Publishes a motion event to the input channel.
243 *
244 * Returns OK on success.
245 * Returns WOULD_BLOCK if the channel is full.
246 * Returns DEAD_OBJECT if the channel's peer has been closed.
247 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
248 * Other errors probably indicate that the channel is broken.
249 */
250 status_t publishMotionEvent(
251 uint32_t seq,
252 int32_t deviceId,
253 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700254 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700255 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100256 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700257 int32_t flags,
258 int32_t edgeFlags,
259 int32_t metaState,
260 int32_t buttonState,
261 float xOffset,
262 float yOffset,
263 float xPrecision,
264 float yPrecision,
265 nsecs_t downTime,
266 nsecs_t eventTime,
Narayan Kamathed5fd382014-05-02 17:53:33 +0100267 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700268 const PointerProperties* pointerProperties,
269 const PointerCoords* pointerCoords);
270
271 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
272 * If a signal was received, returns the message sequence number,
273 * and whether the consumer handled the message.
274 *
275 * The returned sequence number is never 0 unless the operation failed.
276 *
277 * Returns OK on success.
278 * Returns WOULD_BLOCK if there is no signal present.
279 * Returns DEAD_OBJECT if the channel's peer has been closed.
280 * Other errors probably indicate that the channel is broken.
281 */
282 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
283
284private:
285 sp<InputChannel> mChannel;
286};
287
288/*
289 * Consumes input events from an input channel.
290 */
291class InputConsumer {
292public:
293 /* Creates a consumer associated with an input channel. */
294 explicit InputConsumer(const sp<InputChannel>& channel);
295
296 /* Destroys the consumer and releases its input channel. */
297 ~InputConsumer();
298
299 /* Gets the underlying input channel. */
300 inline sp<InputChannel> getChannel() { return mChannel; }
301
302 /* Consumes an input event from the input channel and copies its contents into
303 * an InputEvent object created using the specified factory.
304 *
305 * Tries to combine a series of move events into larger batches whenever possible.
306 *
307 * If consumeBatches is false, then defers consuming pending batched events if it
308 * is possible for additional samples to be added to them later. Call hasPendingBatch()
309 * to determine whether a pending batch is available to be consumed.
310 *
311 * If consumeBatches is true, then events are still batched but they are consumed
312 * immediately as soon as the input channel is exhausted.
313 *
314 * The frameTime parameter specifies the time when the current display frame started
315 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
316 *
317 * The returned sequence number is never 0 unless the operation failed.
318 *
319 * Returns OK on success.
320 * Returns WOULD_BLOCK if there is no event present.
321 * Returns DEAD_OBJECT if the channel's peer has been closed.
322 * Returns NO_MEMORY if the event could not be created.
323 * Other errors probably indicate that the channel is broken.
324 */
325 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800326 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700327
328 /* Sends a finished signal to the publisher to inform it that the message
329 * with the specified sequence number has finished being process and whether
330 * the message was handled by the consumer.
331 *
332 * Returns OK on success.
333 * Returns BAD_VALUE if seq is 0.
334 * Other errors probably indicate that the channel is broken.
335 */
336 status_t sendFinishedSignal(uint32_t seq, bool handled);
337
338 /* Returns true if there is a deferred event waiting.
339 *
340 * Should be called after calling consume() to determine whether the consumer
341 * has a deferred event to be processed. Deferred events are somewhat special in
342 * that they have already been removed from the input channel. If the input channel
343 * becomes empty, the client may need to do extra work to ensure that it processes
344 * the deferred event despite the fact that the input channel's file descriptor
345 * is not readable.
346 *
347 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
348 * This guarantees that all deferred events will be processed.
349 *
350 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
351 * a deferred event waiting and then ensure that its event loop wakes up at least
352 * one more time to consume the deferred event.
353 */
354 bool hasDeferredEvent() const;
355
356 /* Returns true if there is a pending batch.
357 *
358 * Should be called after calling consume() with consumeBatches == false to determine
359 * whether consume() should be called again later on with consumeBatches == true.
360 */
361 bool hasPendingBatch() const;
362
363private:
364 // True if touch resampling is enabled.
365 const bool mResampleTouch;
366
367 // The input channel.
368 sp<InputChannel> mChannel;
369
370 // The current input message.
371 InputMessage mMsg;
372
373 // True if mMsg contains a valid input message that was deferred from the previous
374 // call to consume and that still needs to be handled.
375 bool mMsgDeferred;
376
377 // Batched motion events per device and source.
378 struct Batch {
379 Vector<InputMessage> samples;
380 };
381 Vector<Batch> mBatches;
382
383 // Touch state per device and source, only for sources of class pointer.
384 struct History {
385 nsecs_t eventTime;
386 BitSet32 idBits;
387 int32_t idToIndex[MAX_POINTER_ID + 1];
388 PointerCoords pointers[MAX_POINTERS];
389
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100390 void initializeFrom(const InputMessage& msg) {
391 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700392 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100393 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
394 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700395 idBits.markBit(id);
396 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100397 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700398 }
399 }
400
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800401 void initializeFrom(const History& other) {
402 eventTime = other.eventTime;
403 idBits = other.idBits; // temporary copy
404 for (size_t i = 0; i < other.idBits.count(); i++) {
405 uint32_t id = idBits.clearFirstMarkedBit();
406 int32_t index = other.idToIndex[id];
407 idToIndex[id] = index;
408 pointers[index].copyFrom(other.pointers[index]);
409 }
410 idBits = other.idBits; // final copy
411 }
412
Jeff Brown5912f952013-07-01 19:10:31 -0700413 const PointerCoords& getPointerById(uint32_t id) const {
414 return pointers[idToIndex[id]];
415 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700416
417 bool hasPointerId(uint32_t id) const {
418 return idBits.hasBit(id);
419 }
Jeff Brown5912f952013-07-01 19:10:31 -0700420 };
421 struct TouchState {
422 int32_t deviceId;
423 int32_t source;
424 size_t historyCurrent;
425 size_t historySize;
426 History history[2];
427 History lastResample;
428
429 void initialize(int32_t deviceId, int32_t source) {
430 this->deviceId = deviceId;
431 this->source = source;
432 historyCurrent = 0;
433 historySize = 0;
434 lastResample.eventTime = 0;
435 lastResample.idBits.clear();
436 }
437
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100438 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700439 historyCurrent ^= 1;
440 if (historySize < 2) {
441 historySize += 1;
442 }
443 history[historyCurrent].initializeFrom(msg);
444 }
445
446 const History* getHistory(size_t index) const {
447 return &history[(historyCurrent + index) & 1];
448 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100449
450 bool recentCoordinatesAreIdentical(uint32_t id) const {
451 // Return true if the two most recently received "raw" coordinates are identical
452 if (historySize < 2) {
453 return false;
454 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700455 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
456 return false;
457 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100458 float currentX = getHistory(0)->getPointerById(id).getX();
459 float currentY = getHistory(0)->getPointerById(id).getY();
460 float previousX = getHistory(1)->getPointerById(id).getX();
461 float previousY = getHistory(1)->getPointerById(id).getY();
462 if (currentX == previousX && currentY == previousY) {
463 return true;
464 }
465 return false;
466 }
Jeff Brown5912f952013-07-01 19:10:31 -0700467 };
468 Vector<TouchState> mTouchStates;
469
470 // Chain of batched sequence numbers. When multiple input messages are combined into
471 // a batch, we append a record here that associates the last sequence number in the
472 // batch with the previous one. When the finished signal is sent, we traverse the
473 // chain to individually finish all input messages that were part of the batch.
474 struct SeqChain {
475 uint32_t seq; // sequence number of batched input message
476 uint32_t chain; // sequence number of previous batched input message
477 };
478 Vector<SeqChain> mSeqChains;
479
480 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800481 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700482 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800483 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700484
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100485 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700486 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
487 const InputMessage *next);
488
489 ssize_t findBatch(int32_t deviceId, int32_t source) const;
490 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
491
492 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
493
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800494 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700495 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
496 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
497 static void addSample(MotionEvent* event, const InputMessage* msg);
498 static bool canAddSample(const Batch& batch, const InputMessage* msg);
499 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
500 static bool shouldResampleTool(int32_t toolType);
501
502 static bool isTouchResamplingEnabled();
503};
504
505} // namespace android
506
507#endif // _LIBINPUT_INPUT_TRANSPORT_H