blob: 5fd86b48f7be69187730e99d7c283b7cef536775 [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 {
40
41/*
42 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080043 *
44 * Note that this structure is used for IPCs so its layout must be identical
45 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Jeff Brown5912f952013-07-01 19:10:31 -070046 */
47struct InputMessage {
48 enum {
49 TYPE_KEY = 1,
50 TYPE_MOTION = 2,
51 TYPE_FINISHED = 3,
52 };
53
54 struct Header {
55 uint32_t type;
Fengwei Yin83e0e422014-05-24 05:32:09 +080056 // We don't need this field in order to align the body below but we
57 // leave it here because InputMessage::size() and other functions
58 // compute the size of this structure as sizeof(Header) + sizeof(Body).
59 uint32_t padding;
Jeff Brown5912f952013-07-01 19:10:31 -070060 } header;
61
Fengwei Yin83e0e422014-05-24 05:32:09 +080062 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070063 union Body {
64 struct Key {
65 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080066 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070067 int32_t deviceId;
68 int32_t source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +010069 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070070 int32_t action;
71 int32_t flags;
72 int32_t keyCode;
73 int32_t scanCode;
74 int32_t metaState;
75 int32_t repeatCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +080076 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070077
78 inline size_t size() const {
79 return sizeof(Key);
80 }
81 } key;
82
83 struct Motion {
84 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080085 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070086 int32_t deviceId;
87 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070088 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070089 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +010090 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -070091 int32_t flags;
92 int32_t metaState;
93 int32_t buttonState;
94 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +080095 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070096 float xOffset;
97 float yOffset;
98 float xPrecision;
99 float yPrecision;
Narayan Kamathed5fd382014-05-02 17:53:33 +0100100 uint32_t pointerCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800101 // Note that PointerCoords requires 8 byte alignment.
Michael Wrightb03f1032015-05-14 16:29:13 +0100102 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700103 PointerProperties properties;
104 PointerCoords coords;
105 } pointers[MAX_POINTERS];
106
107 int32_t getActionId() const {
108 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
109 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
110 return pointers[index].properties.id;
111 }
112
113 inline size_t size() const {
114 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
115 + sizeof(Pointer) * pointerCount;
116 }
117 } motion;
118
119 struct Finished {
120 uint32_t seq;
121 bool handled;
122
123 inline size_t size() const {
124 return sizeof(Finished);
125 }
126 } finished;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800127 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700128
129 bool isValid(size_t actualSize) const;
130 size_t size() const;
131};
132
133/*
134 * An input channel consists of a local unix domain socket used to send and receive
135 * input messages across processes. Each channel has a descriptive name for debugging purposes.
136 *
137 * Each endpoint has its own InputChannel object that specifies its file descriptor.
138 *
139 * The input channel is closed when all references to it are released.
140 */
141class InputChannel : public RefBase {
142protected:
143 virtual ~InputChannel();
144
145public:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800146 InputChannel(const std::string& name, int fd);
Jeff Brown5912f952013-07-01 19:10:31 -0700147
148 /* Creates a pair of input channels.
149 *
150 * Returns OK on success.
151 */
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800152 static status_t openInputChannelPair(const std::string& name,
Jeff Brown5912f952013-07-01 19:10:31 -0700153 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
154
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800155 inline std::string getName() const { return mName; }
Jeff Brown5912f952013-07-01 19:10:31 -0700156 inline int getFd() const { return mFd; }
157
158 /* Sends a message to the other endpoint.
159 *
160 * If the channel is full then the message is guaranteed not to have been sent at all.
161 * Try again after the consumer has sent a finished signal indicating that it has
162 * consumed some of the pending messages from the channel.
163 *
164 * Returns OK on success.
165 * Returns WOULD_BLOCK if the channel is full.
166 * Returns DEAD_OBJECT if the channel's peer has been closed.
167 * Other errors probably indicate that the channel is broken.
168 */
169 status_t sendMessage(const InputMessage* msg);
170
171 /* Receives a message sent by the other endpoint.
172 *
173 * If there is no message present, try again after poll() indicates that the fd
174 * is readable.
175 *
176 * Returns OK on success.
177 * Returns WOULD_BLOCK if there is no message present.
178 * Returns DEAD_OBJECT if the channel's peer has been closed.
179 * Other errors probably indicate that the channel is broken.
180 */
181 status_t receiveMessage(InputMessage* msg);
182
183 /* Returns a new object that has a duplicate of this channel's fd. */
184 sp<InputChannel> dup() const;
185
186private:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800187 std::string mName;
Jeff Brown5912f952013-07-01 19:10:31 -0700188 int mFd;
189};
190
191/*
192 * Publishes input events to an input channel.
193 */
194class InputPublisher {
195public:
196 /* Creates a publisher associated with an input channel. */
197 explicit InputPublisher(const sp<InputChannel>& channel);
198
199 /* Destroys the publisher and releases its input channel. */
200 ~InputPublisher();
201
202 /* Gets the underlying input channel. */
203 inline sp<InputChannel> getChannel() { return mChannel; }
204
205 /* Publishes a key event to the input channel.
206 *
207 * Returns OK on success.
208 * Returns WOULD_BLOCK if the channel is full.
209 * Returns DEAD_OBJECT if the channel's peer has been closed.
210 * Returns BAD_VALUE if seq is 0.
211 * Other errors probably indicate that the channel is broken.
212 */
213 status_t publishKeyEvent(
214 uint32_t seq,
215 int32_t deviceId,
216 int32_t source,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100217 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700218 int32_t action,
219 int32_t flags,
220 int32_t keyCode,
221 int32_t scanCode,
222 int32_t metaState,
223 int32_t repeatCount,
224 nsecs_t downTime,
225 nsecs_t eventTime);
226
227 /* Publishes a motion event to the input channel.
228 *
229 * Returns OK on success.
230 * Returns WOULD_BLOCK if the channel is full.
231 * Returns DEAD_OBJECT if the channel's peer has been closed.
232 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
233 * Other errors probably indicate that the channel is broken.
234 */
235 status_t publishMotionEvent(
236 uint32_t seq,
237 int32_t deviceId,
238 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700239 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700240 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100241 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700242 int32_t flags,
243 int32_t edgeFlags,
244 int32_t metaState,
245 int32_t buttonState,
246 float xOffset,
247 float yOffset,
248 float xPrecision,
249 float yPrecision,
250 nsecs_t downTime,
251 nsecs_t eventTime,
Narayan Kamathed5fd382014-05-02 17:53:33 +0100252 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700253 const PointerProperties* pointerProperties,
254 const PointerCoords* pointerCoords);
255
256 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
257 * If a signal was received, returns the message sequence number,
258 * and whether the consumer handled the message.
259 *
260 * The returned sequence number is never 0 unless the operation failed.
261 *
262 * Returns OK on success.
263 * Returns WOULD_BLOCK if there is no signal present.
264 * Returns DEAD_OBJECT if the channel's peer has been closed.
265 * Other errors probably indicate that the channel is broken.
266 */
267 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
268
269private:
270 sp<InputChannel> mChannel;
271};
272
273/*
274 * Consumes input events from an input channel.
275 */
276class InputConsumer {
277public:
278 /* Creates a consumer associated with an input channel. */
279 explicit InputConsumer(const sp<InputChannel>& channel);
280
281 /* Destroys the consumer and releases its input channel. */
282 ~InputConsumer();
283
284 /* Gets the underlying input channel. */
285 inline sp<InputChannel> getChannel() { return mChannel; }
286
287 /* Consumes an input event from the input channel and copies its contents into
288 * an InputEvent object created using the specified factory.
289 *
290 * Tries to combine a series of move events into larger batches whenever possible.
291 *
292 * If consumeBatches is false, then defers consuming pending batched events if it
293 * is possible for additional samples to be added to them later. Call hasPendingBatch()
294 * to determine whether a pending batch is available to be consumed.
295 *
296 * If consumeBatches is true, then events are still batched but they are consumed
297 * immediately as soon as the input channel is exhausted.
298 *
299 * The frameTime parameter specifies the time when the current display frame started
300 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
301 *
302 * The returned sequence number is never 0 unless the operation failed.
303 *
304 * Returns OK on success.
305 * Returns WOULD_BLOCK if there is no event present.
306 * Returns DEAD_OBJECT if the channel's peer has been closed.
307 * Returns NO_MEMORY if the event could not be created.
308 * Other errors probably indicate that the channel is broken.
309 */
310 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800311 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700312
313 /* Sends a finished signal to the publisher to inform it that the message
314 * with the specified sequence number has finished being process and whether
315 * the message was handled by the consumer.
316 *
317 * Returns OK on success.
318 * Returns BAD_VALUE if seq is 0.
319 * Other errors probably indicate that the channel is broken.
320 */
321 status_t sendFinishedSignal(uint32_t seq, bool handled);
322
323 /* Returns true if there is a deferred event waiting.
324 *
325 * Should be called after calling consume() to determine whether the consumer
326 * has a deferred event to be processed. Deferred events are somewhat special in
327 * that they have already been removed from the input channel. If the input channel
328 * becomes empty, the client may need to do extra work to ensure that it processes
329 * the deferred event despite the fact that the input channel's file descriptor
330 * is not readable.
331 *
332 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
333 * This guarantees that all deferred events will be processed.
334 *
335 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
336 * a deferred event waiting and then ensure that its event loop wakes up at least
337 * one more time to consume the deferred event.
338 */
339 bool hasDeferredEvent() const;
340
341 /* Returns true if there is a pending batch.
342 *
343 * Should be called after calling consume() with consumeBatches == false to determine
344 * whether consume() should be called again later on with consumeBatches == true.
345 */
346 bool hasPendingBatch() const;
347
348private:
349 // True if touch resampling is enabled.
350 const bool mResampleTouch;
351
352 // The input channel.
353 sp<InputChannel> mChannel;
354
355 // The current input message.
356 InputMessage mMsg;
357
358 // True if mMsg contains a valid input message that was deferred from the previous
359 // call to consume and that still needs to be handled.
360 bool mMsgDeferred;
361
362 // Batched motion events per device and source.
363 struct Batch {
364 Vector<InputMessage> samples;
365 };
366 Vector<Batch> mBatches;
367
368 // Touch state per device and source, only for sources of class pointer.
369 struct History {
370 nsecs_t eventTime;
371 BitSet32 idBits;
372 int32_t idToIndex[MAX_POINTER_ID + 1];
373 PointerCoords pointers[MAX_POINTERS];
374
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100375 void initializeFrom(const InputMessage& msg) {
376 eventTime = msg.body.motion.eventTime;
Jeff Brown5912f952013-07-01 19:10:31 -0700377 idBits.clear();
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100378 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
379 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -0700380 idBits.markBit(id);
381 idToIndex[id] = i;
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100382 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
Jeff Brown5912f952013-07-01 19:10:31 -0700383 }
384 }
385
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800386 void initializeFrom(const History& other) {
387 eventTime = other.eventTime;
388 idBits = other.idBits; // temporary copy
389 for (size_t i = 0; i < other.idBits.count(); i++) {
390 uint32_t id = idBits.clearFirstMarkedBit();
391 int32_t index = other.idToIndex[id];
392 idToIndex[id] = index;
393 pointers[index].copyFrom(other.pointers[index]);
394 }
395 idBits = other.idBits; // final copy
396 }
397
Jeff Brown5912f952013-07-01 19:10:31 -0700398 const PointerCoords& getPointerById(uint32_t id) const {
399 return pointers[idToIndex[id]];
400 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700401
402 bool hasPointerId(uint32_t id) const {
403 return idBits.hasBit(id);
404 }
Jeff Brown5912f952013-07-01 19:10:31 -0700405 };
406 struct TouchState {
407 int32_t deviceId;
408 int32_t source;
409 size_t historyCurrent;
410 size_t historySize;
411 History history[2];
412 History lastResample;
413
414 void initialize(int32_t deviceId, int32_t source) {
415 this->deviceId = deviceId;
416 this->source = source;
417 historyCurrent = 0;
418 historySize = 0;
419 lastResample.eventTime = 0;
420 lastResample.idBits.clear();
421 }
422
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100423 void addHistory(const InputMessage& msg) {
Jeff Brown5912f952013-07-01 19:10:31 -0700424 historyCurrent ^= 1;
425 if (historySize < 2) {
426 historySize += 1;
427 }
428 history[historyCurrent].initializeFrom(msg);
429 }
430
431 const History* getHistory(size_t index) const {
432 return &history[(historyCurrent + index) & 1];
433 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100434
435 bool recentCoordinatesAreIdentical(uint32_t id) const {
436 // Return true if the two most recently received "raw" coordinates are identical
437 if (historySize < 2) {
438 return false;
439 }
Siarhei Vishniakouc7dc3782017-08-24 20:36:28 -0700440 if (!getHistory(0)->hasPointerId(id) || !getHistory(1)->hasPointerId(id)) {
441 return false;
442 }
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100443 float currentX = getHistory(0)->getPointerById(id).getX();
444 float currentY = getHistory(0)->getPointerById(id).getY();
445 float previousX = getHistory(1)->getPointerById(id).getX();
446 float previousY = getHistory(1)->getPointerById(id).getY();
447 if (currentX == previousX && currentY == previousY) {
448 return true;
449 }
450 return false;
451 }
Jeff Brown5912f952013-07-01 19:10:31 -0700452 };
453 Vector<TouchState> mTouchStates;
454
455 // Chain of batched sequence numbers. When multiple input messages are combined into
456 // a batch, we append a record here that associates the last sequence number in the
457 // batch with the previous one. When the finished signal is sent, we traverse the
458 // chain to individually finish all input messages that were part of the batch.
459 struct SeqChain {
460 uint32_t seq; // sequence number of batched input message
461 uint32_t chain; // sequence number of previous batched input message
462 };
463 Vector<SeqChain> mSeqChains;
464
465 status_t consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800466 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700467 status_t consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800468 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700469
Siarhei Vishniakou086a02a2017-06-12 15:01:41 +0100470 void updateTouchState(InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700471 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
472 const InputMessage *next);
473
474 ssize_t findBatch(int32_t deviceId, int32_t source) const;
475 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
476
477 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
478
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -0800479 static void rewriteMessage(TouchState& state, InputMessage& msg);
Jeff Brown5912f952013-07-01 19:10:31 -0700480 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
481 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
482 static void addSample(MotionEvent* event, const InputMessage* msg);
483 static bool canAddSample(const Batch& batch, const InputMessage* msg);
484 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
485 static bool shouldResampleTool(int32_t toolType);
486
487 static bool isTouchResamplingEnabled();
488};
489
490} // namespace android
491
492#endif // _LIBINPUT_INPUT_TRANSPORT_H