blob: ecdc075ac89ab7c1e969606a006d914c03994f68 [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
30#include <input/Input.h>
31#include <utils/Errors.h>
32#include <utils/Timers.h>
33#include <utils/RefBase.h>
Jeff Brown5912f952013-07-01 19:10:31 -070034#include <utils/Vector.h>
35#include <utils/BitSet.h>
36
37namespace android {
38
39/*
40 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080041 *
42 * Note that this structure is used for IPCs so its layout must be identical
43 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Siarhei Vishniakoue730f5a2018-11-16 22:18:53 -080044 *
45 * Since the struct must be aligned to an 8-byte boundary, there could be uninitialized bytes
46 * in-between the defined fields. This padding data should be explicitly accounted for by adding
47 * "empty" fields into the struct. This data is memset to zero before sending the struct across
48 * the socket. Adding the explicit fields ensures that the memset is not optimized away by the
49 * compiler. When a new field is added to the struct, the corresponding change
50 * in StructLayout_test should be made.
Jeff Brown5912f952013-07-01 19:10:31 -070051 */
52struct InputMessage {
53 enum {
54 TYPE_KEY = 1,
55 TYPE_MOTION = 2,
56 TYPE_FINISHED = 3,
57 };
58
59 struct Header {
60 uint32_t type;
Fengwei Yin83e0e422014-05-24 05:32:09 +080061 // We don't need this field in order to align the body below but we
62 // leave it here because InputMessage::size() and other functions
63 // compute the size of this structure as sizeof(Header) + sizeof(Body).
64 uint32_t padding;
Jeff Brown5912f952013-07-01 19:10:31 -070065 } header;
66
Fengwei Yin83e0e422014-05-24 05:32:09 +080067 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070068 union Body {
69 struct Key {
70 uint32_t seq;
Siarhei Vishniakoue730f5a2018-11-16 22:18:53 -080071 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080072 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070073 int32_t deviceId;
74 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070075 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070076 int32_t action;
77 int32_t flags;
78 int32_t keyCode;
79 int32_t scanCode;
80 int32_t metaState;
81 int32_t repeatCount;
Siarhei Vishniakoue730f5a2018-11-16 22:18:53 -080082 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +080083 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070084
85 inline size_t size() const {
86 return sizeof(Key);
87 }
88 } key;
89
90 struct Motion {
91 uint32_t seq;
Siarhei Vishniakoue730f5a2018-11-16 22:18:53 -080092 uint32_t empty1;
Fengwei Yin83e0e422014-05-24 05:32:09 +080093 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070094 int32_t deviceId;
95 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070096 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070097 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +010098 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -070099 int32_t flags;
100 int32_t metaState;
101 int32_t buttonState;
102 int32_t edgeFlags;
Siarhei Vishniakoue730f5a2018-11-16 22:18:53 -0800103 uint32_t empty2;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800104 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -0700105 float xOffset;
106 float yOffset;
107 float xPrecision;
108 float yPrecision;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100109 uint32_t pointerCount;
Siarhei Vishniakoue730f5a2018-11-16 22:18:53 -0800110 uint32_t empty3;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800111 // Note that PointerCoords requires 8 byte alignment.
Michael Wrightb03f1032015-05-14 16:29:13 +0100112 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700113 PointerProperties properties;
114 PointerCoords coords;
115 } pointers[MAX_POINTERS];
116
117 int32_t getActionId() const {
118 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
119 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
120 return pointers[index].properties.id;
121 }
122
123 inline size_t size() const {
124 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
125 + sizeof(Pointer) * pointerCount;
126 }
127 } motion;
128
129 struct Finished {
130 uint32_t seq;
131 bool handled;
132
133 inline size_t size() const {
134 return sizeof(Finished);
135 }
136 } finished;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800137 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700138
139 bool isValid(size_t actualSize) const;
140 size_t size() const;
Siarhei Vishniakoue730f5a2018-11-16 22:18:53 -0800141 void getSanitizedCopy(InputMessage* msg) const;
Jeff Brown5912f952013-07-01 19:10:31 -0700142};
143
144/*
145 * An input channel consists of a local unix domain socket used to send and receive
146 * input messages across processes. Each channel has a descriptive name for debugging purposes.
147 *
148 * Each endpoint has its own InputChannel object that specifies its file descriptor.
149 *
150 * The input channel is closed when all references to it are released.
151 */
152class InputChannel : public RefBase {
153protected:
154 virtual ~InputChannel();
155
156public:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800157 InputChannel(const std::string& name, int fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700158
159 /* Creates a pair of input channels.
160 *
161 * Returns OK on success.
162 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800163 static status_t openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700164 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
165
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800166 inline std::string getName() const { return mName; }
Jeff Brown5912f952013-07-01 19:10:31 -0700167 inline int getFd() const { return mFd; }
168
169 /* Sends a message to the other endpoint.
170 *
171 * If the channel is full then the message is guaranteed not to have been sent at all.
172 * Try again after the consumer has sent a finished signal indicating that it has
173 * consumed some of the pending messages from the channel.
174 *
175 * Returns OK on success.
176 * Returns WOULD_BLOCK if the channel is full.
177 * Returns DEAD_OBJECT if the channel's peer has been closed.
178 * Other errors probably indicate that the channel is broken.
179 */
180 status_t sendMessage(const InputMessage* msg);
181
182 /* Receives a message sent by the other endpoint.
183 *
184 * If there is no message present, try again after poll() indicates that the fd
185 * is readable.
186 *
187 * Returns OK on success.
188 * Returns WOULD_BLOCK if there is no message present.
189 * Returns DEAD_OBJECT if the channel's peer has been closed.
190 * Other errors probably indicate that the channel is broken.
191 */
192 status_t receiveMessage(InputMessage* msg);
193
194 /* Returns a new object that has a duplicate of this channel's fd. */
195 sp<InputChannel> dup() const;
196
197private:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800198 std::string mName;
Jeff Brown5912f952013-07-01 19:10:31 -0700199 int mFd;
200};
201
202/*
203 * Publishes input events to an input channel.
204 */
205class InputPublisher {
206public:
207 /* Creates a publisher associated with an input channel. */
208 explicit InputPublisher(const sp<InputChannel>& channel);
209
210 /* Destroys the publisher and releases its input channel. */
211 ~InputPublisher();
212
213 /* Gets the underlying input channel. */
214 inline sp<InputChannel> getChannel() { return mChannel; }
215
216 /* Publishes a key event to the input channel.
217 *
218 * Returns OK on success.
219 * Returns WOULD_BLOCK if the channel is full.
220 * Returns DEAD_OBJECT if the channel's peer has been closed.
221 * Returns BAD_VALUE if seq is 0.
222 * Other errors probably indicate that the channel is broken.
223 */
224 status_t publishKeyEvent(
225 uint32_t seq,
226 int32_t deviceId,
227 int32_t source,
228 int32_t action,
229 int32_t flags,
230 int32_t keyCode,
231 int32_t scanCode,
232 int32_t metaState,
233 int32_t repeatCount,
234 nsecs_t downTime,
235 nsecs_t eventTime);
236
237 /* Publishes a motion event to the input channel.
238 *
239 * Returns OK on success.
240 * Returns WOULD_BLOCK if the channel is full.
241 * Returns DEAD_OBJECT if the channel's peer has been closed.
242 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
243 * Other errors probably indicate that the channel is broken.
244 */
245 status_t publishMotionEvent(
246 uint32_t seq,
247 int32_t deviceId,
248 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700249 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700250 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100251 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700252 int32_t flags,
253 int32_t edgeFlags,
254 int32_t metaState,
255 int32_t buttonState,
256 float xOffset,
257 float yOffset,
258 float xPrecision,
259 float yPrecision,
260 nsecs_t downTime,
261 nsecs_t eventTime,
Narayan Kamathed5fd382014-05-02 17:53:33 +0100262 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700263 const PointerProperties* pointerProperties,
264 const PointerCoords* pointerCoords);
265
266 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
267 * If a signal was received, returns the message sequence number,
268 * and whether the consumer handled the message.
269 *
270 * The returned sequence number is never 0 unless the operation failed.
271 *
272 * Returns OK on success.
273 * Returns WOULD_BLOCK if there is no signal present.
274 * Returns DEAD_OBJECT if the channel's peer has been closed.
275 * Other errors probably indicate that the channel is broken.
276 */
277 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
278
279private:
280 sp<InputChannel> mChannel;
281};
282
283/*
284 * Consumes input events from an input channel.
285 */
286class InputConsumer {
287public:
288 /* Creates a consumer associated with an input channel. */
289 explicit InputConsumer(const sp<InputChannel>& channel);
290
291 /* Destroys the consumer and releases its input channel. */
292 ~InputConsumer();
293
294 /* Gets the underlying input channel. */
295 inline sp<InputChannel> getChannel() { return mChannel; }
296
297 /* Consumes an input event from the input channel and copies its contents into
298 * an InputEvent object created using the specified factory.
299 *
300 * Tries to combine a series of move events into larger batches whenever possible.
301 *
302 * If consumeBatches is false, then defers consuming pending batched events if it
303 * is possible for additional samples to be added to them later. Call hasPendingBatch()
304 * to determine whether a pending batch is available to be consumed.
305 *
306 * If consumeBatches is true, then events are still batched but they are consumed
307 * immediately as soon as the input channel is exhausted.
308 *
309 * The frameTime parameter specifies the time when the current display frame started
310 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
311 *
312 * The returned sequence number is never 0 unless the operation failed.
313 *
314 * Returns OK on success.
315 * Returns WOULD_BLOCK if there is no event present.
316 * Returns DEAD_OBJECT if the channel's peer has been closed.
317 * Returns NO_MEMORY if the event could not be created.
318 * Other errors probably indicate that the channel is broken.
319 */
320 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
Tarandeep Singh58641502017-07-31 10:51:54 -0700321 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId);
Jeff Brown5912f952013-07-01 19:10:31 -0700322
323 /* Sends a finished signal to the publisher to inform it that the message
324 * with the specified sequence number has finished being process and whether
325 * the message was handled by the consumer.
326 *
327 * Returns OK on success.
328 * Returns BAD_VALUE if seq is 0.
329 * Other errors probably indicate that the channel is broken.
330 */
331 status_t sendFinishedSignal(uint32_t seq, bool handled);
332
333 /* Returns true if there is a deferred event waiting.
334 *
335 * Should be called after calling consume() to determine whether the consumer
336 * has a deferred event to be processed. Deferred events are somewhat special in
337 * that they have already been removed from the input channel. If the input channel
338 * becomes empty, the client may need to do extra work to ensure that it processes
339 * the deferred event despite the fact that the input channel's file descriptor
340 * is not readable.
341 *
342 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
343 * This guarantees that all deferred events will be processed.
344 *
345 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
346 * a deferred event waiting and then ensure that its event loop wakes up at least
347 * one more time to consume the deferred event.
348 */
349 bool hasDeferredEvent() const;
350
351 /* Returns true if there is a pending batch.
352 *
353 * Should be called after calling consume() with consumeBatches == false to determine
354 * whether consume() should be called again later on with consumeBatches == true.
355 */
356 bool hasPendingBatch() const;
357
358private:
359 // True if touch resampling is enabled.
360 const bool mResampleTouch;
361
362 // The input channel.
363 sp<InputChannel> mChannel;
364
365 // The current input message.
366 InputMessage mMsg;
367
368 // True if mMsg contains a valid input message that was deferred from the previous
369 // call to consume and that still needs to be handled.
370 bool mMsgDeferred;
371
372 // Batched motion events per device and source.
373 struct Batch {
374 Vector<InputMessage> samples;
375 };
376 Vector<Batch> mBatches;
377
378 // Touch state per device and source, only for sources of class pointer.
379 struct History {
380 nsecs_t eventTime;
381 BitSet32 idBits;
382 int32_t idToIndex[MAX_POINTER_ID + 1];
383 PointerCoords pointers[MAX_POINTERS];
384
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100385 void initializeFrom(const InputMessage& msg) {
386 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700387 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100388 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
389 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700390 idBits.markBit(id);
391 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100392 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700393 }
394 }
395
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800396 void initializeFrom(const History& other) {
397 eventTime = other.eventTime;
398 idBits = other.idBits; // temporary copy
399 for (size_t i = 0; i < other.idBits.count(); i++) {
400 uint32_t id = idBits.clearFirstMarkedBit();
401 int32_t index = other.idToIndex[id];
402 idToIndex[id] = index;
403 pointers[index].copyFrom(other.pointers[index]);
404 }
405 idBits = other.idBits; // final copy
406 }
407
Jeff Brown5912f952013-07-01 19:10:31 -0700408 const PointerCoords& getPointerById(uint32_t id) const {
409 return pointers[idToIndex[id]];
410 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700411
412 bool hasPointerId(uint32_t id) const {
413 return idBits.hasBit(id);
414 }
Jeff Brown5912f952013-07-01 19:10:31 -0700415 };
416 struct TouchState {
417 int32_t deviceId;
418 int32_t source;
419 size_t historyCurrent;
420 size_t historySize;
421 History history[2];
422 History lastResample;
423
424 void initialize(int32_t deviceId, int32_t source) {
425 this->deviceId = deviceId;
426 this->source = source;
427 historyCurrent = 0;
428 historySize = 0;
429 lastResample.eventTime = 0;
430 lastResample.idBits.clear();
431 }
432
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100433 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700434 historyCurrent ^= 1;
435 if (historySize < 2) {
436 historySize += 1;
437 }
438 history[historyCurrent].initializeFrom(msg);
439 }
440
441 const History* getHistory(size_t index) const {
442 return &history[(historyCurrent + index) & 1];
443 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100444
445 bool recentCoordinatesAreIdentical(uint32_t id) const {
446 // Return true if the two most recently received "raw" coordinates are identical
447 if (historySize < 2) {
448 return false;
449 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700450 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
451 return false;
452 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100453 float currentX = getHistory(0)->getPointerById(id).getX();
454 float currentY = getHistory(0)->getPointerById(id).getY();
455 float previousX = getHistory(1)->getPointerById(id).getX();
456 float previousY = getHistory(1)->getPointerById(id).getY();
457 if (currentX == previousX && currentY == previousY) {
458 return true;
459 }
460 return false;
461 }
Jeff Brown5912f952013-07-01 19:10:31 -0700462 };
463 Vector<TouchState> mTouchStates;
464
465 // Chain of batched sequence numbers. When multiple input messages are combined into
466 // a batch, we append a record here that associates the last sequence number in the
467 // batch with the previous one. When the finished signal is sent, we traverse the
468 // chain to individually finish all input messages that were part of the batch.
469 struct SeqChain {
470 uint32_t seq; // sequence number of batched input message
471 uint32_t chain; // sequence number of previous batched input message
472 };
473 Vector<SeqChain> mSeqChains;
474
475 status_t consumeBatch(InputEventFactoryInterface* factory,
Tarandeep Singh58641502017-07-31 10:51:54 -0700476 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId);
Jeff Brown5912f952013-07-01 19:10:31 -0700477 status_t consumeSamples(InputEventFactoryInterface* factory,
Tarandeep Singh58641502017-07-31 10:51:54 -0700478 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent,
479 int32_t* displayId);
Jeff Brown5912f952013-07-01 19:10:31 -0700480
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100481 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700482 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
483 const InputMessage *next);
484
485 ssize_t findBatch(int32_t deviceId, int32_t source) const;
486 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
487
488 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
489
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800490 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700491 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
492 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
493 static void addSample(MotionEvent* event, const InputMessage* msg);
494 static bool canAddSample(const Batch& batch, const InputMessage* msg);
495 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
496 static bool shouldResampleTool(int32_t toolType);
497
498 static bool isTouchResamplingEnabled();
499};
500
501} // namespace android
502
503#endif // _LIBINPUT_INPUT_TRANSPORT_H