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