2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef _LIBINPUT_INPUT_TRANSPORT_H
18 #define _LIBINPUT_INPUT_TRANSPORT_H
21 * Native input transport.
23 * The InputChannel provides a mechanism for exchanging InputMessage structures across processes.
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.
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>
41 * Intermediate representation used to send input events and related signals.
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.
55 // 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).
61 // Body *must* be 8 byte aligned.
65 nsecs_t eventTime __attribute__((aligned(8)));
74 nsecs_t downTime __attribute__((aligned(8)));
76 inline size_t size() const {
83 nsecs_t eventTime __attribute__((aligned(8)));
92 nsecs_t downTime __attribute__((aligned(8)));
97 uint32_t pointerCount;
98 // Note that PointerCoords requires 8 byte alignment.
100 PointerProperties properties;
101 PointerCoords coords;
102 } pointers[MAX_POINTERS];
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;
110 inline size_t size() const {
111 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
112 + sizeof(Pointer) * pointerCount;
120 inline size_t size() const {
121 return sizeof(Finished);
124 } __attribute__((aligned(8))) body;
126 bool isValid(size_t actualSize) const;
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.
134 * Each endpoint has its own InputChannel object that specifies its file descriptor.
136 * The input channel is closed when all references to it are released.
138 class InputChannel : public RefBase {
140 virtual ~InputChannel();
143 InputChannel(const String8& name, int fd);
145 /* Creates a pair of input channels.
147 * Returns OK on success.
149 static status_t openInputChannelPair(const String8& name,
150 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
152 inline String8 getName() const { return mName; }
153 inline int getFd() const { return mFd; }
155 /* Sends a message to the other endpoint.
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.
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.
166 status_t sendMessage(const InputMessage* msg);
168 /* Receives a message sent by the other endpoint.
170 * If there is no message present, try again after poll() indicates that the fd
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.
178 status_t receiveMessage(InputMessage* msg);
180 /* Returns a new object that has a duplicate of this channel's fd. */
181 sp<InputChannel> dup() const;
189 * Publishes input events to an input channel.
191 class InputPublisher {
193 /* Creates a publisher associated with an input channel. */
194 explicit InputPublisher(const sp<InputChannel>& channel);
196 /* Destroys the publisher and releases its input channel. */
199 /* Gets the underlying input channel. */
200 inline sp<InputChannel> getChannel() { return mChannel; }
202 /* Publishes a key event to the input channel.
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.
210 status_t publishKeyEvent(
223 /* Publishes a motion event to the input channel.
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.
231 status_t publishMotionEvent(
236 int32_t actionButton,
247 uint32_t pointerCount,
248 const PointerProperties* pointerProperties,
249 const PointerCoords* pointerCoords);
251 /* Receives the finished signal from the consumer in reply to the original dispatch signal.
252 * If a signal was received, returns the message sequence number,
253 * and whether the consumer handled the message.
255 * The returned sequence number is never 0 unless the operation failed.
257 * Returns OK on success.
258 * Returns WOULD_BLOCK if there is no signal present.
259 * Returns DEAD_OBJECT if the channel's peer has been closed.
260 * Other errors probably indicate that the channel is broken.
262 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
265 sp<InputChannel> mChannel;
269 * Consumes input events from an input channel.
271 class InputConsumer {
273 /* Creates a consumer associated with an input channel. */
274 explicit InputConsumer(const sp<InputChannel>& channel);
276 /* Destroys the consumer and releases its input channel. */
279 /* Gets the underlying input channel. */
280 inline sp<InputChannel> getChannel() { return mChannel; }
282 /* Consumes an input event from the input channel and copies its contents into
283 * an InputEvent object created using the specified factory.
285 * Tries to combine a series of move events into larger batches whenever possible.
287 * If consumeBatches is false, then defers consuming pending batched events if it
288 * is possible for additional samples to be added to them later. Call hasPendingBatch()
289 * to determine whether a pending batch is available to be consumed.
291 * If consumeBatches is true, then events are still batched but they are consumed
292 * immediately as soon as the input channel is exhausted.
294 * The frameTime parameter specifies the time when the current display frame started
295 * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
297 * The returned sequence number is never 0 unless the operation failed.
299 * Returns OK on success.
300 * Returns WOULD_BLOCK if there is no event present.
301 * Returns DEAD_OBJECT if the channel's peer has been closed.
302 * Returns NO_MEMORY if the event could not be created.
303 * Other errors probably indicate that the channel is broken.
305 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
306 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
308 /* Sends a finished signal to the publisher to inform it that the message
309 * with the specified sequence number has finished being process and whether
310 * the message was handled by the consumer.
312 * Returns OK on success.
313 * Returns BAD_VALUE if seq is 0.
314 * Other errors probably indicate that the channel is broken.
316 status_t sendFinishedSignal(uint32_t seq, bool handled);
318 /* Returns true if there is a deferred event waiting.
320 * Should be called after calling consume() to determine whether the consumer
321 * has a deferred event to be processed. Deferred events are somewhat special in
322 * that they have already been removed from the input channel. If the input channel
323 * becomes empty, the client may need to do extra work to ensure that it processes
324 * the deferred event despite the fact that the input channel's file descriptor
327 * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
328 * This guarantees that all deferred events will be processed.
330 * Alternately, the caller can call hasDeferredEvent() to determine whether there is
331 * a deferred event waiting and then ensure that its event loop wakes up at least
332 * one more time to consume the deferred event.
334 bool hasDeferredEvent() const;
336 /* Returns true if there is a pending batch.
338 * Should be called after calling consume() with consumeBatches == false to determine
339 * whether consume() should be called again later on with consumeBatches == true.
341 bool hasPendingBatch() const;
344 // True if touch resampling is enabled.
345 const bool mResampleTouch;
347 // The input channel.
348 sp<InputChannel> mChannel;
350 // The current input message.
353 // True if mMsg contains a valid input message that was deferred from the previous
354 // call to consume and that still needs to be handled.
357 // Batched motion events per device and source.
359 Vector<InputMessage> samples;
361 Vector<Batch> mBatches;
363 // Touch state per device and source, only for sources of class pointer.
367 int32_t idToIndex[MAX_POINTER_ID + 1];
368 PointerCoords pointers[MAX_POINTERS];
370 void initializeFrom(const InputMessage* msg) {
371 eventTime = msg->body.motion.eventTime;
373 for (uint32_t i = 0; i < msg->body.motion.pointerCount; i++) {
374 uint32_t id = msg->body.motion.pointers[i].properties.id;
377 pointers[i].copyFrom(msg->body.motion.pointers[i].coords);
381 const PointerCoords& getPointerById(uint32_t id) const {
382 return pointers[idToIndex[id]];
388 size_t historyCurrent;
391 History lastResample;
393 void initialize(int32_t deviceId, int32_t source) {
394 this->deviceId = deviceId;
395 this->source = source;
398 lastResample.eventTime = 0;
399 lastResample.idBits.clear();
402 void addHistory(const InputMessage* msg) {
404 if (historySize < 2) {
407 history[historyCurrent].initializeFrom(msg);
410 const History* getHistory(size_t index) const {
411 return &history[(historyCurrent + index) & 1];
414 Vector<TouchState> mTouchStates;
416 // Chain of batched sequence numbers. When multiple input messages are combined into
417 // a batch, we append a record here that associates the last sequence number in the
418 // batch with the previous one. When the finished signal is sent, we traverse the
419 // chain to individually finish all input messages that were part of the batch.
421 uint32_t seq; // sequence number of batched input message
422 uint32_t chain; // sequence number of previous batched input message
424 Vector<SeqChain> mSeqChains;
426 status_t consumeBatch(InputEventFactoryInterface* factory,
427 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
428 status_t consumeSamples(InputEventFactoryInterface* factory,
429 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
431 void updateTouchState(InputMessage* msg);
432 void rewriteMessage(const TouchState& state, InputMessage* msg);
433 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
434 const InputMessage *next);
436 ssize_t findBatch(int32_t deviceId, int32_t source) const;
437 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
439 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
441 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
442 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
443 static void addSample(MotionEvent* event, const InputMessage* msg);
444 static bool canAddSample(const Batch& batch, const InputMessage* msg);
445 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
446 static bool shouldResampleTool(int32_t toolType);
448 static bool isTouchResamplingEnabled();
451 } // namespace android
453 #endif // _LIBINPUT_INPUT_TRANSPORT_H