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