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)));
75 nsecs_t downTime __attribute__((aligned(8)));
77 inline size_t size() const {
84 nsecs_t eventTime __attribute__((aligned(8)));
94 nsecs_t downTime __attribute__((aligned(8)));
99 uint32_t pointerCount;
100 // Note that PointerCoords requires 8 byte alignment.
102 PointerProperties properties;
103 PointerCoords coords;
104 } pointers[MAX_POINTERS];
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;
112 inline size_t size() const {
113 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
114 + sizeof(Pointer) * pointerCount;
122 inline size_t size() const {
123 return sizeof(Finished);
126 } __attribute__((aligned(8))) body;
128 bool isValid(size_t actualSize) const;
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.
136 * Each endpoint has its own InputChannel object that specifies its file descriptor.
138 * The input channel is closed when all references to it are released.
140 class InputChannel : public RefBase {
142 virtual ~InputChannel();
145 InputChannel(const String8& name, int fd);
147 /* Creates a pair of input channels.
149 * Returns OK on success.
151 static status_t openInputChannelPair(const String8& name,
152 sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
154 inline String8 getName() const { return mName; }
155 inline int getFd() const { return mFd; }
157 /* Sends a message to the other endpoint.
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.
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.
168 status_t sendMessage(const InputMessage* msg);
170 /* Receives a message sent by the other endpoint.
172 * If there is no message present, try again after poll() indicates that the fd
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.
180 status_t receiveMessage(InputMessage* msg);
182 /* Returns a new object that has a duplicate of this channel's fd. */
183 sp<InputChannel> dup() const;
191 * Publishes input events to an input channel.
193 class InputPublisher {
195 /* Creates a publisher associated with an input channel. */
196 explicit InputPublisher(const sp<InputChannel>& channel);
198 /* Destroys the publisher and releases its input channel. */
201 /* Gets the underlying input channel. */
202 inline sp<InputChannel> getChannel() { return mChannel; }
204 /* Publishes a key event to the input channel.
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.
212 status_t publishKeyEvent(
225 /* Publishes a motion event to the input channel.
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.
233 status_t publishMotionEvent(
239 int32_t actionButton,
250 uint32_t pointerCount,
251 const PointerProperties* pointerProperties,
252 const PointerCoords* pointerCoords);
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.
258 * The returned sequence number is never 0 unless the operation failed.
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.
265 status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
268 sp<InputChannel> mChannel;
272 * Consumes input events from an input channel.
274 class InputConsumer {
276 /* Creates a consumer associated with an input channel. */
277 explicit InputConsumer(const sp<InputChannel>& channel);
279 /* Destroys the consumer and releases its input channel. */
282 /* Gets the underlying input channel. */
283 inline sp<InputChannel> getChannel() { return mChannel; }
285 /* Consumes an input event from the input channel and copies its contents into
286 * an InputEvent object created using the specified factory.
288 * Tries to combine a series of move events into larger batches whenever possible.
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.
294 * If consumeBatches is true, then events are still batched but they are consumed
295 * immediately as soon as the input channel is exhausted.
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.
300 * The returned sequence number is never 0 unless the operation failed.
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.
308 status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
309 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId);
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.
315 * Returns OK on success.
316 * Returns BAD_VALUE if seq is 0.
317 * Other errors probably indicate that the channel is broken.
319 status_t sendFinishedSignal(uint32_t seq, bool handled);
321 /* Returns true if there is a deferred event waiting.
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
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.
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.
337 bool hasDeferredEvent() const;
339 /* Returns true if there is a pending batch.
341 * Should be called after calling consume() with consumeBatches == false to determine
342 * whether consume() should be called again later on with consumeBatches == true.
344 bool hasPendingBatch() const;
347 // True if touch resampling is enabled.
348 const bool mResampleTouch;
350 // The input channel.
351 sp<InputChannel> mChannel;
353 // The current input message.
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.
360 // Batched motion events per device and source.
362 Vector<InputMessage> samples;
364 Vector<Batch> mBatches;
366 // Touch state per device and source, only for sources of class pointer.
370 int32_t idToIndex[MAX_POINTER_ID + 1];
371 PointerCoords pointers[MAX_POINTERS];
373 void initializeFrom(const InputMessage& msg) {
374 eventTime = msg.body.motion.eventTime;
376 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
377 uint32_t id = msg.body.motion.pointers[i].properties.id;
380 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
384 const PointerCoords& getPointerById(uint32_t id) const {
385 return pointers[idToIndex[id]];
391 size_t historyCurrent;
394 History lastResample;
396 void initialize(int32_t deviceId, int32_t source) {
397 this->deviceId = deviceId;
398 this->source = source;
401 lastResample.eventTime = 0;
402 lastResample.idBits.clear();
405 void addHistory(const InputMessage& msg) {
407 if (historySize < 2) {
410 history[historyCurrent].initializeFrom(msg);
413 const History* getHistory(size_t index) const {
414 return &history[(historyCurrent + index) & 1];
417 bool recentCoordinatesAreIdentical(uint32_t id) const {
418 // Return true if the two most recently received "raw" coordinates are identical
419 if (historySize < 2) {
422 float currentX = getHistory(0)->getPointerById(id).getX();
423 float currentY = getHistory(0)->getPointerById(id).getY();
424 float previousX = getHistory(1)->getPointerById(id).getX();
425 float previousY = getHistory(1)->getPointerById(id).getY();
426 if (currentX == previousX && currentY == previousY) {
432 Vector<TouchState> mTouchStates;
434 // Chain of batched sequence numbers. When multiple input messages are combined into
435 // a batch, we append a record here that associates the last sequence number in the
436 // batch with the previous one. When the finished signal is sent, we traverse the
437 // chain to individually finish all input messages that were part of the batch.
439 uint32_t seq; // sequence number of batched input message
440 uint32_t chain; // sequence number of previous batched input message
442 Vector<SeqChain> mSeqChains;
444 status_t consumeBatch(InputEventFactoryInterface* factory,
445 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId);
446 status_t consumeSamples(InputEventFactoryInterface* factory,
447 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent,
450 void updateTouchState(InputMessage& msg);
451 bool rewriteMessage(const TouchState& state, InputMessage& msg);
452 void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
453 const InputMessage *next);
455 ssize_t findBatch(int32_t deviceId, int32_t source) const;
456 ssize_t findTouchState(int32_t deviceId, int32_t source) const;
458 status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
460 static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
461 static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
462 static void addSample(MotionEvent* event, const InputMessage* msg);
463 static bool canAddSample(const Batch& batch, const InputMessage* msg);
464 static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
465 static bool shouldResampleTool(int32_t toolType);
467 static bool isTouchResamplingEnabled();
470 } // namespace android
472 #endif // _LIBINPUT_INPUT_TRANSPORT_H