blob: 4782c9b237095f111a5b58af1407b8ab1cd7418f [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
20/**
21 * Native input transport.
22 *
23 * The InputChannel provides a mechanism for exchanging InputMessage structures across processes.
24 *
25 * The InputPublisher and InputConsumer each handle one end-point of an input channel.
26 * The InputPublisher is used by the input dispatcher to send events to the application.
27 * The InputConsumer is used by the application to receive events from the input dispatcher.
28 */
29
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010030#include <string>
31
Jeff Brown5912f952013-07-01 19:10:31 -070032#include <input/Input.h>
33#include <utils/Errors.h>
34#include <utils/Timers.h>
35#include <utils/RefBase.h>
Jeff Brown5912f952013-07-01 19:10:31 -070036#include <utils/Vector.h>
37#include <utils/BitSet.h>
38
39namespace android {
Robert Carr3720ed02018-08-08 16:08:27 -070040class Parcel;
Jeff Brown5912f952013-07-01 19:10:31 -070041
42/*
43 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080044 *
45 * Note that this structure is used for IPCs so its layout must be identical
46 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Jeff Brown5912f952013-07-01 19:10:31 -070047 */
48struct InputMessage {
49 enum {
50 TYPE_KEY = 1,
51 TYPE_MOTION = 2,
52 TYPE_FINISHED = 3,
53 };
54
55 struct Header {
56 uint32_t type;
Fengwei Yin83e0e422014-05-24 05:32:09 +080057 // We don't need this field in order to align the body below but we
58 // leave it here because InputMessage::size() and other functions
59 // compute the size of this structure as sizeof(Header) + sizeof(Body).
60 uint32_t padding;
Jeff Brown5912f952013-07-01 19:10:31 -070061 } header;
62
Fengwei Yin83e0e422014-05-24 05:32:09 +080063 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070064 union Body {
65 struct Key {
66 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080067 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070068 int32_t deviceId;
69 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010070 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070071 int32_t action;
72 int32_t flags;
73 int32_t keyCode;
74 int32_t scanCode;
75 int32_t metaState;
76 int32_t repeatCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +080077 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070078
79 inline size_t size() const {
80 return sizeof(Key);
81 }
82 } key;
83
84 struct Motion {
85 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080086 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070087 int32_t deviceId;
88 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070089 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070090 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +010091 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -070092 int32_t flags;
93 int32_t metaState;
94 int32_t buttonState;
95 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +080096 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070097 float xOffset;
98 float yOffset;
99 float xPrecision;
100 float yPrecision;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100101 uint32_t pointerCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800102 // Note that PointerCoords requires 8 byte alignment.
Michael Wrightb03f1032015-05-14 16:29:13 +0100103 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700104 PointerProperties properties;
105 PointerCoords coords;
106 } pointers[MAX_POINTERS];
107
108 int32_t getActionId() const {
109 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
110 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
111 return pointers[index].properties.id;
112 }
113
114 inline size_t size() const {
115 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
116 + sizeof(Pointer) * pointerCount;
117 }
118 } motion;
119
120 struct Finished {
121 uint32_t seq;
122 bool handled;
123
124 inline size_t size() const {
125 return sizeof(Finished);
126 }
127 } finished;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800128 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700129
130 bool isValid(size_t actualSize) const;
131 size_t size() const;
132};
133
134/*
135 * An input channel consists of a local unix domain socket used to send and receive
136 * input messages across processes. Each channel has a descriptive name for debugging purposes.
137 *
138 * Each endpoint has its own InputChannel object that specifies its file descriptor.
139 *
140 * The input channel is closed when all references to it are released.
141 */
142class InputChannel : public RefBase {
143protected:
144 virtual ~InputChannel();
145
146public:
Robert Carr3720ed02018-08-08 16:08:27 -0700147 InputChannel() = default;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800148 InputChannel(const std::string& name, int fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700149
150 /* Creates a pair of input channels.
151 *
152 * Returns OK on success.
153 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800154 static status_t openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700155 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
156
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800157 inline std::string getName() const { return mName; }
Jeff Brown5912f952013-07-01 19:10:31 -0700158 inline int getFd() const { return mFd; }
159
160 /* Sends a message to the other endpoint.
161 *
162 * If the channel is full then the message is guaranteed not to have been sent at all.
163 * Try again after the consumer has sent a finished signal indicating that it has
164 * consumed some of the pending messages from the channel.
165 *
166 * Returns OK on success.
167 * Returns WOULD_BLOCK if the channel is full.
168 * Returns DEAD_OBJECT if the channel's peer has been closed.
169 * Other errors probably indicate that the channel is broken.
170 */
171 status_t sendMessage(const InputMessage* msg);
172
173 /* Receives a message sent by the other endpoint.
174 *
175 * If there is no message present, try again after poll() indicates that the fd
176 * is readable.
177 *
178 * Returns OK on success.
179 * Returns WOULD_BLOCK if there is no message present.
180 * Returns DEAD_OBJECT if the channel's peer has been closed.
181 * Other errors probably indicate that the channel is broken.
182 */
183 status_t receiveMessage(InputMessage* msg);
184
185 /* Returns a new object that has a duplicate of this channel's fd. */
186 sp<InputChannel> dup() const;
187
Robert Carr3720ed02018-08-08 16:08:27 -0700188 status_t write(Parcel& out) const;
189 status_t read(const Parcel& from);
190
Jeff Brown5912f952013-07-01 19:10:31 -0700191private:
Robert Carr3720ed02018-08-08 16:08:27 -0700192 void setFd(int fd);
193
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800194 std::string mName;
Robert Carr3720ed02018-08-08 16:08:27 -0700195 int mFd = -1;
Jeff Brown5912f952013-07-01 19:10:31 -0700196};
197
198/*
199 * Publishes input events to an input channel.
200 */
201class InputPublisher {
202public:
203 /* Creates a publisher associated with an input channel. */
204 explicit InputPublisher(const sp<InputChannel>& channel);
205
206 /* Destroys the publisher and releases its input channel. */
207 ~InputPublisher();
208
209 /* Gets the underlying input channel. */
210 inline sp<InputChannel> getChannel() { return mChannel; }
211
212 /* Publishes a key event to the input channel.
213 *
214 * Returns OK on success.
215 * Returns WOULD_BLOCK if the channel is full.
216 * Returns DEAD_OBJECT if the channel's peer has been closed.
217 * Returns BAD_VALUE if seq is 0.
218 * Other errors probably indicate that the channel is broken.
219 */
220 status_t publishKeyEvent(
221 uint32_t seq,
222 int32_t deviceId,
223 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100224 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700225 int32_t action,
226 int32_t flags,
227 int32_t keyCode,
228 int32_t scanCode,
229 int32_t metaState,
230 int32_t repeatCount,
231 nsecs_t downTime,
232 nsecs_t eventTime);
233
234 /* Publishes a motion event to the input channel.
235 *
236 * Returns OK on success.
237 * Returns WOULD_BLOCK if the channel is full.
238 * Returns DEAD_OBJECT if the channel's peer has been closed.
239 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
240 * Other errors probably indicate that the channel is broken.
241 */
242 status_t publishMotionEvent(
243 uint32_t seq,
244 int32_t deviceId,
245 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700246 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700247 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100248 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700249 int32_t flags,
250 int32_t edgeFlags,
251 int32_t metaState,
252 int32_t buttonState,
253 float xOffset,
254 float yOffset,
255 float xPrecision,
256 float yPrecision,
257 nsecs_t downTime,
258 nsecs_t eventTime,
Narayan Kamathed5fd382014-05-02 17:53:33 +0100259 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700260 const PointerProperties* pointerProperties,
261 const PointerCoords* pointerCoords);
262
263 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
264 * If a signal was received, returns the message sequence number,
265 * and whether the consumer handled the message.
266 *
267 * The returned sequence number is never 0 unless the operation failed.
268 *
269 * Returns OK on success.
270 * Returns WOULD_BLOCK if there is no signal present.
271 * Returns DEAD_OBJECT if the channel's peer has been closed.
272 * Other errors probably indicate that the channel is broken.
273 */
274 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
275
276private:
277 sp<InputChannel> mChannel;
278};
279
280/*
281 * Consumes input events from an input channel.
282 */
283class InputConsumer {
284public:
285 /* Creates a consumer associated with an input channel. */
286 explicit InputConsumer(const sp<InputChannel>& channel);
287
288 /* Destroys the consumer and releases its input channel. */
289 ~InputConsumer();
290
291 /* Gets the underlying input channel. */
292 inline sp<InputChannel> getChannel() { return mChannel; }
293
294 /* Consumes an input event from the input channel and copies its contents into
295 * an InputEvent object created using the specified factory.
296 *
297 * Tries to combine a series of move events into larger batches whenever possible.
298 *
299 * If consumeBatches is false, then defers consuming pending batched events if it
300 * is possible for additional samples to be added to them later. Call hasPendingBatch()
301 * to determine whether a pending batch is available to be consumed.
302 *
303 * If consumeBatches is true, then events are still batched but they are consumed
304 * immediately as soon as the input channel is exhausted.
305 *
306 * The frameTime parameter specifies the time when the current display frame started
307 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
308 *
309 * The returned sequence number is never 0 unless the operation failed.
310 *
311 * Returns OK on success.
312 * Returns WOULD_BLOCK if there is no event present.
313 * Returns DEAD_OBJECT if the channel's peer has been closed.
314 * Returns NO_MEMORY if the event could not be created.
315 * Other errors probably indicate that the channel is broken.
316 */
317 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800318 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700319
320 /* Sends a finished signal to the publisher to inform it that the message
321 * with the specified sequence number has finished being process and whether
322 * the message was handled by the consumer.
323 *
324 * Returns OK on success.
325 * Returns BAD_VALUE if seq is 0.
326 * Other errors probably indicate that the channel is broken.
327 */
328 status_t sendFinishedSignal(uint32_t seq, bool handled);
329
330 /* Returns true if there is a deferred event waiting.
331 *
332 * Should be called after calling consume() to determine whether the consumer
333 * has a deferred event to be processed. Deferred events are somewhat special in
334 * that they have already been removed from the input channel. If the input channel
335 * becomes empty, the client may need to do extra work to ensure that it processes
336 * the deferred event despite the fact that the input channel's file descriptor
337 * is not readable.
338 *
339 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
340 * This guarantees that all deferred events will be processed.
341 *
342 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
343 * a deferred event waiting and then ensure that its event loop wakes up at least
344 * one more time to consume the deferred event.
345 */
346 bool hasDeferredEvent() const;
347
348 /* Returns true if there is a pending batch.
349 *
350 * Should be called after calling consume() with consumeBatches == false to determine
351 * whether consume() should be called again later on with consumeBatches == true.
352 */
353 bool hasPendingBatch() const;
354
355private:
356 // True if touch resampling is enabled.
357 const bool mResampleTouch;
358
359 // The input channel.
360 sp<InputChannel> mChannel;
361
362 // The current input message.
363 InputMessage mMsg;
364
365 // True if mMsg contains a valid input message that was deferred from the previous
366 // call to consume and that still needs to be handled.
367 bool mMsgDeferred;
368
369 // Batched motion events per device and source.
370 struct Batch {
371 Vector<InputMessage> samples;
372 };
373 Vector<Batch> mBatches;
374
375 // Touch state per device and source, only for sources of class pointer.
376 struct History {
377 nsecs_t eventTime;
378 BitSet32 idBits;
379 int32_t idToIndex[MAX_POINTER_ID + 1];
380 PointerCoords pointers[MAX_POINTERS];
381
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100382 void initializeFrom(const InputMessage& msg) {
383 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700384 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100385 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
386 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700387 idBits.markBit(id);
388 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100389 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700390 }
391 }
392
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800393 void initializeFrom(const History& other) {
394 eventTime = other.eventTime;
395 idBits = other.idBits; // temporary copy
396 for (size_t i = 0; i < other.idBits.count(); i++) {
397 uint32_t id = idBits.clearFirstMarkedBit();
398 int32_t index = other.idToIndex[id];
399 idToIndex[id] = index;
400 pointers[index].copyFrom(other.pointers[index]);
401 }
402 idBits = other.idBits; // final copy
403 }
404
Jeff Brown5912f952013-07-01 19:10:31 -0700405 const PointerCoords& getPointerById(uint32_t id) const {
406 return pointers[idToIndex[id]];
407 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700408
409 bool hasPointerId(uint32_t id) const {
410 return idBits.hasBit(id);
411 }
Jeff Brown5912f952013-07-01 19:10:31 -0700412 };
413 struct TouchState {
414 int32_t deviceId;
415 int32_t source;
416 size_t historyCurrent;
417 size_t historySize;
418 History history[2];
419 History lastResample;
420
421 void initialize(int32_t deviceId, int32_t source) {
422 this->deviceId = deviceId;
423 this->source = source;
424 historyCurrent = 0;
425 historySize = 0;
426 lastResample.eventTime = 0;
427 lastResample.idBits.clear();
428 }
429
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100430 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700431 historyCurrent ^= 1;
432 if (historySize < 2) {
433 historySize += 1;
434 }
435 history[historyCurrent].initializeFrom(msg);
436 }
437
438 const History* getHistory(size_t index) const {
439 return &history[(historyCurrent + index) & 1];
440 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100441
442 bool recentCoordinatesAreIdentical(uint32_t id) const {
443 // Return true if the two most recently received "raw" coordinates are identical
444 if (historySize < 2) {
445 return false;
446 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700447 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
448 return false;
449 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100450 float currentX = getHistory(0)->getPointerById(id).getX();
451 float currentY = getHistory(0)->getPointerById(id).getY();
452 float previousX = getHistory(1)->getPointerById(id).getX();
453 float previousY = getHistory(1)->getPointerById(id).getY();
454 if (currentX == previousX && currentY == previousY) {
455 return true;
456 }
457 return false;
458 }
Jeff Brown5912f952013-07-01 19:10:31 -0700459 };
460 Vector<TouchState> mTouchStates;
461
462 // Chain of batched sequence numbers. When multiple input messages are combined into
463 // a batch, we append a record here that associates the last sequence number in the
464 // batch with the previous one. When the finished signal is sent, we traverse the
465 // chain to individually finish all input messages that were part of the batch.
466 struct SeqChain {
467 uint32_t seq; // sequence number of batched input message
468 uint32_t chain; // sequence number of previous batched input message
469 };
470 Vector<SeqChain> mSeqChains;
471
472 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800473 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700474 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800475 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700476
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100477 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700478 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
479 const InputMessage *next);
480
481 ssize_t findBatch(int32_t deviceId, int32_t source) const;
482 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
483
484 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
485
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800486 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700487 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
488 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
489 static void addSample(MotionEvent* event, const InputMessage* msg);
490 static bool canAddSample(const Batch& batch, const InputMessage* msg);
491 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
492 static bool shouldResampleTool(int32_t toolType);
493
494 static bool isTouchResamplingEnabled();
495};
496
497} // namespace android
498
499#endif // _LIBINPUT_INPUT_TRANSPORT_H