OSDN Git Service

release-request-6c9f747d-7df5-465f-8bde-1149394b99b4-for-git_oc-mr1-release-4296189...
[android-x86/frameworks-native.git] / include / input / InputTransport.h
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
38 namespace 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  */
46 struct 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 displayId;
69             int32_t action;
70             int32_t flags;
71             int32_t keyCode;
72             int32_t scanCode;
73             int32_t metaState;
74             int32_t repeatCount;
75             nsecs_t downTime __attribute__((aligned(8)));
76
77             inline size_t size() const {
78                 return sizeof(Key);
79             }
80         } key;
81
82         struct Motion {
83             uint32_t seq;
84             nsecs_t eventTime __attribute__((aligned(8)));
85             int32_t deviceId;
86             int32_t source;
87             int32_t displayId;
88             int32_t action;
89             int32_t actionButton;
90             int32_t flags;
91             int32_t metaState;
92             int32_t buttonState;
93             int32_t edgeFlags;
94             nsecs_t downTime __attribute__((aligned(8)));
95             float xOffset;
96             float yOffset;
97             float xPrecision;
98             float yPrecision;
99             uint32_t pointerCount;
100             // Note that PointerCoords requires 8 byte alignment.
101             struct Pointer {
102                 PointerProperties properties;
103                 PointerCoords coords;
104             } pointers[MAX_POINTERS];
105
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;
110             }
111
112             inline size_t size() const {
113                 return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
114                         + sizeof(Pointer) * pointerCount;
115             }
116         } motion;
117
118         struct Finished {
119             uint32_t seq;
120             bool handled;
121
122             inline size_t size() const {
123                 return sizeof(Finished);
124             }
125         } finished;
126     } __attribute__((aligned(8))) body;
127
128     bool isValid(size_t actualSize) const;
129     size_t size() const;
130 };
131
132 /*
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.
135  *
136  * Each endpoint has its own InputChannel object that specifies its file descriptor.
137  *
138  * The input channel is closed when all references to it are released.
139  */
140 class InputChannel : public RefBase {
141 protected:
142     virtual ~InputChannel();
143
144 public:
145     InputChannel(const String8& name, int fd);
146
147     /* Creates a pair of input channels.
148      *
149      * Returns OK on success.
150      */
151     static status_t openInputChannelPair(const String8& name,
152             sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
153
154     inline String8 getName() const { return mName; }
155     inline int getFd() const { return mFd; }
156
157     /* Sends a message to the other endpoint.
158      *
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.
162      *
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.
167      */
168     status_t sendMessage(const InputMessage* msg);
169
170     /* Receives a message sent by the other endpoint.
171      *
172      * If there is no message present, try again after poll() indicates that the fd
173      * is readable.
174      *
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.
179      */
180     status_t receiveMessage(InputMessage* msg);
181
182     /* Returns a new object that has a duplicate of this channel's fd. */
183     sp<InputChannel> dup() const;
184
185 private:
186     String8 mName;
187     int mFd;
188 };
189
190 /*
191  * Publishes input events to an input channel.
192  */
193 class InputPublisher {
194 public:
195     /* Creates a publisher associated with an input channel. */
196     explicit InputPublisher(const sp<InputChannel>& channel);
197
198     /* Destroys the publisher and releases its input channel. */
199     ~InputPublisher();
200
201     /* Gets the underlying input channel. */
202     inline sp<InputChannel> getChannel() { return mChannel; }
203
204     /* Publishes a key event to the input channel.
205      *
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.
211      */
212     status_t publishKeyEvent(
213             uint32_t seq,
214             int32_t deviceId,
215             int32_t source,
216             int32_t action,
217             int32_t flags,
218             int32_t keyCode,
219             int32_t scanCode,
220             int32_t metaState,
221             int32_t repeatCount,
222             nsecs_t downTime,
223             nsecs_t eventTime);
224
225     /* Publishes a motion event to the input channel.
226      *
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.
232      */
233     status_t publishMotionEvent(
234             uint32_t seq,
235             int32_t deviceId,
236             int32_t source,
237             int32_t displayId,
238             int32_t action,
239             int32_t actionButton,
240             int32_t flags,
241             int32_t edgeFlags,
242             int32_t metaState,
243             int32_t buttonState,
244             float xOffset,
245             float yOffset,
246             float xPrecision,
247             float yPrecision,
248             nsecs_t downTime,
249             nsecs_t eventTime,
250             uint32_t pointerCount,
251             const PointerProperties* pointerProperties,
252             const PointerCoords* pointerCoords);
253
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.
257      *
258      * The returned sequence number is never 0 unless the operation failed.
259      *
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.
264      */
265     status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
266
267 private:
268     sp<InputChannel> mChannel;
269 };
270
271 /*
272  * Consumes input events from an input channel.
273  */
274 class InputConsumer {
275 public:
276     /* Creates a consumer associated with an input channel. */
277     explicit InputConsumer(const sp<InputChannel>& channel);
278
279     /* Destroys the consumer and releases its input channel. */
280     ~InputConsumer();
281
282     /* Gets the underlying input channel. */
283     inline sp<InputChannel> getChannel() { return mChannel; }
284
285     /* Consumes an input event from the input channel and copies its contents into
286      * an InputEvent object created using the specified factory.
287      *
288      * Tries to combine a series of move events into larger batches whenever possible.
289      *
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.
293      *
294      * If consumeBatches is true, then events are still batched but they are consumed
295      * immediately as soon as the input channel is exhausted.
296      *
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.
299      *
300      * The returned sequence number is never 0 unless the operation failed.
301      *
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.
307      */
308     status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
309             nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent, int32_t* displayId);
310
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.
314      *
315      * Returns OK on success.
316      * Returns BAD_VALUE if seq is 0.
317      * Other errors probably indicate that the channel is broken.
318      */
319     status_t sendFinishedSignal(uint32_t seq, bool handled);
320
321     /* Returns true if there is a deferred event waiting.
322      *
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
328      * is not readable.
329      *
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.
332      *
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.
336      */
337     bool hasDeferredEvent() const;
338
339     /* Returns true if there is a pending batch.
340      *
341      * Should be called after calling consume() with consumeBatches == false to determine
342      * whether consume() should be called again later on with consumeBatches == true.
343      */
344     bool hasPendingBatch() const;
345
346 private:
347     // True if touch resampling is enabled.
348     const bool mResampleTouch;
349
350     // The input channel.
351     sp<InputChannel> mChannel;
352
353     // The current input message.
354     InputMessage mMsg;
355
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.
358     bool mMsgDeferred;
359
360     // Batched motion events per device and source.
361     struct Batch {
362         Vector<InputMessage> samples;
363     };
364     Vector<Batch> mBatches;
365
366     // Touch state per device and source, only for sources of class pointer.
367     struct History {
368         nsecs_t eventTime;
369         BitSet32 idBits;
370         int32_t idToIndex[MAX_POINTER_ID + 1];
371         PointerCoords pointers[MAX_POINTERS];
372
373         void initializeFrom(const InputMessage& msg) {
374             eventTime = msg.body.motion.eventTime;
375             idBits.clear();
376             for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
377                 uint32_t id = msg.body.motion.pointers[i].properties.id;
378                 idBits.markBit(id);
379                 idToIndex[id] = i;
380                 pointers[i].copyFrom(msg.body.motion.pointers[i].coords);
381             }
382         }
383
384         const PointerCoords& getPointerById(uint32_t id) const {
385             return pointers[idToIndex[id]];
386         }
387     };
388     struct TouchState {
389         int32_t deviceId;
390         int32_t source;
391         size_t historyCurrent;
392         size_t historySize;
393         History history[2];
394         History lastResample;
395
396         void initialize(int32_t deviceId, int32_t source) {
397             this->deviceId = deviceId;
398             this->source = source;
399             historyCurrent = 0;
400             historySize = 0;
401             lastResample.eventTime = 0;
402             lastResample.idBits.clear();
403         }
404
405         void addHistory(const InputMessage& msg) {
406             historyCurrent ^= 1;
407             if (historySize < 2) {
408                 historySize += 1;
409             }
410             history[historyCurrent].initializeFrom(msg);
411         }
412
413         const History* getHistory(size_t index) const {
414             return &history[(historyCurrent + index) & 1];
415         }
416
417         bool recentCoordinatesAreIdentical(uint32_t id) const {
418             // Return true if the two most recently received "raw" coordinates are identical
419             if (historySize < 2) {
420                 return false;
421             }
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) {
427                 return true;
428             }
429             return false;
430         }
431     };
432     Vector<TouchState> mTouchStates;
433
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.
438     struct SeqChain {
439         uint32_t seq;   // sequence number of batched input message
440         uint32_t chain; // sequence number of previous batched input message
441     };
442     Vector<SeqChain> mSeqChains;
443
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,
448             int32_t* displayId);
449
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);
454
455     ssize_t findBatch(int32_t deviceId, int32_t source) const;
456     ssize_t findTouchState(int32_t deviceId, int32_t source) const;
457
458     status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
459
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);
466
467     static bool isTouchResamplingEnabled();
468 };
469
470 } // namespace android
471
472 #endif // _LIBINPUT_INPUT_TRANSPORT_H