1/*
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.
42 *
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.
45 */
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;
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).
58        uint32_t padding;
59    } header;
60
61    // Body *must* be 8 byte aligned.
62    union Body {
63        struct Key {
64            uint32_t seq;
65            nsecs_t eventTime __attribute__((aligned(8)));
66            int32_t deviceId;
67            int32_t source;
68            int32_t action;
69            int32_t flags;
70            int32_t keyCode;
71            int32_t scanCode;
72            int32_t metaState;
73            int32_t repeatCount;
74            nsecs_t downTime __attribute__((aligned(8)));
75
76            inline size_t size() const {
77                return sizeof(Key);
78            }
79        } key;
80
81        struct Motion {
82            uint32_t seq;
83            nsecs_t eventTime __attribute__((aligned(8)));
84            int32_t deviceId;
85            int32_t source;
86            int32_t action;
87            int32_t actionButton;
88            int32_t flags;
89            int32_t metaState;
90            int32_t buttonState;
91            int32_t edgeFlags;
92            nsecs_t downTime __attribute__((aligned(8)));
93            float xOffset;
94            float yOffset;
95            float xPrecision;
96            float yPrecision;
97            uint32_t pointerCount;
98            // Note that PointerCoords requires 8 byte alignment.
99            struct Pointer {
100                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;
124    } __attribute__((aligned(8))) body;
125
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:
143    InputChannel(const String8& name, int fd);
144
145    /* Creates a pair of input channels.
146     *
147     * Returns OK on success.
148     */
149    static status_t openInputChannelPair(const String8& name,
150            sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
151
152    inline String8 getName() const { return mName; }
153    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:
184    String8 mName;
185    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,
235            int32_t action,
236            int32_t actionButton,
237            int32_t flags,
238            int32_t edgeFlags,
239            int32_t metaState,
240            int32_t buttonState,
241            float xOffset,
242            float yOffset,
243            float xPrecision,
244            float yPrecision,
245            nsecs_t downTime,
246            nsecs_t eventTime,
247            uint32_t pointerCount,
248            const PointerProperties* pointerProperties,
249            const PointerCoords* pointerCoords);
250
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.
254     *
255     * The returned sequence number is never 0 unless the operation failed.
256     *
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.
261     */
262    status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
263
264private:
265    sp<InputChannel> mChannel;
266};
267
268/*
269 * Consumes input events from an input channel.
270 */
271class InputConsumer {
272public:
273    /* Creates a consumer associated with an input channel. */
274    explicit InputConsumer(const sp<InputChannel>& channel);
275
276    /* Destroys the consumer and releases its input channel. */
277    ~InputConsumer();
278
279    /* Gets the underlying input channel. */
280    inline sp<InputChannel> getChannel() { return mChannel; }
281
282    /* Consumes an input event from the input channel and copies its contents into
283     * an InputEvent object created using the specified factory.
284     *
285     * Tries to combine a series of move events into larger batches whenever possible.
286     *
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.
290     *
291     * If consumeBatches is true, then events are still batched but they are consumed
292     * immediately as soon as the input channel is exhausted.
293     *
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.
296     *
297     * The returned sequence number is never 0 unless the operation failed.
298     *
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.
304     */
305    status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
306            nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
307
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.
311     *
312     * Returns OK on success.
313     * Returns BAD_VALUE if seq is 0.
314     * Other errors probably indicate that the channel is broken.
315     */
316    status_t sendFinishedSignal(uint32_t seq, bool handled);
317
318    /* Returns true if there is a deferred event waiting.
319     *
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
325     * is not readable.
326     *
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.
329     *
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.
333     */
334    bool hasDeferredEvent() const;
335
336    /* Returns true if there is a pending batch.
337     *
338     * Should be called after calling consume() with consumeBatches == false to determine
339     * whether consume() should be called again later on with consumeBatches == true.
340     */
341    bool hasPendingBatch() const;
342
343private:
344    // True if touch resampling is enabled.
345    const bool mResampleTouch;
346
347    // The input channel.
348    sp<InputChannel> mChannel;
349
350    // The current input message.
351    InputMessage mMsg;
352
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.
355    bool mMsgDeferred;
356
357    // Batched motion events per device and source.
358    struct Batch {
359        Vector<InputMessage> samples;
360    };
361    Vector<Batch> mBatches;
362
363    // Touch state per device and source, only for sources of class pointer.
364    struct History {
365        nsecs_t eventTime;
366        BitSet32 idBits;
367        int32_t idToIndex[MAX_POINTER_ID + 1];
368        PointerCoords pointers[MAX_POINTERS];
369
370        void initializeFrom(const InputMessage* msg) {
371            eventTime = msg->body.motion.eventTime;
372            idBits.clear();
373            for (uint32_t i = 0; i < msg->body.motion.pointerCount; i++) {
374                uint32_t id = msg->body.motion.pointers[i].properties.id;
375                idBits.markBit(id);
376                idToIndex[id] = i;
377                pointers[i].copyFrom(msg->body.motion.pointers[i].coords);
378            }
379        }
380
381        const PointerCoords& getPointerById(uint32_t id) const {
382            return pointers[idToIndex[id]];
383        }
384    };
385    struct TouchState {
386        int32_t deviceId;
387        int32_t source;
388        size_t historyCurrent;
389        size_t historySize;
390        History history[2];
391        History lastResample;
392
393        void initialize(int32_t deviceId, int32_t source) {
394            this->deviceId = deviceId;
395            this->source = source;
396            historyCurrent = 0;
397            historySize = 0;
398            lastResample.eventTime = 0;
399            lastResample.idBits.clear();
400        }
401
402        void addHistory(const InputMessage* msg) {
403            historyCurrent ^= 1;
404            if (historySize < 2) {
405                historySize += 1;
406            }
407            history[historyCurrent].initializeFrom(msg);
408        }
409
410        const History* getHistory(size_t index) const {
411            return &history[(historyCurrent + index) & 1];
412        }
413    };
414    Vector<TouchState> mTouchStates;
415
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.
420    struct SeqChain {
421        uint32_t seq;   // sequence number of batched input message
422        uint32_t chain; // sequence number of previous batched input message
423    };
424    Vector<SeqChain> mSeqChains;
425
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);
430
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);
435
436    ssize_t findBatch(int32_t deviceId, int32_t source) const;
437    ssize_t findTouchState(int32_t deviceId, int32_t source) const;
438
439    status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
440
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);
447
448    static bool isTouchResamplingEnabled();
449};
450
451} // namespace android
452
453#endif // _LIBINPUT_INPUT_TRANSPORT_H
454