blob: 4c91427a778a2320ef6ad33803641b1505a40779 [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
Jeff Brown5912f952013-07-01 19:10:31 -070034#include <input/Input.h>
35#include <utils/Errors.h>
36#include <utils/Timers.h>
37#include <utils/RefBase.h>
Jeff Brown5912f952013-07-01 19:10:31 -070038#include <utils/Vector.h>
39#include <utils/BitSet.h>
40
41namespace android {
Robert Carr3720ed02018-08-08 16:08:27 -070042class Parcel;
Jeff Brown5912f952013-07-01 19:10:31 -070043
44/*
45 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080046 *
47 * Note that this structure is used for IPCs so its layout must be identical
48 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Jeff Brown5912f952013-07-01 19:10:31 -070049 */
50struct InputMessage {
51 enum {
52 TYPE_KEY = 1,
53 TYPE_MOTION = 2,
54 TYPE_FINISHED = 3,
55 };
56
57 struct Header {
58 uint32_t type;
Fengwei Yin83e0e422014-05-24 05:32:09 +080059 // We don't need this field in order to align the body below but we
60 // leave it here because InputMessage::size() and other functions
61 // compute the size of this structure as sizeof(Header) + sizeof(Body).
62 uint32_t padding;
Jeff Brown5912f952013-07-01 19:10:31 -070063 } header;
64
Fengwei Yin83e0e422014-05-24 05:32:09 +080065 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070066 union Body {
67 struct Key {
68 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080069 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070070 int32_t deviceId;
71 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010072 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070073 int32_t action;
74 int32_t flags;
75 int32_t keyCode;
76 int32_t scanCode;
77 int32_t metaState;
78 int32_t repeatCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +080079 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070080
81 inline size_t size() const {
82 return sizeof(Key);
83 }
84 } key;
85
86 struct Motion {
87 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080088 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070089 int32_t deviceId;
90 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070091 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070092 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +010093 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -070094 int32_t flags;
95 int32_t metaState;
96 int32_t buttonState;
97 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +080098 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070099 float xOffset;
100 float yOffset;
101 float xPrecision;
102 float yPrecision;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100103 uint32_t pointerCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800104 // Note that PointerCoords requires 8 byte alignment.
Michael Wrightb03f1032015-05-14 16:29:13 +0100105 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700106 PointerProperties properties;
107 PointerCoords coords;
108 } pointers[MAX_POINTERS];
109
110 int32_t getActionId() const {
111 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
112 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
113 return pointers[index].properties.id;
114 }
115
116 inline size_t size() const {
117 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
118 + sizeof(Pointer) * pointerCount;
119 }
120 } motion;
121
122 struct Finished {
123 uint32_t seq;
124 bool handled;
125
126 inline size_t size() const {
127 return sizeof(Finished);
128 }
129 } finished;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800130 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700131
132 bool isValid(size_t actualSize) const;
133 size_t size() const;
134};
135
136/*
137 * An input channel consists of a local unix domain socket used to send and receive
138 * input messages across processes. Each channel has a descriptive name for debugging purposes.
139 *
140 * Each endpoint has its own InputChannel object that specifies its file descriptor.
141 *
142 * The input channel is closed when all references to it are released.
143 */
144class InputChannel : public RefBase {
145protected:
146 virtual ~InputChannel();
147
148public:
Robert Carr3720ed02018-08-08 16:08:27 -0700149 InputChannel() = default;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800150 InputChannel(const std::string& name, int fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700151
152 /* Creates a pair of input channels.
153 *
154 * Returns OK on success.
155 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800156 static status_t openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700157 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800159 inline std::string getName() const { return mName; }
Jeff Brown5912f952013-07-01 19:10:31 -0700160 inline int getFd() const { return mFd; }
161
162 /* Sends a message to the other endpoint.
163 *
164 * If the channel is full then the message is guaranteed not to have been sent at all.
165 * Try again after the consumer has sent a finished signal indicating that it has
166 * consumed some of the pending messages from the channel.
167 *
168 * Returns OK on success.
169 * Returns WOULD_BLOCK if the channel is full.
170 * Returns DEAD_OBJECT if the channel's peer has been closed.
171 * Other errors probably indicate that the channel is broken.
172 */
173 status_t sendMessage(const InputMessage* msg);
174
175 /* Receives a message sent by the other endpoint.
176 *
177 * If there is no message present, try again after poll() indicates that the fd
178 * is readable.
179 *
180 * Returns OK on success.
181 * Returns WOULD_BLOCK if there is no message present.
182 * Returns DEAD_OBJECT if the channel's peer has been closed.
183 * Other errors probably indicate that the channel is broken.
184 */
185 status_t receiveMessage(InputMessage* msg);
186
187 /* Returns a new object that has a duplicate of this channel's fd. */
188 sp<InputChannel> dup() const;
189
Robert Carr3720ed02018-08-08 16:08:27 -0700190 status_t write(Parcel& out) const;
191 status_t read(const Parcel& from);
192
Jeff Brown5912f952013-07-01 19:10:31 -0700193private:
Robert Carr3720ed02018-08-08 16:08:27 -0700194 void setFd(int fd);
195
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800196 std::string mName;
Robert Carr3720ed02018-08-08 16:08:27 -0700197 int mFd = -1;
Jeff Brown5912f952013-07-01 19:10:31 -0700198};
199
200/*
201 * Publishes input events to an input channel.
202 */
203class InputPublisher {
204public:
205 /* Creates a publisher associated with an input channel. */
206 explicit InputPublisher(const sp<InputChannel>& channel);
207
208 /* Destroys the publisher and releases its input channel. */
209 ~InputPublisher();
210
211 /* Gets the underlying input channel. */
212 inline sp<InputChannel> getChannel() { return mChannel; }
213
214 /* Publishes a key event to the input channel.
215 *
216 * Returns OK on success.
217 * Returns WOULD_BLOCK if the channel is full.
218 * Returns DEAD_OBJECT if the channel's peer has been closed.
219 * Returns BAD_VALUE if seq is 0.
220 * Other errors probably indicate that the channel is broken.
221 */
222 status_t publishKeyEvent(
223 uint32_t seq,
224 int32_t deviceId,
225 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100226 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700227 int32_t action,
228 int32_t flags,
229 int32_t keyCode,
230 int32_t scanCode,
231 int32_t metaState,
232 int32_t repeatCount,
233 nsecs_t downTime,
234 nsecs_t eventTime);
235
236 /* Publishes a motion event to the input channel.
237 *
238 * Returns OK on success.
239 * Returns WOULD_BLOCK if the channel is full.
240 * Returns DEAD_OBJECT if the channel's peer has been closed.
241 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
242 * Other errors probably indicate that the channel is broken.
243 */
244 status_t publishMotionEvent(
245 uint32_t seq,
246 int32_t deviceId,
247 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700248 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700249 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100250 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700251 int32_t flags,
252 int32_t edgeFlags,
253 int32_t metaState,
254 int32_t buttonState,
255 float xOffset,
256 float yOffset,
257 float xPrecision,
258 float yPrecision,
259 nsecs_t downTime,
260 nsecs_t eventTime,
Narayan Kamathed5fd382014-05-02 17:53:33 +0100261 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700262 const PointerProperties* pointerProperties,
263 const PointerCoords* pointerCoords);
264
265 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
266 * If a signal was received, returns the message sequence number,
267 * and whether the consumer handled the message.
268 *
269 * The returned sequence number is never 0 unless the operation failed.
270 *
271 * Returns OK on success.
272 * Returns WOULD_BLOCK if there is no signal present.
273 * Returns DEAD_OBJECT if the channel's peer has been closed.
274 * Other errors probably indicate that the channel is broken.
275 */
276 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
277
278private:
279 sp<InputChannel> mChannel;
280};
281
282/*
283 * Consumes input events from an input channel.
284 */
285class InputConsumer {
286public:
287 /* Creates a consumer associated with an input channel. */
288 explicit InputConsumer(const sp<InputChannel>& channel);
289
290 /* Destroys the consumer and releases its input channel. */
291 ~InputConsumer();
292
293 /* Gets the underlying input channel. */
294 inline sp<InputChannel> getChannel() { return mChannel; }
295
296 /* Consumes an input event from the input channel and copies its contents into
297 * an InputEvent object created using the specified factory.
298 *
299 * Tries to combine a series of move events into larger batches whenever possible.
300 *
301 * If consumeBatches is false, then defers consuming pending batched events if it
302 * is possible for additional samples to be added to them later. Call hasPendingBatch()
303 * to determine whether a pending batch is available to be consumed.
304 *
305 * If consumeBatches is true, then events are still batched but they are consumed
306 * immediately as soon as the input channel is exhausted.
307 *
308 * The frameTime parameter specifies the time when the current display frame started
309 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
310 *
311 * The returned sequence number is never 0 unless the operation failed.
312 *
313 * Returns OK on success.
314 * Returns WOULD_BLOCK if there is no event present.
315 * Returns DEAD_OBJECT if the channel's peer has been closed.
316 * Returns NO_MEMORY if the event could not be created.
317 * Other errors probably indicate that the channel is broken.
318 */
319 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800320 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700321
322 /* Sends a finished signal to the publisher to inform it that the message
323 * with the specified sequence number has finished being process and whether
324 * the message was handled by the consumer.
325 *
326 * Returns OK on success.
327 * Returns BAD_VALUE if seq is 0.
328 * Other errors probably indicate that the channel is broken.
329 */
330 status_t sendFinishedSignal(uint32_t seq, bool handled);
331
332 /* Returns true if there is a deferred event waiting.
333 *
334 * Should be called after calling consume() to determine whether the consumer
335 * has a deferred event to be processed. Deferred events are somewhat special in
336 * that they have already been removed from the input channel. If the input channel
337 * becomes empty, the client may need to do extra work to ensure that it processes
338 * the deferred event despite the fact that the input channel's file descriptor
339 * is not readable.
340 *
341 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
342 * This guarantees that all deferred events will be processed.
343 *
344 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
345 * a deferred event waiting and then ensure that its event loop wakes up at least
346 * one more time to consume the deferred event.
347 */
348 bool hasDeferredEvent() const;
349
350 /* Returns true if there is a pending batch.
351 *
352 * Should be called after calling consume() with consumeBatches == false to determine
353 * whether consume() should be called again later on with consumeBatches == true.
354 */
355 bool hasPendingBatch() const;
356
357private:
358 // True if touch resampling is enabled.
359 const bool mResampleTouch;
360
361 // The input channel.
362 sp<InputChannel> mChannel;
363
364 // The current input message.
365 InputMessage mMsg;
366
367 // True if mMsg contains a valid input message that was deferred from the previous
368 // call to consume and that still needs to be handled.
369 bool mMsgDeferred;
370
371 // Batched motion events per device and source.
372 struct Batch {
373 Vector<InputMessage> samples;
374 };
375 Vector<Batch> mBatches;
376
377 // Touch state per device and source, only for sources of class pointer.
378 struct History {
379 nsecs_t eventTime;
380 BitSet32 idBits;
381 int32_t idToIndex[MAX_POINTER_ID + 1];
382 PointerCoords pointers[MAX_POINTERS];
383
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100384 void initializeFrom(const InputMessage& msg) {
385 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700386 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100387 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
388 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700389 idBits.markBit(id);
390 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100391 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700392 }
393 }
394
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800395 void initializeFrom(const History& other) {
396 eventTime = other.eventTime;
397 idBits = other.idBits; // temporary copy
398 for (size_t i = 0; i < other.idBits.count(); i++) {
399 uint32_t id = idBits.clearFirstMarkedBit();
400 int32_t index = other.idToIndex[id];
401 idToIndex[id] = index;
402 pointers[index].copyFrom(other.pointers[index]);
403 }
404 idBits = other.idBits; // final copy
405 }
406
Jeff Brown5912f952013-07-01 19:10:31 -0700407 const PointerCoords& getPointerById(uint32_t id) const {
408 return pointers[idToIndex[id]];
409 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700410
411 bool hasPointerId(uint32_t id) const {
412 return idBits.hasBit(id);
413 }
Jeff Brown5912f952013-07-01 19:10:31 -0700414 };
415 struct TouchState {
416 int32_t deviceId;
417 int32_t source;
418 size_t historyCurrent;
419 size_t historySize;
420 History history[2];
421 History lastResample;
422
423 void initialize(int32_t deviceId, int32_t source) {
424 this->deviceId = deviceId;
425 this->source = source;
426 historyCurrent = 0;
427 historySize = 0;
428 lastResample.eventTime = 0;
429 lastResample.idBits.clear();
430 }
431
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100432 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700433 historyCurrent ^= 1;
434 if (historySize < 2) {
435 historySize += 1;
436 }
437 history[historyCurrent].initializeFrom(msg);
438 }
439
440 const History* getHistory(size_t index) const {
441 return &history[(historyCurrent + index) & 1];
442 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100443
444 bool recentCoordinatesAreIdentical(uint32_t id) const {
445 // Return true if the two most recently received "raw" coordinates are identical
446 if (historySize < 2) {
447 return false;
448 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700449 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
450 return false;
451 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100452 float currentX = getHistory(0)->getPointerById(id).getX();
453 float currentY = getHistory(0)->getPointerById(id).getY();
454 float previousX = getHistory(1)->getPointerById(id).getX();
455 float previousY = getHistory(1)->getPointerById(id).getY();
456 if (currentX == previousX && currentY == previousY) {
457 return true;
458 }
459 return false;
460 }
Jeff Brown5912f952013-07-01 19:10:31 -0700461 };
462 Vector<TouchState> mTouchStates;
463
464 // Chain of batched sequence numbers. When multiple input messages are combined into
465 // a batch, we append a record here that associates the last sequence number in the
466 // batch with the previous one. When the finished signal is sent, we traverse the
467 // chain to individually finish all input messages that were part of the batch.
468 struct SeqChain {
469 uint32_t seq; // sequence number of batched input message
470 uint32_t chain; // sequence number of previous batched input message
471 };
472 Vector<SeqChain> mSeqChains;
473
474 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800475 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700476 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800477 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700478
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100479 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700480 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
481 const InputMessage *next);
482
483 ssize_t findBatch(int32_t deviceId, int32_t source) const;
484 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
485
486 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
487
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800488 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700489 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
490 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
491 static void addSample(MotionEvent* event, const InputMessage* msg);
492 static bool canAddSample(const Batch& batch, const InputMessage* msg);
493 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
494 static bool shouldResampleTool(int32_t toolType);
495
496 static bool isTouchResamplingEnabled();
497};
498
499} // namespace android
500
501#endif // _LIBINPUT_INPUT_TRANSPORT_H