blob: ee5266108bfc7f189771430b493b08b9e0c00ca4 [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.
Jeff Brown5912f952013-07-01 19:10:31 -070044 */
45struct InputMessage {
46 enum {
47 TYPE_KEY = 1,
48 TYPE_MOTION = 2,
49 TYPE_FINISHED = 3,
50 };
51
52 struct Header {
53 uint32_t type;
Fengwei Yin83e0e422014-05-24 05:32:09 +080054 // We don't need this field in order to align the body below but we
55 // leave it here because InputMessage::size() and other functions
56 // compute the size of this structure as sizeof(Header) + sizeof(Body).
57 uint32_t padding;
Jeff Brown5912f952013-07-01 19:10:31 -070058 } header;
59
Fengwei Yin83e0e422014-05-24 05:32:09 +080060 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070061 union Body {
62 struct Key {
63 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080064 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070065 int32_t deviceId;
66 int32_t source;
67 int32_t action;
68 int32_t flags;
69 int32_t keyCode;
70 int32_t scanCode;
71 int32_t metaState;
72 int32_t repeatCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +080073 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070074
75 inline size_t size() const {
76 return sizeof(Key);
77 }
78 } key;
79
80 struct Motion {
81 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080082 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070083 int32_t deviceId;
84 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070085 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070086 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +010087 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -070088 int32_t flags;
89 int32_t metaState;
90 int32_t buttonState;
91 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +080092 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070093 float xOffset;
94 float yOffset;
95 float xPrecision;
96 float yPrecision;
Narayan Kamathed5fd382014-05-02 17:53:33 +010097 uint32_t pointerCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +080098 // Note that PointerCoords requires 8 byte alignment.
Michael Wrightb03f1032015-05-14 16:29:13 +010099 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700100 PointerProperties properties;
101 PointerCoords coords;
102 } pointers[MAX_POINTERS];
103
104 int32_t getActionId() const {
105 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
106 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
107 return pointers[index].properties.id;
108 }
109
110 inline size_t size() const {
111 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
112 + sizeof(Pointer) * pointerCount;
113 }
114 } motion;
115
116 struct Finished {
117 uint32_t seq;
118 bool handled;
119
120 inline size_t size() const {
121 return sizeof(Finished);
122 }
123 } finished;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800124 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700125
126 bool isValid(size_t actualSize) const;
127 size_t size() const;
128};
129
130/*
131 * An input channel consists of a local unix domain socket used to send and receive
132 * input messages across processes. Each channel has a descriptive name for debugging purposes.
133 *
134 * Each endpoint has its own InputChannel object that specifies its file descriptor.
135 *
136 * The input channel is closed when all references to it are released.
137 */
138class InputChannel : public RefBase {
139protected:
140 virtual ~InputChannel();
141
142public:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800143 InputChannel(const std::string& name, int fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700144
145 /* Creates a pair of input channels.
146 *
147 * Returns OK on success.
148 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800149 static status_t openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700150 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800152 inline std::string getName() const { return mName; }
Jeff Brown5912f952013-07-01 19:10:31 -0700153 inline int getFd() const { return mFd; }
154
155 /* Sends a message to the other endpoint.
156 *
157 * If the channel is full then the message is guaranteed not to have been sent at all.
158 * Try again after the consumer has sent a finished signal indicating that it has
159 * consumed some of the pending messages from the channel.
160 *
161 * Returns OK on success.
162 * Returns WOULD_BLOCK if the channel is full.
163 * Returns DEAD_OBJECT if the channel's peer has been closed.
164 * Other errors probably indicate that the channel is broken.
165 */
166 status_t sendMessage(const InputMessage* msg);
167
168 /* Receives a message sent by the other endpoint.
169 *
170 * If there is no message present, try again after poll() indicates that the fd
171 * is readable.
172 *
173 * Returns OK on success.
174 * Returns WOULD_BLOCK if there is no message present.
175 * Returns DEAD_OBJECT if the channel's peer has been closed.
176 * Other errors probably indicate that the channel is broken.
177 */
178 status_t receiveMessage(InputMessage* msg);
179
180 /* Returns a new object that has a duplicate of this channel's fd. */
181 sp<InputChannel> dup() const;
182
183private:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800184 std::string mName;
Jeff Brown5912f952013-07-01 19:10:31 -0700185 int mFd;
186};
187
188/*
189 * Publishes input events to an input channel.
190 */
191class InputPublisher {
192public:
193 /* Creates a publisher associated with an input channel. */
194 explicit InputPublisher(const sp<InputChannel>& channel);
195
196 /* Destroys the publisher and releases its input channel. */
197 ~InputPublisher();
198
199 /* Gets the underlying input channel. */
200 inline sp<InputChannel> getChannel() { return mChannel; }
201
202 /* Publishes a key event to the input channel.
203 *
204 * Returns OK on success.
205 * Returns WOULD_BLOCK if the channel is full.
206 * Returns DEAD_OBJECT if the channel's peer has been closed.
207 * Returns BAD_VALUE if seq is 0.
208 * Other errors probably indicate that the channel is broken.
209 */
210 status_t publishKeyEvent(
211 uint32_t seq,
212 int32_t deviceId,
213 int32_t source,
214 int32_t action,
215 int32_t flags,
216 int32_t keyCode,
217 int32_t scanCode,
218 int32_t metaState,
219 int32_t repeatCount,
220 nsecs_t downTime,
221 nsecs_t eventTime);
222
223 /* Publishes a motion event to the input channel.
224 *
225 * Returns OK on success.
226 * Returns WOULD_BLOCK if the channel is full.
227 * Returns DEAD_OBJECT if the channel's peer has been closed.
228 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
229 * Other errors probably indicate that the channel is broken.
230 */
231 status_t publishMotionEvent(
232 uint32_t seq,
233 int32_t deviceId,
234 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700235 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700236 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100237 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700238 int32_t flags,
239 int32_t edgeFlags,
240 int32_t metaState,
241 int32_t buttonState,
242 float xOffset,
243 float yOffset,
244 float xPrecision,
245 float yPrecision,
246 nsecs_t downTime,
247 nsecs_t eventTime,
Narayan Kamathed5fd382014-05-02 17:53:33 +0100248 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700249 const PointerProperties* pointerProperties,
250 const PointerCoords* pointerCoords);
251
252 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
253 * If a signal was received, returns the message sequence number,
254 * and whether the consumer handled the message.
255 *
256 * The returned sequence number is never 0 unless the operation failed.
257 *
258 * Returns OK on success.
259 * Returns WOULD_BLOCK if there is no signal present.
260 * Returns DEAD_OBJECT if the channel's peer has been closed.
261 * Other errors probably indicate that the channel is broken.
262 */
263 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
264
265private:
266 sp<InputChannel> mChannel;
267};
268
269/*
270 * Consumes input events from an input channel.
271 */
272class InputConsumer {
273public:
274 /* Creates a consumer associated with an input channel. */
275 explicit InputConsumer(const sp<InputChannel>& channel);
276
277 /* Destroys the consumer and releases its input channel. */
278 ~InputConsumer();
279
280 /* Gets the underlying input channel. */
281 inline sp<InputChannel> getChannel() { return mChannel; }
282
283 /* Consumes an input event from the input channel and copies its contents into
284 * an InputEvent object created using the specified factory.
285 *
286 * Tries to combine a series of move events into larger batches whenever possible.
287 *
288 * If consumeBatches is false, then defers consuming pending batched events if it
289 * is possible for additional samples to be added to them later. Call hasPendingBatch()
290 * to determine whether a pending batch is available to be consumed.
291 *
292 * If consumeBatches is true, then events are still batched but they are consumed
293 * immediately as soon as the input channel is exhausted.
294 *
295 * The frameTime parameter specifies the time when the current display frame started
296 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
297 *
298 * The returned sequence number is never 0 unless the operation failed.
299 *
300 * Returns OK on success.
301 * Returns WOULD_BLOCK if there is no event present.
302 * Returns DEAD_OBJECT if the channel's peer has been closed.
303 * Returns NO_MEMORY if the event could not be created.
304 * Other errors probably indicate that the channel is broken.
305 */
306 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800307 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700308
309 /* Sends a finished signal to the publisher to inform it that the message
310 * with the specified sequence number has finished being process and whether
311 * the message was handled by the consumer.
312 *
313 * Returns OK on success.
314 * Returns BAD_VALUE if seq is 0.
315 * Other errors probably indicate that the channel is broken.
316 */
317 status_t sendFinishedSignal(uint32_t seq, bool handled);
318
319 /* Returns true if there is a deferred event waiting.
320 *
321 * Should be called after calling consume() to determine whether the consumer
322 * has a deferred event to be processed. Deferred events are somewhat special in
323 * that they have already been removed from the input channel. If the input channel
324 * becomes empty, the client may need to do extra work to ensure that it processes
325 * the deferred event despite the fact that the input channel's file descriptor
326 * is not readable.
327 *
328 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
329 * This guarantees that all deferred events will be processed.
330 *
331 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
332 * a deferred event waiting and then ensure that its event loop wakes up at least
333 * one more time to consume the deferred event.
334 */
335 bool hasDeferredEvent() const;
336
337 /* Returns true if there is a pending batch.
338 *
339 * Should be called after calling consume() with consumeBatches == false to determine
340 * whether consume() should be called again later on with consumeBatches == true.
341 */
342 bool hasPendingBatch() const;
343
344private:
345 // True if touch resampling is enabled.
346 const bool mResampleTouch;
347
348 // The input channel.
349 sp<InputChannel> mChannel;
350
351 // The current input message.
352 InputMessage mMsg;
353
354 // True if mMsg contains a valid input message that was deferred from the previous
355 // call to consume and that still needs to be handled.
356 bool mMsgDeferred;
357
358 // Batched motion events per device and source.
359 struct Batch {
360 Vector<InputMessage> samples;
361 };
362 Vector<Batch> mBatches;
363
364 // Touch state per device and source, only for sources of class pointer.
365 struct History {
366 nsecs_t eventTime;
367 BitSet32 idBits;
368 int32_t idToIndex[MAX_POINTER_ID + 1];
369 PointerCoords pointers[MAX_POINTERS];
370
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100371 void initializeFrom(const InputMessage& msg) {
372 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700373 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100374 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
375 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700376 idBits.markBit(id);
377 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100378 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700379 }
380 }
381
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800382 void initializeFrom(const History& other) {
383 eventTime = other.eventTime;
384 idBits = other.idBits; // temporary copy
385 for (size_t i = 0; i < other.idBits.count(); i++) {
386 uint32_t id = idBits.clearFirstMarkedBit();
387 int32_t index = other.idToIndex[id];
388 idToIndex[id] = index;
389 pointers[index].copyFrom(other.pointers[index]);
390 }
391 idBits = other.idBits; // final copy
392 }
393
Jeff Brown5912f952013-07-01 19:10:31 -0700394 const PointerCoords& getPointerById(uint32_t id) const {
395 return pointers[idToIndex[id]];
396 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700397
398 bool hasPointerId(uint32_t id) const {
399 return idBits.hasBit(id);
400 }
Jeff Brown5912f952013-07-01 19:10:31 -0700401 };
402 struct TouchState {
403 int32_t deviceId;
404 int32_t source;
405 size_t historyCurrent;
406 size_t historySize;
407 History history[2];
408 History lastResample;
409
410 void initialize(int32_t deviceId, int32_t source) {
411 this->deviceId = deviceId;
412 this->source = source;
413 historyCurrent = 0;
414 historySize = 0;
415 lastResample.eventTime = 0;
416 lastResample.idBits.clear();
417 }
418
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100419 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700420 historyCurrent ^= 1;
421 if (historySize < 2) {
422 historySize += 1;
423 }
424 history[historyCurrent].initializeFrom(msg);
425 }
426
427 const History* getHistory(size_t index) const {
428 return &history[(historyCurrent + index) & 1];
429 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100430
431 bool recentCoordinatesAreIdentical(uint32_t id) const {
432 // Return true if the two most recently received "raw" coordinates are identical
433 if (historySize < 2) {
434 return false;
435 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700436 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
437 return false;
438 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100439 float currentX = getHistory(0)->getPointerById(id).getX();
440 float currentY = getHistory(0)->getPointerById(id).getY();
441 float previousX = getHistory(1)->getPointerById(id).getX();
442 float previousY = getHistory(1)->getPointerById(id).getY();
443 if (currentX == previousX && currentY == previousY) {
444 return true;
445 }
446 return false;
447 }
Jeff Brown5912f952013-07-01 19:10:31 -0700448 };
449 Vector<TouchState> mTouchStates;
450
451 // Chain of batched sequence numbers. When multiple input messages are combined into
452 // a batch, we append a record here that associates the last sequence number in the
453 // batch with the previous one. When the finished signal is sent, we traverse the
454 // chain to individually finish all input messages that were part of the batch.
455 struct SeqChain {
456 uint32_t seq; // sequence number of batched input message
457 uint32_t chain; // sequence number of previous batched input message
458 };
459 Vector<SeqChain> mSeqChains;
460
461 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800462 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700463 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800464 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700465
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100466 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700467 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
468 const InputMessage *next);
469
470 ssize_t findBatch(int32_t deviceId, int32_t source) const;
471 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
472
473 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
474
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800475 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700476 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
477 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
478 static void addSample(MotionEvent* event, const InputMessage* msg);
479 static bool canAddSample(const Batch& batch, const InputMessage* msg);
480 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
481 static bool shouldResampleTool(int32_t toolType);
482
483 static bool isTouchResamplingEnabled();
484};
485
486} // namespace android
487
488#endif // _LIBINPUT_INPUT_TRANSPORT_H