blob: efa1ffbfeec1b454be41e12309acd3f9577fe48a [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>
34#include <utils/String8.h>
35#include <utils/Vector.h>
36#include <utils/BitSet.h>
37
38namespace android {
39
40/*
41 * Intermediate representation used to send input events and related signals.
Fengwei Yin83e0e422014-05-24 05:32:09 +080042 *
43 * Note that this structure is used for IPCs so its layout must be identical
44 * on 64 and 32 bit processes. This is tested in StructLayout_test.cpp.
Jeff Brown5912f952013-07-01 19:10:31 -070045 */
46struct InputMessage {
47 enum {
48 TYPE_KEY = 1,
49 TYPE_MOTION = 2,
50 TYPE_FINISHED = 3,
51 };
52
53 struct Header {
54 uint32_t type;
Fengwei Yin83e0e422014-05-24 05:32:09 +080055 // We don't need this field in order to align the body below but we
56 // leave it here because InputMessage::size() and other functions
57 // compute the size of this structure as sizeof(Header) + sizeof(Body).
58 uint32_t padding;
Jeff Brown5912f952013-07-01 19:10:31 -070059 } header;
60
Fengwei Yin83e0e422014-05-24 05:32:09 +080061 // Body *must* be 8 byte aligned.
Jeff Brown5912f952013-07-01 19:10:31 -070062 union Body {
63 struct Key {
64 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080065 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070066 int32_t deviceId;
67 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070068 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070069 int32_t action;
70 int32_t flags;
71 int32_t keyCode;
72 int32_t scanCode;
73 int32_t metaState;
74 int32_t repeatCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +080075 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070076
77 inline size_t size() const {
78 return sizeof(Key);
79 }
80 } key;
81
82 struct Motion {
83 uint32_t seq;
Fengwei Yin83e0e422014-05-24 05:32:09 +080084 nsecs_t eventTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070085 int32_t deviceId;
86 int32_t source;
Tarandeep Singh58641502017-07-31 10:51:54 -070087 int32_t displayId;
Jeff Brown5912f952013-07-01 19:10:31 -070088 int32_t action;
Michael Wright7b159c92015-05-14 14:48:03 +010089 int32_t actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -070090 int32_t flags;
91 int32_t metaState;
92 int32_t buttonState;
93 int32_t edgeFlags;
Fengwei Yin83e0e422014-05-24 05:32:09 +080094 nsecs_t downTime __attribute__((aligned(8)));
Jeff Brown5912f952013-07-01 19:10:31 -070095 float xOffset;
96 float yOffset;
97 float xPrecision;
98 float yPrecision;
Narayan Kamathed5fd382014-05-02 17:53:33 +010099 uint32_t pointerCount;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800100 // Note that PointerCoords requires 8 byte alignment.
Michael Wrightb03f1032015-05-14 16:29:13 +0100101 struct Pointer {
Jeff Brown5912f952013-07-01 19:10:31 -0700102 PointerProperties properties;
103 PointerCoords coords;
104 } pointers[MAX_POINTERS];
105
106 int32_t getActionId() const {
107 uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
108 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
109 return pointers[index].properties.id;
110 }
111
112 inline size_t size() const {
113 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
114 + sizeof(Pointer) * pointerCount;
115 }
116 } motion;
117
118 struct Finished {
119 uint32_t seq;
120 bool handled;
121
122 inline size_t size() const {
123 return sizeof(Finished);
124 }
125 } finished;
Fengwei Yin83e0e422014-05-24 05:32:09 +0800126 } __attribute__((aligned(8))) body;
Jeff Brown5912f952013-07-01 19:10:31 -0700127
128 bool isValid(size_t actualSize) const;
129 size_t size() const;
130};
131
132/*
133 * An input channel consists of a local unix domain socket used to send and receive
134 * input messages across processes. Each channel has a descriptive name for debugging purposes.
135 *
136 * Each endpoint has its own InputChannel object that specifies its file descriptor.
137 *
138 * The input channel is closed when all references to it are released.
139 */
140class InputChannel : public RefBase {
141protected:
142 virtual ~InputChannel();
143
144public:
145 InputChannel(const String8& name, int fd);
146
147 /* Creates a pair of input channels.
148 *
149 * Returns OK on success.
150 */
151 static status_t openInputChannelPair(const String8& name,
152 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
153
154 inline String8 getName() const { return mName; }
155 inline int getFd() const { return mFd; }
156
157 /* Sends a message to the other endpoint.
158 *
159 * If the channel is full then the message is guaranteed not to have been sent at all.
160 * Try again after the consumer has sent a finished signal indicating that it has
161 * consumed some of the pending messages from the channel.
162 *
163 * Returns OK on success.
164 * Returns WOULD_BLOCK if the channel is full.
165 * Returns DEAD_OBJECT if the channel's peer has been closed.
166 * Other errors probably indicate that the channel is broken.
167 */
168 status_t sendMessage(const InputMessage* msg);
169
170 /* Receives a message sent by the other endpoint.
171 *
172 * If there is no message present, try again after poll() indicates that the fd
173 * is readable.
174 *
175 * Returns OK on success.
176 * Returns WOULD_BLOCK if there is no message present.
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 receiveMessage(InputMessage* msg);
181
182 /* Returns a new object that has a duplicate of this channel's fd. */
183 sp<InputChannel> dup() const;
184
185private:
186 String8 mName;
187 int mFd;
188};
189
190/*
191 * Publishes input events to an input channel.
192 */
193class InputPublisher {
194public:
195 /* Creates a publisher associated with an input channel. */
196 explicit InputPublisher(const sp<InputChannel>& channel);
197
198 /* Destroys the publisher and releases its input channel. */
199 ~InputPublisher();
200
201 /* Gets the underlying input channel. */
202 inline sp<InputChannel> getChannel() { return mChannel; }
203
204 /* Publishes a key event to the input channel.
205 *
206 * Returns OK on success.
207 * Returns WOULD_BLOCK if the channel is full.
208 * Returns DEAD_OBJECT if the channel's peer has been closed.
209 * Returns BAD_VALUE if seq is 0.
210 * Other errors probably indicate that the channel is broken.
211 */
212 status_t publishKeyEvent(
213 uint32_t seq,
214 int32_t deviceId,
215 int32_t source,
216 int32_t action,
217 int32_t flags,
218 int32_t keyCode,
219 int32_t scanCode,
220 int32_t metaState,
221 int32_t repeatCount,
222 nsecs_t downTime,
223 nsecs_t eventTime);
224
225 /* Publishes a motion event to the input channel.
226 *
227 * Returns OK on success.
228 * Returns WOULD_BLOCK if the channel is full.
229 * Returns DEAD_OBJECT if the channel's peer has been closed.
230 * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
231 * Other errors probably indicate that the channel is broken.
232 */
233 status_t publishMotionEvent(
234 uint32_t seq,
235 int32_t deviceId,
236 int32_t source,
Tarandeep Singh58641502017-07-31 10:51:54 -0700237 int32_t displayId,
Jeff Brown5912f952013-07-01 19:10:31 -0700238 int32_t action,
Michael Wright7b159c92015-05-14 14:48:03 +0100239 int32_t actionButton,
Jeff Brown5912f952013-07-01 19:10:31 -0700240 int32_t flags,
241 int32_t edgeFlags,
242 int32_t metaState,
243 int32_t buttonState,
244 float xOffset,
245 float yOffset,
246 float xPrecision,
247 float yPrecision,
248 nsecs_t downTime,
249 nsecs_t eventTime,
Narayan Kamathed5fd382014-05-02 17:53:33 +0100250 uint32_t pointerCount,
Jeff Brown5912f952013-07-01 19:10:31 -0700251 const PointerProperties* pointerProperties,
252 const PointerCoords* pointerCoords);
253
254 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
255 * If a signal was received, returns the message sequence number,
256 * and whether the consumer handled the message.
257 *
258 * The returned sequence number is never 0 unless the operation failed.
259 *
260 * Returns OK on success.
261 * Returns WOULD_BLOCK if there is no signal present.
262 * Returns DEAD_OBJECT if the channel's peer has been closed.
263 * Other errors probably indicate that the channel is broken.
264 */
265 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
266
267private:
268 sp<InputChannel> mChannel;
269};
270
271/*
272 * Consumes input events from an input channel.
273 */
274class InputConsumer {
275public:
276 /* Creates a consumer associated with an input channel. */
277 explicit InputConsumer(const sp<InputChannel>& channel);
278
279 /* Destroys the consumer and releases its input channel. */
280 ~InputConsumer();
281
282 /* Gets the underlying input channel. */
283 inline sp<InputChannel> getChannel() { return mChannel; }
284
285 /* Consumes an input event from the input channel and copies its contents into
286 * an InputEvent object created using the specified factory.
287 *
288 * Tries to combine a series of move events into larger batches whenever possible.
289 *
290 * If consumeBatches is false, then defers consuming pending batched events if it
291 * is possible for additional samples to be added to them later. Call hasPendingBatch()
292 * to determine whether a pending batch is available to be consumed.
293 *
294 * If consumeBatches is true, then events are still batched but they are consumed
295 * immediately as soon as the input channel is exhausted.
296 *
297 * The frameTime parameter specifies the time when the current display frame started
298 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
299 *
300 * The returned sequence number is never 0 unless the operation failed.
301 *
302 * Returns OK on success.
303 * Returns WOULD_BLOCK if there is no event present.
304 * Returns DEAD_OBJECT if the channel's peer has been closed.
305 * Returns NO_MEMORY if the event could not be created.
306 * Other errors probably indicate that the channel is broken.
307 */
308 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
Tarandeep Singh58641502017-07-31 10:51:54 -0700309 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId);
Jeff Brown5912f952013-07-01 19:10:31 -0700310
311 /* Sends a finished signal to the publisher to inform it that the message
312 * with the specified sequence number has finished being process and whether
313 * the message was handled by the consumer.
314 *
315 * Returns OK on success.
316 * Returns BAD_VALUE if seq is 0.
317 * Other errors probably indicate that the channel is broken.
318 */
319 status_t sendFinishedSignal(uint32_t seq, bool handled);
320
321 /* Returns true if there is a deferred event waiting.
322 *
323 * Should be called after calling consume() to determine whether the consumer
324 * has a deferred event to be processed. Deferred events are somewhat special in
325 * that they have already been removed from the input channel. If the input channel
326 * becomes empty, the client may need to do extra work to ensure that it processes
327 * the deferred event despite the fact that the input channel's file descriptor
328 * is not readable.
329 *
330 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
331 * This guarantees that all deferred events will be processed.
332 *
333 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
334 * a deferred event waiting and then ensure that its event loop wakes up at least
335 * one more time to consume the deferred event.
336 */
337 bool hasDeferredEvent() const;
338
339 /* Returns true if there is a pending batch.
340 *
341 * Should be called after calling consume() with consumeBatches == false to determine
342 * whether consume() should be called again later on with consumeBatches == true.
343 */
344 bool hasPendingBatch() const;
345
346private:
347 // True if touch resampling is enabled.
348 const bool mResampleTouch;
349
350 // The input channel.
351 sp<InputChannel> mChannel;
352
353 // The current input message.
354 InputMessage mMsg;
355
356 // True if mMsg contains a valid input message that was deferred from the previous
357 // call to consume and that still needs to be handled.
358 bool mMsgDeferred;
359
360 // Batched motion events per device and source.
361 struct Batch {
362 Vector<InputMessage> samples;
363 };
364 Vector<Batch> mBatches;
365
366 // Touch state per device and source, only for sources of class pointer.
367 struct History {
368 nsecs_t eventTime;
369 BitSet32 idBits;
370 int32_t idToIndex[MAX_POINTER_ID + 1];
371 PointerCoords pointers[MAX_POINTERS];
372
373 void initializeFrom(const InputMessage* msg) {
374 eventTime = msg->body.motion.eventTime;
375 idBits.clear();
Narayan Kamathed5fd382014-05-02 17:53:33 +0100376 for (uint32_t i = 0; i < msg->body.motion.pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700377 uint32_t id = msg->body.motion.pointers[i].properties.id;
378 idBits.markBit(id);
379 idToIndex[id] = i;
380 pointers[i].copyFrom(msg->body.motion.pointers[i].coords);
381 }
382 }
383
384 const PointerCoords& getPointerById(uint32_t id) const {
385 return pointers[idToIndex[id]];
386 }
387 };
388 struct TouchState {
389 int32_t deviceId;
390 int32_t source;
391 size_t historyCurrent;
392 size_t historySize;
393 History history[2];
394 History lastResample;
395
396 void initialize(int32_t deviceId, int32_t source) {
397 this->deviceId = deviceId;
398 this->source = source;
399 historyCurrent = 0;
400 historySize = 0;
401 lastResample.eventTime = 0;
402 lastResample.idBits.clear();
403 }
404
405 void addHistory(const InputMessage* msg) {
406 historyCurrent ^= 1;
407 if (historySize < 2) {
408 historySize += 1;
409 }
410 history[historyCurrent].initializeFrom(msg);
411 }
412
413 const History* getHistory(size_t index) const {
414 return &history[(historyCurrent + index) & 1];
415 }
416 };
417 Vector<TouchState> mTouchStates;
418
419 // Chain of batched sequence numbers. When multiple input messages are combined into
420 // a batch, we append a record here that associates the last sequence number in the
421 // batch with the previous one. When the finished signal is sent, we traverse the
422 // chain to individually finish all input messages that were part of the batch.
423 struct SeqChain {
424 uint32_t seq; // sequence number of batched input message
425 uint32_t chain; // sequence number of previous batched input message
426 };
427 Vector<SeqChain> mSeqChains;
428
429 status_t consumeBatch(InputEventFactoryInterface* factory,
Tarandeep Singh58641502017-07-31 10:51:54 -0700430 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId);
Jeff Brown5912f952013-07-01 19:10:31 -0700431 status_t consumeSamples(InputEventFactoryInterface* factory,
Tarandeep Singh58641502017-07-31 10:51:54 -0700432 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent,
433 int32_t* displayId);
Jeff Brown5912f952013-07-01 19:10:31 -0700434
435 void updateTouchState(InputMessage* msg);
436 void rewriteMessage(const TouchState& state, InputMessage* msg);
437 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
438 const InputMessage *next);
439
440 ssize_t findBatch(int32_t deviceId, int32_t source) const;
441 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
442
443 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
444
445 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
446 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
447 static void addSample(MotionEvent* event, const InputMessage* msg);
448 static bool canAddSample(const Batch& batch, const InputMessage* msg);
449 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
450 static bool shouldResampleTool(int32_t toolType);
451
452 static bool isTouchResamplingEnabled();
453};
454
455} // namespace android
456
457#endif // _LIBINPUT_INPUT_TRANSPORT_H