blob: dddbfb04da195c5f03b9ab9ef6b14855a703faee [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.
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080050 *
51 * Since the struct must be aligned to an 8-byte boundary, there could be uninitialized bytes
52 * in-between the defined fields. This padding data should be explicitly accounted for by adding
53 * "empty" fields into the struct. This data is memset to zero before sending the struct across
54 * the socket. Adding the explicit fields ensures that the memset is not optimized away by the
55 * compiler. When a new field is added to the struct, the corresponding change
56 * in StructLayout_test should be made.
Jeff Brown5912f952013-07-01 19:10:31 -070057 */
58struct InputMessage {
59 enum {
60 TYPE_KEY = 1,
61 TYPE_MOTION = 2,
62 TYPE_FINISHED = 3,
63 };
64
65 struct Header {
66 uint32_t type;
Fengwei Yin83e0e422014-05-24 05:32:09 +080067 // We don't need this field in order to align the body below but we
68 // leave it here because InputMessage::size() and other functions
69 // compute the size of this structure as sizeof(Header) + sizeof(Body).
70 uint32_t padding;
Jeff Brown5912f952013-07-01 19:10:31 -070071 } header;
72
Fengwei Yin83e0e422014-05-24 05:32:09 +080073 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070074 union Body {
75 struct Key {
76 uint32_t seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080077 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080078 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070079 int32_t deviceId;
80 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010081 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070082 int32_t action;
83 int32_t flags;
84 int32_t keyCode;
85 int32_t scanCode;
86 int32_t metaState;
87 int32_t repeatCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080088 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +080089 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070090
91 inline size_t size() const {
92 return sizeof(Key);
93 }
94 } key;
95
96 struct Motion {
97 uint32_t seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -080098 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080099 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700100 int32_t deviceId;
101 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700102 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -0700103 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +0100104 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700105 int32_t flags;
106 int32_t metaState;
107 int32_t buttonState;
108 int32_t edgeFlags;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800109 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800110 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700111 float xOffset;
112 float yOffset;
113 float xPrecision;
114 float yPrecision;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100115 uint32_t pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800116 uint32_t empty3;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800117 // Note that PointerCoords requires 8 byte alignment.
Michael Wrightb03f1032015-05-14 16:29:13 +0100118 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700119 PointerProperties properties;
120 PointerCoords coords;
121 } pointers[MAX_POINTERS];
122
123 int32_t getActionId() const {
124 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
125 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
126 return pointers[index].properties.id;
127 }
128
129 inline size_t size() const {
130 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
131 + sizeof(Pointer) * pointerCount;
132 }
133 } motion;
134
135 struct Finished {
136 uint32_t seq;
137 bool handled;
138
139 inline size_t size() const {
140 return sizeof(Finished);
141 }
142 } finished;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800143 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700144
145 bool isValid(size_t actualSize) const;
146 size_t size() const;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800147 void getSanitizedCopy(InputMessage* msg) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700148};
149
150/*
151 * An input channel consists of a local unix domain socket used to send and receive
152 * input messages across processes. Each channel has a descriptive name for debugging purposes.
153 *
154 * Each endpoint has its own InputChannel object that specifies its file descriptor.
155 *
156 * The input channel is closed when all references to it are released.
157 */
158class InputChannel : public RefBase {
159protected:
160 virtual ~InputChannel();
161
162public:
Robert Carr3720ed02018-08-08 16:08:27 -0700163 InputChannel() = default;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800164 InputChannel(const std::string& name, int fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700165
166 /* Creates a pair of input channels.
167 *
168 * Returns OK on success.
169 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800170 static status_t openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700171 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
172
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800173 inline std::string getName() const { return mName; }
Jeff Brown5912f952013-07-01 19:10:31 -0700174 inline int getFd() const { return mFd; }
175
176 /* Sends a message to the other endpoint.
177 *
178 * If the channel is full then the message is guaranteed not to have been sent at all.
179 * Try again after the consumer has sent a finished signal indicating that it has
180 * consumed some of the pending messages from the channel.
181 *
182 * Returns OK on success.
183 * Returns WOULD_BLOCK if the channel is full.
184 * Returns DEAD_OBJECT if the channel's peer has been closed.
185 * Other errors probably indicate that the channel is broken.
186 */
187 status_t sendMessage(const InputMessage* msg);
188
189 /* Receives a message sent by the other endpoint.
190 *
191 * If there is no message present, try again after poll() indicates that the fd
192 * is readable.
193 *
194 * Returns OK on success.
195 * Returns WOULD_BLOCK if there is no message present.
196 * Returns DEAD_OBJECT if the channel's peer has been closed.
197 * Other errors probably indicate that the channel is broken.
198 */
199 status_t receiveMessage(InputMessage* msg);
200
201 /* Returns a new object that has a duplicate of this channel's fd. */
202 sp<InputChannel> dup() const;
203
Robert Carr3720ed02018-08-08 16:08:27 -0700204 status_t write(Parcel& out) const;
205 status_t read(const Parcel& from);
206
Robert Carr803535b2018-08-02 16:38:15 -0700207 sp<IBinder> getToken() const;
208 void setToken(const sp<IBinder>& token);
209
Jeff Brown5912f952013-07-01 19:10:31 -0700210private:
Robert Carr3720ed02018-08-08 16:08:27 -0700211 void setFd(int fd);
212
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 std::string mName;
Robert Carr3720ed02018-08-08 16:08:27 -0700214 int mFd = -1;
Robert Carr803535b2018-08-02 16:38:15 -0700215
216 sp<IBinder> mToken = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700217};
218
219/*
220 * Publishes input events to an input channel.
221 */
222class InputPublisher {
223public:
224 /* Creates a publisher associated with an input channel. */
225 explicit InputPublisher(const sp<InputChannel>& channel);
226
227 /* Destroys the publisher and releases its input channel. */
228 ~InputPublisher();
229
230 /* Gets the underlying input channel. */
231 inline sp<InputChannel> getChannel() { return mChannel; }
232
233 /* Publishes a key event to the input channel.
234 *
235 * Returns OK on success.
236 * Returns WOULD_BLOCK if the channel is full.
237 * Returns DEAD_OBJECT if the channel's peer has been closed.
238 * Returns BAD_VALUE if seq is 0.
239 * Other errors probably indicate that the channel is broken.
240 */
241 status_t publishKeyEvent(
242 uint32_t seq,
243 int32_t deviceId,
244 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100245 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700246 int32_t action,
247 int32_t flags,
248 int32_t keyCode,
249 int32_t scanCode,
250 int32_t metaState,
251 int32_t repeatCount,
252 nsecs_t downTime,
253 nsecs_t eventTime);
254
255 /* Publishes a motion event to the input channel.
256 *
257 * Returns OK on success.
258 * Returns WOULD_BLOCK if the channel is full.
259 * Returns DEAD_OBJECT if the channel's peer has been closed.
260 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
261 * Other errors probably indicate that the channel is broken.
262 */
263 status_t publishMotionEvent(
264 uint32_t seq,
265 int32_t deviceId,
266 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700267 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700268 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100269 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700270 int32_t flags,
271 int32_t edgeFlags,
272 int32_t metaState,
273 int32_t buttonState,
274 float xOffset,
275 float yOffset,
276 float xPrecision,
277 float yPrecision,
278 nsecs_t downTime,
279 nsecs_t eventTime,
Narayan Kamathed5fd382014-05-02 17:53:33 +0100280 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700281 const PointerProperties* pointerProperties,
282 const PointerCoords* pointerCoords);
283
284 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
285 * If a signal was received, returns the message sequence number,
286 * and whether the consumer handled the message.
287 *
288 * The returned sequence number is never 0 unless the operation failed.
289 *
290 * Returns OK on success.
291 * Returns WOULD_BLOCK if there is no signal present.
292 * Returns DEAD_OBJECT if the channel's peer has been closed.
293 * Other errors probably indicate that the channel is broken.
294 */
295 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
296
297private:
298 sp<InputChannel> mChannel;
299};
300
301/*
302 * Consumes input events from an input channel.
303 */
304class InputConsumer {
305public:
306 /* Creates a consumer associated with an input channel. */
307 explicit InputConsumer(const sp<InputChannel>& channel);
308
309 /* Destroys the consumer and releases its input channel. */
310 ~InputConsumer();
311
312 /* Gets the underlying input channel. */
313 inline sp<InputChannel> getChannel() { return mChannel; }
314
315 /* Consumes an input event from the input channel and copies its contents into
316 * an InputEvent object created using the specified factory.
317 *
318 * Tries to combine a series of move events into larger batches whenever possible.
319 *
320 * If consumeBatches is false, then defers consuming pending batched events if it
321 * is possible for additional samples to be added to them later. Call hasPendingBatch()
322 * to determine whether a pending batch is available to be consumed.
323 *
324 * If consumeBatches is true, then events are still batched but they are consumed
325 * immediately as soon as the input channel is exhausted.
326 *
327 * The frameTime parameter specifies the time when the current display frame started
328 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
329 *
330 * The returned sequence number is never 0 unless the operation failed.
331 *
332 * Returns OK on success.
333 * Returns WOULD_BLOCK if there is no event present.
334 * Returns DEAD_OBJECT if the channel's peer has been closed.
335 * Returns NO_MEMORY if the event could not be created.
336 * Other errors probably indicate that the channel is broken.
337 */
338 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800339 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700340
341 /* Sends a finished signal to the publisher to inform it that the message
342 * with the specified sequence number has finished being process and whether
343 * the message was handled by the consumer.
344 *
345 * Returns OK on success.
346 * Returns BAD_VALUE if seq is 0.
347 * Other errors probably indicate that the channel is broken.
348 */
349 status_t sendFinishedSignal(uint32_t seq, bool handled);
350
351 /* Returns true if there is a deferred event waiting.
352 *
353 * Should be called after calling consume() to determine whether the consumer
354 * has a deferred event to be processed. Deferred events are somewhat special in
355 * that they have already been removed from the input channel. If the input channel
356 * becomes empty, the client may need to do extra work to ensure that it processes
357 * the deferred event despite the fact that the input channel's file descriptor
358 * is not readable.
359 *
360 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
361 * This guarantees that all deferred events will be processed.
362 *
363 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
364 * a deferred event waiting and then ensure that its event loop wakes up at least
365 * one more time to consume the deferred event.
366 */
367 bool hasDeferredEvent() const;
368
369 /* Returns true if there is a pending batch.
370 *
371 * Should be called after calling consume() with consumeBatches == false to determine
372 * whether consume() should be called again later on with consumeBatches == true.
373 */
374 bool hasPendingBatch() const;
375
376private:
377 // True if touch resampling is enabled.
378 const bool mResampleTouch;
379
380 // The input channel.
381 sp<InputChannel> mChannel;
382
383 // The current input message.
384 InputMessage mMsg;
385
386 // True if mMsg contains a valid input message that was deferred from the previous
387 // call to consume and that still needs to be handled.
388 bool mMsgDeferred;
389
390 // Batched motion events per device and source.
391 struct Batch {
392 Vector<InputMessage> samples;
393 };
394 Vector<Batch> mBatches;
395
396 // Touch state per device and source, only for sources of class pointer.
397 struct History {
398 nsecs_t eventTime;
399 BitSet32 idBits;
400 int32_t idToIndex[MAX_POINTER_ID + 1];
401 PointerCoords pointers[MAX_POINTERS];
402
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100403 void initializeFrom(const InputMessage& msg) {
404 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700405 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100406 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
407 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700408 idBits.markBit(id);
409 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100410 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700411 }
412 }
413
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800414 void initializeFrom(const History& other) {
415 eventTime = other.eventTime;
416 idBits = other.idBits; // temporary copy
417 for (size_t i = 0; i < other.idBits.count(); i++) {
418 uint32_t id = idBits.clearFirstMarkedBit();
419 int32_t index = other.idToIndex[id];
420 idToIndex[id] = index;
421 pointers[index].copyFrom(other.pointers[index]);
422 }
423 idBits = other.idBits; // final copy
424 }
425
Jeff Brown5912f952013-07-01 19:10:31 -0700426 const PointerCoords& getPointerById(uint32_t id) const {
427 return pointers[idToIndex[id]];
428 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700429
430 bool hasPointerId(uint32_t id) const {
431 return idBits.hasBit(id);
432 }
Jeff Brown5912f952013-07-01 19:10:31 -0700433 };
434 struct TouchState {
435 int32_t deviceId;
436 int32_t source;
437 size_t historyCurrent;
438 size_t historySize;
439 History history[2];
440 History lastResample;
441
442 void initialize(int32_t deviceId, int32_t source) {
443 this->deviceId = deviceId;
444 this->source = source;
445 historyCurrent = 0;
446 historySize = 0;
447 lastResample.eventTime = 0;
448 lastResample.idBits.clear();
449 }
450
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100451 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700452 historyCurrent ^= 1;
453 if (historySize < 2) {
454 historySize += 1;
455 }
456 history[historyCurrent].initializeFrom(msg);
457 }
458
459 const History* getHistory(size_t index) const {
460 return &history[(historyCurrent + index) & 1];
461 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100462
463 bool recentCoordinatesAreIdentical(uint32_t id) const {
464 // Return true if the two most recently received "raw" coordinates are identical
465 if (historySize < 2) {
466 return false;
467 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700468 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
469 return false;
470 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100471 float currentX = getHistory(0)->getPointerById(id).getX();
472 float currentY = getHistory(0)->getPointerById(id).getY();
473 float previousX = getHistory(1)->getPointerById(id).getX();
474 float previousY = getHistory(1)->getPointerById(id).getY();
475 if (currentX == previousX && currentY == previousY) {
476 return true;
477 }
478 return false;
479 }
Jeff Brown5912f952013-07-01 19:10:31 -0700480 };
481 Vector<TouchState> mTouchStates;
482
483 // Chain of batched sequence numbers. When multiple input messages are combined into
484 // a batch, we append a record here that associates the last sequence number in the
485 // batch with the previous one. When the finished signal is sent, we traverse the
486 // chain to individually finish all input messages that were part of the batch.
487 struct SeqChain {
488 uint32_t seq; // sequence number of batched input message
489 uint32_t chain; // sequence number of previous batched input message
490 };
491 Vector<SeqChain> mSeqChains;
492
493 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800494 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700495 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800496 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700497
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100498 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700499 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
500 const InputMessage *next);
501
502 ssize_t findBatch(int32_t deviceId, int32_t source) const;
503 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
504
505 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
506
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800507 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700508 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
509 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
510 static void addSample(MotionEvent* event, const InputMessage* msg);
511 static bool canAddSample(const Batch& batch, const InputMessage* msg);
512 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
513 static bool shouldResampleTool(int32_t toolType);
514
515 static bool isTouchResamplingEnabled();
516};
517
518} // namespace android
519
520#endif // _LIBINPUT_INPUT_TRANSPORT_H